PackageManagerService.java revision dea3fd8cf1000d786ff40e1036a8bf76a55d5fcd
1/*
2 * Copyright (C) 2006 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 *      http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17package com.android.server.pm;
18
19import static android.Manifest.permission.DELETE_PACKAGES;
20import static android.Manifest.permission.INSTALL_PACKAGES;
21import static android.Manifest.permission.MANAGE_PROFILE_AND_DEVICE_OWNERS;
22import static android.Manifest.permission.READ_EXTERNAL_STORAGE;
23import static android.Manifest.permission.REQUEST_DELETE_PACKAGES;
24import static android.Manifest.permission.WRITE_EXTERNAL_STORAGE;
25import static android.Manifest.permission.WRITE_MEDIA_STORAGE;
26import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DEFAULT;
27import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED;
28import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED;
29import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED_USER;
30import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_ENABLED;
31import static android.content.pm.PackageManager.DELETE_KEEP_DATA;
32import static android.content.pm.PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT;
33import static android.content.pm.PackageManager.FLAG_PERMISSION_POLICY_FIXED;
34import static android.content.pm.PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED;
35import static android.content.pm.PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE;
36import static android.content.pm.PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
37import static android.content.pm.PackageManager.FLAG_PERMISSION_USER_FIXED;
38import static android.content.pm.PackageManager.FLAG_PERMISSION_USER_SET;
39import static android.content.pm.PackageManager.INSTALL_EXTERNAL;
40import static android.content.pm.PackageManager.INSTALL_FAILED_ALREADY_EXISTS;
41import static android.content.pm.PackageManager.INSTALL_FAILED_CONFLICTING_PROVIDER;
42import static android.content.pm.PackageManager.INSTALL_FAILED_DUPLICATE_PACKAGE;
43import static android.content.pm.PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION;
44import static android.content.pm.PackageManager.INSTALL_FAILED_INSTANT_APP_INVALID;
45import static android.content.pm.PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
46import static android.content.pm.PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
47import static android.content.pm.PackageManager.INSTALL_FAILED_INVALID_APK;
48import static android.content.pm.PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
49import static android.content.pm.PackageManager.INSTALL_FAILED_MISSING_SHARED_LIBRARY;
50import static android.content.pm.PackageManager.INSTALL_FAILED_PACKAGE_CHANGED;
51import static android.content.pm.PackageManager.INSTALL_FAILED_REPLACE_COULDNT_DELETE;
52import static android.content.pm.PackageManager.INSTALL_FAILED_SANDBOX_VERSION_DOWNGRADE;
53import static android.content.pm.PackageManager.INSTALL_FAILED_SHARED_USER_INCOMPATIBLE;
54import static android.content.pm.PackageManager.INSTALL_FAILED_TEST_ONLY;
55import static android.content.pm.PackageManager.INSTALL_FAILED_UPDATE_INCOMPATIBLE;
56import static android.content.pm.PackageManager.INSTALL_FAILED_USER_RESTRICTED;
57import static android.content.pm.PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE;
58import static android.content.pm.PackageManager.INSTALL_FORWARD_LOCK;
59import static android.content.pm.PackageManager.INSTALL_INTERNAL;
60import static android.content.pm.PackageManager.INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES;
61import static android.content.pm.PackageManager.INSTALL_PARSE_FAILED_MANIFEST_MALFORMED;
62import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS;
63import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK;
64import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK;
65import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER;
66import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED;
67import static android.content.pm.PackageManager.MATCH_ALL;
68import static android.content.pm.PackageManager.MATCH_ANY_USER;
69import static android.content.pm.PackageManager.MATCH_DEBUG_TRIAGED_MISSING;
70import static android.content.pm.PackageManager.MATCH_DIRECT_BOOT_AWARE;
71import static android.content.pm.PackageManager.MATCH_DIRECT_BOOT_UNAWARE;
72import static android.content.pm.PackageManager.MATCH_DISABLED_COMPONENTS;
73import static android.content.pm.PackageManager.MATCH_FACTORY_ONLY;
74import static android.content.pm.PackageManager.MATCH_KNOWN_PACKAGES;
75import static android.content.pm.PackageManager.MATCH_SYSTEM_ONLY;
76import static android.content.pm.PackageManager.MATCH_UNINSTALLED_PACKAGES;
77import static android.content.pm.PackageManager.MOVE_FAILED_3RD_PARTY_NOT_ALLOWED_ON_INTERNAL;
78import static android.content.pm.PackageManager.MOVE_FAILED_DEVICE_ADMIN;
79import static android.content.pm.PackageManager.MOVE_FAILED_DOESNT_EXIST;
80import static android.content.pm.PackageManager.MOVE_FAILED_INTERNAL_ERROR;
81import static android.content.pm.PackageManager.MOVE_FAILED_OPERATION_PENDING;
82import static android.content.pm.PackageManager.MOVE_FAILED_SYSTEM_PACKAGE;
83import static android.content.pm.PackageManager.PERMISSION_DENIED;
84import static android.content.pm.PackageManager.PERMISSION_GRANTED;
85import static android.content.pm.PackageParser.PARSE_IS_PRIVILEGED;
86import static android.content.pm.PackageParser.isApkFile;
87import static android.os.Trace.TRACE_TAG_PACKAGE_MANAGER;
88import static android.system.OsConstants.O_CREAT;
89import static android.system.OsConstants.O_RDWR;
90import static com.android.internal.app.IntentForwarderActivity.FORWARD_INTENT_TO_MANAGED_PROFILE;
91import static com.android.internal.app.IntentForwarderActivity.FORWARD_INTENT_TO_PARENT;
92import static com.android.internal.content.NativeLibraryHelper.LIB64_DIR_NAME;
93import static com.android.internal.content.NativeLibraryHelper.LIB_DIR_NAME;
94import static com.android.internal.util.ArrayUtils.appendInt;
95import static com.android.server.pm.InstructionSets.getAppDexInstructionSets;
96import static com.android.server.pm.InstructionSets.getDexCodeInstructionSet;
97import static com.android.server.pm.InstructionSets.getDexCodeInstructionSets;
98import static com.android.server.pm.InstructionSets.getPreferredInstructionSet;
99import static com.android.server.pm.InstructionSets.getPrimaryInstructionSet;
100import static com.android.server.pm.PackageManagerServiceCompilerMapping.getCompilerFilterForReason;
101import static com.android.server.pm.PackageManagerServiceCompilerMapping.getDefaultCompilerFilter;
102import static com.android.server.pm.PermissionsState.PERMISSION_OPERATION_FAILURE;
103import static com.android.server.pm.PermissionsState.PERMISSION_OPERATION_SUCCESS;
104import static com.android.server.pm.PermissionsState.PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED;
105import static dalvik.system.DexFile.getNonProfileGuidedCompilerFilter;
106
107import android.Manifest;
108import android.annotation.IntDef;
109import android.annotation.NonNull;
110import android.annotation.Nullable;
111import android.app.ActivityManager;
112import android.app.AppOpsManager;
113import android.app.IActivityManager;
114import android.app.ResourcesManager;
115import android.app.admin.IDevicePolicyManager;
116import android.app.admin.SecurityLog;
117import android.app.backup.IBackupManager;
118import android.content.BroadcastReceiver;
119import android.content.ComponentName;
120import android.content.ContentResolver;
121import android.content.Context;
122import android.content.IIntentReceiver;
123import android.content.Intent;
124import android.content.IntentFilter;
125import android.content.IntentSender;
126import android.content.IntentSender.SendIntentException;
127import android.content.ServiceConnection;
128import android.content.pm.ActivityInfo;
129import android.content.pm.ApplicationInfo;
130import android.content.pm.AppsQueryHelper;
131import android.content.pm.AuxiliaryResolveInfo;
132import android.content.pm.ChangedPackages;
133import android.content.pm.FallbackCategoryProvider;
134import android.content.pm.FeatureInfo;
135import android.content.pm.IDexModuleRegisterCallback;
136import android.content.pm.IOnPermissionsChangeListener;
137import android.content.pm.IPackageDataObserver;
138import android.content.pm.IPackageDeleteObserver;
139import android.content.pm.IPackageDeleteObserver2;
140import android.content.pm.IPackageInstallObserver2;
141import android.content.pm.IPackageInstaller;
142import android.content.pm.IPackageManager;
143import android.content.pm.IPackageMoveObserver;
144import android.content.pm.IPackageStatsObserver;
145import android.content.pm.InstantAppInfo;
146import android.content.pm.InstantAppRequest;
147import android.content.pm.InstantAppResolveInfo;
148import android.content.pm.InstrumentationInfo;
149import android.content.pm.IntentFilterVerificationInfo;
150import android.content.pm.KeySet;
151import android.content.pm.PackageCleanItem;
152import android.content.pm.PackageInfo;
153import android.content.pm.PackageInfoLite;
154import android.content.pm.PackageInstaller;
155import android.content.pm.PackageManager;
156import android.content.pm.PackageManager.LegacyPackageDeleteObserver;
157import android.content.pm.PackageManagerInternal;
158import android.content.pm.PackageParser;
159import android.content.pm.PackageParser.ActivityIntentInfo;
160import android.content.pm.PackageParser.PackageLite;
161import android.content.pm.PackageParser.PackageParserException;
162import android.content.pm.PackageStats;
163import android.content.pm.PackageUserState;
164import android.content.pm.ParceledListSlice;
165import android.content.pm.PermissionGroupInfo;
166import android.content.pm.PermissionInfo;
167import android.content.pm.ProviderInfo;
168import android.content.pm.ResolveInfo;
169import android.content.pm.ServiceInfo;
170import android.content.pm.SharedLibraryInfo;
171import android.content.pm.Signature;
172import android.content.pm.UserInfo;
173import android.content.pm.VerifierDeviceIdentity;
174import android.content.pm.VerifierInfo;
175import android.content.pm.VersionedPackage;
176import android.content.res.Resources;
177import android.database.ContentObserver;
178import android.graphics.Bitmap;
179import android.hardware.display.DisplayManager;
180import android.net.Uri;
181import android.os.Binder;
182import android.os.Build;
183import android.os.Bundle;
184import android.os.Debug;
185import android.os.Environment;
186import android.os.Environment.UserEnvironment;
187import android.os.FileUtils;
188import android.os.Handler;
189import android.os.IBinder;
190import android.os.Looper;
191import android.os.Message;
192import android.os.Parcel;
193import android.os.ParcelFileDescriptor;
194import android.os.PatternMatcher;
195import android.os.Process;
196import android.os.RemoteCallbackList;
197import android.os.RemoteException;
198import android.os.ResultReceiver;
199import android.os.SELinux;
200import android.os.ServiceManager;
201import android.os.ShellCallback;
202import android.os.SystemClock;
203import android.os.SystemProperties;
204import android.os.Trace;
205import android.os.UserHandle;
206import android.os.UserManager;
207import android.os.UserManagerInternal;
208import android.os.storage.IStorageManager;
209import android.os.storage.StorageEventListener;
210import android.os.storage.StorageManager;
211import android.os.storage.StorageManagerInternal;
212import android.os.storage.VolumeInfo;
213import android.os.storage.VolumeRecord;
214import android.provider.Settings.Global;
215import android.provider.Settings.Secure;
216import android.security.KeyStore;
217import android.security.SystemKeyStore;
218import android.service.pm.PackageServiceDumpProto;
219import android.system.ErrnoException;
220import android.system.Os;
221import android.text.TextUtils;
222import android.text.format.DateUtils;
223import android.util.ArrayMap;
224import android.util.ArraySet;
225import android.util.Base64;
226import android.util.BootTimingsTraceLog;
227import android.util.DisplayMetrics;
228import android.util.EventLog;
229import android.util.ExceptionUtils;
230import android.util.Log;
231import android.util.LogPrinter;
232import android.util.MathUtils;
233import android.util.PackageUtils;
234import android.util.Pair;
235import android.util.PrintStreamPrinter;
236import android.util.Slog;
237import android.util.SparseArray;
238import android.util.SparseBooleanArray;
239import android.util.SparseIntArray;
240import android.util.Xml;
241import android.util.jar.StrictJarFile;
242import android.util.proto.ProtoOutputStream;
243import android.view.Display;
244
245import com.android.internal.R;
246import com.android.internal.annotations.GuardedBy;
247import com.android.internal.app.IMediaContainerService;
248import com.android.internal.app.ResolverActivity;
249import com.android.internal.content.NativeLibraryHelper;
250import com.android.internal.content.PackageHelper;
251import com.android.internal.logging.MetricsLogger;
252import com.android.internal.logging.nano.MetricsProto.MetricsEvent;
253import com.android.internal.os.IParcelFileDescriptorFactory;
254import com.android.internal.os.RoSystemProperties;
255import com.android.internal.os.SomeArgs;
256import com.android.internal.os.Zygote;
257import com.android.internal.telephony.CarrierAppUtils;
258import com.android.internal.util.ArrayUtils;
259import com.android.internal.util.ConcurrentUtils;
260import com.android.internal.util.DumpUtils;
261import com.android.internal.util.FastPrintWriter;
262import com.android.internal.util.FastXmlSerializer;
263import com.android.internal.util.IndentingPrintWriter;
264import com.android.internal.util.Preconditions;
265import com.android.internal.util.XmlUtils;
266import com.android.server.AttributeCache;
267import com.android.server.DeviceIdleController;
268import com.android.server.EventLogTags;
269import com.android.server.FgThread;
270import com.android.server.IntentResolver;
271import com.android.server.LocalServices;
272import com.android.server.LockGuard;
273import com.android.server.ServiceThread;
274import com.android.server.SystemConfig;
275import com.android.server.SystemServerInitThreadPool;
276import com.android.server.Watchdog;
277import com.android.server.net.NetworkPolicyManagerInternal;
278import com.android.server.pm.Installer.InstallerException;
279import com.android.server.pm.PermissionsState.PermissionState;
280import com.android.server.pm.Settings.DatabaseVersion;
281import com.android.server.pm.Settings.VersionInfo;
282import com.android.server.pm.dex.DexManager;
283import com.android.server.pm.dex.DexoptOptions;
284import com.android.server.pm.dex.PackageDexUsage;
285import com.android.server.storage.DeviceStorageMonitorInternal;
286
287import dalvik.system.CloseGuard;
288import dalvik.system.DexFile;
289import dalvik.system.VMRuntime;
290
291import libcore.io.IoUtils;
292import libcore.util.EmptyArray;
293
294import org.xmlpull.v1.XmlPullParser;
295import org.xmlpull.v1.XmlPullParserException;
296import org.xmlpull.v1.XmlSerializer;
297
298import java.io.BufferedOutputStream;
299import java.io.BufferedReader;
300import java.io.ByteArrayInputStream;
301import java.io.ByteArrayOutputStream;
302import java.io.File;
303import java.io.FileDescriptor;
304import java.io.FileInputStream;
305import java.io.FileOutputStream;
306import java.io.FileReader;
307import java.io.FilenameFilter;
308import java.io.IOException;
309import java.io.PrintWriter;
310import java.lang.annotation.Retention;
311import java.lang.annotation.RetentionPolicy;
312import java.nio.charset.StandardCharsets;
313import java.security.DigestInputStream;
314import java.security.MessageDigest;
315import java.security.NoSuchAlgorithmException;
316import java.security.PublicKey;
317import java.security.SecureRandom;
318import java.security.cert.Certificate;
319import java.security.cert.CertificateEncodingException;
320import java.security.cert.CertificateException;
321import java.text.SimpleDateFormat;
322import java.util.ArrayList;
323import java.util.Arrays;
324import java.util.Collection;
325import java.util.Collections;
326import java.util.Comparator;
327import java.util.Date;
328import java.util.HashMap;
329import java.util.HashSet;
330import java.util.Iterator;
331import java.util.LinkedHashSet;
332import java.util.List;
333import java.util.Map;
334import java.util.Objects;
335import java.util.Set;
336import java.util.concurrent.CountDownLatch;
337import java.util.concurrent.Future;
338import java.util.concurrent.TimeUnit;
339import java.util.concurrent.atomic.AtomicBoolean;
340import java.util.concurrent.atomic.AtomicInteger;
341
342/**
343 * Keep track of all those APKs everywhere.
344 * <p>
345 * Internally there are two important locks:
346 * <ul>
347 * <li>{@link #mPackages} is used to guard all in-memory parsed package details
348 * and other related state. It is a fine-grained lock that should only be held
349 * momentarily, as it's one of the most contended locks in the system.
350 * <li>{@link #mInstallLock} is used to guard all {@code installd} access, whose
351 * operations typically involve heavy lifting of application data on disk. Since
352 * {@code installd} is single-threaded, and it's operations can often be slow,
353 * this lock should never be acquired while already holding {@link #mPackages}.
354 * Conversely, it's safe to acquire {@link #mPackages} momentarily while already
355 * holding {@link #mInstallLock}.
356 * </ul>
357 * Many internal methods rely on the caller to hold the appropriate locks, and
358 * this contract is expressed through method name suffixes:
359 * <ul>
360 * <li>fooLI(): the caller must hold {@link #mInstallLock}
361 * <li>fooLIF(): the caller must hold {@link #mInstallLock} and the package
362 * being modified must be frozen
363 * <li>fooLPr(): the caller must hold {@link #mPackages} for reading
364 * <li>fooLPw(): the caller must hold {@link #mPackages} for writing
365 * </ul>
366 * <p>
367 * Because this class is very central to the platform's security; please run all
368 * CTS and unit tests whenever making modifications:
369 *
370 * <pre>
371 * $ runtest -c android.content.pm.PackageManagerTests frameworks-core
372 * $ cts-tradefed run commandAndExit cts -m CtsAppSecurityHostTestCases
373 * </pre>
374 */
375public class PackageManagerService extends IPackageManager.Stub
376        implements PackageSender {
377    static final String TAG = "PackageManager";
378    static final boolean DEBUG_SETTINGS = false;
379    static final boolean DEBUG_PREFERRED = false;
380    static final boolean DEBUG_UPGRADE = false;
381    static final boolean DEBUG_DOMAIN_VERIFICATION = false;
382    private static final boolean DEBUG_BACKUP = false;
383    private static final boolean DEBUG_INSTALL = false;
384    private static final boolean DEBUG_REMOVE = false;
385    private static final boolean DEBUG_BROADCASTS = false;
386    private static final boolean DEBUG_SHOW_INFO = false;
387    private static final boolean DEBUG_PACKAGE_INFO = false;
388    private static final boolean DEBUG_INTENT_MATCHING = false;
389    private static final boolean DEBUG_PACKAGE_SCANNING = false;
390    private static final boolean DEBUG_VERIFY = false;
391    private static final boolean DEBUG_FILTERS = false;
392    private static final boolean DEBUG_PERMISSIONS = false;
393    private static final boolean DEBUG_SHARED_LIBRARIES = false;
394
395    // Debug output for dexopting. This is shared between PackageManagerService, OtaDexoptService
396    // and PackageDexOptimizer. All these classes have their own flag to allow switching a single
397    // user, but by default initialize to this.
398    public static final boolean DEBUG_DEXOPT = false;
399
400    private static final boolean DEBUG_ABI_SELECTION = false;
401    private static final boolean DEBUG_EPHEMERAL = Build.IS_DEBUGGABLE;
402    private static final boolean DEBUG_TRIAGED_MISSING = false;
403    private static final boolean DEBUG_APP_DATA = false;
404
405    /** REMOVE. According to Svet, this was only used to reset permissions during development. */
406    static final boolean CLEAR_RUNTIME_PERMISSIONS_ON_UPGRADE = false;
407
408    private static final boolean HIDE_EPHEMERAL_APIS = false;
409
410    private static final boolean ENABLE_FREE_CACHE_V2 =
411            SystemProperties.getBoolean("fw.free_cache_v2", true);
412
413    private static final int RADIO_UID = Process.PHONE_UID;
414    private static final int LOG_UID = Process.LOG_UID;
415    private static final int NFC_UID = Process.NFC_UID;
416    private static final int BLUETOOTH_UID = Process.BLUETOOTH_UID;
417    private static final int SHELL_UID = Process.SHELL_UID;
418
419    // Cap the size of permission trees that 3rd party apps can define
420    private static final int MAX_PERMISSION_TREE_FOOTPRINT = 32768;     // characters of text
421
422    // Suffix used during package installation when copying/moving
423    // package apks to install directory.
424    private static final String INSTALL_PACKAGE_SUFFIX = "-";
425
426    static final int SCAN_NO_DEX = 1<<1;
427    static final int SCAN_FORCE_DEX = 1<<2;
428    static final int SCAN_UPDATE_SIGNATURE = 1<<3;
429    static final int SCAN_NEW_INSTALL = 1<<4;
430    static final int SCAN_UPDATE_TIME = 1<<5;
431    static final int SCAN_BOOTING = 1<<6;
432    static final int SCAN_TRUSTED_OVERLAY = 1<<7;
433    static final int SCAN_DELETE_DATA_ON_FAILURES = 1<<8;
434    static final int SCAN_REPLACING = 1<<9;
435    static final int SCAN_REQUIRE_KNOWN = 1<<10;
436    static final int SCAN_MOVE = 1<<11;
437    static final int SCAN_INITIAL = 1<<12;
438    static final int SCAN_CHECK_ONLY = 1<<13;
439    static final int SCAN_DONT_KILL_APP = 1<<14;
440    static final int SCAN_IGNORE_FROZEN = 1<<15;
441    static final int SCAN_FIRST_BOOT_OR_UPGRADE = 1<<16;
442    static final int SCAN_AS_INSTANT_APP = 1<<17;
443    static final int SCAN_AS_FULL_APP = 1<<18;
444    /** Should not be with the scan flags */
445    static final int FLAGS_REMOVE_CHATTY = 1<<31;
446
447    private static final String STATIC_SHARED_LIB_DELIMITER = "_";
448
449    private static final int[] EMPTY_INT_ARRAY = new int[0];
450
451    private static final int TYPE_UNKNOWN = 0;
452    private static final int TYPE_ACTIVITY = 1;
453    private static final int TYPE_RECEIVER = 2;
454    private static final int TYPE_SERVICE = 3;
455    private static final int TYPE_PROVIDER = 4;
456    @IntDef(prefix = { "TYPE_" }, value = {
457            TYPE_UNKNOWN,
458            TYPE_ACTIVITY,
459            TYPE_RECEIVER,
460            TYPE_SERVICE,
461            TYPE_PROVIDER,
462    })
463    @Retention(RetentionPolicy.SOURCE)
464    public @interface ComponentType {}
465
466    /**
467     * Timeout (in milliseconds) after which the watchdog should declare that
468     * our handler thread is wedged.  The usual default for such things is one
469     * minute but we sometimes do very lengthy I/O operations on this thread,
470     * such as installing multi-gigabyte applications, so ours needs to be longer.
471     */
472    static final long WATCHDOG_TIMEOUT = 1000*60*10;     // ten minutes
473
474    /**
475     * Wall-clock timeout (in milliseconds) after which we *require* that an fstrim
476     * be run on this device.  We use the value in the Settings.Global.MANDATORY_FSTRIM_INTERVAL
477     * settings entry if available, otherwise we use the hardcoded default.  If it's been
478     * more than this long since the last fstrim, we force one during the boot sequence.
479     *
480     * This backstops other fstrim scheduling:  if the device is alive at midnight+idle,
481     * one gets run at the next available charging+idle time.  This final mandatory
482     * no-fstrim check kicks in only of the other scheduling criteria is never met.
483     */
484    private static final long DEFAULT_MANDATORY_FSTRIM_INTERVAL = 3 * DateUtils.DAY_IN_MILLIS;
485
486    /**
487     * Whether verification is enabled by default.
488     */
489    private static final boolean DEFAULT_VERIFY_ENABLE = true;
490
491    /**
492     * The default maximum time to wait for the verification agent to return in
493     * milliseconds.
494     */
495    private static final long DEFAULT_VERIFICATION_TIMEOUT = 10 * 1000;
496
497    /**
498     * The default response for package verification timeout.
499     *
500     * This can be either PackageManager.VERIFICATION_ALLOW or
501     * PackageManager.VERIFICATION_REJECT.
502     */
503    private static final int DEFAULT_VERIFICATION_RESPONSE = PackageManager.VERIFICATION_ALLOW;
504
505    static final String PLATFORM_PACKAGE_NAME = "android";
506
507    static final String DEFAULT_CONTAINER_PACKAGE = "com.android.defcontainer";
508
509    static final ComponentName DEFAULT_CONTAINER_COMPONENT = new ComponentName(
510            DEFAULT_CONTAINER_PACKAGE,
511            "com.android.defcontainer.DefaultContainerService");
512
513    private static final String KILL_APP_REASON_GIDS_CHANGED =
514            "permission grant or revoke changed gids";
515
516    private static final String KILL_APP_REASON_PERMISSIONS_REVOKED =
517            "permissions revoked";
518
519    private static final String PACKAGE_MIME_TYPE = "application/vnd.android.package-archive";
520
521    private static final String PACKAGE_SCHEME = "package";
522
523    private static final String VENDOR_OVERLAY_DIR = "/vendor/overlay";
524
525    /** Permission grant: not grant the permission. */
526    private static final int GRANT_DENIED = 1;
527
528    /** Permission grant: grant the permission as an install permission. */
529    private static final int GRANT_INSTALL = 2;
530
531    /** Permission grant: grant the permission as a runtime one. */
532    private static final int GRANT_RUNTIME = 3;
533
534    /** Permission grant: grant as runtime a permission that was granted as an install time one. */
535    private static final int GRANT_UPGRADE = 4;
536
537    /** Canonical intent used to identify what counts as a "web browser" app */
538    private static final Intent sBrowserIntent;
539    static {
540        sBrowserIntent = new Intent();
541        sBrowserIntent.setAction(Intent.ACTION_VIEW);
542        sBrowserIntent.addCategory(Intent.CATEGORY_BROWSABLE);
543        sBrowserIntent.setData(Uri.parse("http:"));
544    }
545
546    /**
547     * The set of all protected actions [i.e. those actions for which a high priority
548     * intent filter is disallowed].
549     */
550    private static final Set<String> PROTECTED_ACTIONS = new ArraySet<>();
551    static {
552        PROTECTED_ACTIONS.add(Intent.ACTION_SEND);
553        PROTECTED_ACTIONS.add(Intent.ACTION_SENDTO);
554        PROTECTED_ACTIONS.add(Intent.ACTION_SEND_MULTIPLE);
555        PROTECTED_ACTIONS.add(Intent.ACTION_VIEW);
556    }
557
558    // Compilation reasons.
559    public static final int REASON_FIRST_BOOT = 0;
560    public static final int REASON_BOOT = 1;
561    public static final int REASON_INSTALL = 2;
562    public static final int REASON_BACKGROUND_DEXOPT = 3;
563    public static final int REASON_AB_OTA = 4;
564    public static final int REASON_INACTIVE_PACKAGE_DOWNGRADE = 5;
565
566    public static final int REASON_LAST = REASON_INACTIVE_PACKAGE_DOWNGRADE;
567
568    /** All dangerous permission names in the same order as the events in MetricsEvent */
569    private static final List<String> ALL_DANGEROUS_PERMISSIONS = Arrays.asList(
570            Manifest.permission.READ_CALENDAR,
571            Manifest.permission.WRITE_CALENDAR,
572            Manifest.permission.CAMERA,
573            Manifest.permission.READ_CONTACTS,
574            Manifest.permission.WRITE_CONTACTS,
575            Manifest.permission.GET_ACCOUNTS,
576            Manifest.permission.ACCESS_FINE_LOCATION,
577            Manifest.permission.ACCESS_COARSE_LOCATION,
578            Manifest.permission.RECORD_AUDIO,
579            Manifest.permission.READ_PHONE_STATE,
580            Manifest.permission.CALL_PHONE,
581            Manifest.permission.READ_CALL_LOG,
582            Manifest.permission.WRITE_CALL_LOG,
583            Manifest.permission.ADD_VOICEMAIL,
584            Manifest.permission.USE_SIP,
585            Manifest.permission.PROCESS_OUTGOING_CALLS,
586            Manifest.permission.READ_CELL_BROADCASTS,
587            Manifest.permission.BODY_SENSORS,
588            Manifest.permission.SEND_SMS,
589            Manifest.permission.RECEIVE_SMS,
590            Manifest.permission.READ_SMS,
591            Manifest.permission.RECEIVE_WAP_PUSH,
592            Manifest.permission.RECEIVE_MMS,
593            Manifest.permission.READ_EXTERNAL_STORAGE,
594            Manifest.permission.WRITE_EXTERNAL_STORAGE,
595            Manifest.permission.READ_PHONE_NUMBERS,
596            Manifest.permission.ANSWER_PHONE_CALLS);
597
598
599    /**
600     * Version number for the package parser cache. Increment this whenever the format or
601     * extent of cached data changes. See {@code PackageParser#setCacheDir}.
602     */
603    private static final String PACKAGE_PARSER_CACHE_VERSION = "1";
604
605    /**
606     * Whether the package parser cache is enabled.
607     */
608    private static final boolean DEFAULT_PACKAGE_PARSER_CACHE_ENABLED = true;
609
610    final ServiceThread mHandlerThread;
611
612    final PackageHandler mHandler;
613
614    private final ProcessLoggingHandler mProcessLoggingHandler;
615
616    /**
617     * Messages for {@link #mHandler} that need to wait for system ready before
618     * being dispatched.
619     */
620    private ArrayList<Message> mPostSystemReadyMessages;
621
622    final int mSdkVersion = Build.VERSION.SDK_INT;
623
624    final Context mContext;
625    final boolean mFactoryTest;
626    final boolean mOnlyCore;
627    final DisplayMetrics mMetrics;
628    final int mDefParseFlags;
629    final String[] mSeparateProcesses;
630    final boolean mIsUpgrade;
631    final boolean mIsPreNUpgrade;
632    final boolean mIsPreNMR1Upgrade;
633
634    // Have we told the Activity Manager to whitelist the default container service by uid yet?
635    @GuardedBy("mPackages")
636    boolean mDefaultContainerWhitelisted = false;
637
638    @GuardedBy("mPackages")
639    private boolean mDexOptDialogShown;
640
641    /** The location for ASEC container files on internal storage. */
642    final String mAsecInternalPath;
643
644    // Used for privilege escalation. MUST NOT BE CALLED WITH mPackages
645    // LOCK HELD.  Can be called with mInstallLock held.
646    @GuardedBy("mInstallLock")
647    final Installer mInstaller;
648
649    /** Directory where installed third-party apps stored */
650    final File mAppInstallDir;
651
652    /**
653     * Directory to which applications installed internally have their
654     * 32 bit native libraries copied.
655     */
656    private File mAppLib32InstallDir;
657
658    // Directory containing the private parts (e.g. code and non-resource assets) of forward-locked
659    // apps.
660    final File mDrmAppPrivateInstallDir;
661
662    // ----------------------------------------------------------------
663
664    // Lock for state used when installing and doing other long running
665    // operations.  Methods that must be called with this lock held have
666    // the suffix "LI".
667    final Object mInstallLock = new Object();
668
669    // ----------------------------------------------------------------
670
671    // Keys are String (package name), values are Package.  This also serves
672    // as the lock for the global state.  Methods that must be called with
673    // this lock held have the prefix "LP".
674    @GuardedBy("mPackages")
675    final ArrayMap<String, PackageParser.Package> mPackages =
676            new ArrayMap<String, PackageParser.Package>();
677
678    final ArrayMap<String, Set<String>> mKnownCodebase =
679            new ArrayMap<String, Set<String>>();
680
681    // Keys are isolated uids and values are the uid of the application
682    // that created the isolated proccess.
683    @GuardedBy("mPackages")
684    final SparseIntArray mIsolatedOwners = new SparseIntArray();
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        PackageSetting ps = (PackageSetting) pkg.mExtras;
2191        if (ps == null) {
2192            return;
2193        }
2194
2195        PermissionsState permissionsState = ps.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>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        packageInfo.packageName = packageInfo.applicationInfo.packageName =
3587                resolveExternalPackageNameLPr(p);
3588
3589        return packageInfo;
3590    }
3591
3592    @Override
3593    public void checkPackageStartable(String packageName, int userId) {
3594        final int callingUid = Binder.getCallingUid();
3595        if (getInstantAppPackageName(callingUid) != null) {
3596            throw new SecurityException("Instant applications don't have access to this method");
3597        }
3598        final boolean userKeyUnlocked = StorageManager.isUserKeyUnlocked(userId);
3599        synchronized (mPackages) {
3600            final PackageSetting ps = mSettings.mPackages.get(packageName);
3601            if (ps == null || filterAppAccessLPr(ps, callingUid, userId)) {
3602                throw new SecurityException("Package " + packageName + " was not found!");
3603            }
3604
3605            if (!ps.getInstalled(userId)) {
3606                throw new SecurityException(
3607                        "Package " + packageName + " was not installed for user " + userId + "!");
3608            }
3609
3610            if (mSafeMode && !ps.isSystem()) {
3611                throw new SecurityException("Package " + packageName + " not a system app!");
3612            }
3613
3614            if (mFrozenPackages.contains(packageName)) {
3615                throw new SecurityException("Package " + packageName + " is currently frozen!");
3616            }
3617
3618            if (!userKeyUnlocked && !(ps.pkg.applicationInfo.isDirectBootAware()
3619                    || ps.pkg.applicationInfo.isPartiallyDirectBootAware())) {
3620                throw new SecurityException("Package " + packageName + " is not encryption aware!");
3621            }
3622        }
3623    }
3624
3625    @Override
3626    public boolean isPackageAvailable(String packageName, int userId) {
3627        if (!sUserManager.exists(userId)) return false;
3628        final int callingUid = Binder.getCallingUid();
3629        enforceCrossUserPermission(callingUid, userId,
3630                false /*requireFullPermission*/, false /*checkShell*/, "is package available");
3631        synchronized (mPackages) {
3632            PackageParser.Package p = mPackages.get(packageName);
3633            if (p != null) {
3634                final PackageSetting ps = (PackageSetting) p.mExtras;
3635                if (filterAppAccessLPr(ps, callingUid, userId)) {
3636                    return false;
3637                }
3638                if (ps != null) {
3639                    final PackageUserState state = ps.readUserState(userId);
3640                    if (state != null) {
3641                        return PackageParser.isAvailable(state);
3642                    }
3643                }
3644            }
3645        }
3646        return false;
3647    }
3648
3649    @Override
3650    public PackageInfo getPackageInfo(String packageName, int flags, int userId) {
3651        return getPackageInfoInternal(packageName, PackageManager.VERSION_CODE_HIGHEST,
3652                flags, Binder.getCallingUid(), userId);
3653    }
3654
3655    @Override
3656    public PackageInfo getPackageInfoVersioned(VersionedPackage versionedPackage,
3657            int flags, int userId) {
3658        return getPackageInfoInternal(versionedPackage.getPackageName(),
3659                versionedPackage.getVersionCode(), flags, Binder.getCallingUid(), userId);
3660    }
3661
3662    /**
3663     * Important: The provided filterCallingUid is used exclusively to filter out packages
3664     * that can be seen based on user state. It's typically the original caller uid prior
3665     * to clearing. Because it can only be provided by trusted code, it's value can be
3666     * trusted and will be used as-is; unlike userId which will be validated by this method.
3667     */
3668    private PackageInfo getPackageInfoInternal(String packageName, int versionCode,
3669            int flags, int filterCallingUid, int userId) {
3670        if (!sUserManager.exists(userId)) return null;
3671        flags = updateFlagsForPackage(flags, userId, packageName);
3672        enforceCrossUserPermission(Binder.getCallingUid(), userId,
3673                false /* requireFullPermission */, false /* checkShell */, "get package info");
3674
3675        // reader
3676        synchronized (mPackages) {
3677            // Normalize package name to handle renamed packages and static libs
3678            packageName = resolveInternalPackageNameLPr(packageName, versionCode);
3679
3680            final boolean matchFactoryOnly = (flags & MATCH_FACTORY_ONLY) != 0;
3681            if (matchFactoryOnly) {
3682                final PackageSetting ps = mSettings.getDisabledSystemPkgLPr(packageName);
3683                if (ps != null) {
3684                    if (filterSharedLibPackageLPr(ps, filterCallingUid, userId, flags)) {
3685                        return null;
3686                    }
3687                    if (filterAppAccessLPr(ps, filterCallingUid, userId)) {
3688                        return null;
3689                    }
3690                    return generatePackageInfo(ps, flags, userId);
3691                }
3692            }
3693
3694            PackageParser.Package p = mPackages.get(packageName);
3695            if (matchFactoryOnly && p != null && !isSystemApp(p)) {
3696                return null;
3697            }
3698            if (DEBUG_PACKAGE_INFO)
3699                Log.v(TAG, "getPackageInfo " + packageName + ": " + p);
3700            if (p != null) {
3701                final PackageSetting ps = (PackageSetting) p.mExtras;
3702                if (filterSharedLibPackageLPr(ps, filterCallingUid, userId, flags)) {
3703                    return null;
3704                }
3705                if (ps != null && filterAppAccessLPr(ps, filterCallingUid, userId)) {
3706                    return null;
3707                }
3708                return generatePackageInfo((PackageSetting)p.mExtras, flags, userId);
3709            }
3710            if (!matchFactoryOnly && (flags & MATCH_KNOWN_PACKAGES) != 0) {
3711                final PackageSetting ps = mSettings.mPackages.get(packageName);
3712                if (ps == null) return null;
3713                if (filterSharedLibPackageLPr(ps, filterCallingUid, userId, flags)) {
3714                    return null;
3715                }
3716                if (filterAppAccessLPr(ps, filterCallingUid, userId)) {
3717                    return null;
3718                }
3719                return generatePackageInfo(ps, flags, userId);
3720            }
3721        }
3722        return null;
3723    }
3724
3725    private boolean isComponentVisibleToInstantApp(@Nullable ComponentName component) {
3726        if (isComponentVisibleToInstantApp(component, TYPE_ACTIVITY)) {
3727            return true;
3728        }
3729        if (isComponentVisibleToInstantApp(component, TYPE_SERVICE)) {
3730            return true;
3731        }
3732        if (isComponentVisibleToInstantApp(component, TYPE_PROVIDER)) {
3733            return true;
3734        }
3735        return false;
3736    }
3737
3738    private boolean isComponentVisibleToInstantApp(
3739            @Nullable ComponentName component, @ComponentType int type) {
3740        if (type == TYPE_ACTIVITY) {
3741            final PackageParser.Activity activity = mActivities.mActivities.get(component);
3742            return activity != null
3743                    ? (activity.info.flags & ActivityInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0
3744                    : false;
3745        } else if (type == TYPE_RECEIVER) {
3746            final PackageParser.Activity activity = mReceivers.mActivities.get(component);
3747            return activity != null
3748                    ? (activity.info.flags & ActivityInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0
3749                    : false;
3750        } else if (type == TYPE_SERVICE) {
3751            final PackageParser.Service service = mServices.mServices.get(component);
3752            return service != null
3753                    ? (service.info.flags & ServiceInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0
3754                    : false;
3755        } else if (type == TYPE_PROVIDER) {
3756            final PackageParser.Provider provider = mProviders.mProviders.get(component);
3757            return provider != null
3758                    ? (provider.info.flags & ProviderInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0
3759                    : false;
3760        } else if (type == TYPE_UNKNOWN) {
3761            return isComponentVisibleToInstantApp(component);
3762        }
3763        return false;
3764    }
3765
3766    /**
3767     * Returns whether or not access to the application should be filtered.
3768     * <p>
3769     * Access may be limited based upon whether the calling or target applications
3770     * are instant applications.
3771     *
3772     * @see #canAccessInstantApps(int)
3773     */
3774    private boolean filterAppAccessLPr(@Nullable PackageSetting ps, int callingUid,
3775            @Nullable ComponentName component, @ComponentType int componentType, int userId) {
3776        // if we're in an isolated process, get the real calling UID
3777        if (Process.isIsolated(callingUid)) {
3778            callingUid = mIsolatedOwners.get(callingUid);
3779        }
3780        final String instantAppPkgName = getInstantAppPackageName(callingUid);
3781        final boolean callerIsInstantApp = instantAppPkgName != null;
3782        if (ps == null) {
3783            if (callerIsInstantApp) {
3784                // pretend the application exists, but, needs to be filtered
3785                return true;
3786            }
3787            return false;
3788        }
3789        // if the target and caller are the same application, don't filter
3790        if (isCallerSameApp(ps.name, callingUid)) {
3791            return false;
3792        }
3793        if (callerIsInstantApp) {
3794            // request for a specific component; if it hasn't been explicitly exposed, filter
3795            if (component != null) {
3796                return !isComponentVisibleToInstantApp(component, componentType);
3797            }
3798            // request for application; if no components have been explicitly exposed, filter
3799            return ps.getInstantApp(userId) || !ps.pkg.visibleToInstantApps;
3800        }
3801        if (ps.getInstantApp(userId)) {
3802            // caller can see all components of all instant applications, don't filter
3803            if (canViewInstantApps(callingUid, userId)) {
3804                return false;
3805            }
3806            // request for a specific instant application component, filter
3807            if (component != null) {
3808                return true;
3809            }
3810            // request for an instant application; if the caller hasn't been granted access, filter
3811            return !mInstantAppRegistry.isInstantAccessGranted(
3812                    userId, UserHandle.getAppId(callingUid), ps.appId);
3813        }
3814        return false;
3815    }
3816
3817    /**
3818     * @see #filterAppAccessLPr(PackageSetting, int, ComponentName, boolean, int)
3819     */
3820    private boolean filterAppAccessLPr(@Nullable PackageSetting ps, int callingUid, int userId) {
3821        return filterAppAccessLPr(ps, callingUid, null, TYPE_UNKNOWN, userId);
3822    }
3823
3824    private boolean filterSharedLibPackageLPr(@Nullable PackageSetting ps, int uid, int userId,
3825            int flags) {
3826        // Callers can access only the libs they depend on, otherwise they need to explicitly
3827        // ask for the shared libraries given the caller is allowed to access all static libs.
3828        if ((flags & PackageManager.MATCH_STATIC_SHARED_LIBRARIES) != 0) {
3829            // System/shell/root get to see all static libs
3830            final int appId = UserHandle.getAppId(uid);
3831            if (appId == Process.SYSTEM_UID || appId == Process.SHELL_UID
3832                    || appId == Process.ROOT_UID) {
3833                return false;
3834            }
3835        }
3836
3837        // No package means no static lib as it is always on internal storage
3838        if (ps == null || ps.pkg == null || !ps.pkg.applicationInfo.isStaticSharedLibrary()) {
3839            return false;
3840        }
3841
3842        final SharedLibraryEntry libEntry = getSharedLibraryEntryLPr(ps.pkg.staticSharedLibName,
3843                ps.pkg.staticSharedLibVersion);
3844        if (libEntry == null) {
3845            return false;
3846        }
3847
3848        final int resolvedUid = UserHandle.getUid(userId, UserHandle.getAppId(uid));
3849        final String[] uidPackageNames = getPackagesForUid(resolvedUid);
3850        if (uidPackageNames == null) {
3851            return true;
3852        }
3853
3854        for (String uidPackageName : uidPackageNames) {
3855            if (ps.name.equals(uidPackageName)) {
3856                return false;
3857            }
3858            PackageSetting uidPs = mSettings.getPackageLPr(uidPackageName);
3859            if (uidPs != null) {
3860                final int index = ArrayUtils.indexOf(uidPs.usesStaticLibraries,
3861                        libEntry.info.getName());
3862                if (index < 0) {
3863                    continue;
3864                }
3865                if (uidPs.pkg.usesStaticLibrariesVersions[index] == libEntry.info.getVersion()) {
3866                    return false;
3867                }
3868            }
3869        }
3870        return true;
3871    }
3872
3873    @Override
3874    public String[] currentToCanonicalPackageNames(String[] names) {
3875        final int callingUid = Binder.getCallingUid();
3876        if (getInstantAppPackageName(callingUid) != null) {
3877            return names;
3878        }
3879        final String[] out = new String[names.length];
3880        // reader
3881        synchronized (mPackages) {
3882            final int callingUserId = UserHandle.getUserId(callingUid);
3883            final boolean canViewInstantApps = canViewInstantApps(callingUid, callingUserId);
3884            for (int i=names.length-1; i>=0; i--) {
3885                final PackageSetting ps = mSettings.mPackages.get(names[i]);
3886                boolean translateName = false;
3887                if (ps != null && ps.realName != null) {
3888                    final boolean targetIsInstantApp = ps.getInstantApp(callingUserId);
3889                    translateName = !targetIsInstantApp
3890                            || canViewInstantApps
3891                            || mInstantAppRegistry.isInstantAccessGranted(callingUserId,
3892                                    UserHandle.getAppId(callingUid), ps.appId);
3893                }
3894                out[i] = translateName ? ps.realName : names[i];
3895            }
3896        }
3897        return out;
3898    }
3899
3900    @Override
3901    public String[] canonicalToCurrentPackageNames(String[] names) {
3902        final int callingUid = Binder.getCallingUid();
3903        if (getInstantAppPackageName(callingUid) != null) {
3904            return names;
3905        }
3906        final String[] out = new String[names.length];
3907        // reader
3908        synchronized (mPackages) {
3909            final int callingUserId = UserHandle.getUserId(callingUid);
3910            final boolean canViewInstantApps = canViewInstantApps(callingUid, callingUserId);
3911            for (int i=names.length-1; i>=0; i--) {
3912                final String cur = mSettings.getRenamedPackageLPr(names[i]);
3913                boolean translateName = false;
3914                if (cur != null) {
3915                    final PackageSetting ps = mSettings.mPackages.get(names[i]);
3916                    final boolean targetIsInstantApp =
3917                            ps != null && ps.getInstantApp(callingUserId);
3918                    translateName = !targetIsInstantApp
3919                            || canViewInstantApps
3920                            || mInstantAppRegistry.isInstantAccessGranted(callingUserId,
3921                                    UserHandle.getAppId(callingUid), ps.appId);
3922                }
3923                out[i] = translateName ? cur : names[i];
3924            }
3925        }
3926        return out;
3927    }
3928
3929    @Override
3930    public int getPackageUid(String packageName, int flags, int userId) {
3931        if (!sUserManager.exists(userId)) return -1;
3932        final int callingUid = Binder.getCallingUid();
3933        flags = updateFlagsForPackage(flags, userId, packageName);
3934        enforceCrossUserPermission(callingUid, userId,
3935                false /*requireFullPermission*/, false /*checkShell*/, "getPackageUid");
3936
3937        // reader
3938        synchronized (mPackages) {
3939            final PackageParser.Package p = mPackages.get(packageName);
3940            if (p != null && p.isMatch(flags)) {
3941                PackageSetting ps = (PackageSetting) p.mExtras;
3942                if (filterAppAccessLPr(ps, callingUid, userId)) {
3943                    return -1;
3944                }
3945                return UserHandle.getUid(userId, p.applicationInfo.uid);
3946            }
3947            if ((flags & MATCH_KNOWN_PACKAGES) != 0) {
3948                final PackageSetting ps = mSettings.mPackages.get(packageName);
3949                if (ps != null && ps.isMatch(flags)
3950                        && !filterAppAccessLPr(ps, callingUid, userId)) {
3951                    return UserHandle.getUid(userId, ps.appId);
3952                }
3953            }
3954        }
3955
3956        return -1;
3957    }
3958
3959    @Override
3960    public int[] getPackageGids(String packageName, int flags, int userId) {
3961        if (!sUserManager.exists(userId)) return null;
3962        final int callingUid = Binder.getCallingUid();
3963        flags = updateFlagsForPackage(flags, userId, packageName);
3964        enforceCrossUserPermission(callingUid, userId,
3965                false /*requireFullPermission*/, false /*checkShell*/, "getPackageGids");
3966
3967        // reader
3968        synchronized (mPackages) {
3969            final PackageParser.Package p = mPackages.get(packageName);
3970            if (p != null && p.isMatch(flags)) {
3971                PackageSetting ps = (PackageSetting) p.mExtras;
3972                if (filterAppAccessLPr(ps, callingUid, userId)) {
3973                    return null;
3974                }
3975                // TODO: Shouldn't this be checking for package installed state for userId and
3976                // return null?
3977                return ps.getPermissionsState().computeGids(userId);
3978            }
3979            if ((flags & MATCH_KNOWN_PACKAGES) != 0) {
3980                final PackageSetting ps = mSettings.mPackages.get(packageName);
3981                if (ps != null && ps.isMatch(flags)
3982                        && !filterAppAccessLPr(ps, callingUid, userId)) {
3983                    return ps.getPermissionsState().computeGids(userId);
3984                }
3985            }
3986        }
3987
3988        return null;
3989    }
3990
3991    static PermissionInfo generatePermissionInfo(BasePermission bp, int flags) {
3992        if (bp.perm != null) {
3993            return PackageParser.generatePermissionInfo(bp.perm, flags);
3994        }
3995        PermissionInfo pi = new PermissionInfo();
3996        pi.name = bp.name;
3997        pi.packageName = bp.sourcePackage;
3998        pi.nonLocalizedLabel = bp.name;
3999        pi.protectionLevel = bp.protectionLevel;
4000        return pi;
4001    }
4002
4003    @Override
4004    public PermissionInfo getPermissionInfo(String name, String packageName, int flags) {
4005        final int callingUid = Binder.getCallingUid();
4006        if (getInstantAppPackageName(callingUid) != null) {
4007            return null;
4008        }
4009        // reader
4010        synchronized (mPackages) {
4011            final BasePermission p = mSettings.mPermissions.get(name);
4012            if (p == null) {
4013                return null;
4014            }
4015            // If the caller is an app that targets pre 26 SDK drop protection flags.
4016            final PermissionInfo permissionInfo = generatePermissionInfo(p, flags);
4017            if (permissionInfo != null) {
4018                permissionInfo.protectionLevel = adjustPermissionProtectionFlagsLPr(
4019                        permissionInfo.protectionLevel, packageName, callingUid);
4020            }
4021            return permissionInfo;
4022        }
4023    }
4024
4025    private int adjustPermissionProtectionFlagsLPr(int protectionLevel,
4026            String packageName, int uid) {
4027        // Signature permission flags area always reported
4028        final int protectionLevelMasked = protectionLevel
4029                & (PermissionInfo.PROTECTION_NORMAL
4030                | PermissionInfo.PROTECTION_DANGEROUS
4031                | PermissionInfo.PROTECTION_SIGNATURE);
4032        if (protectionLevelMasked == PermissionInfo.PROTECTION_SIGNATURE) {
4033            return protectionLevel;
4034        }
4035
4036        // System sees all flags.
4037        final int appId = UserHandle.getAppId(uid);
4038        if (appId == Process.SYSTEM_UID || appId == Process.ROOT_UID
4039                || appId == Process.SHELL_UID) {
4040            return protectionLevel;
4041        }
4042
4043        // Normalize package name to handle renamed packages and static libs
4044        packageName = resolveInternalPackageNameLPr(packageName,
4045                PackageManager.VERSION_CODE_HIGHEST);
4046
4047        // Apps that target O see flags for all protection levels.
4048        final PackageSetting ps = mSettings.mPackages.get(packageName);
4049        if (ps == null) {
4050            return protectionLevel;
4051        }
4052        if (ps.appId != appId) {
4053            return protectionLevel;
4054        }
4055
4056        final PackageParser.Package pkg = mPackages.get(packageName);
4057        if (pkg == null) {
4058            return protectionLevel;
4059        }
4060        if (pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.O) {
4061            return protectionLevelMasked;
4062        }
4063
4064        return protectionLevel;
4065    }
4066
4067    @Override
4068    public @Nullable ParceledListSlice<PermissionInfo> queryPermissionsByGroup(String group,
4069            int flags) {
4070        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
4071            return null;
4072        }
4073        // reader
4074        synchronized (mPackages) {
4075            if (group != null && !mPermissionGroups.containsKey(group)) {
4076                // This is thrown as NameNotFoundException
4077                return null;
4078            }
4079
4080            ArrayList<PermissionInfo> out = new ArrayList<PermissionInfo>(10);
4081            for (BasePermission p : mSettings.mPermissions.values()) {
4082                if (group == null) {
4083                    if (p.perm == null || p.perm.info.group == null) {
4084                        out.add(generatePermissionInfo(p, flags));
4085                    }
4086                } else {
4087                    if (p.perm != null && group.equals(p.perm.info.group)) {
4088                        out.add(PackageParser.generatePermissionInfo(p.perm, flags));
4089                    }
4090                }
4091            }
4092            return new ParceledListSlice<>(out);
4093        }
4094    }
4095
4096    @Override
4097    public PermissionGroupInfo getPermissionGroupInfo(String name, int flags) {
4098        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
4099            return null;
4100        }
4101        // reader
4102        synchronized (mPackages) {
4103            return PackageParser.generatePermissionGroupInfo(
4104                    mPermissionGroups.get(name), flags);
4105        }
4106    }
4107
4108    @Override
4109    public @NonNull ParceledListSlice<PermissionGroupInfo> getAllPermissionGroups(int flags) {
4110        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
4111            return ParceledListSlice.emptyList();
4112        }
4113        // reader
4114        synchronized (mPackages) {
4115            final int N = mPermissionGroups.size();
4116            ArrayList<PermissionGroupInfo> out
4117                    = new ArrayList<PermissionGroupInfo>(N);
4118            for (PackageParser.PermissionGroup pg : mPermissionGroups.values()) {
4119                out.add(PackageParser.generatePermissionGroupInfo(pg, flags));
4120            }
4121            return new ParceledListSlice<>(out);
4122        }
4123    }
4124
4125    private ApplicationInfo generateApplicationInfoFromSettingsLPw(String packageName, int flags,
4126            int filterCallingUid, int userId) {
4127        if (!sUserManager.exists(userId)) return null;
4128        PackageSetting ps = mSettings.mPackages.get(packageName);
4129        if (ps != null) {
4130            if (filterSharedLibPackageLPr(ps, filterCallingUid, userId, flags)) {
4131                return null;
4132            }
4133            if (filterAppAccessLPr(ps, filterCallingUid, userId)) {
4134                return null;
4135            }
4136            if (ps.pkg == null) {
4137                final PackageInfo pInfo = generatePackageInfo(ps, flags, userId);
4138                if (pInfo != null) {
4139                    return pInfo.applicationInfo;
4140                }
4141                return null;
4142            }
4143            ApplicationInfo ai = PackageParser.generateApplicationInfo(ps.pkg, flags,
4144                    ps.readUserState(userId), userId);
4145            if (ai != null) {
4146                ai.packageName = resolveExternalPackageNameLPr(ps.pkg);
4147            }
4148            return ai;
4149        }
4150        return null;
4151    }
4152
4153    @Override
4154    public ApplicationInfo getApplicationInfo(String packageName, int flags, int userId) {
4155        return getApplicationInfoInternal(packageName, flags, Binder.getCallingUid(), userId);
4156    }
4157
4158    /**
4159     * Important: The provided filterCallingUid is used exclusively to filter out applications
4160     * that can be seen based on user state. It's typically the original caller uid prior
4161     * to clearing. Because it can only be provided by trusted code, it's value can be
4162     * trusted and will be used as-is; unlike userId which will be validated by this method.
4163     */
4164    private ApplicationInfo getApplicationInfoInternal(String packageName, int flags,
4165            int filterCallingUid, int userId) {
4166        if (!sUserManager.exists(userId)) return null;
4167        flags = updateFlagsForApplication(flags, userId, packageName);
4168        enforceCrossUserPermission(Binder.getCallingUid(), userId,
4169                false /* requireFullPermission */, false /* checkShell */, "get application info");
4170
4171        // writer
4172        synchronized (mPackages) {
4173            // Normalize package name to handle renamed packages and static libs
4174            packageName = resolveInternalPackageNameLPr(packageName,
4175                    PackageManager.VERSION_CODE_HIGHEST);
4176
4177            PackageParser.Package p = mPackages.get(packageName);
4178            if (DEBUG_PACKAGE_INFO) Log.v(
4179                    TAG, "getApplicationInfo " + packageName
4180                    + ": " + p);
4181            if (p != null) {
4182                PackageSetting ps = mSettings.mPackages.get(packageName);
4183                if (ps == null) return null;
4184                if (filterSharedLibPackageLPr(ps, filterCallingUid, userId, flags)) {
4185                    return null;
4186                }
4187                if (filterAppAccessLPr(ps, filterCallingUid, userId)) {
4188                    return null;
4189                }
4190                // Note: isEnabledLP() does not apply here - always return info
4191                ApplicationInfo ai = PackageParser.generateApplicationInfo(
4192                        p, flags, ps.readUserState(userId), userId);
4193                if (ai != null) {
4194                    ai.packageName = resolveExternalPackageNameLPr(p);
4195                }
4196                return ai;
4197            }
4198            if ("android".equals(packageName)||"system".equals(packageName)) {
4199                return mAndroidApplication;
4200            }
4201            if ((flags & MATCH_KNOWN_PACKAGES) != 0) {
4202                // Already generates the external package name
4203                return generateApplicationInfoFromSettingsLPw(packageName,
4204                        flags, filterCallingUid, userId);
4205            }
4206        }
4207        return null;
4208    }
4209
4210    private String normalizePackageNameLPr(String packageName) {
4211        String normalizedPackageName = mSettings.getRenamedPackageLPr(packageName);
4212        return normalizedPackageName != null ? normalizedPackageName : packageName;
4213    }
4214
4215    @Override
4216    public void deletePreloadsFileCache() {
4217        if (!UserHandle.isSameApp(Binder.getCallingUid(), Process.SYSTEM_UID)) {
4218            throw new SecurityException("Only system or settings may call deletePreloadsFileCache");
4219        }
4220        File dir = Environment.getDataPreloadsFileCacheDirectory();
4221        Slog.i(TAG, "Deleting preloaded file cache " + dir);
4222        FileUtils.deleteContents(dir);
4223    }
4224
4225    @Override
4226    public void freeStorageAndNotify(final String volumeUuid, final long freeStorageSize,
4227            final int storageFlags, final IPackageDataObserver observer) {
4228        mContext.enforceCallingOrSelfPermission(
4229                android.Manifest.permission.CLEAR_APP_CACHE, null);
4230        mHandler.post(() -> {
4231            boolean success = false;
4232            try {
4233                freeStorage(volumeUuid, freeStorageSize, storageFlags);
4234                success = true;
4235            } catch (IOException e) {
4236                Slog.w(TAG, e);
4237            }
4238            if (observer != null) {
4239                try {
4240                    observer.onRemoveCompleted(null, success);
4241                } catch (RemoteException e) {
4242                    Slog.w(TAG, e);
4243                }
4244            }
4245        });
4246    }
4247
4248    @Override
4249    public void freeStorage(final String volumeUuid, final long freeStorageSize,
4250            final int storageFlags, final IntentSender pi) {
4251        mContext.enforceCallingOrSelfPermission(
4252                android.Manifest.permission.CLEAR_APP_CACHE, TAG);
4253        mHandler.post(() -> {
4254            boolean success = false;
4255            try {
4256                freeStorage(volumeUuid, freeStorageSize, storageFlags);
4257                success = true;
4258            } catch (IOException e) {
4259                Slog.w(TAG, e);
4260            }
4261            if (pi != null) {
4262                try {
4263                    pi.sendIntent(null, success ? 1 : 0, null, null, null);
4264                } catch (SendIntentException e) {
4265                    Slog.w(TAG, e);
4266                }
4267            }
4268        });
4269    }
4270
4271    /**
4272     * Blocking call to clear various types of cached data across the system
4273     * until the requested bytes are available.
4274     */
4275    public void freeStorage(String volumeUuid, long bytes, int storageFlags) throws IOException {
4276        final StorageManager storage = mContext.getSystemService(StorageManager.class);
4277        final File file = storage.findPathForUuid(volumeUuid);
4278        if (file.getUsableSpace() >= bytes) return;
4279
4280        if (ENABLE_FREE_CACHE_V2) {
4281            final boolean internalVolume = Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL,
4282                    volumeUuid);
4283            final boolean aggressive = (storageFlags
4284                    & StorageManager.FLAG_ALLOCATE_AGGRESSIVE) != 0;
4285            final long reservedBytes = storage.getStorageCacheBytes(file, storageFlags);
4286
4287            // 1. Pre-flight to determine if we have any chance to succeed
4288            // 2. Consider preloaded data (after 1w honeymoon, unless aggressive)
4289            if (internalVolume && (aggressive || SystemProperties
4290                    .getBoolean("persist.sys.preloads.file_cache_expired", false))) {
4291                deletePreloadsFileCache();
4292                if (file.getUsableSpace() >= bytes) return;
4293            }
4294
4295            // 3. Consider parsed APK data (aggressive only)
4296            if (internalVolume && aggressive) {
4297                FileUtils.deleteContents(mCacheDir);
4298                if (file.getUsableSpace() >= bytes) return;
4299            }
4300
4301            // 4. Consider cached app data (above quotas)
4302            try {
4303                mInstaller.freeCache(volumeUuid, bytes, reservedBytes,
4304                        Installer.FLAG_FREE_CACHE_V2);
4305            } catch (InstallerException ignored) {
4306            }
4307            if (file.getUsableSpace() >= bytes) return;
4308
4309            // 5. Consider shared libraries with refcount=0 and age>min cache period
4310            if (internalVolume && pruneUnusedStaticSharedLibraries(bytes,
4311                    android.provider.Settings.Global.getLong(mContext.getContentResolver(),
4312                            Global.UNUSED_STATIC_SHARED_LIB_MIN_CACHE_PERIOD,
4313                            DEFAULT_UNUSED_STATIC_SHARED_LIB_MIN_CACHE_PERIOD))) {
4314                return;
4315            }
4316
4317            // 6. Consider dexopt output (aggressive only)
4318            // TODO: Implement
4319
4320            // 7. Consider installed instant apps unused longer than min cache period
4321            if (internalVolume && mInstantAppRegistry.pruneInstalledInstantApps(bytes,
4322                    android.provider.Settings.Global.getLong(mContext.getContentResolver(),
4323                            Global.INSTALLED_INSTANT_APP_MIN_CACHE_PERIOD,
4324                            InstantAppRegistry.DEFAULT_INSTALLED_INSTANT_APP_MIN_CACHE_PERIOD))) {
4325                return;
4326            }
4327
4328            // 8. Consider cached app data (below quotas)
4329            try {
4330                mInstaller.freeCache(volumeUuid, bytes, reservedBytes,
4331                        Installer.FLAG_FREE_CACHE_V2 | Installer.FLAG_FREE_CACHE_V2_DEFY_QUOTA);
4332            } catch (InstallerException ignored) {
4333            }
4334            if (file.getUsableSpace() >= bytes) return;
4335
4336            // 9. Consider DropBox entries
4337            // TODO: Implement
4338
4339            // 10. Consider instant meta-data (uninstalled apps) older that min cache period
4340            if (internalVolume && mInstantAppRegistry.pruneUninstalledInstantApps(bytes,
4341                    android.provider.Settings.Global.getLong(mContext.getContentResolver(),
4342                            Global.UNINSTALLED_INSTANT_APP_MIN_CACHE_PERIOD,
4343                            InstantAppRegistry.DEFAULT_UNINSTALLED_INSTANT_APP_MIN_CACHE_PERIOD))) {
4344                return;
4345            }
4346        } else {
4347            try {
4348                mInstaller.freeCache(volumeUuid, bytes, 0, 0);
4349            } catch (InstallerException ignored) {
4350            }
4351            if (file.getUsableSpace() >= bytes) return;
4352        }
4353
4354        throw new IOException("Failed to free " + bytes + " on storage device at " + file);
4355    }
4356
4357    private boolean pruneUnusedStaticSharedLibraries(long neededSpace, long maxCachePeriod)
4358            throws IOException {
4359        final StorageManager storage = mContext.getSystemService(StorageManager.class);
4360        final File volume = storage.findPathForUuid(StorageManager.UUID_PRIVATE_INTERNAL);
4361
4362        List<VersionedPackage> packagesToDelete = null;
4363        final long now = System.currentTimeMillis();
4364
4365        synchronized (mPackages) {
4366            final int[] allUsers = sUserManager.getUserIds();
4367            final int libCount = mSharedLibraries.size();
4368            for (int i = 0; i < libCount; i++) {
4369                final SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.valueAt(i);
4370                if (versionedLib == null) {
4371                    continue;
4372                }
4373                final int versionCount = versionedLib.size();
4374                for (int j = 0; j < versionCount; j++) {
4375                    SharedLibraryInfo libInfo = versionedLib.valueAt(j).info;
4376                    // Skip packages that are not static shared libs.
4377                    if (!libInfo.isStatic()) {
4378                        break;
4379                    }
4380                    // Important: We skip static shared libs used for some user since
4381                    // in such a case we need to keep the APK on the device. The check for
4382                    // a lib being used for any user is performed by the uninstall call.
4383                    final VersionedPackage declaringPackage = libInfo.getDeclaringPackage();
4384                    // Resolve the package name - we use synthetic package names internally
4385                    final String internalPackageName = resolveInternalPackageNameLPr(
4386                            declaringPackage.getPackageName(), declaringPackage.getVersionCode());
4387                    final PackageSetting ps = mSettings.getPackageLPr(internalPackageName);
4388                    // Skip unused static shared libs cached less than the min period
4389                    // to prevent pruning a lib needed by a subsequently installed package.
4390                    if (ps == null || now - ps.lastUpdateTime < maxCachePeriod) {
4391                        continue;
4392                    }
4393                    if (packagesToDelete == null) {
4394                        packagesToDelete = new ArrayList<>();
4395                    }
4396                    packagesToDelete.add(new VersionedPackage(internalPackageName,
4397                            declaringPackage.getVersionCode()));
4398                }
4399            }
4400        }
4401
4402        if (packagesToDelete != null) {
4403            final int packageCount = packagesToDelete.size();
4404            for (int i = 0; i < packageCount; i++) {
4405                final VersionedPackage pkgToDelete = packagesToDelete.get(i);
4406                // Delete the package synchronously (will fail of the lib used for any user).
4407                if (deletePackageX(pkgToDelete.getPackageName(), pkgToDelete.getVersionCode(),
4408                        UserHandle.USER_SYSTEM, PackageManager.DELETE_ALL_USERS)
4409                                == PackageManager.DELETE_SUCCEEDED) {
4410                    if (volume.getUsableSpace() >= neededSpace) {
4411                        return true;
4412                    }
4413                }
4414            }
4415        }
4416
4417        return false;
4418    }
4419
4420    /**
4421     * Update given flags based on encryption status of current user.
4422     */
4423    private int updateFlags(int flags, int userId) {
4424        if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE
4425                | PackageManager.MATCH_DIRECT_BOOT_AWARE)) != 0) {
4426            // Caller expressed an explicit opinion about what encryption
4427            // aware/unaware components they want to see, so fall through and
4428            // give them what they want
4429        } else {
4430            // Caller expressed no opinion, so match based on user state
4431            if (getUserManagerInternal().isUserUnlockingOrUnlocked(userId)) {
4432                flags |= PackageManager.MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE;
4433            } else {
4434                flags |= PackageManager.MATCH_DIRECT_BOOT_AWARE;
4435            }
4436        }
4437        return flags;
4438    }
4439
4440    private UserManagerInternal getUserManagerInternal() {
4441        if (mUserManagerInternal == null) {
4442            mUserManagerInternal = LocalServices.getService(UserManagerInternal.class);
4443        }
4444        return mUserManagerInternal;
4445    }
4446
4447    private DeviceIdleController.LocalService getDeviceIdleController() {
4448        if (mDeviceIdleController == null) {
4449            mDeviceIdleController =
4450                    LocalServices.getService(DeviceIdleController.LocalService.class);
4451        }
4452        return mDeviceIdleController;
4453    }
4454
4455    /**
4456     * Update given flags when being used to request {@link PackageInfo}.
4457     */
4458    private int updateFlagsForPackage(int flags, int userId, Object cookie) {
4459        final boolean isCallerSystemUser = UserHandle.getCallingUserId() == UserHandle.USER_SYSTEM;
4460        boolean triaged = true;
4461        if ((flags & (PackageManager.GET_ACTIVITIES | PackageManager.GET_RECEIVERS
4462                | PackageManager.GET_SERVICES | PackageManager.GET_PROVIDERS)) != 0) {
4463            // Caller is asking for component details, so they'd better be
4464            // asking for specific encryption matching behavior, or be triaged
4465            if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE
4466                    | PackageManager.MATCH_DIRECT_BOOT_AWARE
4467                    | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) {
4468                triaged = false;
4469            }
4470        }
4471        if ((flags & (PackageManager.MATCH_UNINSTALLED_PACKAGES
4472                | PackageManager.MATCH_SYSTEM_ONLY
4473                | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) {
4474            triaged = false;
4475        }
4476        if ((flags & PackageManager.MATCH_ANY_USER) != 0) {
4477            enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false,
4478                    "MATCH_ANY_USER flag requires INTERACT_ACROSS_USERS permission at "
4479                    + Debug.getCallers(5));
4480        } else if ((flags & PackageManager.MATCH_UNINSTALLED_PACKAGES) != 0 && isCallerSystemUser
4481                && sUserManager.hasManagedProfile(UserHandle.USER_SYSTEM)) {
4482            // If the caller wants all packages and has a restricted profile associated with it,
4483            // then match all users. This is to make sure that launchers that need to access work
4484            // profile apps don't start breaking. TODO: Remove this hack when launchers stop using
4485            // MATCH_UNINSTALLED_PACKAGES to query apps in other profiles. b/31000380
4486            flags |= PackageManager.MATCH_ANY_USER;
4487        }
4488        if (DEBUG_TRIAGED_MISSING && (Binder.getCallingUid() == Process.SYSTEM_UID) && !triaged) {
4489            Log.w(TAG, "Caller hasn't been triaged for missing apps; they asked about " + cookie
4490                    + " with flags 0x" + Integer.toHexString(flags), new Throwable());
4491        }
4492        return updateFlags(flags, userId);
4493    }
4494
4495    /**
4496     * Update given flags when being used to request {@link ApplicationInfo}.
4497     */
4498    private int updateFlagsForApplication(int flags, int userId, Object cookie) {
4499        return updateFlagsForPackage(flags, userId, cookie);
4500    }
4501
4502    /**
4503     * Update given flags when being used to request {@link ComponentInfo}.
4504     */
4505    private int updateFlagsForComponent(int flags, int userId, Object cookie) {
4506        if (cookie instanceof Intent) {
4507            if ((((Intent) cookie).getFlags() & Intent.FLAG_DEBUG_TRIAGED_MISSING) != 0) {
4508                flags |= PackageManager.MATCH_DEBUG_TRIAGED_MISSING;
4509            }
4510        }
4511
4512        boolean triaged = true;
4513        // Caller is asking for component details, so they'd better be
4514        // asking for specific encryption matching behavior, or be triaged
4515        if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE
4516                | PackageManager.MATCH_DIRECT_BOOT_AWARE
4517                | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) {
4518            triaged = false;
4519        }
4520        if (DEBUG_TRIAGED_MISSING && (Binder.getCallingUid() == Process.SYSTEM_UID) && !triaged) {
4521            Log.w(TAG, "Caller hasn't been triaged for missing apps; they asked about " + cookie
4522                    + " with flags 0x" + Integer.toHexString(flags), new Throwable());
4523        }
4524
4525        return updateFlags(flags, userId);
4526    }
4527
4528    /**
4529     * Update given intent when being used to request {@link ResolveInfo}.
4530     */
4531    private Intent updateIntentForResolve(Intent intent) {
4532        if (intent.getSelector() != null) {
4533            intent = intent.getSelector();
4534        }
4535        if (DEBUG_PREFERRED) {
4536            intent.addFlags(Intent.FLAG_DEBUG_LOG_RESOLUTION);
4537        }
4538        return intent;
4539    }
4540
4541    /**
4542     * Update given flags when being used to request {@link ResolveInfo}.
4543     * <p>Instant apps are resolved specially, depending upon context. Minimally,
4544     * {@code}flags{@code} must have the {@link PackageManager#MATCH_INSTANT}
4545     * flag set. However, this flag is only honoured in three circumstances:
4546     * <ul>
4547     * <li>when called from a system process</li>
4548     * <li>when the caller holds the permission {@code android.permission.ACCESS_INSTANT_APPS}</li>
4549     * <li>when resolution occurs to start an activity with a {@code android.intent.action.VIEW}
4550     * action and a {@code android.intent.category.BROWSABLE} category</li>
4551     * </ul>
4552     */
4553    int updateFlagsForResolve(int flags, int userId, Intent intent, int callingUid) {
4554        return updateFlagsForResolve(flags, userId, intent, callingUid,
4555                false /*wantInstantApps*/, false /*onlyExposedExplicitly*/);
4556    }
4557    int updateFlagsForResolve(int flags, int userId, Intent intent, int callingUid,
4558            boolean wantInstantApps) {
4559        return updateFlagsForResolve(flags, userId, intent, callingUid,
4560                wantInstantApps, false /*onlyExposedExplicitly*/);
4561    }
4562    int updateFlagsForResolve(int flags, int userId, Intent intent, int callingUid,
4563            boolean wantInstantApps, boolean onlyExposedExplicitly) {
4564        // Safe mode means we shouldn't match any third-party components
4565        if (mSafeMode) {
4566            flags |= PackageManager.MATCH_SYSTEM_ONLY;
4567        }
4568        if (getInstantAppPackageName(callingUid) != null) {
4569            // But, ephemeral apps see both ephemeral and exposed, non-ephemeral components
4570            if (onlyExposedExplicitly) {
4571                flags |= PackageManager.MATCH_EXPLICITLY_VISIBLE_ONLY;
4572            }
4573            flags |= PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY;
4574            flags |= PackageManager.MATCH_INSTANT;
4575        } else {
4576            final boolean wantMatchInstant = (flags & PackageManager.MATCH_INSTANT) != 0;
4577            final boolean allowMatchInstant =
4578                    (wantInstantApps
4579                            && Intent.ACTION_VIEW.equals(intent.getAction())
4580                            && hasWebURI(intent))
4581                    || (wantMatchInstant && canViewInstantApps(callingUid, userId));
4582            flags &= ~(PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY
4583                    | PackageManager.MATCH_EXPLICITLY_VISIBLE_ONLY);
4584            if (!allowMatchInstant) {
4585                flags &= ~PackageManager.MATCH_INSTANT;
4586            }
4587        }
4588        return updateFlagsForComponent(flags, userId, intent /*cookie*/);
4589    }
4590
4591    @Override
4592    public ActivityInfo getActivityInfo(ComponentName component, int flags, int userId) {
4593        return getActivityInfoInternal(component, flags, Binder.getCallingUid(), userId);
4594    }
4595
4596    /**
4597     * Important: The provided filterCallingUid is used exclusively to filter out activities
4598     * that can be seen based on user state. It's typically the original caller uid prior
4599     * to clearing. Because it can only be provided by trusted code, it's value can be
4600     * trusted and will be used as-is; unlike userId which will be validated by this method.
4601     */
4602    private ActivityInfo getActivityInfoInternal(ComponentName component, int flags,
4603            int filterCallingUid, int userId) {
4604        if (!sUserManager.exists(userId)) return null;
4605        flags = updateFlagsForComponent(flags, userId, component);
4606        enforceCrossUserPermission(Binder.getCallingUid(), userId,
4607                false /* requireFullPermission */, false /* checkShell */, "get activity info");
4608        synchronized (mPackages) {
4609            PackageParser.Activity a = mActivities.mActivities.get(component);
4610
4611            if (DEBUG_PACKAGE_INFO) Log.v(TAG, "getActivityInfo " + component + ": " + a);
4612            if (a != null && mSettings.isEnabledAndMatchLPr(a.info, flags, userId)) {
4613                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
4614                if (ps == null) return null;
4615                if (filterAppAccessLPr(ps, filterCallingUid, component, TYPE_ACTIVITY, userId)) {
4616                    return null;
4617                }
4618                return PackageParser.generateActivityInfo(
4619                        a, flags, ps.readUserState(userId), userId);
4620            }
4621            if (mResolveComponentName.equals(component)) {
4622                return PackageParser.generateActivityInfo(
4623                        mResolveActivity, flags, new PackageUserState(), userId);
4624            }
4625        }
4626        return null;
4627    }
4628
4629    @Override
4630    public boolean activitySupportsIntent(ComponentName component, Intent intent,
4631            String resolvedType) {
4632        synchronized (mPackages) {
4633            if (component.equals(mResolveComponentName)) {
4634                // The resolver supports EVERYTHING!
4635                return true;
4636            }
4637            final int callingUid = Binder.getCallingUid();
4638            final int callingUserId = UserHandle.getUserId(callingUid);
4639            PackageParser.Activity a = mActivities.mActivities.get(component);
4640            if (a == null) {
4641                return false;
4642            }
4643            PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
4644            if (ps == null) {
4645                return false;
4646            }
4647            if (filterAppAccessLPr(ps, callingUid, component, TYPE_ACTIVITY, callingUserId)) {
4648                return false;
4649            }
4650            for (int i=0; i<a.intents.size(); i++) {
4651                if (a.intents.get(i).match(intent.getAction(), resolvedType, intent.getScheme(),
4652                        intent.getData(), intent.getCategories(), TAG) >= 0) {
4653                    return true;
4654                }
4655            }
4656            return false;
4657        }
4658    }
4659
4660    @Override
4661    public ActivityInfo getReceiverInfo(ComponentName component, int flags, int userId) {
4662        if (!sUserManager.exists(userId)) return null;
4663        final int callingUid = Binder.getCallingUid();
4664        flags = updateFlagsForComponent(flags, userId, component);
4665        enforceCrossUserPermission(callingUid, userId,
4666                false /* requireFullPermission */, false /* checkShell */, "get receiver info");
4667        synchronized (mPackages) {
4668            PackageParser.Activity a = mReceivers.mActivities.get(component);
4669            if (DEBUG_PACKAGE_INFO) Log.v(
4670                TAG, "getReceiverInfo " + component + ": " + a);
4671            if (a != null && mSettings.isEnabledAndMatchLPr(a.info, flags, userId)) {
4672                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
4673                if (ps == null) return null;
4674                if (filterAppAccessLPr(ps, callingUid, component, TYPE_RECEIVER, userId)) {
4675                    return null;
4676                }
4677                return PackageParser.generateActivityInfo(
4678                        a, flags, ps.readUserState(userId), userId);
4679            }
4680        }
4681        return null;
4682    }
4683
4684    @Override
4685    public ParceledListSlice<SharedLibraryInfo> getSharedLibraries(String packageName,
4686            int flags, int userId) {
4687        if (!sUserManager.exists(userId)) return null;
4688        Preconditions.checkArgumentNonnegative(userId, "userId must be >= 0");
4689        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
4690            return null;
4691        }
4692
4693        flags = updateFlagsForPackage(flags, userId, null);
4694
4695        final boolean canSeeStaticLibraries =
4696                mContext.checkCallingOrSelfPermission(INSTALL_PACKAGES)
4697                        == PERMISSION_GRANTED
4698                || mContext.checkCallingOrSelfPermission(DELETE_PACKAGES)
4699                        == PERMISSION_GRANTED
4700                || canRequestPackageInstallsInternal(packageName,
4701                        PackageManager.MATCH_STATIC_SHARED_LIBRARIES, userId,
4702                        false  /* throwIfPermNotDeclared*/)
4703                || mContext.checkCallingOrSelfPermission(REQUEST_DELETE_PACKAGES)
4704                        == PERMISSION_GRANTED;
4705
4706        synchronized (mPackages) {
4707            List<SharedLibraryInfo> result = null;
4708
4709            final int libCount = mSharedLibraries.size();
4710            for (int i = 0; i < libCount; i++) {
4711                SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.valueAt(i);
4712                if (versionedLib == null) {
4713                    continue;
4714                }
4715
4716                final int versionCount = versionedLib.size();
4717                for (int j = 0; j < versionCount; j++) {
4718                    SharedLibraryInfo libInfo = versionedLib.valueAt(j).info;
4719                    if (!canSeeStaticLibraries && libInfo.isStatic()) {
4720                        break;
4721                    }
4722                    final long identity = Binder.clearCallingIdentity();
4723                    try {
4724                        PackageInfo packageInfo = getPackageInfoVersioned(
4725                                libInfo.getDeclaringPackage(), flags
4726                                        | PackageManager.MATCH_STATIC_SHARED_LIBRARIES, userId);
4727                        if (packageInfo == null) {
4728                            continue;
4729                        }
4730                    } finally {
4731                        Binder.restoreCallingIdentity(identity);
4732                    }
4733
4734                    SharedLibraryInfo resLibInfo = new SharedLibraryInfo(libInfo.getName(),
4735                            libInfo.getVersion(), libInfo.getType(),
4736                            libInfo.getDeclaringPackage(), getPackagesUsingSharedLibraryLPr(libInfo,
4737                            flags, userId));
4738
4739                    if (result == null) {
4740                        result = new ArrayList<>();
4741                    }
4742                    result.add(resLibInfo);
4743                }
4744            }
4745
4746            return result != null ? new ParceledListSlice<>(result) : null;
4747        }
4748    }
4749
4750    private List<VersionedPackage> getPackagesUsingSharedLibraryLPr(
4751            SharedLibraryInfo libInfo, int flags, int userId) {
4752        List<VersionedPackage> versionedPackages = null;
4753        final int packageCount = mSettings.mPackages.size();
4754        for (int i = 0; i < packageCount; i++) {
4755            PackageSetting ps = mSettings.mPackages.valueAt(i);
4756
4757            if (ps == null) {
4758                continue;
4759            }
4760
4761            if (!ps.getUserState().get(userId).isAvailable(flags)) {
4762                continue;
4763            }
4764
4765            final String libName = libInfo.getName();
4766            if (libInfo.isStatic()) {
4767                final int libIdx = ArrayUtils.indexOf(ps.usesStaticLibraries, libName);
4768                if (libIdx < 0) {
4769                    continue;
4770                }
4771                if (ps.usesStaticLibrariesVersions[libIdx] != libInfo.getVersion()) {
4772                    continue;
4773                }
4774                if (versionedPackages == null) {
4775                    versionedPackages = new ArrayList<>();
4776                }
4777                // If the dependent is a static shared lib, use the public package name
4778                String dependentPackageName = ps.name;
4779                if (ps.pkg != null && ps.pkg.applicationInfo.isStaticSharedLibrary()) {
4780                    dependentPackageName = ps.pkg.manifestPackageName;
4781                }
4782                versionedPackages.add(new VersionedPackage(dependentPackageName, ps.versionCode));
4783            } else if (ps.pkg != null) {
4784                if (ArrayUtils.contains(ps.pkg.usesLibraries, libName)
4785                        || ArrayUtils.contains(ps.pkg.usesOptionalLibraries, libName)) {
4786                    if (versionedPackages == null) {
4787                        versionedPackages = new ArrayList<>();
4788                    }
4789                    versionedPackages.add(new VersionedPackage(ps.name, ps.versionCode));
4790                }
4791            }
4792        }
4793
4794        return versionedPackages;
4795    }
4796
4797    @Override
4798    public ServiceInfo getServiceInfo(ComponentName component, int flags, int userId) {
4799        if (!sUserManager.exists(userId)) return null;
4800        final int callingUid = Binder.getCallingUid();
4801        flags = updateFlagsForComponent(flags, userId, component);
4802        enforceCrossUserPermission(callingUid, userId,
4803                false /* requireFullPermission */, false /* checkShell */, "get service info");
4804        synchronized (mPackages) {
4805            PackageParser.Service s = mServices.mServices.get(component);
4806            if (DEBUG_PACKAGE_INFO) Log.v(
4807                TAG, "getServiceInfo " + component + ": " + s);
4808            if (s != null && mSettings.isEnabledAndMatchLPr(s.info, flags, userId)) {
4809                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
4810                if (ps == null) return null;
4811                if (filterAppAccessLPr(ps, callingUid, component, TYPE_SERVICE, userId)) {
4812                    return null;
4813                }
4814                return PackageParser.generateServiceInfo(
4815                        s, flags, ps.readUserState(userId), userId);
4816            }
4817        }
4818        return null;
4819    }
4820
4821    @Override
4822    public ProviderInfo getProviderInfo(ComponentName component, int flags, int userId) {
4823        if (!sUserManager.exists(userId)) return null;
4824        final int callingUid = Binder.getCallingUid();
4825        flags = updateFlagsForComponent(flags, userId, component);
4826        enforceCrossUserPermission(callingUid, userId,
4827                false /* requireFullPermission */, false /* checkShell */, "get provider info");
4828        synchronized (mPackages) {
4829            PackageParser.Provider p = mProviders.mProviders.get(component);
4830            if (DEBUG_PACKAGE_INFO) Log.v(
4831                TAG, "getProviderInfo " + component + ": " + p);
4832            if (p != null && mSettings.isEnabledAndMatchLPr(p.info, flags, userId)) {
4833                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
4834                if (ps == null) return null;
4835                if (filterAppAccessLPr(ps, callingUid, component, TYPE_PROVIDER, userId)) {
4836                    return null;
4837                }
4838                return PackageParser.generateProviderInfo(
4839                        p, flags, ps.readUserState(userId), userId);
4840            }
4841        }
4842        return null;
4843    }
4844
4845    @Override
4846    public String[] getSystemSharedLibraryNames() {
4847        // allow instant applications
4848        synchronized (mPackages) {
4849            Set<String> libs = null;
4850            final int libCount = mSharedLibraries.size();
4851            for (int i = 0; i < libCount; i++) {
4852                SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.valueAt(i);
4853                if (versionedLib == null) {
4854                    continue;
4855                }
4856                final int versionCount = versionedLib.size();
4857                for (int j = 0; j < versionCount; j++) {
4858                    SharedLibraryEntry libEntry = versionedLib.valueAt(j);
4859                    if (!libEntry.info.isStatic()) {
4860                        if (libs == null) {
4861                            libs = new ArraySet<>();
4862                        }
4863                        libs.add(libEntry.info.getName());
4864                        break;
4865                    }
4866                    PackageSetting ps = mSettings.getPackageLPr(libEntry.apk);
4867                    if (ps != null && !filterSharedLibPackageLPr(ps, Binder.getCallingUid(),
4868                            UserHandle.getUserId(Binder.getCallingUid()),
4869                            PackageManager.MATCH_STATIC_SHARED_LIBRARIES)) {
4870                        if (libs == null) {
4871                            libs = new ArraySet<>();
4872                        }
4873                        libs.add(libEntry.info.getName());
4874                        break;
4875                    }
4876                }
4877            }
4878
4879            if (libs != null) {
4880                String[] libsArray = new String[libs.size()];
4881                libs.toArray(libsArray);
4882                return libsArray;
4883            }
4884
4885            return null;
4886        }
4887    }
4888
4889    @Override
4890    public @NonNull String getServicesSystemSharedLibraryPackageName() {
4891        // allow instant applications
4892        synchronized (mPackages) {
4893            return mServicesSystemSharedLibraryPackageName;
4894        }
4895    }
4896
4897    @Override
4898    public @NonNull String getSharedSystemSharedLibraryPackageName() {
4899        // allow instant applications
4900        synchronized (mPackages) {
4901            return mSharedSystemSharedLibraryPackageName;
4902        }
4903    }
4904
4905    private void updateSequenceNumberLP(PackageSetting pkgSetting, int[] userList) {
4906        for (int i = userList.length - 1; i >= 0; --i) {
4907            final int userId = userList[i];
4908            // don't add instant app to the list of updates
4909            if (pkgSetting.getInstantApp(userId)) {
4910                continue;
4911            }
4912            SparseArray<String> changedPackages = mChangedPackages.get(userId);
4913            if (changedPackages == null) {
4914                changedPackages = new SparseArray<>();
4915                mChangedPackages.put(userId, changedPackages);
4916            }
4917            Map<String, Integer> sequenceNumbers = mChangedPackagesSequenceNumbers.get(userId);
4918            if (sequenceNumbers == null) {
4919                sequenceNumbers = new HashMap<>();
4920                mChangedPackagesSequenceNumbers.put(userId, sequenceNumbers);
4921            }
4922            final Integer sequenceNumber = sequenceNumbers.get(pkgSetting.name);
4923            if (sequenceNumber != null) {
4924                changedPackages.remove(sequenceNumber);
4925            }
4926            changedPackages.put(mChangedPackagesSequenceNumber, pkgSetting.name);
4927            sequenceNumbers.put(pkgSetting.name, mChangedPackagesSequenceNumber);
4928        }
4929        mChangedPackagesSequenceNumber++;
4930    }
4931
4932    @Override
4933    public ChangedPackages getChangedPackages(int sequenceNumber, int userId) {
4934        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
4935            return null;
4936        }
4937        synchronized (mPackages) {
4938            if (sequenceNumber >= mChangedPackagesSequenceNumber) {
4939                return null;
4940            }
4941            final SparseArray<String> changedPackages = mChangedPackages.get(userId);
4942            if (changedPackages == null) {
4943                return null;
4944            }
4945            final List<String> packageNames =
4946                    new ArrayList<>(mChangedPackagesSequenceNumber - sequenceNumber);
4947            for (int i = sequenceNumber; i < mChangedPackagesSequenceNumber; i++) {
4948                final String packageName = changedPackages.get(i);
4949                if (packageName != null) {
4950                    packageNames.add(packageName);
4951                }
4952            }
4953            return packageNames.isEmpty()
4954                    ? null : new ChangedPackages(mChangedPackagesSequenceNumber, packageNames);
4955        }
4956    }
4957
4958    @Override
4959    public @NonNull ParceledListSlice<FeatureInfo> getSystemAvailableFeatures() {
4960        // allow instant applications
4961        ArrayList<FeatureInfo> res;
4962        synchronized (mAvailableFeatures) {
4963            res = new ArrayList<>(mAvailableFeatures.size() + 1);
4964            res.addAll(mAvailableFeatures.values());
4965        }
4966        final FeatureInfo fi = new FeatureInfo();
4967        fi.reqGlEsVersion = SystemProperties.getInt("ro.opengles.version",
4968                FeatureInfo.GL_ES_VERSION_UNDEFINED);
4969        res.add(fi);
4970
4971        return new ParceledListSlice<>(res);
4972    }
4973
4974    @Override
4975    public boolean hasSystemFeature(String name, int version) {
4976        // allow instant applications
4977        synchronized (mAvailableFeatures) {
4978            final FeatureInfo feat = mAvailableFeatures.get(name);
4979            if (feat == null) {
4980                return false;
4981            } else {
4982                return feat.version >= version;
4983            }
4984        }
4985    }
4986
4987    @Override
4988    public int checkPermission(String permName, String pkgName, int userId) {
4989        if (!sUserManager.exists(userId)) {
4990            return PackageManager.PERMISSION_DENIED;
4991        }
4992        final int callingUid = Binder.getCallingUid();
4993
4994        synchronized (mPackages) {
4995            final PackageParser.Package p = mPackages.get(pkgName);
4996            if (p != null && p.mExtras != null) {
4997                final PackageSetting ps = (PackageSetting) p.mExtras;
4998                if (filterAppAccessLPr(ps, callingUid, userId)) {
4999                    return PackageManager.PERMISSION_DENIED;
5000                }
5001                final boolean instantApp = ps.getInstantApp(userId);
5002                final PermissionsState permissionsState = ps.getPermissionsState();
5003                if (permissionsState.hasPermission(permName, userId)) {
5004                    if (instantApp) {
5005                        BasePermission bp = mSettings.mPermissions.get(permName);
5006                        if (bp != null && bp.isInstant()) {
5007                            return PackageManager.PERMISSION_GRANTED;
5008                        }
5009                    } else {
5010                        return PackageManager.PERMISSION_GRANTED;
5011                    }
5012                }
5013                // Special case: ACCESS_FINE_LOCATION permission includes ACCESS_COARSE_LOCATION
5014                if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && permissionsState
5015                        .hasPermission(Manifest.permission.ACCESS_FINE_LOCATION, userId)) {
5016                    return PackageManager.PERMISSION_GRANTED;
5017                }
5018            }
5019        }
5020
5021        return PackageManager.PERMISSION_DENIED;
5022    }
5023
5024    @Override
5025    public int checkUidPermission(String permName, int uid) {
5026        final int callingUid = Binder.getCallingUid();
5027        final int callingUserId = UserHandle.getUserId(callingUid);
5028        final boolean isCallerInstantApp = getInstantAppPackageName(callingUid) != null;
5029        final boolean isUidInstantApp = getInstantAppPackageName(uid) != null;
5030        final int userId = UserHandle.getUserId(uid);
5031        if (!sUserManager.exists(userId)) {
5032            return PackageManager.PERMISSION_DENIED;
5033        }
5034
5035        synchronized (mPackages) {
5036            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
5037            if (obj != null) {
5038                if (obj instanceof SharedUserSetting) {
5039                    if (isCallerInstantApp) {
5040                        return PackageManager.PERMISSION_DENIED;
5041                    }
5042                } else if (obj instanceof PackageSetting) {
5043                    final PackageSetting ps = (PackageSetting) obj;
5044                    if (filterAppAccessLPr(ps, callingUid, callingUserId)) {
5045                        return PackageManager.PERMISSION_DENIED;
5046                    }
5047                }
5048                final SettingBase settingBase = (SettingBase) obj;
5049                final PermissionsState permissionsState = settingBase.getPermissionsState();
5050                if (permissionsState.hasPermission(permName, userId)) {
5051                    if (isUidInstantApp) {
5052                        BasePermission bp = mSettings.mPermissions.get(permName);
5053                        if (bp != null && bp.isInstant()) {
5054                            return PackageManager.PERMISSION_GRANTED;
5055                        }
5056                    } else {
5057                        return PackageManager.PERMISSION_GRANTED;
5058                    }
5059                }
5060                // Special case: ACCESS_FINE_LOCATION permission includes ACCESS_COARSE_LOCATION
5061                if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && permissionsState
5062                        .hasPermission(Manifest.permission.ACCESS_FINE_LOCATION, userId)) {
5063                    return PackageManager.PERMISSION_GRANTED;
5064                }
5065            } else {
5066                ArraySet<String> perms = mSystemPermissions.get(uid);
5067                if (perms != null) {
5068                    if (perms.contains(permName)) {
5069                        return PackageManager.PERMISSION_GRANTED;
5070                    }
5071                    if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && perms
5072                            .contains(Manifest.permission.ACCESS_FINE_LOCATION)) {
5073                        return PackageManager.PERMISSION_GRANTED;
5074                    }
5075                }
5076            }
5077        }
5078
5079        return PackageManager.PERMISSION_DENIED;
5080    }
5081
5082    @Override
5083    public boolean isPermissionRevokedByPolicy(String permission, String packageName, int userId) {
5084        if (UserHandle.getCallingUserId() != userId) {
5085            mContext.enforceCallingPermission(
5086                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
5087                    "isPermissionRevokedByPolicy for user " + userId);
5088        }
5089
5090        if (checkPermission(permission, packageName, userId)
5091                == PackageManager.PERMISSION_GRANTED) {
5092            return false;
5093        }
5094
5095        final int callingUid = Binder.getCallingUid();
5096        if (getInstantAppPackageName(callingUid) != null) {
5097            if (!isCallerSameApp(packageName, callingUid)) {
5098                return false;
5099            }
5100        } else {
5101            if (isInstantApp(packageName, userId)) {
5102                return false;
5103            }
5104        }
5105
5106        final long identity = Binder.clearCallingIdentity();
5107        try {
5108            final int flags = getPermissionFlags(permission, packageName, userId);
5109            return (flags & PackageManager.FLAG_PERMISSION_POLICY_FIXED) != 0;
5110        } finally {
5111            Binder.restoreCallingIdentity(identity);
5112        }
5113    }
5114
5115    @Override
5116    public String getPermissionControllerPackageName() {
5117        synchronized (mPackages) {
5118            return mRequiredInstallerPackage;
5119        }
5120    }
5121
5122    /**
5123     * Checks if the request is from the system or an app that has INTERACT_ACROSS_USERS
5124     * or INTERACT_ACROSS_USERS_FULL permissions, if the userid is not for the caller.
5125     * @param checkShell whether to prevent shell from access if there's a debugging restriction
5126     * @param message the message to log on security exception
5127     */
5128    void enforceCrossUserPermission(int callingUid, int userId, boolean requireFullPermission,
5129            boolean checkShell, String message) {
5130        if (userId < 0) {
5131            throw new IllegalArgumentException("Invalid userId " + userId);
5132        }
5133        if (checkShell) {
5134            enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, userId);
5135        }
5136        if (userId == UserHandle.getUserId(callingUid)) return;
5137        if (callingUid != Process.SYSTEM_UID && callingUid != 0) {
5138            if (requireFullPermission) {
5139                mContext.enforceCallingOrSelfPermission(
5140                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message);
5141            } else {
5142                try {
5143                    mContext.enforceCallingOrSelfPermission(
5144                            android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message);
5145                } catch (SecurityException se) {
5146                    mContext.enforceCallingOrSelfPermission(
5147                            android.Manifest.permission.INTERACT_ACROSS_USERS, message);
5148                }
5149            }
5150        }
5151    }
5152
5153    void enforceShellRestriction(String restriction, int callingUid, int userHandle) {
5154        if (callingUid == Process.SHELL_UID) {
5155            if (userHandle >= 0
5156                    && sUserManager.hasUserRestriction(restriction, userHandle)) {
5157                throw new SecurityException("Shell does not have permission to access user "
5158                        + userHandle);
5159            } else if (userHandle < 0) {
5160                Slog.e(TAG, "Unable to check shell permission for user " + userHandle + "\n\t"
5161                        + Debug.getCallers(3));
5162            }
5163        }
5164    }
5165
5166    private BasePermission findPermissionTreeLP(String permName) {
5167        for(BasePermission bp : mSettings.mPermissionTrees.values()) {
5168            if (permName.startsWith(bp.name) &&
5169                    permName.length() > bp.name.length() &&
5170                    permName.charAt(bp.name.length()) == '.') {
5171                return bp;
5172            }
5173        }
5174        return null;
5175    }
5176
5177    private BasePermission checkPermissionTreeLP(String permName) {
5178        if (permName != null) {
5179            BasePermission bp = findPermissionTreeLP(permName);
5180            if (bp != null) {
5181                if (bp.uid == UserHandle.getAppId(Binder.getCallingUid())) {
5182                    return bp;
5183                }
5184                throw new SecurityException("Calling uid "
5185                        + Binder.getCallingUid()
5186                        + " is not allowed to add to permission tree "
5187                        + bp.name + " owned by uid " + bp.uid);
5188            }
5189        }
5190        throw new SecurityException("No permission tree found for " + permName);
5191    }
5192
5193    static boolean compareStrings(CharSequence s1, CharSequence s2) {
5194        if (s1 == null) {
5195            return s2 == null;
5196        }
5197        if (s2 == null) {
5198            return false;
5199        }
5200        if (s1.getClass() != s2.getClass()) {
5201            return false;
5202        }
5203        return s1.equals(s2);
5204    }
5205
5206    static boolean comparePermissionInfos(PermissionInfo pi1, PermissionInfo pi2) {
5207        if (pi1.icon != pi2.icon) return false;
5208        if (pi1.logo != pi2.logo) return false;
5209        if (pi1.protectionLevel != pi2.protectionLevel) return false;
5210        if (!compareStrings(pi1.name, pi2.name)) return false;
5211        if (!compareStrings(pi1.nonLocalizedLabel, pi2.nonLocalizedLabel)) return false;
5212        // We'll take care of setting this one.
5213        if (!compareStrings(pi1.packageName, pi2.packageName)) return false;
5214        // These are not currently stored in settings.
5215        //if (!compareStrings(pi1.group, pi2.group)) return false;
5216        //if (!compareStrings(pi1.nonLocalizedDescription, pi2.nonLocalizedDescription)) return false;
5217        //if (pi1.labelRes != pi2.labelRes) return false;
5218        //if (pi1.descriptionRes != pi2.descriptionRes) return false;
5219        return true;
5220    }
5221
5222    int permissionInfoFootprint(PermissionInfo info) {
5223        int size = info.name.length();
5224        if (info.nonLocalizedLabel != null) size += info.nonLocalizedLabel.length();
5225        if (info.nonLocalizedDescription != null) size += info.nonLocalizedDescription.length();
5226        return size;
5227    }
5228
5229    int calculateCurrentPermissionFootprintLocked(BasePermission tree) {
5230        int size = 0;
5231        for (BasePermission perm : mSettings.mPermissions.values()) {
5232            if (perm.uid == tree.uid) {
5233                size += perm.name.length() + permissionInfoFootprint(perm.perm.info);
5234            }
5235        }
5236        return size;
5237    }
5238
5239    void enforcePermissionCapLocked(PermissionInfo info, BasePermission tree) {
5240        // We calculate the max size of permissions defined by this uid and throw
5241        // if that plus the size of 'info' would exceed our stated maximum.
5242        if (tree.uid != Process.SYSTEM_UID) {
5243            final int curTreeSize = calculateCurrentPermissionFootprintLocked(tree);
5244            if (curTreeSize + permissionInfoFootprint(info) > MAX_PERMISSION_TREE_FOOTPRINT) {
5245                throw new SecurityException("Permission tree size cap exceeded");
5246            }
5247        }
5248    }
5249
5250    boolean addPermissionLocked(PermissionInfo info, boolean async) {
5251        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
5252            throw new SecurityException("Instant apps can't add permissions");
5253        }
5254        if (info.labelRes == 0 && info.nonLocalizedLabel == null) {
5255            throw new SecurityException("Label must be specified in permission");
5256        }
5257        BasePermission tree = checkPermissionTreeLP(info.name);
5258        BasePermission bp = mSettings.mPermissions.get(info.name);
5259        boolean added = bp == null;
5260        boolean changed = true;
5261        int fixedLevel = PermissionInfo.fixProtectionLevel(info.protectionLevel);
5262        if (added) {
5263            enforcePermissionCapLocked(info, tree);
5264            bp = new BasePermission(info.name, tree.sourcePackage,
5265                    BasePermission.TYPE_DYNAMIC);
5266        } else if (bp.type != BasePermission.TYPE_DYNAMIC) {
5267            throw new SecurityException(
5268                    "Not allowed to modify non-dynamic permission "
5269                    + info.name);
5270        } else {
5271            if (bp.protectionLevel == fixedLevel
5272                    && bp.perm.owner.equals(tree.perm.owner)
5273                    && bp.uid == tree.uid
5274                    && comparePermissionInfos(bp.perm.info, info)) {
5275                changed = false;
5276            }
5277        }
5278        bp.protectionLevel = fixedLevel;
5279        info = new PermissionInfo(info);
5280        info.protectionLevel = fixedLevel;
5281        bp.perm = new PackageParser.Permission(tree.perm.owner, info);
5282        bp.perm.info.packageName = tree.perm.info.packageName;
5283        bp.uid = tree.uid;
5284        if (added) {
5285            mSettings.mPermissions.put(info.name, bp);
5286        }
5287        if (changed) {
5288            if (!async) {
5289                mSettings.writeLPr();
5290            } else {
5291                scheduleWriteSettingsLocked();
5292            }
5293        }
5294        return added;
5295    }
5296
5297    @Override
5298    public boolean addPermission(PermissionInfo info) {
5299        synchronized (mPackages) {
5300            return addPermissionLocked(info, false);
5301        }
5302    }
5303
5304    @Override
5305    public boolean addPermissionAsync(PermissionInfo info) {
5306        synchronized (mPackages) {
5307            return addPermissionLocked(info, true);
5308        }
5309    }
5310
5311    @Override
5312    public void removePermission(String name) {
5313        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
5314            throw new SecurityException("Instant applications don't have access to this method");
5315        }
5316        synchronized (mPackages) {
5317            checkPermissionTreeLP(name);
5318            BasePermission bp = mSettings.mPermissions.get(name);
5319            if (bp != null) {
5320                if (bp.type != BasePermission.TYPE_DYNAMIC) {
5321                    throw new SecurityException(
5322                            "Not allowed to modify non-dynamic permission "
5323                            + name);
5324                }
5325                mSettings.mPermissions.remove(name);
5326                mSettings.writeLPr();
5327            }
5328        }
5329    }
5330
5331    private static void enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(
5332            PackageParser.Package pkg, BasePermission bp) {
5333        int index = pkg.requestedPermissions.indexOf(bp.name);
5334        if (index == -1) {
5335            throw new SecurityException("Package " + pkg.packageName
5336                    + " has not requested permission " + bp.name);
5337        }
5338        if (!bp.isRuntime() && !bp.isDevelopment()) {
5339            throw new SecurityException("Permission " + bp.name
5340                    + " is not a changeable permission type");
5341        }
5342    }
5343
5344    @Override
5345    public void grantRuntimePermission(String packageName, String name, final int userId) {
5346        grantRuntimePermission(packageName, name, userId, false /* Only if not fixed by policy */);
5347    }
5348
5349    private void grantRuntimePermission(String packageName, String name, final int userId,
5350            boolean overridePolicy) {
5351        if (!sUserManager.exists(userId)) {
5352            Log.e(TAG, "No such user:" + userId);
5353            return;
5354        }
5355        final int callingUid = Binder.getCallingUid();
5356
5357        mContext.enforceCallingOrSelfPermission(
5358                android.Manifest.permission.GRANT_RUNTIME_PERMISSIONS,
5359                "grantRuntimePermission");
5360
5361        enforceCrossUserPermission(callingUid, userId,
5362                true /* requireFullPermission */, true /* checkShell */,
5363                "grantRuntimePermission");
5364
5365        final int uid;
5366        final PackageSetting ps;
5367
5368        synchronized (mPackages) {
5369            final PackageParser.Package pkg = mPackages.get(packageName);
5370            if (pkg == null) {
5371                throw new IllegalArgumentException("Unknown package: " + packageName);
5372            }
5373            final BasePermission bp = mSettings.mPermissions.get(name);
5374            if (bp == null) {
5375                throw new IllegalArgumentException("Unknown permission: " + name);
5376            }
5377            ps = (PackageSetting) pkg.mExtras;
5378            if (ps == null
5379                    || filterAppAccessLPr(ps, callingUid, userId)) {
5380                throw new IllegalArgumentException("Unknown package: " + packageName);
5381            }
5382
5383            enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(pkg, bp);
5384
5385            // If a permission review is required for legacy apps we represent
5386            // their permissions as always granted runtime ones since we need
5387            // to keep the review required permission flag per user while an
5388            // install permission's state is shared across all users.
5389            if (mPermissionReviewRequired
5390                    && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M
5391                    && bp.isRuntime()) {
5392                return;
5393            }
5394
5395            uid = UserHandle.getUid(userId, pkg.applicationInfo.uid);
5396
5397            final PermissionsState permissionsState = ps.getPermissionsState();
5398
5399            final int flags = permissionsState.getPermissionFlags(name, userId);
5400            if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) {
5401                throw new SecurityException("Cannot grant system fixed permission "
5402                        + name + " for package " + packageName);
5403            }
5404            if (!overridePolicy && (flags & PackageManager.FLAG_PERMISSION_POLICY_FIXED) != 0) {
5405                throw new SecurityException("Cannot grant policy fixed permission "
5406                        + name + " for package " + packageName);
5407            }
5408
5409            if (bp.isDevelopment()) {
5410                // Development permissions must be handled specially, since they are not
5411                // normal runtime permissions.  For now they apply to all users.
5412                if (permissionsState.grantInstallPermission(bp) !=
5413                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
5414                    scheduleWriteSettingsLocked();
5415                }
5416                return;
5417            }
5418
5419            if (ps.getInstantApp(userId) && !bp.isInstant()) {
5420                throw new SecurityException("Cannot grant non-ephemeral permission"
5421                        + name + " for package " + packageName);
5422            }
5423
5424            if (pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) {
5425                Slog.w(TAG, "Cannot grant runtime permission to a legacy app");
5426                return;
5427            }
5428
5429            final int result = permissionsState.grantRuntimePermission(bp, userId);
5430            switch (result) {
5431                case PermissionsState.PERMISSION_OPERATION_FAILURE: {
5432                    return;
5433                }
5434
5435                case PermissionsState.PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: {
5436                    final int appId = UserHandle.getAppId(pkg.applicationInfo.uid);
5437                    mHandler.post(new Runnable() {
5438                        @Override
5439                        public void run() {
5440                            killUid(appId, userId, KILL_APP_REASON_GIDS_CHANGED);
5441                        }
5442                    });
5443                }
5444                break;
5445            }
5446
5447            if (bp.isRuntime()) {
5448                logPermissionGranted(mContext, name, packageName);
5449            }
5450
5451            mOnPermissionChangeListeners.onPermissionsChanged(uid);
5452
5453            // Not critical if that is lost - app has to request again.
5454            mSettings.writeRuntimePermissionsForUserLPr(userId, false);
5455        }
5456
5457        // Only need to do this if user is initialized. Otherwise it's a new user
5458        // and there are no processes running as the user yet and there's no need
5459        // to make an expensive call to remount processes for the changed permissions.
5460        if (READ_EXTERNAL_STORAGE.equals(name)
5461                || WRITE_EXTERNAL_STORAGE.equals(name)) {
5462            final long token = Binder.clearCallingIdentity();
5463            try {
5464                if (sUserManager.isInitialized(userId)) {
5465                    StorageManagerInternal storageManagerInternal = LocalServices.getService(
5466                            StorageManagerInternal.class);
5467                    storageManagerInternal.onExternalStoragePolicyChanged(uid, packageName);
5468                }
5469            } finally {
5470                Binder.restoreCallingIdentity(token);
5471            }
5472        }
5473    }
5474
5475    @Override
5476    public void revokeRuntimePermission(String packageName, String name, int userId) {
5477        revokeRuntimePermission(packageName, name, userId, false /* Only if not fixed by policy */);
5478    }
5479
5480    private void revokeRuntimePermission(String packageName, String name, int userId,
5481            boolean overridePolicy) {
5482        if (!sUserManager.exists(userId)) {
5483            Log.e(TAG, "No such user:" + userId);
5484            return;
5485        }
5486
5487        mContext.enforceCallingOrSelfPermission(
5488                android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS,
5489                "revokeRuntimePermission");
5490
5491        enforceCrossUserPermission(Binder.getCallingUid(), userId,
5492                true /* requireFullPermission */, true /* checkShell */,
5493                "revokeRuntimePermission");
5494
5495        final int appId;
5496
5497        synchronized (mPackages) {
5498            final PackageParser.Package pkg = mPackages.get(packageName);
5499            if (pkg == null) {
5500                throw new IllegalArgumentException("Unknown package: " + packageName);
5501            }
5502            final PackageSetting ps = (PackageSetting) pkg.mExtras;
5503            if (ps == null
5504                    || filterAppAccessLPr(ps, Binder.getCallingUid(), userId)) {
5505                throw new IllegalArgumentException("Unknown package: " + packageName);
5506            }
5507            final BasePermission bp = mSettings.mPermissions.get(name);
5508            if (bp == null) {
5509                throw new IllegalArgumentException("Unknown permission: " + name);
5510            }
5511
5512            enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(pkg, bp);
5513
5514            // If a permission review is required for legacy apps we represent
5515            // their permissions as always granted runtime ones since we need
5516            // to keep the review required permission flag per user while an
5517            // install permission's state is shared across all users.
5518            if (mPermissionReviewRequired
5519                    && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M
5520                    && bp.isRuntime()) {
5521                return;
5522            }
5523
5524            final PermissionsState permissionsState = ps.getPermissionsState();
5525
5526            final int flags = permissionsState.getPermissionFlags(name, userId);
5527            if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) {
5528                throw new SecurityException("Cannot revoke system fixed permission "
5529                        + name + " for package " + packageName);
5530            }
5531            if (!overridePolicy && (flags & PackageManager.FLAG_PERMISSION_POLICY_FIXED) != 0) {
5532                throw new SecurityException("Cannot revoke policy fixed permission "
5533                        + name + " for package " + packageName);
5534            }
5535
5536            if (bp.isDevelopment()) {
5537                // Development permissions must be handled specially, since they are not
5538                // normal runtime permissions.  For now they apply to all users.
5539                if (permissionsState.revokeInstallPermission(bp) !=
5540                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
5541                    scheduleWriteSettingsLocked();
5542                }
5543                return;
5544            }
5545
5546            if (permissionsState.revokeRuntimePermission(bp, userId) ==
5547                    PermissionsState.PERMISSION_OPERATION_FAILURE) {
5548                return;
5549            }
5550
5551            if (bp.isRuntime()) {
5552                logPermissionRevoked(mContext, name, packageName);
5553            }
5554
5555            mOnPermissionChangeListeners.onPermissionsChanged(pkg.applicationInfo.uid);
5556
5557            // Critical, after this call app should never have the permission.
5558            mSettings.writeRuntimePermissionsForUserLPr(userId, true);
5559
5560            appId = UserHandle.getAppId(pkg.applicationInfo.uid);
5561        }
5562
5563        killUid(appId, userId, KILL_APP_REASON_PERMISSIONS_REVOKED);
5564    }
5565
5566    /**
5567     * Get the first event id for the permission.
5568     *
5569     * <p>There are four events for each permission: <ul>
5570     *     <li>Request permission: first id + 0</li>
5571     *     <li>Grant permission: first id + 1</li>
5572     *     <li>Request for permission denied: first id + 2</li>
5573     *     <li>Revoke permission: first id + 3</li>
5574     * </ul></p>
5575     *
5576     * @param name name of the permission
5577     *
5578     * @return The first event id for the permission
5579     */
5580    private static int getBaseEventId(@NonNull String name) {
5581        int eventIdIndex = ALL_DANGEROUS_PERMISSIONS.indexOf(name);
5582
5583        if (eventIdIndex == -1) {
5584            if (AppOpsManager.permissionToOpCode(name) == AppOpsManager.OP_NONE
5585                    || "user".equals(Build.TYPE)) {
5586                Log.i(TAG, "Unknown permission " + name);
5587
5588                return MetricsEvent.ACTION_PERMISSION_REQUEST_UNKNOWN;
5589            } else {
5590                // Most likely #ALL_DANGEROUS_PERMISSIONS needs to be updated.
5591                //
5592                // Also update
5593                // - EventLogger#ALL_DANGEROUS_PERMISSIONS
5594                // - metrics_constants.proto
5595                throw new IllegalStateException("Unknown permission " + name);
5596            }
5597        }
5598
5599        return MetricsEvent.ACTION_PERMISSION_REQUEST_READ_CALENDAR + eventIdIndex * 4;
5600    }
5601
5602    /**
5603     * Log that a permission was revoked.
5604     *
5605     * @param context Context of the caller
5606     * @param name name of the permission
5607     * @param packageName package permission if for
5608     */
5609    private static void logPermissionRevoked(@NonNull Context context, @NonNull String name,
5610            @NonNull String packageName) {
5611        MetricsLogger.action(context, getBaseEventId(name) + 3, packageName);
5612    }
5613
5614    /**
5615     * Log that a permission request was granted.
5616     *
5617     * @param context Context of the caller
5618     * @param name name of the permission
5619     * @param packageName package permission if for
5620     */
5621    private static void logPermissionGranted(@NonNull Context context, @NonNull String name,
5622            @NonNull String packageName) {
5623        MetricsLogger.action(context, getBaseEventId(name) + 1, packageName);
5624    }
5625
5626    @Override
5627    public void resetRuntimePermissions() {
5628        mContext.enforceCallingOrSelfPermission(
5629                android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS,
5630                "revokeRuntimePermission");
5631
5632        int callingUid = Binder.getCallingUid();
5633        if (callingUid != Process.SYSTEM_UID && callingUid != 0) {
5634            mContext.enforceCallingOrSelfPermission(
5635                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
5636                    "resetRuntimePermissions");
5637        }
5638
5639        synchronized (mPackages) {
5640            updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL);
5641            for (int userId : UserManagerService.getInstance().getUserIds()) {
5642                final int packageCount = mPackages.size();
5643                for (int i = 0; i < packageCount; i++) {
5644                    PackageParser.Package pkg = mPackages.valueAt(i);
5645                    if (!(pkg.mExtras instanceof PackageSetting)) {
5646                        continue;
5647                    }
5648                    PackageSetting ps = (PackageSetting) pkg.mExtras;
5649                    resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
5650                }
5651            }
5652        }
5653    }
5654
5655    @Override
5656    public int getPermissionFlags(String name, String packageName, int userId) {
5657        if (!sUserManager.exists(userId)) {
5658            return 0;
5659        }
5660
5661        enforceGrantRevokeRuntimePermissionPermissions("getPermissionFlags");
5662
5663        final int callingUid = Binder.getCallingUid();
5664        enforceCrossUserPermission(callingUid, userId,
5665                true /* requireFullPermission */, false /* checkShell */,
5666                "getPermissionFlags");
5667
5668        synchronized (mPackages) {
5669            final PackageParser.Package pkg = mPackages.get(packageName);
5670            if (pkg == null) {
5671                return 0;
5672            }
5673            final BasePermission bp = mSettings.mPermissions.get(name);
5674            if (bp == null) {
5675                return 0;
5676            }
5677            final PackageSetting ps = (PackageSetting) pkg.mExtras;
5678            if (ps == null
5679                    || filterAppAccessLPr(ps, callingUid, userId)) {
5680                return 0;
5681            }
5682            PermissionsState permissionsState = ps.getPermissionsState();
5683            return permissionsState.getPermissionFlags(name, userId);
5684        }
5685    }
5686
5687    @Override
5688    public void updatePermissionFlags(String name, String packageName, int flagMask,
5689            int flagValues, int userId) {
5690        if (!sUserManager.exists(userId)) {
5691            return;
5692        }
5693
5694        enforceGrantRevokeRuntimePermissionPermissions("updatePermissionFlags");
5695
5696        final int callingUid = Binder.getCallingUid();
5697        enforceCrossUserPermission(callingUid, userId,
5698                true /* requireFullPermission */, true /* checkShell */,
5699                "updatePermissionFlags");
5700
5701        // Only the system can change these flags and nothing else.
5702        if (getCallingUid() != Process.SYSTEM_UID) {
5703            flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
5704            flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
5705            flagMask &= ~PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT;
5706            flagValues &= ~PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT;
5707            flagValues &= ~PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED;
5708        }
5709
5710        synchronized (mPackages) {
5711            final PackageParser.Package pkg = mPackages.get(packageName);
5712            if (pkg == null) {
5713                throw new IllegalArgumentException("Unknown package: " + packageName);
5714            }
5715            final PackageSetting ps = (PackageSetting) pkg.mExtras;
5716            if (ps == null
5717                    || filterAppAccessLPr(ps, callingUid, userId)) {
5718                throw new IllegalArgumentException("Unknown package: " + packageName);
5719            }
5720
5721            final BasePermission bp = mSettings.mPermissions.get(name);
5722            if (bp == null) {
5723                throw new IllegalArgumentException("Unknown permission: " + name);
5724            }
5725
5726            PermissionsState permissionsState = ps.getPermissionsState();
5727
5728            boolean hadState = permissionsState.getRuntimePermissionState(name, userId) != null;
5729
5730            if (permissionsState.updatePermissionFlags(bp, userId, flagMask, flagValues)) {
5731                // Install and runtime permissions are stored in different places,
5732                // so figure out what permission changed and persist the change.
5733                if (permissionsState.getInstallPermissionState(name) != null) {
5734                    scheduleWriteSettingsLocked();
5735                } else if (permissionsState.getRuntimePermissionState(name, userId) != null
5736                        || hadState) {
5737                    mSettings.writeRuntimePermissionsForUserLPr(userId, false);
5738                }
5739            }
5740        }
5741    }
5742
5743    /**
5744     * Update the permission flags for all packages and runtime permissions of a user in order
5745     * to allow device or profile owner to remove POLICY_FIXED.
5746     */
5747    @Override
5748    public void updatePermissionFlagsForAllApps(int flagMask, int flagValues, int userId) {
5749        if (!sUserManager.exists(userId)) {
5750            return;
5751        }
5752
5753        enforceGrantRevokeRuntimePermissionPermissions("updatePermissionFlagsForAllApps");
5754
5755        enforceCrossUserPermission(Binder.getCallingUid(), userId,
5756                true /* requireFullPermission */, true /* checkShell */,
5757                "updatePermissionFlagsForAllApps");
5758
5759        // Only the system can change system fixed flags.
5760        if (getCallingUid() != Process.SYSTEM_UID) {
5761            flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
5762            flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
5763        }
5764
5765        synchronized (mPackages) {
5766            boolean changed = false;
5767            final int packageCount = mPackages.size();
5768            for (int pkgIndex = 0; pkgIndex < packageCount; pkgIndex++) {
5769                final PackageParser.Package pkg = mPackages.valueAt(pkgIndex);
5770                final PackageSetting ps = (PackageSetting) pkg.mExtras;
5771                if (ps == null) {
5772                    continue;
5773                }
5774                PermissionsState permissionsState = ps.getPermissionsState();
5775                changed |= permissionsState.updatePermissionFlagsForAllPermissions(
5776                        userId, flagMask, flagValues);
5777            }
5778            if (changed) {
5779                mSettings.writeRuntimePermissionsForUserLPr(userId, false);
5780            }
5781        }
5782    }
5783
5784    private void enforceGrantRevokeRuntimePermissionPermissions(String message) {
5785        if (mContext.checkCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS)
5786                != PackageManager.PERMISSION_GRANTED
5787            && mContext.checkCallingOrSelfPermission(Manifest.permission.REVOKE_RUNTIME_PERMISSIONS)
5788                != PackageManager.PERMISSION_GRANTED) {
5789            throw new SecurityException(message + " requires "
5790                    + Manifest.permission.GRANT_RUNTIME_PERMISSIONS + " or "
5791                    + Manifest.permission.REVOKE_RUNTIME_PERMISSIONS);
5792        }
5793    }
5794
5795    @Override
5796    public boolean shouldShowRequestPermissionRationale(String permissionName,
5797            String packageName, int userId) {
5798        if (UserHandle.getCallingUserId() != userId) {
5799            mContext.enforceCallingPermission(
5800                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
5801                    "canShowRequestPermissionRationale for user " + userId);
5802        }
5803
5804        final int uid = getPackageUid(packageName, MATCH_DEBUG_TRIAGED_MISSING, userId);
5805        if (UserHandle.getAppId(getCallingUid()) != UserHandle.getAppId(uid)) {
5806            return false;
5807        }
5808
5809        if (checkPermission(permissionName, packageName, userId)
5810                == PackageManager.PERMISSION_GRANTED) {
5811            return false;
5812        }
5813
5814        final int flags;
5815
5816        final long identity = Binder.clearCallingIdentity();
5817        try {
5818            flags = getPermissionFlags(permissionName,
5819                    packageName, userId);
5820        } finally {
5821            Binder.restoreCallingIdentity(identity);
5822        }
5823
5824        final int fixedFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED
5825                | PackageManager.FLAG_PERMISSION_POLICY_FIXED
5826                | PackageManager.FLAG_PERMISSION_USER_FIXED;
5827
5828        if ((flags & fixedFlags) != 0) {
5829            return false;
5830        }
5831
5832        return (flags & PackageManager.FLAG_PERMISSION_USER_SET) != 0;
5833    }
5834
5835    @Override
5836    public void addOnPermissionsChangeListener(IOnPermissionsChangeListener listener) {
5837        mContext.enforceCallingOrSelfPermission(
5838                Manifest.permission.OBSERVE_GRANT_REVOKE_PERMISSIONS,
5839                "addOnPermissionsChangeListener");
5840
5841        synchronized (mPackages) {
5842            mOnPermissionChangeListeners.addListenerLocked(listener);
5843        }
5844    }
5845
5846    @Override
5847    public void removeOnPermissionsChangeListener(IOnPermissionsChangeListener listener) {
5848        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
5849            throw new SecurityException("Instant applications don't have access to this method");
5850        }
5851        synchronized (mPackages) {
5852            mOnPermissionChangeListeners.removeListenerLocked(listener);
5853        }
5854    }
5855
5856    @Override
5857    public boolean isProtectedBroadcast(String actionName) {
5858        // allow instant applications
5859        synchronized (mPackages) {
5860            if (mProtectedBroadcasts.contains(actionName)) {
5861                return true;
5862            } else if (actionName != null) {
5863                // TODO: remove these terrible hacks
5864                if (actionName.startsWith("android.net.netmon.lingerExpired")
5865                        || actionName.startsWith("com.android.server.sip.SipWakeupTimer")
5866                        || actionName.startsWith("com.android.internal.telephony.data-reconnect")
5867                        || actionName.startsWith("android.net.netmon.launchCaptivePortalApp")) {
5868                    return true;
5869                }
5870            }
5871        }
5872        return false;
5873    }
5874
5875    @Override
5876    public int checkSignatures(String pkg1, String pkg2) {
5877        synchronized (mPackages) {
5878            final PackageParser.Package p1 = mPackages.get(pkg1);
5879            final PackageParser.Package p2 = mPackages.get(pkg2);
5880            if (p1 == null || p1.mExtras == null
5881                    || p2 == null || p2.mExtras == null) {
5882                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5883            }
5884            final int callingUid = Binder.getCallingUid();
5885            final int callingUserId = UserHandle.getUserId(callingUid);
5886            final PackageSetting ps1 = (PackageSetting) p1.mExtras;
5887            final PackageSetting ps2 = (PackageSetting) p2.mExtras;
5888            if (filterAppAccessLPr(ps1, callingUid, callingUserId)
5889                    || filterAppAccessLPr(ps2, callingUid, callingUserId)) {
5890                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5891            }
5892            return compareSignatures(p1.mSignatures, p2.mSignatures);
5893        }
5894    }
5895
5896    @Override
5897    public int checkUidSignatures(int uid1, int uid2) {
5898        final int callingUid = Binder.getCallingUid();
5899        final int callingUserId = UserHandle.getUserId(callingUid);
5900        final boolean isCallerInstantApp = getInstantAppPackageName(callingUid) != null;
5901        // Map to base uids.
5902        uid1 = UserHandle.getAppId(uid1);
5903        uid2 = UserHandle.getAppId(uid2);
5904        // reader
5905        synchronized (mPackages) {
5906            Signature[] s1;
5907            Signature[] s2;
5908            Object obj = mSettings.getUserIdLPr(uid1);
5909            if (obj != null) {
5910                if (obj instanceof SharedUserSetting) {
5911                    if (isCallerInstantApp) {
5912                        return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5913                    }
5914                    s1 = ((SharedUserSetting)obj).signatures.mSignatures;
5915                } else if (obj instanceof PackageSetting) {
5916                    final PackageSetting ps = (PackageSetting) obj;
5917                    if (filterAppAccessLPr(ps, callingUid, callingUserId)) {
5918                        return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5919                    }
5920                    s1 = ps.signatures.mSignatures;
5921                } else {
5922                    return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5923                }
5924            } else {
5925                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5926            }
5927            obj = mSettings.getUserIdLPr(uid2);
5928            if (obj != null) {
5929                if (obj instanceof SharedUserSetting) {
5930                    if (isCallerInstantApp) {
5931                        return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5932                    }
5933                    s2 = ((SharedUserSetting)obj).signatures.mSignatures;
5934                } else if (obj instanceof PackageSetting) {
5935                    final PackageSetting ps = (PackageSetting) obj;
5936                    if (filterAppAccessLPr(ps, callingUid, callingUserId)) {
5937                        return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5938                    }
5939                    s2 = ps.signatures.mSignatures;
5940                } else {
5941                    return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5942                }
5943            } else {
5944                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5945            }
5946            return compareSignatures(s1, s2);
5947        }
5948    }
5949
5950    /**
5951     * This method should typically only be used when granting or revoking
5952     * permissions, since the app may immediately restart after this call.
5953     * <p>
5954     * If you're doing surgery on app code/data, use {@link PackageFreezer} to
5955     * guard your work against the app being relaunched.
5956     */
5957    private void killUid(int appId, int userId, String reason) {
5958        final long identity = Binder.clearCallingIdentity();
5959        try {
5960            IActivityManager am = ActivityManager.getService();
5961            if (am != null) {
5962                try {
5963                    am.killUid(appId, userId, reason);
5964                } catch (RemoteException e) {
5965                    /* ignore - same process */
5966                }
5967            }
5968        } finally {
5969            Binder.restoreCallingIdentity(identity);
5970        }
5971    }
5972
5973    /**
5974     * Compares two sets of signatures. Returns:
5975     * <br />
5976     * {@link PackageManager#SIGNATURE_NEITHER_SIGNED}: if both signature sets are null,
5977     * <br />
5978     * {@link PackageManager#SIGNATURE_FIRST_NOT_SIGNED}: if the first signature set is null,
5979     * <br />
5980     * {@link PackageManager#SIGNATURE_SECOND_NOT_SIGNED}: if the second signature set is null,
5981     * <br />
5982     * {@link PackageManager#SIGNATURE_MATCH}: if the two signature sets are identical,
5983     * <br />
5984     * {@link PackageManager#SIGNATURE_NO_MATCH}: if the two signature sets differ.
5985     */
5986    static int compareSignatures(Signature[] s1, Signature[] s2) {
5987        if (s1 == null) {
5988            return s2 == null
5989                    ? PackageManager.SIGNATURE_NEITHER_SIGNED
5990                    : PackageManager.SIGNATURE_FIRST_NOT_SIGNED;
5991        }
5992
5993        if (s2 == null) {
5994            return PackageManager.SIGNATURE_SECOND_NOT_SIGNED;
5995        }
5996
5997        if (s1.length != s2.length) {
5998            return PackageManager.SIGNATURE_NO_MATCH;
5999        }
6000
6001        // Since both signature sets are of size 1, we can compare without HashSets.
6002        if (s1.length == 1) {
6003            return s1[0].equals(s2[0]) ?
6004                    PackageManager.SIGNATURE_MATCH :
6005                    PackageManager.SIGNATURE_NO_MATCH;
6006        }
6007
6008        ArraySet<Signature> set1 = new ArraySet<Signature>();
6009        for (Signature sig : s1) {
6010            set1.add(sig);
6011        }
6012        ArraySet<Signature> set2 = new ArraySet<Signature>();
6013        for (Signature sig : s2) {
6014            set2.add(sig);
6015        }
6016        // Make sure s2 contains all signatures in s1.
6017        if (set1.equals(set2)) {
6018            return PackageManager.SIGNATURE_MATCH;
6019        }
6020        return PackageManager.SIGNATURE_NO_MATCH;
6021    }
6022
6023    /**
6024     * If the database version for this type of package (internal storage or
6025     * external storage) is less than the version where package signatures
6026     * were updated, return true.
6027     */
6028    private boolean isCompatSignatureUpdateNeeded(PackageParser.Package scannedPkg) {
6029        final VersionInfo ver = getSettingsVersionForPackage(scannedPkg);
6030        return ver.databaseVersion < DatabaseVersion.SIGNATURE_END_ENTITY;
6031    }
6032
6033    /**
6034     * Used for backward compatibility to make sure any packages with
6035     * certificate chains get upgraded to the new style. {@code existingSigs}
6036     * will be in the old format (since they were stored on disk from before the
6037     * system upgrade) and {@code scannedSigs} will be in the newer format.
6038     */
6039    private int compareSignaturesCompat(PackageSignatures existingSigs,
6040            PackageParser.Package scannedPkg) {
6041        if (!isCompatSignatureUpdateNeeded(scannedPkg)) {
6042            return PackageManager.SIGNATURE_NO_MATCH;
6043        }
6044
6045        ArraySet<Signature> existingSet = new ArraySet<Signature>();
6046        for (Signature sig : existingSigs.mSignatures) {
6047            existingSet.add(sig);
6048        }
6049        ArraySet<Signature> scannedCompatSet = new ArraySet<Signature>();
6050        for (Signature sig : scannedPkg.mSignatures) {
6051            try {
6052                Signature[] chainSignatures = sig.getChainSignatures();
6053                for (Signature chainSig : chainSignatures) {
6054                    scannedCompatSet.add(chainSig);
6055                }
6056            } catch (CertificateEncodingException e) {
6057                scannedCompatSet.add(sig);
6058            }
6059        }
6060        /*
6061         * Make sure the expanded scanned set contains all signatures in the
6062         * existing one.
6063         */
6064        if (scannedCompatSet.equals(existingSet)) {
6065            // Migrate the old signatures to the new scheme.
6066            existingSigs.assignSignatures(scannedPkg.mSignatures);
6067            // The new KeySets will be re-added later in the scanning process.
6068            synchronized (mPackages) {
6069                mSettings.mKeySetManagerService.removeAppKeySetDataLPw(scannedPkg.packageName);
6070            }
6071            return PackageManager.SIGNATURE_MATCH;
6072        }
6073        return PackageManager.SIGNATURE_NO_MATCH;
6074    }
6075
6076    private boolean isRecoverSignatureUpdateNeeded(PackageParser.Package scannedPkg) {
6077        final VersionInfo ver = getSettingsVersionForPackage(scannedPkg);
6078        return ver.databaseVersion < DatabaseVersion.SIGNATURE_MALFORMED_RECOVER;
6079    }
6080
6081    private int compareSignaturesRecover(PackageSignatures existingSigs,
6082            PackageParser.Package scannedPkg) {
6083        if (!isRecoverSignatureUpdateNeeded(scannedPkg)) {
6084            return PackageManager.SIGNATURE_NO_MATCH;
6085        }
6086
6087        String msg = null;
6088        try {
6089            if (Signature.areEffectiveMatch(existingSigs.mSignatures, scannedPkg.mSignatures)) {
6090                logCriticalInfo(Log.INFO, "Recovered effectively matching certificates for "
6091                        + scannedPkg.packageName);
6092                return PackageManager.SIGNATURE_MATCH;
6093            }
6094        } catch (CertificateException e) {
6095            msg = e.getMessage();
6096        }
6097
6098        logCriticalInfo(Log.INFO,
6099                "Failed to recover certificates for " + scannedPkg.packageName + ": " + msg);
6100        return PackageManager.SIGNATURE_NO_MATCH;
6101    }
6102
6103    @Override
6104    public List<String> getAllPackages() {
6105        final int callingUid = Binder.getCallingUid();
6106        final int callingUserId = UserHandle.getUserId(callingUid);
6107        synchronized (mPackages) {
6108            if (canViewInstantApps(callingUid, callingUserId)) {
6109                return new ArrayList<String>(mPackages.keySet());
6110            }
6111            final String instantAppPkgName = getInstantAppPackageName(callingUid);
6112            final List<String> result = new ArrayList<>();
6113            if (instantAppPkgName != null) {
6114                // caller is an instant application; filter unexposed applications
6115                for (PackageParser.Package pkg : mPackages.values()) {
6116                    if (!pkg.visibleToInstantApps) {
6117                        continue;
6118                    }
6119                    result.add(pkg.packageName);
6120                }
6121            } else {
6122                // caller is a normal application; filter instant applications
6123                for (PackageParser.Package pkg : mPackages.values()) {
6124                    final PackageSetting ps =
6125                            pkg.mExtras != null ? (PackageSetting) pkg.mExtras : null;
6126                    if (ps != null
6127                            && ps.getInstantApp(callingUserId)
6128                            && !mInstantAppRegistry.isInstantAccessGranted(
6129                                    callingUserId, UserHandle.getAppId(callingUid), ps.appId)) {
6130                        continue;
6131                    }
6132                    result.add(pkg.packageName);
6133                }
6134            }
6135            return result;
6136        }
6137    }
6138
6139    @Override
6140    public String[] getPackagesForUid(int uid) {
6141        final int callingUid = Binder.getCallingUid();
6142        final boolean isCallerInstantApp = getInstantAppPackageName(callingUid) != null;
6143        final int userId = UserHandle.getUserId(uid);
6144        uid = UserHandle.getAppId(uid);
6145        // reader
6146        synchronized (mPackages) {
6147            Object obj = mSettings.getUserIdLPr(uid);
6148            if (obj instanceof SharedUserSetting) {
6149                if (isCallerInstantApp) {
6150                    return null;
6151                }
6152                final SharedUserSetting sus = (SharedUserSetting) obj;
6153                final int N = sus.packages.size();
6154                String[] res = new String[N];
6155                final Iterator<PackageSetting> it = sus.packages.iterator();
6156                int i = 0;
6157                while (it.hasNext()) {
6158                    PackageSetting ps = it.next();
6159                    if (ps.getInstalled(userId)) {
6160                        res[i++] = ps.name;
6161                    } else {
6162                        res = ArrayUtils.removeElement(String.class, res, res[i]);
6163                    }
6164                }
6165                return res;
6166            } else if (obj instanceof PackageSetting) {
6167                final PackageSetting ps = (PackageSetting) obj;
6168                if (ps.getInstalled(userId) && !filterAppAccessLPr(ps, callingUid, userId)) {
6169                    return new String[]{ps.name};
6170                }
6171            }
6172        }
6173        return null;
6174    }
6175
6176    @Override
6177    public String getNameForUid(int uid) {
6178        final int callingUid = Binder.getCallingUid();
6179        if (getInstantAppPackageName(callingUid) != null) {
6180            return null;
6181        }
6182        synchronized (mPackages) {
6183            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
6184            if (obj instanceof SharedUserSetting) {
6185                final SharedUserSetting sus = (SharedUserSetting) obj;
6186                return sus.name + ":" + sus.userId;
6187            } else if (obj instanceof PackageSetting) {
6188                final PackageSetting ps = (PackageSetting) obj;
6189                if (filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
6190                    return null;
6191                }
6192                return ps.name;
6193            }
6194        }
6195        return null;
6196    }
6197
6198    @Override
6199    public int getUidForSharedUser(String sharedUserName) {
6200        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
6201            return -1;
6202        }
6203        if (sharedUserName == null) {
6204            return -1;
6205        }
6206        // reader
6207        synchronized (mPackages) {
6208            SharedUserSetting suid;
6209            try {
6210                suid = mSettings.getSharedUserLPw(sharedUserName, 0, 0, false);
6211                if (suid != null) {
6212                    return suid.userId;
6213                }
6214            } catch (PackageManagerException ignore) {
6215                // can't happen, but, still need to catch it
6216            }
6217            return -1;
6218        }
6219    }
6220
6221    @Override
6222    public int getFlagsForUid(int uid) {
6223        final int callingUid = Binder.getCallingUid();
6224        if (getInstantAppPackageName(callingUid) != null) {
6225            return 0;
6226        }
6227        synchronized (mPackages) {
6228            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
6229            if (obj instanceof SharedUserSetting) {
6230                final SharedUserSetting sus = (SharedUserSetting) obj;
6231                return sus.pkgFlags;
6232            } else if (obj instanceof PackageSetting) {
6233                final PackageSetting ps = (PackageSetting) obj;
6234                if (filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
6235                    return 0;
6236                }
6237                return ps.pkgFlags;
6238            }
6239        }
6240        return 0;
6241    }
6242
6243    @Override
6244    public int getPrivateFlagsForUid(int uid) {
6245        final int callingUid = Binder.getCallingUid();
6246        if (getInstantAppPackageName(callingUid) != null) {
6247            return 0;
6248        }
6249        synchronized (mPackages) {
6250            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
6251            if (obj instanceof SharedUserSetting) {
6252                final SharedUserSetting sus = (SharedUserSetting) obj;
6253                return sus.pkgPrivateFlags;
6254            } else if (obj instanceof PackageSetting) {
6255                final PackageSetting ps = (PackageSetting) obj;
6256                if (filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
6257                    return 0;
6258                }
6259                return ps.pkgPrivateFlags;
6260            }
6261        }
6262        return 0;
6263    }
6264
6265    @Override
6266    public boolean isUidPrivileged(int uid) {
6267        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
6268            return false;
6269        }
6270        uid = UserHandle.getAppId(uid);
6271        // reader
6272        synchronized (mPackages) {
6273            Object obj = mSettings.getUserIdLPr(uid);
6274            if (obj instanceof SharedUserSetting) {
6275                final SharedUserSetting sus = (SharedUserSetting) obj;
6276                final Iterator<PackageSetting> it = sus.packages.iterator();
6277                while (it.hasNext()) {
6278                    if (it.next().isPrivileged()) {
6279                        return true;
6280                    }
6281                }
6282            } else if (obj instanceof PackageSetting) {
6283                final PackageSetting ps = (PackageSetting) obj;
6284                return ps.isPrivileged();
6285            }
6286        }
6287        return false;
6288    }
6289
6290    @Override
6291    public String[] getAppOpPermissionPackages(String permissionName) {
6292        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
6293            return null;
6294        }
6295        synchronized (mPackages) {
6296            ArraySet<String> pkgs = mAppOpPermissionPackages.get(permissionName);
6297            if (pkgs == null) {
6298                return null;
6299            }
6300            return pkgs.toArray(new String[pkgs.size()]);
6301        }
6302    }
6303
6304    @Override
6305    public ResolveInfo resolveIntent(Intent intent, String resolvedType,
6306            int flags, int userId) {
6307        return resolveIntentInternal(
6308                intent, resolvedType, flags, userId, false /*includeInstantApps*/);
6309    }
6310
6311    private ResolveInfo resolveIntentInternal(Intent intent, String resolvedType,
6312            int flags, int userId, boolean resolveForStart) {
6313        try {
6314            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "resolveIntent");
6315
6316            if (!sUserManager.exists(userId)) return null;
6317            final int callingUid = Binder.getCallingUid();
6318            flags = updateFlagsForResolve(flags, userId, intent, callingUid, resolveForStart);
6319            enforceCrossUserPermission(callingUid, userId,
6320                    false /*requireFullPermission*/, false /*checkShell*/, "resolve intent");
6321
6322            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "queryIntentActivities");
6323            final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType,
6324                    flags, callingUid, userId, resolveForStart);
6325            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
6326
6327            final ResolveInfo bestChoice =
6328                    chooseBestActivity(intent, resolvedType, flags, query, userId);
6329            return bestChoice;
6330        } finally {
6331            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
6332        }
6333    }
6334
6335    @Override
6336    public ResolveInfo findPersistentPreferredActivity(Intent intent, int userId) {
6337        if (!UserHandle.isSameApp(Binder.getCallingUid(), Process.SYSTEM_UID)) {
6338            throw new SecurityException(
6339                    "findPersistentPreferredActivity can only be run by the system");
6340        }
6341        if (!sUserManager.exists(userId)) {
6342            return null;
6343        }
6344        final int callingUid = Binder.getCallingUid();
6345        intent = updateIntentForResolve(intent);
6346        final String resolvedType = intent.resolveTypeIfNeeded(mContext.getContentResolver());
6347        final int flags = updateFlagsForResolve(
6348                0, userId, intent, callingUid, false /*includeInstantApps*/);
6349        final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags,
6350                userId);
6351        synchronized (mPackages) {
6352            return findPersistentPreferredActivityLP(intent, resolvedType, flags, query, false,
6353                    userId);
6354        }
6355    }
6356
6357    @Override
6358    public void setLastChosenActivity(Intent intent, String resolvedType, int flags,
6359            IntentFilter filter, int match, ComponentName activity) {
6360        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
6361            return;
6362        }
6363        final int userId = UserHandle.getCallingUserId();
6364        if (DEBUG_PREFERRED) {
6365            Log.v(TAG, "setLastChosenActivity intent=" + intent
6366                + " resolvedType=" + resolvedType
6367                + " flags=" + flags
6368                + " filter=" + filter
6369                + " match=" + match
6370                + " activity=" + activity);
6371            filter.dump(new PrintStreamPrinter(System.out), "    ");
6372        }
6373        intent.setComponent(null);
6374        final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags,
6375                userId);
6376        // Find any earlier preferred or last chosen entries and nuke them
6377        findPreferredActivity(intent, resolvedType,
6378                flags, query, 0, false, true, false, userId);
6379        // Add the new activity as the last chosen for this filter
6380        addPreferredActivityInternal(filter, match, null, activity, false, userId,
6381                "Setting last chosen");
6382    }
6383
6384    @Override
6385    public ResolveInfo getLastChosenActivity(Intent intent, String resolvedType, int flags) {
6386        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
6387            return null;
6388        }
6389        final int userId = UserHandle.getCallingUserId();
6390        if (DEBUG_PREFERRED) Log.v(TAG, "Querying last chosen activity for " + intent);
6391        final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags,
6392                userId);
6393        return findPreferredActivity(intent, resolvedType, flags, query, 0,
6394                false, false, false, userId);
6395    }
6396
6397    /**
6398     * Returns whether or not instant apps have been disabled remotely.
6399     */
6400    private boolean isEphemeralDisabled() {
6401        return mEphemeralAppsDisabled;
6402    }
6403
6404    private boolean isInstantAppAllowed(
6405            Intent intent, List<ResolveInfo> resolvedActivities, int userId,
6406            boolean skipPackageCheck) {
6407        if (mInstantAppResolverConnection == null) {
6408            return false;
6409        }
6410        if (mInstantAppInstallerActivity == null) {
6411            return false;
6412        }
6413        if (intent.getComponent() != null) {
6414            return false;
6415        }
6416        if ((intent.getFlags() & Intent.FLAG_IGNORE_EPHEMERAL) != 0) {
6417            return false;
6418        }
6419        if (!skipPackageCheck && intent.getPackage() != null) {
6420            return false;
6421        }
6422        final boolean isWebUri = hasWebURI(intent);
6423        if (!isWebUri || intent.getData().getHost() == null) {
6424            return false;
6425        }
6426        // Deny ephemeral apps if the user chose _ALWAYS or _ALWAYS_ASK for intent resolution.
6427        // Or if there's already an ephemeral app installed that handles the action
6428        synchronized (mPackages) {
6429            final int count = (resolvedActivities == null ? 0 : resolvedActivities.size());
6430            for (int n = 0; n < count; n++) {
6431                final ResolveInfo info = resolvedActivities.get(n);
6432                final String packageName = info.activityInfo.packageName;
6433                final PackageSetting ps = mSettings.mPackages.get(packageName);
6434                if (ps != null) {
6435                    // only check domain verification status if the app is not a browser
6436                    if (!info.handleAllWebDataURI) {
6437                        // Try to get the status from User settings first
6438                        final long packedStatus = getDomainVerificationStatusLPr(ps, userId);
6439                        final int status = (int) (packedStatus >> 32);
6440                        if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS
6441                            || status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) {
6442                            if (DEBUG_EPHEMERAL) {
6443                                Slog.v(TAG, "DENY instant app;"
6444                                    + " pkg: " + packageName + ", status: " + status);
6445                            }
6446                            return false;
6447                        }
6448                    }
6449                    if (ps.getInstantApp(userId)) {
6450                        if (DEBUG_EPHEMERAL) {
6451                            Slog.v(TAG, "DENY instant app installed;"
6452                                    + " pkg: " + packageName);
6453                        }
6454                        return false;
6455                    }
6456                }
6457            }
6458        }
6459        // We've exhausted all ways to deny ephemeral application; let the system look for them.
6460        return true;
6461    }
6462
6463    private void requestInstantAppResolutionPhaseTwo(AuxiliaryResolveInfo responseObj,
6464            Intent origIntent, String resolvedType, String callingPackage,
6465            Bundle verificationBundle, int userId) {
6466        final Message msg = mHandler.obtainMessage(INSTANT_APP_RESOLUTION_PHASE_TWO,
6467                new InstantAppRequest(responseObj, origIntent, resolvedType,
6468                        callingPackage, userId, verificationBundle));
6469        mHandler.sendMessage(msg);
6470    }
6471
6472    private ResolveInfo chooseBestActivity(Intent intent, String resolvedType,
6473            int flags, List<ResolveInfo> query, int userId) {
6474        if (query != null) {
6475            final int N = query.size();
6476            if (N == 1) {
6477                return query.get(0);
6478            } else if (N > 1) {
6479                final boolean debug = ((intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0);
6480                // If there is more than one activity with the same priority,
6481                // then let the user decide between them.
6482                ResolveInfo r0 = query.get(0);
6483                ResolveInfo r1 = query.get(1);
6484                if (DEBUG_INTENT_MATCHING || debug) {
6485                    Slog.v(TAG, r0.activityInfo.name + "=" + r0.priority + " vs "
6486                            + r1.activityInfo.name + "=" + r1.priority);
6487                }
6488                // If the first activity has a higher priority, or a different
6489                // default, then it is always desirable to pick it.
6490                if (r0.priority != r1.priority
6491                        || r0.preferredOrder != r1.preferredOrder
6492                        || r0.isDefault != r1.isDefault) {
6493                    return query.get(0);
6494                }
6495                // If we have saved a preference for a preferred activity for
6496                // this Intent, use that.
6497                ResolveInfo ri = findPreferredActivity(intent, resolvedType,
6498                        flags, query, r0.priority, true, false, debug, userId);
6499                if (ri != null) {
6500                    return ri;
6501                }
6502                // If we have an ephemeral app, use it
6503                for (int i = 0; i < N; i++) {
6504                    ri = query.get(i);
6505                    if (ri.activityInfo.applicationInfo.isInstantApp()) {
6506                        final String packageName = ri.activityInfo.packageName;
6507                        final PackageSetting ps = mSettings.mPackages.get(packageName);
6508                        final long packedStatus = getDomainVerificationStatusLPr(ps, userId);
6509                        final int status = (int)(packedStatus >> 32);
6510                        if (status != INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) {
6511                            return ri;
6512                        }
6513                    }
6514                }
6515                ri = new ResolveInfo(mResolveInfo);
6516                ri.activityInfo = new ActivityInfo(ri.activityInfo);
6517                ri.activityInfo.labelRes = ResolverActivity.getLabelRes(intent.getAction());
6518                // If all of the options come from the same package, show the application's
6519                // label and icon instead of the generic resolver's.
6520                // Some calls like Intent.resolveActivityInfo query the ResolveInfo from here
6521                // and then throw away the ResolveInfo itself, meaning that the caller loses
6522                // the resolvePackageName. Therefore the activityInfo.labelRes above provides
6523                // a fallback for this case; we only set the target package's resources on
6524                // the ResolveInfo, not the ActivityInfo.
6525                final String intentPackage = intent.getPackage();
6526                if (!TextUtils.isEmpty(intentPackage) && allHavePackage(query, intentPackage)) {
6527                    final ApplicationInfo appi = query.get(0).activityInfo.applicationInfo;
6528                    ri.resolvePackageName = intentPackage;
6529                    if (userNeedsBadging(userId)) {
6530                        ri.noResourceId = true;
6531                    } else {
6532                        ri.icon = appi.icon;
6533                    }
6534                    ri.iconResourceId = appi.icon;
6535                    ri.labelRes = appi.labelRes;
6536                }
6537                ri.activityInfo.applicationInfo = new ApplicationInfo(
6538                        ri.activityInfo.applicationInfo);
6539                if (userId != 0) {
6540                    ri.activityInfo.applicationInfo.uid = UserHandle.getUid(userId,
6541                            UserHandle.getAppId(ri.activityInfo.applicationInfo.uid));
6542                }
6543                // Make sure that the resolver is displayable in car mode
6544                if (ri.activityInfo.metaData == null) ri.activityInfo.metaData = new Bundle();
6545                ri.activityInfo.metaData.putBoolean(Intent.METADATA_DOCK_HOME, true);
6546                return ri;
6547            }
6548        }
6549        return null;
6550    }
6551
6552    /**
6553     * Return true if the given list is not empty and all of its contents have
6554     * an activityInfo with the given package name.
6555     */
6556    private boolean allHavePackage(List<ResolveInfo> list, String packageName) {
6557        if (ArrayUtils.isEmpty(list)) {
6558            return false;
6559        }
6560        for (int i = 0, N = list.size(); i < N; i++) {
6561            final ResolveInfo ri = list.get(i);
6562            final ActivityInfo ai = ri != null ? ri.activityInfo : null;
6563            if (ai == null || !packageName.equals(ai.packageName)) {
6564                return false;
6565            }
6566        }
6567        return true;
6568    }
6569
6570    private ResolveInfo findPersistentPreferredActivityLP(Intent intent, String resolvedType,
6571            int flags, List<ResolveInfo> query, boolean debug, int userId) {
6572        final int N = query.size();
6573        PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities
6574                .get(userId);
6575        // Get the list of persistent preferred activities that handle the intent
6576        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for presistent preferred activities...");
6577        List<PersistentPreferredActivity> pprefs = ppir != null
6578                ? ppir.queryIntent(intent, resolvedType,
6579                        (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0,
6580                        userId)
6581                : null;
6582        if (pprefs != null && pprefs.size() > 0) {
6583            final int M = pprefs.size();
6584            for (int i=0; i<M; i++) {
6585                final PersistentPreferredActivity ppa = pprefs.get(i);
6586                if (DEBUG_PREFERRED || debug) {
6587                    Slog.v(TAG, "Checking PersistentPreferredActivity ds="
6588                            + (ppa.countDataSchemes() > 0 ? ppa.getDataScheme(0) : "<none>")
6589                            + "\n  component=" + ppa.mComponent);
6590                    ppa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
6591                }
6592                final ActivityInfo ai = getActivityInfo(ppa.mComponent,
6593                        flags | MATCH_DISABLED_COMPONENTS, userId);
6594                if (DEBUG_PREFERRED || debug) {
6595                    Slog.v(TAG, "Found persistent preferred activity:");
6596                    if (ai != null) {
6597                        ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
6598                    } else {
6599                        Slog.v(TAG, "  null");
6600                    }
6601                }
6602                if (ai == null) {
6603                    // This previously registered persistent preferred activity
6604                    // component is no longer known. Ignore it and do NOT remove it.
6605                    continue;
6606                }
6607                for (int j=0; j<N; j++) {
6608                    final ResolveInfo ri = query.get(j);
6609                    if (!ri.activityInfo.applicationInfo.packageName
6610                            .equals(ai.applicationInfo.packageName)) {
6611                        continue;
6612                    }
6613                    if (!ri.activityInfo.name.equals(ai.name)) {
6614                        continue;
6615                    }
6616                    //  Found a persistent preference that can handle the intent.
6617                    if (DEBUG_PREFERRED || debug) {
6618                        Slog.v(TAG, "Returning persistent preferred activity: " +
6619                                ri.activityInfo.packageName + "/" + ri.activityInfo.name);
6620                    }
6621                    return ri;
6622                }
6623            }
6624        }
6625        return null;
6626    }
6627
6628    // TODO: handle preferred activities missing while user has amnesia
6629    ResolveInfo findPreferredActivity(Intent intent, String resolvedType, int flags,
6630            List<ResolveInfo> query, int priority, boolean always,
6631            boolean removeMatches, boolean debug, int userId) {
6632        if (!sUserManager.exists(userId)) return null;
6633        final int callingUid = Binder.getCallingUid();
6634        flags = updateFlagsForResolve(
6635                flags, userId, intent, callingUid, false /*includeInstantApps*/);
6636        intent = updateIntentForResolve(intent);
6637        // writer
6638        synchronized (mPackages) {
6639            // Try to find a matching persistent preferred activity.
6640            ResolveInfo pri = findPersistentPreferredActivityLP(intent, resolvedType, flags, query,
6641                    debug, userId);
6642
6643            // If a persistent preferred activity matched, use it.
6644            if (pri != null) {
6645                return pri;
6646            }
6647
6648            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
6649            // Get the list of preferred activities that handle the intent
6650            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for preferred activities...");
6651            List<PreferredActivity> prefs = pir != null
6652                    ? pir.queryIntent(intent, resolvedType,
6653                            (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0,
6654                            userId)
6655                    : null;
6656            if (prefs != null && prefs.size() > 0) {
6657                boolean changed = false;
6658                try {
6659                    // First figure out how good the original match set is.
6660                    // We will only allow preferred activities that came
6661                    // from the same match quality.
6662                    int match = 0;
6663
6664                    if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Figuring out best match...");
6665
6666                    final int N = query.size();
6667                    for (int j=0; j<N; j++) {
6668                        final ResolveInfo ri = query.get(j);
6669                        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Match for " + ri.activityInfo
6670                                + ": 0x" + Integer.toHexString(match));
6671                        if (ri.match > match) {
6672                            match = ri.match;
6673                        }
6674                    }
6675
6676                    if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Best match: 0x"
6677                            + Integer.toHexString(match));
6678
6679                    match &= IntentFilter.MATCH_CATEGORY_MASK;
6680                    final int M = prefs.size();
6681                    for (int i=0; i<M; i++) {
6682                        final PreferredActivity pa = prefs.get(i);
6683                        if (DEBUG_PREFERRED || debug) {
6684                            Slog.v(TAG, "Checking PreferredActivity ds="
6685                                    + (pa.countDataSchemes() > 0 ? pa.getDataScheme(0) : "<none>")
6686                                    + "\n  component=" + pa.mPref.mComponent);
6687                            pa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
6688                        }
6689                        if (pa.mPref.mMatch != match) {
6690                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping bad match "
6691                                    + Integer.toHexString(pa.mPref.mMatch));
6692                            continue;
6693                        }
6694                        // If it's not an "always" type preferred activity and that's what we're
6695                        // looking for, skip it.
6696                        if (always && !pa.mPref.mAlways) {
6697                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping mAlways=false entry");
6698                            continue;
6699                        }
6700                        final ActivityInfo ai = getActivityInfo(
6701                                pa.mPref.mComponent, flags | MATCH_DISABLED_COMPONENTS
6702                                        | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
6703                                userId);
6704                        if (DEBUG_PREFERRED || debug) {
6705                            Slog.v(TAG, "Found preferred activity:");
6706                            if (ai != null) {
6707                                ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
6708                            } else {
6709                                Slog.v(TAG, "  null");
6710                            }
6711                        }
6712                        if (ai == null) {
6713                            // This previously registered preferred activity
6714                            // component is no longer known.  Most likely an update
6715                            // to the app was installed and in the new version this
6716                            // component no longer exists.  Clean it up by removing
6717                            // it from the preferred activities list, and skip it.
6718                            Slog.w(TAG, "Removing dangling preferred activity: "
6719                                    + pa.mPref.mComponent);
6720                            pir.removeFilter(pa);
6721                            changed = true;
6722                            continue;
6723                        }
6724                        for (int j=0; j<N; j++) {
6725                            final ResolveInfo ri = query.get(j);
6726                            if (!ri.activityInfo.applicationInfo.packageName
6727                                    .equals(ai.applicationInfo.packageName)) {
6728                                continue;
6729                            }
6730                            if (!ri.activityInfo.name.equals(ai.name)) {
6731                                continue;
6732                            }
6733
6734                            if (removeMatches) {
6735                                pir.removeFilter(pa);
6736                                changed = true;
6737                                if (DEBUG_PREFERRED) {
6738                                    Slog.v(TAG, "Removing match " + pa.mPref.mComponent);
6739                                }
6740                                break;
6741                            }
6742
6743                            // Okay we found a previously set preferred or last chosen app.
6744                            // If the result set is different from when this
6745                            // was created, we need to clear it and re-ask the
6746                            // user their preference, if we're looking for an "always" type entry.
6747                            if (always && !pa.mPref.sameSet(query)) {
6748                                Slog.i(TAG, "Result set changed, dropping preferred activity for "
6749                                        + intent + " type " + resolvedType);
6750                                if (DEBUG_PREFERRED) {
6751                                    Slog.v(TAG, "Removing preferred activity since set changed "
6752                                            + pa.mPref.mComponent);
6753                                }
6754                                pir.removeFilter(pa);
6755                                // Re-add the filter as a "last chosen" entry (!always)
6756                                PreferredActivity lastChosen = new PreferredActivity(
6757                                        pa, pa.mPref.mMatch, null, pa.mPref.mComponent, false);
6758                                pir.addFilter(lastChosen);
6759                                changed = true;
6760                                return null;
6761                            }
6762
6763                            // Yay! Either the set matched or we're looking for the last chosen
6764                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Returning preferred activity: "
6765                                    + ri.activityInfo.packageName + "/" + ri.activityInfo.name);
6766                            return ri;
6767                        }
6768                    }
6769                } finally {
6770                    if (changed) {
6771                        if (DEBUG_PREFERRED) {
6772                            Slog.v(TAG, "Preferred activity bookkeeping changed; writing restrictions");
6773                        }
6774                        scheduleWritePackageRestrictionsLocked(userId);
6775                    }
6776                }
6777            }
6778        }
6779        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "No preferred activity to return");
6780        return null;
6781    }
6782
6783    /*
6784     * Returns if intent can be forwarded from the sourceUserId to the targetUserId
6785     */
6786    @Override
6787    public boolean canForwardTo(Intent intent, String resolvedType, int sourceUserId,
6788            int targetUserId) {
6789        mContext.enforceCallingOrSelfPermission(
6790                android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
6791        List<CrossProfileIntentFilter> matches =
6792                getMatchingCrossProfileIntentFilters(intent, resolvedType, sourceUserId);
6793        if (matches != null) {
6794            int size = matches.size();
6795            for (int i = 0; i < size; i++) {
6796                if (matches.get(i).getTargetUserId() == targetUserId) return true;
6797            }
6798        }
6799        if (hasWebURI(intent)) {
6800            // cross-profile app linking works only towards the parent.
6801            final int callingUid = Binder.getCallingUid();
6802            final UserInfo parent = getProfileParent(sourceUserId);
6803            synchronized(mPackages) {
6804                int flags = updateFlagsForResolve(0, parent.id, intent, callingUid,
6805                        false /*includeInstantApps*/);
6806                CrossProfileDomainInfo xpDomainInfo = getCrossProfileDomainPreferredLpr(
6807                        intent, resolvedType, flags, sourceUserId, parent.id);
6808                return xpDomainInfo != null;
6809            }
6810        }
6811        return false;
6812    }
6813
6814    private UserInfo getProfileParent(int userId) {
6815        final long identity = Binder.clearCallingIdentity();
6816        try {
6817            return sUserManager.getProfileParent(userId);
6818        } finally {
6819            Binder.restoreCallingIdentity(identity);
6820        }
6821    }
6822
6823    private List<CrossProfileIntentFilter> getMatchingCrossProfileIntentFilters(Intent intent,
6824            String resolvedType, int userId) {
6825        CrossProfileIntentResolver resolver = mSettings.mCrossProfileIntentResolvers.get(userId);
6826        if (resolver != null) {
6827            return resolver.queryIntent(intent, resolvedType, false /*defaultOnly*/, userId);
6828        }
6829        return null;
6830    }
6831
6832    @Override
6833    public @NonNull ParceledListSlice<ResolveInfo> queryIntentActivities(Intent intent,
6834            String resolvedType, int flags, int userId) {
6835        try {
6836            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "queryIntentActivities");
6837
6838            return new ParceledListSlice<>(
6839                    queryIntentActivitiesInternal(intent, resolvedType, flags, userId));
6840        } finally {
6841            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
6842        }
6843    }
6844
6845    /**
6846     * Returns the package name of the calling Uid if it's an instant app. If it isn't
6847     * instant, returns {@code null}.
6848     */
6849    private String getInstantAppPackageName(int callingUid) {
6850        synchronized (mPackages) {
6851            // If the caller is an isolated app use the owner's uid for the lookup.
6852            if (Process.isIsolated(callingUid)) {
6853                callingUid = mIsolatedOwners.get(callingUid);
6854            }
6855            final int appId = UserHandle.getAppId(callingUid);
6856            final Object obj = mSettings.getUserIdLPr(appId);
6857            if (obj instanceof PackageSetting) {
6858                final PackageSetting ps = (PackageSetting) obj;
6859                final boolean isInstantApp = ps.getInstantApp(UserHandle.getUserId(callingUid));
6860                return isInstantApp ? ps.pkg.packageName : null;
6861            }
6862        }
6863        return null;
6864    }
6865
6866    private @NonNull List<ResolveInfo> queryIntentActivitiesInternal(Intent intent,
6867            String resolvedType, int flags, int userId) {
6868        return queryIntentActivitiesInternal(
6869                intent, resolvedType, flags, Binder.getCallingUid(), userId, false);
6870    }
6871
6872    private @NonNull List<ResolveInfo> queryIntentActivitiesInternal(Intent intent,
6873            String resolvedType, int flags, int filterCallingUid, int userId,
6874            boolean resolveForStart) {
6875        if (!sUserManager.exists(userId)) return Collections.emptyList();
6876        final String instantAppPkgName = getInstantAppPackageName(filterCallingUid);
6877        enforceCrossUserPermission(Binder.getCallingUid(), userId,
6878                false /* requireFullPermission */, false /* checkShell */,
6879                "query intent activities");
6880        final String pkgName = intent.getPackage();
6881        ComponentName comp = intent.getComponent();
6882        if (comp == null) {
6883            if (intent.getSelector() != null) {
6884                intent = intent.getSelector();
6885                comp = intent.getComponent();
6886            }
6887        }
6888
6889        flags = updateFlagsForResolve(flags, userId, intent, filterCallingUid, resolveForStart,
6890                comp != null || pkgName != null /*onlyExposedExplicitly*/);
6891        if (comp != null) {
6892            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
6893            final ActivityInfo ai = getActivityInfo(comp, flags, userId);
6894            if (ai != null) {
6895                // When specifying an explicit component, we prevent the activity from being
6896                // used when either 1) the calling package is normal and the activity is within
6897                // an ephemeral application or 2) the calling package is ephemeral and the
6898                // activity is not visible to ephemeral applications.
6899                final boolean matchInstantApp =
6900                        (flags & PackageManager.MATCH_INSTANT) != 0;
6901                final boolean matchVisibleToInstantAppOnly =
6902                        (flags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
6903                final boolean matchExplicitlyVisibleOnly =
6904                        (flags & PackageManager.MATCH_EXPLICITLY_VISIBLE_ONLY) != 0;
6905                final boolean isCallerInstantApp =
6906                        instantAppPkgName != null;
6907                final boolean isTargetSameInstantApp =
6908                        comp.getPackageName().equals(instantAppPkgName);
6909                final boolean isTargetInstantApp =
6910                        (ai.applicationInfo.privateFlags
6911                                & ApplicationInfo.PRIVATE_FLAG_INSTANT) != 0;
6912                final boolean isTargetVisibleToInstantApp =
6913                        (ai.flags & ActivityInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0;
6914                final boolean isTargetExplicitlyVisibleToInstantApp =
6915                        isTargetVisibleToInstantApp
6916                        && (ai.flags & ActivityInfo.FLAG_IMPLICITLY_VISIBLE_TO_INSTANT_APP) == 0;
6917                final boolean isTargetHiddenFromInstantApp =
6918                        !isTargetVisibleToInstantApp
6919                        || (matchExplicitlyVisibleOnly && !isTargetExplicitlyVisibleToInstantApp);
6920                final boolean blockResolution =
6921                        !isTargetSameInstantApp
6922                        && ((!matchInstantApp && !isCallerInstantApp && isTargetInstantApp)
6923                                || (matchVisibleToInstantAppOnly && isCallerInstantApp
6924                                        && isTargetHiddenFromInstantApp));
6925                if (!blockResolution) {
6926                    final ResolveInfo ri = new ResolveInfo();
6927                    ri.activityInfo = ai;
6928                    list.add(ri);
6929                }
6930            }
6931            return applyPostResolutionFilter(list, instantAppPkgName);
6932        }
6933
6934        // reader
6935        boolean sortResult = false;
6936        boolean addEphemeral = false;
6937        List<ResolveInfo> result;
6938        final boolean ephemeralDisabled = isEphemeralDisabled();
6939        synchronized (mPackages) {
6940            if (pkgName == null) {
6941                List<CrossProfileIntentFilter> matchingFilters =
6942                        getMatchingCrossProfileIntentFilters(intent, resolvedType, userId);
6943                // Check for results that need to skip the current profile.
6944                ResolveInfo xpResolveInfo  = querySkipCurrentProfileIntents(matchingFilters, intent,
6945                        resolvedType, flags, userId);
6946                if (xpResolveInfo != null) {
6947                    List<ResolveInfo> xpResult = new ArrayList<ResolveInfo>(1);
6948                    xpResult.add(xpResolveInfo);
6949                    return applyPostResolutionFilter(
6950                            filterIfNotSystemUser(xpResult, userId), instantAppPkgName);
6951                }
6952
6953                // Check for results in the current profile.
6954                result = filterIfNotSystemUser(mActivities.queryIntent(
6955                        intent, resolvedType, flags, userId), userId);
6956                addEphemeral = !ephemeralDisabled
6957                        && isInstantAppAllowed(intent, result, userId, false /*skipPackageCheck*/);
6958                // Check for cross profile results.
6959                boolean hasNonNegativePriorityResult = hasNonNegativePriority(result);
6960                xpResolveInfo = queryCrossProfileIntents(
6961                        matchingFilters, intent, resolvedType, flags, userId,
6962                        hasNonNegativePriorityResult);
6963                if (xpResolveInfo != null && isUserEnabled(xpResolveInfo.targetUserId)) {
6964                    boolean isVisibleToUser = filterIfNotSystemUser(
6965                            Collections.singletonList(xpResolveInfo), userId).size() > 0;
6966                    if (isVisibleToUser) {
6967                        result.add(xpResolveInfo);
6968                        sortResult = true;
6969                    }
6970                }
6971                if (hasWebURI(intent)) {
6972                    CrossProfileDomainInfo xpDomainInfo = null;
6973                    final UserInfo parent = getProfileParent(userId);
6974                    if (parent != null) {
6975                        xpDomainInfo = getCrossProfileDomainPreferredLpr(intent, resolvedType,
6976                                flags, userId, parent.id);
6977                    }
6978                    if (xpDomainInfo != null) {
6979                        if (xpResolveInfo != null) {
6980                            // If we didn't remove it, the cross-profile ResolveInfo would be twice
6981                            // in the result.
6982                            result.remove(xpResolveInfo);
6983                        }
6984                        if (result.size() == 0 && !addEphemeral) {
6985                            // No result in current profile, but found candidate in parent user.
6986                            // And we are not going to add emphemeral app, so we can return the
6987                            // result straight away.
6988                            result.add(xpDomainInfo.resolveInfo);
6989                            return applyPostResolutionFilter(result, instantAppPkgName);
6990                        }
6991                    } else if (result.size() <= 1 && !addEphemeral) {
6992                        // No result in parent user and <= 1 result in current profile, and we
6993                        // are not going to add emphemeral app, so we can return the result without
6994                        // further processing.
6995                        return applyPostResolutionFilter(result, instantAppPkgName);
6996                    }
6997                    // We have more than one candidate (combining results from current and parent
6998                    // profile), so we need filtering and sorting.
6999                    result = filterCandidatesWithDomainPreferredActivitiesLPr(
7000                            intent, flags, result, xpDomainInfo, userId);
7001                    sortResult = true;
7002                }
7003            } else {
7004                final PackageParser.Package pkg = mPackages.get(pkgName);
7005                result = null;
7006                if (pkg != null) {
7007                    result = filterIfNotSystemUser(
7008                            mActivities.queryIntentForPackage(
7009                                    intent, resolvedType, flags, pkg.activities, userId),
7010                            userId);
7011                }
7012                if (result == null || result.size() == 0) {
7013                    // the caller wants to resolve for a particular package; however, there
7014                    // were no installed results, so, try to find an ephemeral result
7015                    addEphemeral = !ephemeralDisabled
7016                            && isInstantAppAllowed(
7017                                    intent, null /*result*/, userId, true /*skipPackageCheck*/);
7018                    if (result == null) {
7019                        result = new ArrayList<>();
7020                    }
7021                }
7022            }
7023        }
7024        if (addEphemeral) {
7025            result = maybeAddInstantAppInstaller(result, intent, resolvedType, flags, userId);
7026        }
7027        if (sortResult) {
7028            Collections.sort(result, mResolvePrioritySorter);
7029        }
7030        return applyPostResolutionFilter(result, instantAppPkgName);
7031    }
7032
7033    private List<ResolveInfo> maybeAddInstantAppInstaller(List<ResolveInfo> result, Intent intent,
7034            String resolvedType, int flags, int userId) {
7035        // first, check to see if we've got an instant app already installed
7036        final boolean alreadyResolvedLocally = (flags & PackageManager.MATCH_INSTANT) != 0;
7037        ResolveInfo localInstantApp = null;
7038        boolean blockResolution = false;
7039        if (!alreadyResolvedLocally) {
7040            final List<ResolveInfo> instantApps = mActivities.queryIntent(intent, resolvedType,
7041                    flags
7042                        | PackageManager.GET_RESOLVED_FILTER
7043                        | PackageManager.MATCH_INSTANT
7044                        | PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY,
7045                    userId);
7046            for (int i = instantApps.size() - 1; i >= 0; --i) {
7047                final ResolveInfo info = instantApps.get(i);
7048                final String packageName = info.activityInfo.packageName;
7049                final PackageSetting ps = mSettings.mPackages.get(packageName);
7050                if (ps.getInstantApp(userId)) {
7051                    final long packedStatus = getDomainVerificationStatusLPr(ps, userId);
7052                    final int status = (int)(packedStatus >> 32);
7053                    final int linkGeneration = (int)(packedStatus & 0xFFFFFFFF);
7054                    if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
7055                        // there's a local instant application installed, but, the user has
7056                        // chosen to never use it; skip resolution and don't acknowledge
7057                        // an instant application is even available
7058                        if (DEBUG_EPHEMERAL) {
7059                            Slog.v(TAG, "Instant app marked to never run; pkg: " + packageName);
7060                        }
7061                        blockResolution = true;
7062                        break;
7063                    } else {
7064                        // we have a locally installed instant application; skip resolution
7065                        // but acknowledge there's an instant application available
7066                        if (DEBUG_EPHEMERAL) {
7067                            Slog.v(TAG, "Found installed instant app; pkg: " + packageName);
7068                        }
7069                        localInstantApp = info;
7070                        break;
7071                    }
7072                }
7073            }
7074        }
7075        // no app installed, let's see if one's available
7076        AuxiliaryResolveInfo auxiliaryResponse = null;
7077        if (!blockResolution) {
7078            if (localInstantApp == null) {
7079                // we don't have an instant app locally, resolve externally
7080                Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "resolveEphemeral");
7081                final InstantAppRequest requestObject = new InstantAppRequest(
7082                        null /*responseObj*/, intent /*origIntent*/, resolvedType,
7083                        null /*callingPackage*/, userId, null /*verificationBundle*/);
7084                auxiliaryResponse =
7085                        InstantAppResolver.doInstantAppResolutionPhaseOne(
7086                                mContext, mInstantAppResolverConnection, requestObject);
7087                Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
7088            } else {
7089                // we have an instant application locally, but, we can't admit that since
7090                // callers shouldn't be able to determine prior browsing. create a dummy
7091                // auxiliary response so the downstream code behaves as if there's an
7092                // instant application available externally. when it comes time to start
7093                // the instant application, we'll do the right thing.
7094                final ApplicationInfo ai = localInstantApp.activityInfo.applicationInfo;
7095                auxiliaryResponse = new AuxiliaryResolveInfo(
7096                        ai.packageName, null /*splitName*/, ai.versionCode, null /*failureIntent*/);
7097            }
7098        }
7099        if (auxiliaryResponse != null) {
7100            if (DEBUG_EPHEMERAL) {
7101                Slog.v(TAG, "Adding ephemeral installer to the ResolveInfo list");
7102            }
7103            final ResolveInfo ephemeralInstaller = new ResolveInfo(mInstantAppInstallerInfo);
7104            final PackageSetting ps =
7105                    mSettings.mPackages.get(mInstantAppInstallerActivity.packageName);
7106            if (ps != null) {
7107                ephemeralInstaller.activityInfo = PackageParser.generateActivityInfo(
7108                        mInstantAppInstallerActivity, 0, ps.readUserState(userId), userId);
7109                ephemeralInstaller.activityInfo.launchToken = auxiliaryResponse.token;
7110                ephemeralInstaller.auxiliaryInfo = auxiliaryResponse;
7111                // make sure this resolver is the default
7112                ephemeralInstaller.isDefault = true;
7113                ephemeralInstaller.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART
7114                        | IntentFilter.MATCH_ADJUSTMENT_NORMAL;
7115                // add a non-generic filter
7116                ephemeralInstaller.filter = new IntentFilter(intent.getAction());
7117                ephemeralInstaller.filter.addDataPath(
7118                        intent.getData().getPath(), PatternMatcher.PATTERN_LITERAL);
7119                ephemeralInstaller.isInstantAppAvailable = true;
7120                result.add(ephemeralInstaller);
7121            }
7122        }
7123        return result;
7124    }
7125
7126    private static class CrossProfileDomainInfo {
7127        /* ResolveInfo for IntentForwarderActivity to send the intent to the other profile */
7128        ResolveInfo resolveInfo;
7129        /* Best domain verification status of the activities found in the other profile */
7130        int bestDomainVerificationStatus;
7131    }
7132
7133    private CrossProfileDomainInfo getCrossProfileDomainPreferredLpr(Intent intent,
7134            String resolvedType, int flags, int sourceUserId, int parentUserId) {
7135        if (!sUserManager.hasUserRestriction(UserManager.ALLOW_PARENT_PROFILE_APP_LINKING,
7136                sourceUserId)) {
7137            return null;
7138        }
7139        List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent,
7140                resolvedType, flags, parentUserId);
7141
7142        if (resultTargetUser == null || resultTargetUser.isEmpty()) {
7143            return null;
7144        }
7145        CrossProfileDomainInfo result = null;
7146        int size = resultTargetUser.size();
7147        for (int i = 0; i < size; i++) {
7148            ResolveInfo riTargetUser = resultTargetUser.get(i);
7149            // Intent filter verification is only for filters that specify a host. So don't return
7150            // those that handle all web uris.
7151            if (riTargetUser.handleAllWebDataURI) {
7152                continue;
7153            }
7154            String packageName = riTargetUser.activityInfo.packageName;
7155            PackageSetting ps = mSettings.mPackages.get(packageName);
7156            if (ps == null) {
7157                continue;
7158            }
7159            long verificationState = getDomainVerificationStatusLPr(ps, parentUserId);
7160            int status = (int)(verificationState >> 32);
7161            if (result == null) {
7162                result = new CrossProfileDomainInfo();
7163                result.resolveInfo = createForwardingResolveInfoUnchecked(new IntentFilter(),
7164                        sourceUserId, parentUserId);
7165                result.bestDomainVerificationStatus = status;
7166            } else {
7167                result.bestDomainVerificationStatus = bestDomainVerificationStatus(status,
7168                        result.bestDomainVerificationStatus);
7169            }
7170        }
7171        // Don't consider matches with status NEVER across profiles.
7172        if (result != null && result.bestDomainVerificationStatus
7173                == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
7174            return null;
7175        }
7176        return result;
7177    }
7178
7179    /**
7180     * Verification statuses are ordered from the worse to the best, except for
7181     * INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER, which is the worse.
7182     */
7183    private int bestDomainVerificationStatus(int status1, int status2) {
7184        if (status1 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
7185            return status2;
7186        }
7187        if (status2 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
7188            return status1;
7189        }
7190        return (int) MathUtils.max(status1, status2);
7191    }
7192
7193    private boolean isUserEnabled(int userId) {
7194        long callingId = Binder.clearCallingIdentity();
7195        try {
7196            UserInfo userInfo = sUserManager.getUserInfo(userId);
7197            return userInfo != null && userInfo.isEnabled();
7198        } finally {
7199            Binder.restoreCallingIdentity(callingId);
7200        }
7201    }
7202
7203    /**
7204     * Filter out activities with systemUserOnly flag set, when current user is not System.
7205     *
7206     * @return filtered list
7207     */
7208    private List<ResolveInfo> filterIfNotSystemUser(List<ResolveInfo> resolveInfos, int userId) {
7209        if (userId == UserHandle.USER_SYSTEM) {
7210            return resolveInfos;
7211        }
7212        for (int i = resolveInfos.size() - 1; i >= 0; i--) {
7213            ResolveInfo info = resolveInfos.get(i);
7214            if ((info.activityInfo.flags & ActivityInfo.FLAG_SYSTEM_USER_ONLY) != 0) {
7215                resolveInfos.remove(i);
7216            }
7217        }
7218        return resolveInfos;
7219    }
7220
7221    /**
7222     * Filters out ephemeral activities.
7223     * <p>When resolving for an ephemeral app, only activities that 1) are defined in the
7224     * ephemeral app or 2) marked with {@code visibleToEphemeral} are returned.
7225     *
7226     * @param resolveInfos The pre-filtered list of resolved activities
7227     * @param ephemeralPkgName The ephemeral package name. If {@code null}, no filtering
7228     *          is performed.
7229     * @return A filtered list of resolved activities.
7230     */
7231    private List<ResolveInfo> applyPostResolutionFilter(List<ResolveInfo> resolveInfos,
7232            String ephemeralPkgName) {
7233        for (int i = resolveInfos.size() - 1; i >= 0; i--) {
7234            final ResolveInfo info = resolveInfos.get(i);
7235            final boolean isEphemeralApp = info.activityInfo.applicationInfo.isInstantApp();
7236            // TODO: When adding on-demand split support for non-instant apps, remove this check
7237            // and always apply post filtering
7238            // allow activities that are defined in the provided package
7239            if (isEphemeralApp) {
7240                if (info.activityInfo.splitName != null
7241                        && !ArrayUtils.contains(info.activityInfo.applicationInfo.splitNames,
7242                                info.activityInfo.splitName)) {
7243                    // requested activity is defined in a split that hasn't been installed yet.
7244                    // add the installer to the resolve list
7245                    if (DEBUG_EPHEMERAL) {
7246                        Slog.v(TAG, "Adding ephemeral installer to the ResolveInfo list");
7247                    }
7248                    final ResolveInfo installerInfo = new ResolveInfo(mInstantAppInstallerInfo);
7249                    installerInfo.auxiliaryInfo = new AuxiliaryResolveInfo(
7250                            info.activityInfo.packageName, info.activityInfo.splitName,
7251                            info.activityInfo.applicationInfo.versionCode, null /*failureIntent*/);
7252                    // make sure this resolver is the default
7253                    installerInfo.isDefault = true;
7254                    installerInfo.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART
7255                            | IntentFilter.MATCH_ADJUSTMENT_NORMAL;
7256                    // add a non-generic filter
7257                    installerInfo.filter = new IntentFilter();
7258                    // load resources from the correct package
7259                    installerInfo.resolvePackageName = info.getComponentInfo().packageName;
7260                    resolveInfos.set(i, installerInfo);
7261                    continue;
7262                }
7263            }
7264            // caller is a full app, don't need to apply any other filtering
7265            if (ephemeralPkgName == null) {
7266                continue;
7267            } else if (ephemeralPkgName.equals(info.activityInfo.packageName)) {
7268                // caller is same app; don't need to apply any other filtering
7269                continue;
7270            }
7271            // allow activities that have been explicitly exposed to ephemeral apps
7272            if (!isEphemeralApp
7273                    && ((info.activityInfo.flags & ActivityInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0)) {
7274                continue;
7275            }
7276            resolveInfos.remove(i);
7277        }
7278        return resolveInfos;
7279    }
7280
7281    /**
7282     * @param resolveInfos list of resolve infos in descending priority order
7283     * @return if the list contains a resolve info with non-negative priority
7284     */
7285    private boolean hasNonNegativePriority(List<ResolveInfo> resolveInfos) {
7286        return resolveInfos.size() > 0 && resolveInfos.get(0).priority >= 0;
7287    }
7288
7289    private static boolean hasWebURI(Intent intent) {
7290        if (intent.getData() == null) {
7291            return false;
7292        }
7293        final String scheme = intent.getScheme();
7294        if (TextUtils.isEmpty(scheme)) {
7295            return false;
7296        }
7297        return scheme.equals(IntentFilter.SCHEME_HTTP) || scheme.equals(IntentFilter.SCHEME_HTTPS);
7298    }
7299
7300    private List<ResolveInfo> filterCandidatesWithDomainPreferredActivitiesLPr(Intent intent,
7301            int matchFlags, List<ResolveInfo> candidates, CrossProfileDomainInfo xpDomainInfo,
7302            int userId) {
7303        final boolean debug = (intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0;
7304
7305        if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) {
7306            Slog.v(TAG, "Filtering results with preferred activities. Candidates count: " +
7307                    candidates.size());
7308        }
7309
7310        ArrayList<ResolveInfo> result = new ArrayList<ResolveInfo>();
7311        ArrayList<ResolveInfo> alwaysList = new ArrayList<ResolveInfo>();
7312        ArrayList<ResolveInfo> undefinedList = new ArrayList<ResolveInfo>();
7313        ArrayList<ResolveInfo> alwaysAskList = new ArrayList<ResolveInfo>();
7314        ArrayList<ResolveInfo> neverList = new ArrayList<ResolveInfo>();
7315        ArrayList<ResolveInfo> matchAllList = new ArrayList<ResolveInfo>();
7316
7317        synchronized (mPackages) {
7318            final int count = candidates.size();
7319            // First, try to use linked apps. Partition the candidates into four lists:
7320            // one for the final results, one for the "do not use ever", one for "undefined status"
7321            // and finally one for "browser app type".
7322            for (int n=0; n<count; n++) {
7323                ResolveInfo info = candidates.get(n);
7324                String packageName = info.activityInfo.packageName;
7325                PackageSetting ps = mSettings.mPackages.get(packageName);
7326                if (ps != null) {
7327                    // Add to the special match all list (Browser use case)
7328                    if (info.handleAllWebDataURI) {
7329                        matchAllList.add(info);
7330                        continue;
7331                    }
7332                    // Try to get the status from User settings first
7333                    long packedStatus = getDomainVerificationStatusLPr(ps, userId);
7334                    int status = (int)(packedStatus >> 32);
7335                    int linkGeneration = (int)(packedStatus & 0xFFFFFFFF);
7336                    if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS) {
7337                        if (DEBUG_DOMAIN_VERIFICATION || debug) {
7338                            Slog.i(TAG, "  + always: " + info.activityInfo.packageName
7339                                    + " : linkgen=" + linkGeneration);
7340                        }
7341                        // Use link-enabled generation as preferredOrder, i.e.
7342                        // prefer newly-enabled over earlier-enabled.
7343                        info.preferredOrder = linkGeneration;
7344                        alwaysList.add(info);
7345                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
7346                        if (DEBUG_DOMAIN_VERIFICATION || debug) {
7347                            Slog.i(TAG, "  + never: " + info.activityInfo.packageName);
7348                        }
7349                        neverList.add(info);
7350                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) {
7351                        if (DEBUG_DOMAIN_VERIFICATION || debug) {
7352                            Slog.i(TAG, "  + always-ask: " + info.activityInfo.packageName);
7353                        }
7354                        alwaysAskList.add(info);
7355                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED ||
7356                            status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK) {
7357                        if (DEBUG_DOMAIN_VERIFICATION || debug) {
7358                            Slog.i(TAG, "  + ask: " + info.activityInfo.packageName);
7359                        }
7360                        undefinedList.add(info);
7361                    }
7362                }
7363            }
7364
7365            // We'll want to include browser possibilities in a few cases
7366            boolean includeBrowser = false;
7367
7368            // First try to add the "always" resolution(s) for the current user, if any
7369            if (alwaysList.size() > 0) {
7370                result.addAll(alwaysList);
7371            } else {
7372                // Add all undefined apps as we want them to appear in the disambiguation dialog.
7373                result.addAll(undefinedList);
7374                // Maybe add one for the other profile.
7375                if (xpDomainInfo != null && (
7376                        xpDomainInfo.bestDomainVerificationStatus
7377                        != INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER)) {
7378                    result.add(xpDomainInfo.resolveInfo);
7379                }
7380                includeBrowser = true;
7381            }
7382
7383            // The presence of any 'always ask' alternatives means we'll also offer browsers.
7384            // If there were 'always' entries their preferred order has been set, so we also
7385            // back that off to make the alternatives equivalent
7386            if (alwaysAskList.size() > 0) {
7387                for (ResolveInfo i : result) {
7388                    i.preferredOrder = 0;
7389                }
7390                result.addAll(alwaysAskList);
7391                includeBrowser = true;
7392            }
7393
7394            if (includeBrowser) {
7395                // Also add browsers (all of them or only the default one)
7396                if (DEBUG_DOMAIN_VERIFICATION) {
7397                    Slog.v(TAG, "   ...including browsers in candidate set");
7398                }
7399                if ((matchFlags & MATCH_ALL) != 0) {
7400                    result.addAll(matchAllList);
7401                } else {
7402                    // Browser/generic handling case.  If there's a default browser, go straight
7403                    // to that (but only if there is no other higher-priority match).
7404                    final String defaultBrowserPackageName = getDefaultBrowserPackageName(userId);
7405                    int maxMatchPrio = 0;
7406                    ResolveInfo defaultBrowserMatch = null;
7407                    final int numCandidates = matchAllList.size();
7408                    for (int n = 0; n < numCandidates; n++) {
7409                        ResolveInfo info = matchAllList.get(n);
7410                        // track the highest overall match priority...
7411                        if (info.priority > maxMatchPrio) {
7412                            maxMatchPrio = info.priority;
7413                        }
7414                        // ...and the highest-priority default browser match
7415                        if (info.activityInfo.packageName.equals(defaultBrowserPackageName)) {
7416                            if (defaultBrowserMatch == null
7417                                    || (defaultBrowserMatch.priority < info.priority)) {
7418                                if (debug) {
7419                                    Slog.v(TAG, "Considering default browser match " + info);
7420                                }
7421                                defaultBrowserMatch = info;
7422                            }
7423                        }
7424                    }
7425                    if (defaultBrowserMatch != null
7426                            && defaultBrowserMatch.priority >= maxMatchPrio
7427                            && !TextUtils.isEmpty(defaultBrowserPackageName))
7428                    {
7429                        if (debug) {
7430                            Slog.v(TAG, "Default browser match " + defaultBrowserMatch);
7431                        }
7432                        result.add(defaultBrowserMatch);
7433                    } else {
7434                        result.addAll(matchAllList);
7435                    }
7436                }
7437
7438                // If there is nothing selected, add all candidates and remove the ones that the user
7439                // has explicitly put into the INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER state
7440                if (result.size() == 0) {
7441                    result.addAll(candidates);
7442                    result.removeAll(neverList);
7443                }
7444            }
7445        }
7446        if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) {
7447            Slog.v(TAG, "Filtered results with preferred activities. New candidates count: " +
7448                    result.size());
7449            for (ResolveInfo info : result) {
7450                Slog.v(TAG, "  + " + info.activityInfo);
7451            }
7452        }
7453        return result;
7454    }
7455
7456    // Returns a packed value as a long:
7457    //
7458    // high 'int'-sized word: link status: undefined/ask/never/always.
7459    // low 'int'-sized word: relative priority among 'always' results.
7460    private long getDomainVerificationStatusLPr(PackageSetting ps, int userId) {
7461        long result = ps.getDomainVerificationStatusForUser(userId);
7462        // if none available, get the master status
7463        if (result >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) {
7464            if (ps.getIntentFilterVerificationInfo() != null) {
7465                result = ((long)ps.getIntentFilterVerificationInfo().getStatus()) << 32;
7466            }
7467        }
7468        return result;
7469    }
7470
7471    private ResolveInfo querySkipCurrentProfileIntents(
7472            List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType,
7473            int flags, int sourceUserId) {
7474        if (matchingFilters != null) {
7475            int size = matchingFilters.size();
7476            for (int i = 0; i < size; i ++) {
7477                CrossProfileIntentFilter filter = matchingFilters.get(i);
7478                if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0) {
7479                    // Checking if there are activities in the target user that can handle the
7480                    // intent.
7481                    ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent,
7482                            resolvedType, flags, sourceUserId);
7483                    if (resolveInfo != null) {
7484                        return resolveInfo;
7485                    }
7486                }
7487            }
7488        }
7489        return null;
7490    }
7491
7492    // Return matching ResolveInfo in target user if any.
7493    private ResolveInfo queryCrossProfileIntents(
7494            List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType,
7495            int flags, int sourceUserId, boolean matchInCurrentProfile) {
7496        if (matchingFilters != null) {
7497            // Two {@link CrossProfileIntentFilter}s can have the same targetUserId and
7498            // match the same intent. For performance reasons, it is better not to
7499            // run queryIntent twice for the same userId
7500            SparseBooleanArray alreadyTriedUserIds = new SparseBooleanArray();
7501            int size = matchingFilters.size();
7502            for (int i = 0; i < size; i++) {
7503                CrossProfileIntentFilter filter = matchingFilters.get(i);
7504                int targetUserId = filter.getTargetUserId();
7505                boolean skipCurrentProfile =
7506                        (filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0;
7507                boolean skipCurrentProfileIfNoMatchFound =
7508                        (filter.getFlags() & PackageManager.ONLY_IF_NO_MATCH_FOUND) != 0;
7509                if (!skipCurrentProfile && !alreadyTriedUserIds.get(targetUserId)
7510                        && (!skipCurrentProfileIfNoMatchFound || !matchInCurrentProfile)) {
7511                    // Checking if there are activities in the target user that can handle the
7512                    // intent.
7513                    ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent,
7514                            resolvedType, flags, sourceUserId);
7515                    if (resolveInfo != null) return resolveInfo;
7516                    alreadyTriedUserIds.put(targetUserId, true);
7517                }
7518            }
7519        }
7520        return null;
7521    }
7522
7523    /**
7524     * If the filter's target user can handle the intent and is enabled: returns a ResolveInfo that
7525     * will forward the intent to the filter's target user.
7526     * Otherwise, returns null.
7527     */
7528    private ResolveInfo createForwardingResolveInfo(CrossProfileIntentFilter filter, Intent intent,
7529            String resolvedType, int flags, int sourceUserId) {
7530        int targetUserId = filter.getTargetUserId();
7531        List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent,
7532                resolvedType, flags, targetUserId);
7533        if (resultTargetUser != null && isUserEnabled(targetUserId)) {
7534            // If all the matches in the target profile are suspended, return null.
7535            for (int i = resultTargetUser.size() - 1; i >= 0; i--) {
7536                if ((resultTargetUser.get(i).activityInfo.applicationInfo.flags
7537                        & ApplicationInfo.FLAG_SUSPENDED) == 0) {
7538                    return createForwardingResolveInfoUnchecked(filter, sourceUserId,
7539                            targetUserId);
7540                }
7541            }
7542        }
7543        return null;
7544    }
7545
7546    private ResolveInfo createForwardingResolveInfoUnchecked(IntentFilter filter,
7547            int sourceUserId, int targetUserId) {
7548        ResolveInfo forwardingResolveInfo = new ResolveInfo();
7549        long ident = Binder.clearCallingIdentity();
7550        boolean targetIsProfile;
7551        try {
7552            targetIsProfile = sUserManager.getUserInfo(targetUserId).isManagedProfile();
7553        } finally {
7554            Binder.restoreCallingIdentity(ident);
7555        }
7556        String className;
7557        if (targetIsProfile) {
7558            className = FORWARD_INTENT_TO_MANAGED_PROFILE;
7559        } else {
7560            className = FORWARD_INTENT_TO_PARENT;
7561        }
7562        ComponentName forwardingActivityComponentName = new ComponentName(
7563                mAndroidApplication.packageName, className);
7564        ActivityInfo forwardingActivityInfo = getActivityInfo(forwardingActivityComponentName, 0,
7565                sourceUserId);
7566        if (!targetIsProfile) {
7567            forwardingActivityInfo.showUserIcon = targetUserId;
7568            forwardingResolveInfo.noResourceId = true;
7569        }
7570        forwardingResolveInfo.activityInfo = forwardingActivityInfo;
7571        forwardingResolveInfo.priority = 0;
7572        forwardingResolveInfo.preferredOrder = 0;
7573        forwardingResolveInfo.match = 0;
7574        forwardingResolveInfo.isDefault = true;
7575        forwardingResolveInfo.filter = filter;
7576        forwardingResolveInfo.targetUserId = targetUserId;
7577        return forwardingResolveInfo;
7578    }
7579
7580    @Override
7581    public @NonNull ParceledListSlice<ResolveInfo> queryIntentActivityOptions(ComponentName caller,
7582            Intent[] specifics, String[] specificTypes, Intent intent,
7583            String resolvedType, int flags, int userId) {
7584        return new ParceledListSlice<>(queryIntentActivityOptionsInternal(caller, specifics,
7585                specificTypes, intent, resolvedType, flags, userId));
7586    }
7587
7588    private @NonNull List<ResolveInfo> queryIntentActivityOptionsInternal(ComponentName caller,
7589            Intent[] specifics, String[] specificTypes, Intent intent,
7590            String resolvedType, int flags, int userId) {
7591        if (!sUserManager.exists(userId)) return Collections.emptyList();
7592        final int callingUid = Binder.getCallingUid();
7593        flags = updateFlagsForResolve(flags, userId, intent, callingUid,
7594                false /*includeInstantApps*/);
7595        enforceCrossUserPermission(callingUid, userId,
7596                false /*requireFullPermission*/, false /*checkShell*/,
7597                "query intent activity options");
7598        final String resultsAction = intent.getAction();
7599
7600        final List<ResolveInfo> results = queryIntentActivitiesInternal(intent, resolvedType, flags
7601                | PackageManager.GET_RESOLVED_FILTER, userId);
7602
7603        if (DEBUG_INTENT_MATCHING) {
7604            Log.v(TAG, "Query " + intent + ": " + results);
7605        }
7606
7607        int specificsPos = 0;
7608        int N;
7609
7610        // todo: note that the algorithm used here is O(N^2).  This
7611        // isn't a problem in our current environment, but if we start running
7612        // into situations where we have more than 5 or 10 matches then this
7613        // should probably be changed to something smarter...
7614
7615        // First we go through and resolve each of the specific items
7616        // that were supplied, taking care of removing any corresponding
7617        // duplicate items in the generic resolve list.
7618        if (specifics != null) {
7619            for (int i=0; i<specifics.length; i++) {
7620                final Intent sintent = specifics[i];
7621                if (sintent == null) {
7622                    continue;
7623                }
7624
7625                if (DEBUG_INTENT_MATCHING) {
7626                    Log.v(TAG, "Specific #" + i + ": " + sintent);
7627                }
7628
7629                String action = sintent.getAction();
7630                if (resultsAction != null && resultsAction.equals(action)) {
7631                    // If this action was explicitly requested, then don't
7632                    // remove things that have it.
7633                    action = null;
7634                }
7635
7636                ResolveInfo ri = null;
7637                ActivityInfo ai = null;
7638
7639                ComponentName comp = sintent.getComponent();
7640                if (comp == null) {
7641                    ri = resolveIntent(
7642                        sintent,
7643                        specificTypes != null ? specificTypes[i] : null,
7644                            flags, userId);
7645                    if (ri == null) {
7646                        continue;
7647                    }
7648                    if (ri == mResolveInfo) {
7649                        // ACK!  Must do something better with this.
7650                    }
7651                    ai = ri.activityInfo;
7652                    comp = new ComponentName(ai.applicationInfo.packageName,
7653                            ai.name);
7654                } else {
7655                    ai = getActivityInfo(comp, flags, userId);
7656                    if (ai == null) {
7657                        continue;
7658                    }
7659                }
7660
7661                // Look for any generic query activities that are duplicates
7662                // of this specific one, and remove them from the results.
7663                if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Specific #" + i + ": " + ai);
7664                N = results.size();
7665                int j;
7666                for (j=specificsPos; j<N; j++) {
7667                    ResolveInfo sri = results.get(j);
7668                    if ((sri.activityInfo.name.equals(comp.getClassName())
7669                            && sri.activityInfo.applicationInfo.packageName.equals(
7670                                    comp.getPackageName()))
7671                        || (action != null && sri.filter.matchAction(action))) {
7672                        results.remove(j);
7673                        if (DEBUG_INTENT_MATCHING) Log.v(
7674                            TAG, "Removing duplicate item from " + j
7675                            + " due to specific " + specificsPos);
7676                        if (ri == null) {
7677                            ri = sri;
7678                        }
7679                        j--;
7680                        N--;
7681                    }
7682                }
7683
7684                // Add this specific item to its proper place.
7685                if (ri == null) {
7686                    ri = new ResolveInfo();
7687                    ri.activityInfo = ai;
7688                }
7689                results.add(specificsPos, ri);
7690                ri.specificIndex = i;
7691                specificsPos++;
7692            }
7693        }
7694
7695        // Now we go through the remaining generic results and remove any
7696        // duplicate actions that are found here.
7697        N = results.size();
7698        for (int i=specificsPos; i<N-1; i++) {
7699            final ResolveInfo rii = results.get(i);
7700            if (rii.filter == null) {
7701                continue;
7702            }
7703
7704            // Iterate over all of the actions of this result's intent
7705            // filter...  typically this should be just one.
7706            final Iterator<String> it = rii.filter.actionsIterator();
7707            if (it == null) {
7708                continue;
7709            }
7710            while (it.hasNext()) {
7711                final String action = it.next();
7712                if (resultsAction != null && resultsAction.equals(action)) {
7713                    // If this action was explicitly requested, then don't
7714                    // remove things that have it.
7715                    continue;
7716                }
7717                for (int j=i+1; j<N; j++) {
7718                    final ResolveInfo rij = results.get(j);
7719                    if (rij.filter != null && rij.filter.hasAction(action)) {
7720                        results.remove(j);
7721                        if (DEBUG_INTENT_MATCHING) Log.v(
7722                            TAG, "Removing duplicate item from " + j
7723                            + " due to action " + action + " at " + i);
7724                        j--;
7725                        N--;
7726                    }
7727                }
7728            }
7729
7730            // If the caller didn't request filter information, drop it now
7731            // so we don't have to marshall/unmarshall it.
7732            if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
7733                rii.filter = null;
7734            }
7735        }
7736
7737        // Filter out the caller activity if so requested.
7738        if (caller != null) {
7739            N = results.size();
7740            for (int i=0; i<N; i++) {
7741                ActivityInfo ainfo = results.get(i).activityInfo;
7742                if (caller.getPackageName().equals(ainfo.applicationInfo.packageName)
7743                        && caller.getClassName().equals(ainfo.name)) {
7744                    results.remove(i);
7745                    break;
7746                }
7747            }
7748        }
7749
7750        // If the caller didn't request filter information,
7751        // drop them now so we don't have to
7752        // marshall/unmarshall it.
7753        if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
7754            N = results.size();
7755            for (int i=0; i<N; i++) {
7756                results.get(i).filter = null;
7757            }
7758        }
7759
7760        if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Result: " + results);
7761        return results;
7762    }
7763
7764    @Override
7765    public @NonNull ParceledListSlice<ResolveInfo> queryIntentReceivers(Intent intent,
7766            String resolvedType, int flags, int userId) {
7767        return new ParceledListSlice<>(
7768                queryIntentReceiversInternal(intent, resolvedType, flags, userId));
7769    }
7770
7771    private @NonNull List<ResolveInfo> queryIntentReceiversInternal(Intent intent,
7772            String resolvedType, int flags, int userId) {
7773        if (!sUserManager.exists(userId)) return Collections.emptyList();
7774        final int callingUid = Binder.getCallingUid();
7775        final String instantAppPkgName = getInstantAppPackageName(callingUid);
7776        flags = updateFlagsForResolve(flags, userId, intent, callingUid,
7777                false /*includeInstantApps*/);
7778        ComponentName comp = intent.getComponent();
7779        if (comp == null) {
7780            if (intent.getSelector() != null) {
7781                intent = intent.getSelector();
7782                comp = intent.getComponent();
7783            }
7784        }
7785        if (comp != null) {
7786            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
7787            final ActivityInfo ai = getReceiverInfo(comp, flags, userId);
7788            if (ai != null) {
7789                // When specifying an explicit component, we prevent the activity from being
7790                // used when either 1) the calling package is normal and the activity is within
7791                // an instant application or 2) the calling package is ephemeral and the
7792                // activity is not visible to instant applications.
7793                final boolean matchInstantApp =
7794                        (flags & PackageManager.MATCH_INSTANT) != 0;
7795                final boolean matchVisibleToInstantAppOnly =
7796                        (flags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
7797                final boolean matchExplicitlyVisibleOnly =
7798                        (flags & PackageManager.MATCH_EXPLICITLY_VISIBLE_ONLY) != 0;
7799                final boolean isCallerInstantApp =
7800                        instantAppPkgName != null;
7801                final boolean isTargetSameInstantApp =
7802                        comp.getPackageName().equals(instantAppPkgName);
7803                final boolean isTargetInstantApp =
7804                        (ai.applicationInfo.privateFlags
7805                                & ApplicationInfo.PRIVATE_FLAG_INSTANT) != 0;
7806                final boolean isTargetVisibleToInstantApp =
7807                        (ai.flags & ActivityInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0;
7808                final boolean isTargetExplicitlyVisibleToInstantApp =
7809                        isTargetVisibleToInstantApp
7810                        && (ai.flags & ActivityInfo.FLAG_IMPLICITLY_VISIBLE_TO_INSTANT_APP) == 0;
7811                final boolean isTargetHiddenFromInstantApp =
7812                        !isTargetVisibleToInstantApp
7813                        || (matchExplicitlyVisibleOnly && !isTargetExplicitlyVisibleToInstantApp);
7814                final boolean blockResolution =
7815                        !isTargetSameInstantApp
7816                        && ((!matchInstantApp && !isCallerInstantApp && isTargetInstantApp)
7817                                || (matchVisibleToInstantAppOnly && isCallerInstantApp
7818                                        && isTargetHiddenFromInstantApp));
7819                if (!blockResolution) {
7820                    ResolveInfo ri = new ResolveInfo();
7821                    ri.activityInfo = ai;
7822                    list.add(ri);
7823                }
7824            }
7825            return applyPostResolutionFilter(list, instantAppPkgName);
7826        }
7827
7828        // reader
7829        synchronized (mPackages) {
7830            String pkgName = intent.getPackage();
7831            if (pkgName == null) {
7832                final List<ResolveInfo> result =
7833                        mReceivers.queryIntent(intent, resolvedType, flags, userId);
7834                return applyPostResolutionFilter(result, instantAppPkgName);
7835            }
7836            final PackageParser.Package pkg = mPackages.get(pkgName);
7837            if (pkg != null) {
7838                final List<ResolveInfo> result = mReceivers.queryIntentForPackage(
7839                        intent, resolvedType, flags, pkg.receivers, userId);
7840                return applyPostResolutionFilter(result, instantAppPkgName);
7841            }
7842            return Collections.emptyList();
7843        }
7844    }
7845
7846    @Override
7847    public ResolveInfo resolveService(Intent intent, String resolvedType, int flags, int userId) {
7848        final int callingUid = Binder.getCallingUid();
7849        return resolveServiceInternal(intent, resolvedType, flags, userId, callingUid);
7850    }
7851
7852    private ResolveInfo resolveServiceInternal(Intent intent, String resolvedType, int flags,
7853            int userId, int callingUid) {
7854        if (!sUserManager.exists(userId)) return null;
7855        flags = updateFlagsForResolve(
7856                flags, userId, intent, callingUid, false /*includeInstantApps*/);
7857        List<ResolveInfo> query = queryIntentServicesInternal(
7858                intent, resolvedType, flags, userId, callingUid, false /*includeInstantApps*/);
7859        if (query != null) {
7860            if (query.size() >= 1) {
7861                // If there is more than one service with the same priority,
7862                // just arbitrarily pick the first one.
7863                return query.get(0);
7864            }
7865        }
7866        return null;
7867    }
7868
7869    @Override
7870    public @NonNull ParceledListSlice<ResolveInfo> queryIntentServices(Intent intent,
7871            String resolvedType, int flags, int userId) {
7872        final int callingUid = Binder.getCallingUid();
7873        return new ParceledListSlice<>(queryIntentServicesInternal(
7874                intent, resolvedType, flags, userId, callingUid, false /*includeInstantApps*/));
7875    }
7876
7877    private @NonNull List<ResolveInfo> queryIntentServicesInternal(Intent intent,
7878            String resolvedType, int flags, int userId, int callingUid,
7879            boolean includeInstantApps) {
7880        if (!sUserManager.exists(userId)) return Collections.emptyList();
7881        final String instantAppPkgName = getInstantAppPackageName(callingUid);
7882        flags = updateFlagsForResolve(flags, userId, intent, callingUid, includeInstantApps);
7883        ComponentName comp = intent.getComponent();
7884        if (comp == null) {
7885            if (intent.getSelector() != null) {
7886                intent = intent.getSelector();
7887                comp = intent.getComponent();
7888            }
7889        }
7890        if (comp != null) {
7891            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
7892            final ServiceInfo si = getServiceInfo(comp, flags, userId);
7893            if (si != null) {
7894                // When specifying an explicit component, we prevent the service from being
7895                // used when either 1) the service is in an instant application and the
7896                // caller is not the same instant application or 2) the calling package is
7897                // ephemeral and the activity is not visible to ephemeral applications.
7898                final boolean matchInstantApp =
7899                        (flags & PackageManager.MATCH_INSTANT) != 0;
7900                final boolean matchVisibleToInstantAppOnly =
7901                        (flags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
7902                final boolean isCallerInstantApp =
7903                        instantAppPkgName != null;
7904                final boolean isTargetSameInstantApp =
7905                        comp.getPackageName().equals(instantAppPkgName);
7906                final boolean isTargetInstantApp =
7907                        (si.applicationInfo.privateFlags
7908                                & ApplicationInfo.PRIVATE_FLAG_INSTANT) != 0;
7909                final boolean isTargetHiddenFromInstantApp =
7910                        (si.flags & ServiceInfo.FLAG_VISIBLE_TO_INSTANT_APP) == 0;
7911                final boolean blockResolution =
7912                        !isTargetSameInstantApp
7913                        && ((!matchInstantApp && !isCallerInstantApp && isTargetInstantApp)
7914                                || (matchVisibleToInstantAppOnly && isCallerInstantApp
7915                                        && isTargetHiddenFromInstantApp));
7916                if (!blockResolution) {
7917                    final ResolveInfo ri = new ResolveInfo();
7918                    ri.serviceInfo = si;
7919                    list.add(ri);
7920                }
7921            }
7922            return list;
7923        }
7924
7925        // reader
7926        synchronized (mPackages) {
7927            String pkgName = intent.getPackage();
7928            if (pkgName == null) {
7929                return applyPostServiceResolutionFilter(
7930                        mServices.queryIntent(intent, resolvedType, flags, userId),
7931                        instantAppPkgName);
7932            }
7933            final PackageParser.Package pkg = mPackages.get(pkgName);
7934            if (pkg != null) {
7935                return applyPostServiceResolutionFilter(
7936                        mServices.queryIntentForPackage(intent, resolvedType, flags, pkg.services,
7937                                userId),
7938                        instantAppPkgName);
7939            }
7940            return Collections.emptyList();
7941        }
7942    }
7943
7944    private List<ResolveInfo> applyPostServiceResolutionFilter(List<ResolveInfo> resolveInfos,
7945            String instantAppPkgName) {
7946        // TODO: When adding on-demand split support for non-instant apps, remove this check
7947        // and always apply post filtering
7948        if (instantAppPkgName == null) {
7949            return resolveInfos;
7950        }
7951        for (int i = resolveInfos.size() - 1; i >= 0; i--) {
7952            final ResolveInfo info = resolveInfos.get(i);
7953            final boolean isEphemeralApp = info.serviceInfo.applicationInfo.isInstantApp();
7954            // allow services that are defined in the provided package
7955            if (isEphemeralApp && instantAppPkgName.equals(info.serviceInfo.packageName)) {
7956                if (info.serviceInfo.splitName != null
7957                        && !ArrayUtils.contains(info.serviceInfo.applicationInfo.splitNames,
7958                                info.serviceInfo.splitName)) {
7959                    // requested service is defined in a split that hasn't been installed yet.
7960                    // add the installer to the resolve list
7961                    if (DEBUG_EPHEMERAL) {
7962                        Slog.v(TAG, "Adding ephemeral installer to the ResolveInfo list");
7963                    }
7964                    final ResolveInfo installerInfo = new ResolveInfo(mInstantAppInstallerInfo);
7965                    installerInfo.auxiliaryInfo = new AuxiliaryResolveInfo(
7966                            info.serviceInfo.packageName, info.serviceInfo.splitName,
7967                            info.serviceInfo.applicationInfo.versionCode, null /*failureIntent*/);
7968                    // make sure this resolver is the default
7969                    installerInfo.isDefault = true;
7970                    installerInfo.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART
7971                            | IntentFilter.MATCH_ADJUSTMENT_NORMAL;
7972                    // add a non-generic filter
7973                    installerInfo.filter = new IntentFilter();
7974                    // load resources from the correct package
7975                    installerInfo.resolvePackageName = info.getComponentInfo().packageName;
7976                    resolveInfos.set(i, installerInfo);
7977                }
7978                continue;
7979            }
7980            // allow services that have been explicitly exposed to ephemeral apps
7981            if (!isEphemeralApp
7982                    && ((info.serviceInfo.flags & ServiceInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0)) {
7983                continue;
7984            }
7985            resolveInfos.remove(i);
7986        }
7987        return resolveInfos;
7988    }
7989
7990    @Override
7991    public @NonNull ParceledListSlice<ResolveInfo> queryIntentContentProviders(Intent intent,
7992            String resolvedType, int flags, int userId) {
7993        return new ParceledListSlice<>(
7994                queryIntentContentProvidersInternal(intent, resolvedType, flags, userId));
7995    }
7996
7997    private @NonNull List<ResolveInfo> queryIntentContentProvidersInternal(
7998            Intent intent, String resolvedType, int flags, int userId) {
7999        if (!sUserManager.exists(userId)) return Collections.emptyList();
8000        final int callingUid = Binder.getCallingUid();
8001        final String instantAppPkgName = getInstantAppPackageName(callingUid);
8002        flags = updateFlagsForResolve(flags, userId, intent, callingUid,
8003                false /*includeInstantApps*/);
8004        ComponentName comp = intent.getComponent();
8005        if (comp == null) {
8006            if (intent.getSelector() != null) {
8007                intent = intent.getSelector();
8008                comp = intent.getComponent();
8009            }
8010        }
8011        if (comp != null) {
8012            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
8013            final ProviderInfo pi = getProviderInfo(comp, flags, userId);
8014            if (pi != null) {
8015                // When specifying an explicit component, we prevent the provider from being
8016                // used when either 1) the provider is in an instant application and the
8017                // caller is not the same instant application or 2) the calling package is an
8018                // instant application and the provider is not visible to instant applications.
8019                final boolean matchInstantApp =
8020                        (flags & PackageManager.MATCH_INSTANT) != 0;
8021                final boolean matchVisibleToInstantAppOnly =
8022                        (flags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
8023                final boolean isCallerInstantApp =
8024                        instantAppPkgName != null;
8025                final boolean isTargetSameInstantApp =
8026                        comp.getPackageName().equals(instantAppPkgName);
8027                final boolean isTargetInstantApp =
8028                        (pi.applicationInfo.privateFlags
8029                                & ApplicationInfo.PRIVATE_FLAG_INSTANT) != 0;
8030                final boolean isTargetHiddenFromInstantApp =
8031                        (pi.flags & ProviderInfo.FLAG_VISIBLE_TO_INSTANT_APP) == 0;
8032                final boolean blockResolution =
8033                        !isTargetSameInstantApp
8034                        && ((!matchInstantApp && !isCallerInstantApp && isTargetInstantApp)
8035                                || (matchVisibleToInstantAppOnly && isCallerInstantApp
8036                                        && isTargetHiddenFromInstantApp));
8037                if (!blockResolution) {
8038                    final ResolveInfo ri = new ResolveInfo();
8039                    ri.providerInfo = pi;
8040                    list.add(ri);
8041                }
8042            }
8043            return list;
8044        }
8045
8046        // reader
8047        synchronized (mPackages) {
8048            String pkgName = intent.getPackage();
8049            if (pkgName == null) {
8050                return applyPostContentProviderResolutionFilter(
8051                        mProviders.queryIntent(intent, resolvedType, flags, userId),
8052                        instantAppPkgName);
8053            }
8054            final PackageParser.Package pkg = mPackages.get(pkgName);
8055            if (pkg != null) {
8056                return applyPostContentProviderResolutionFilter(
8057                        mProviders.queryIntentForPackage(
8058                        intent, resolvedType, flags, pkg.providers, userId),
8059                        instantAppPkgName);
8060            }
8061            return Collections.emptyList();
8062        }
8063    }
8064
8065    private List<ResolveInfo> applyPostContentProviderResolutionFilter(
8066            List<ResolveInfo> resolveInfos, String instantAppPkgName) {
8067        // TODO: When adding on-demand split support for non-instant applications, remove
8068        // this check and always apply post filtering
8069        if (instantAppPkgName == null) {
8070            return resolveInfos;
8071        }
8072        for (int i = resolveInfos.size() - 1; i >= 0; i--) {
8073            final ResolveInfo info = resolveInfos.get(i);
8074            final boolean isEphemeralApp = info.providerInfo.applicationInfo.isInstantApp();
8075            // allow providers that are defined in the provided package
8076            if (isEphemeralApp && instantAppPkgName.equals(info.providerInfo.packageName)) {
8077                if (info.providerInfo.splitName != null
8078                        && !ArrayUtils.contains(info.providerInfo.applicationInfo.splitNames,
8079                                info.providerInfo.splitName)) {
8080                    // requested provider is defined in a split that hasn't been installed yet.
8081                    // add the installer to the resolve list
8082                    if (DEBUG_EPHEMERAL) {
8083                        Slog.v(TAG, "Adding ephemeral installer to the ResolveInfo list");
8084                    }
8085                    final ResolveInfo installerInfo = new ResolveInfo(mInstantAppInstallerInfo);
8086                    installerInfo.auxiliaryInfo = new AuxiliaryResolveInfo(
8087                            info.providerInfo.packageName, info.providerInfo.splitName,
8088                            info.providerInfo.applicationInfo.versionCode, null /*failureIntent*/);
8089                    // make sure this resolver is the default
8090                    installerInfo.isDefault = true;
8091                    installerInfo.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART
8092                            | IntentFilter.MATCH_ADJUSTMENT_NORMAL;
8093                    // add a non-generic filter
8094                    installerInfo.filter = new IntentFilter();
8095                    // load resources from the correct package
8096                    installerInfo.resolvePackageName = info.getComponentInfo().packageName;
8097                    resolveInfos.set(i, installerInfo);
8098                }
8099                continue;
8100            }
8101            // allow providers that have been explicitly exposed to instant applications
8102            if (!isEphemeralApp
8103                    && ((info.providerInfo.flags & ProviderInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0)) {
8104                continue;
8105            }
8106            resolveInfos.remove(i);
8107        }
8108        return resolveInfos;
8109    }
8110
8111    @Override
8112    public ParceledListSlice<PackageInfo> getInstalledPackages(int flags, int userId) {
8113        final int callingUid = Binder.getCallingUid();
8114        if (getInstantAppPackageName(callingUid) != null) {
8115            return ParceledListSlice.emptyList();
8116        }
8117        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
8118        flags = updateFlagsForPackage(flags, userId, null);
8119        final boolean listUninstalled = (flags & MATCH_KNOWN_PACKAGES) != 0;
8120        enforceCrossUserPermission(callingUid, userId,
8121                true /* requireFullPermission */, false /* checkShell */,
8122                "get installed packages");
8123
8124        // writer
8125        synchronized (mPackages) {
8126            ArrayList<PackageInfo> list;
8127            if (listUninstalled) {
8128                list = new ArrayList<>(mSettings.mPackages.size());
8129                for (PackageSetting ps : mSettings.mPackages.values()) {
8130                    if (filterSharedLibPackageLPr(ps, callingUid, userId, flags)) {
8131                        continue;
8132                    }
8133                    if (filterAppAccessLPr(ps, callingUid, userId)) {
8134                        return null;
8135                    }
8136                    final PackageInfo pi = generatePackageInfo(ps, flags, userId);
8137                    if (pi != null) {
8138                        list.add(pi);
8139                    }
8140                }
8141            } else {
8142                list = new ArrayList<>(mPackages.size());
8143                for (PackageParser.Package p : mPackages.values()) {
8144                    final PackageSetting ps = (PackageSetting) p.mExtras;
8145                    if (filterSharedLibPackageLPr(ps, callingUid, userId, flags)) {
8146                        continue;
8147                    }
8148                    if (filterAppAccessLPr(ps, callingUid, userId)) {
8149                        return null;
8150                    }
8151                    final PackageInfo pi = generatePackageInfo((PackageSetting)
8152                            p.mExtras, flags, userId);
8153                    if (pi != null) {
8154                        list.add(pi);
8155                    }
8156                }
8157            }
8158
8159            return new ParceledListSlice<>(list);
8160        }
8161    }
8162
8163    private void addPackageHoldingPermissions(ArrayList<PackageInfo> list, PackageSetting ps,
8164            String[] permissions, boolean[] tmp, int flags, int userId) {
8165        int numMatch = 0;
8166        final PermissionsState permissionsState = ps.getPermissionsState();
8167        for (int i=0; i<permissions.length; i++) {
8168            final String permission = permissions[i];
8169            if (permissionsState.hasPermission(permission, userId)) {
8170                tmp[i] = true;
8171                numMatch++;
8172            } else {
8173                tmp[i] = false;
8174            }
8175        }
8176        if (numMatch == 0) {
8177            return;
8178        }
8179        final PackageInfo pi = generatePackageInfo(ps, flags, userId);
8180
8181        // The above might return null in cases of uninstalled apps or install-state
8182        // skew across users/profiles.
8183        if (pi != null) {
8184            if ((flags&PackageManager.GET_PERMISSIONS) == 0) {
8185                if (numMatch == permissions.length) {
8186                    pi.requestedPermissions = permissions;
8187                } else {
8188                    pi.requestedPermissions = new String[numMatch];
8189                    numMatch = 0;
8190                    for (int i=0; i<permissions.length; i++) {
8191                        if (tmp[i]) {
8192                            pi.requestedPermissions[numMatch] = permissions[i];
8193                            numMatch++;
8194                        }
8195                    }
8196                }
8197            }
8198            list.add(pi);
8199        }
8200    }
8201
8202    @Override
8203    public ParceledListSlice<PackageInfo> getPackagesHoldingPermissions(
8204            String[] permissions, int flags, int userId) {
8205        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
8206        flags = updateFlagsForPackage(flags, userId, permissions);
8207        enforceCrossUserPermission(Binder.getCallingUid(), userId,
8208                true /* requireFullPermission */, false /* checkShell */,
8209                "get packages holding permissions");
8210        final boolean listUninstalled = (flags & MATCH_KNOWN_PACKAGES) != 0;
8211
8212        // writer
8213        synchronized (mPackages) {
8214            ArrayList<PackageInfo> list = new ArrayList<PackageInfo>();
8215            boolean[] tmpBools = new boolean[permissions.length];
8216            if (listUninstalled) {
8217                for (PackageSetting ps : mSettings.mPackages.values()) {
8218                    addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags,
8219                            userId);
8220                }
8221            } else {
8222                for (PackageParser.Package pkg : mPackages.values()) {
8223                    PackageSetting ps = (PackageSetting)pkg.mExtras;
8224                    if (ps != null) {
8225                        addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags,
8226                                userId);
8227                    }
8228                }
8229            }
8230
8231            return new ParceledListSlice<PackageInfo>(list);
8232        }
8233    }
8234
8235    @Override
8236    public ParceledListSlice<ApplicationInfo> getInstalledApplications(int flags, int userId) {
8237        final int callingUid = Binder.getCallingUid();
8238        if (getInstantAppPackageName(callingUid) != null) {
8239            return ParceledListSlice.emptyList();
8240        }
8241        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
8242        flags = updateFlagsForApplication(flags, userId, null);
8243        final boolean listUninstalled = (flags & MATCH_KNOWN_PACKAGES) != 0;
8244
8245        // writer
8246        synchronized (mPackages) {
8247            ArrayList<ApplicationInfo> list;
8248            if (listUninstalled) {
8249                list = new ArrayList<>(mSettings.mPackages.size());
8250                for (PackageSetting ps : mSettings.mPackages.values()) {
8251                    ApplicationInfo ai;
8252                    int effectiveFlags = flags;
8253                    if (ps.isSystem()) {
8254                        effectiveFlags |= PackageManager.MATCH_ANY_USER;
8255                    }
8256                    if (ps.pkg != null) {
8257                        if (filterSharedLibPackageLPr(ps, callingUid, userId, flags)) {
8258                            continue;
8259                        }
8260                        if (filterAppAccessLPr(ps, callingUid, userId)) {
8261                            return null;
8262                        }
8263                        ai = PackageParser.generateApplicationInfo(ps.pkg, effectiveFlags,
8264                                ps.readUserState(userId), userId);
8265                        if (ai != null) {
8266                            ai.packageName = resolveExternalPackageNameLPr(ps.pkg);
8267                        }
8268                    } else {
8269                        // Shared lib filtering done in generateApplicationInfoFromSettingsLPw
8270                        // and already converts to externally visible package name
8271                        ai = generateApplicationInfoFromSettingsLPw(ps.name,
8272                                callingUid, effectiveFlags, userId);
8273                    }
8274                    if (ai != null) {
8275                        list.add(ai);
8276                    }
8277                }
8278            } else {
8279                list = new ArrayList<>(mPackages.size());
8280                for (PackageParser.Package p : mPackages.values()) {
8281                    if (p.mExtras != null) {
8282                        PackageSetting ps = (PackageSetting) p.mExtras;
8283                        if (filterSharedLibPackageLPr(ps, Binder.getCallingUid(), userId, flags)) {
8284                            continue;
8285                        }
8286                        if (filterAppAccessLPr(ps, callingUid, userId)) {
8287                            return null;
8288                        }
8289                        ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags,
8290                                ps.readUserState(userId), userId);
8291                        if (ai != null) {
8292                            ai.packageName = resolveExternalPackageNameLPr(p);
8293                            list.add(ai);
8294                        }
8295                    }
8296                }
8297            }
8298
8299            return new ParceledListSlice<>(list);
8300        }
8301    }
8302
8303    @Override
8304    public ParceledListSlice<InstantAppInfo> getInstantApps(int userId) {
8305        if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) {
8306            return null;
8307        }
8308        mContext.enforceCallingOrSelfPermission(Manifest.permission.ACCESS_INSTANT_APPS,
8309                "getEphemeralApplications");
8310        enforceCrossUserPermission(Binder.getCallingUid(), userId,
8311                true /* requireFullPermission */, false /* checkShell */,
8312                "getEphemeralApplications");
8313        synchronized (mPackages) {
8314            List<InstantAppInfo> instantApps = mInstantAppRegistry
8315                    .getInstantAppsLPr(userId);
8316            if (instantApps != null) {
8317                return new ParceledListSlice<>(instantApps);
8318            }
8319        }
8320        return null;
8321    }
8322
8323    @Override
8324    public boolean isInstantApp(String packageName, int userId) {
8325        enforceCrossUserPermission(Binder.getCallingUid(), userId,
8326                true /* requireFullPermission */, false /* checkShell */,
8327                "isInstantApp");
8328        if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) {
8329            return false;
8330        }
8331        int callingUid = Binder.getCallingUid();
8332        if (Process.isIsolated(callingUid)) {
8333            callingUid = mIsolatedOwners.get(callingUid);
8334        }
8335
8336        synchronized (mPackages) {
8337            final PackageSetting ps = mSettings.mPackages.get(packageName);
8338            PackageParser.Package pkg = mPackages.get(packageName);
8339            final boolean returnAllowed =
8340                    ps != null
8341                    && (isCallerSameApp(packageName, callingUid)
8342                            || canViewInstantApps(callingUid, userId)
8343                            || mInstantAppRegistry.isInstantAccessGranted(
8344                                    userId, UserHandle.getAppId(callingUid), ps.appId));
8345            if (returnAllowed) {
8346                return ps.getInstantApp(userId);
8347            }
8348        }
8349        return false;
8350    }
8351
8352    @Override
8353    public byte[] getInstantAppCookie(String packageName, int userId) {
8354        if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) {
8355            return null;
8356        }
8357
8358        enforceCrossUserPermission(Binder.getCallingUid(), userId,
8359                true /* requireFullPermission */, false /* checkShell */,
8360                "getInstantAppCookie");
8361        if (!isCallerSameApp(packageName, Binder.getCallingUid())) {
8362            return null;
8363        }
8364        synchronized (mPackages) {
8365            return mInstantAppRegistry.getInstantAppCookieLPw(
8366                    packageName, userId);
8367        }
8368    }
8369
8370    @Override
8371    public boolean setInstantAppCookie(String packageName, byte[] cookie, int userId) {
8372        if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) {
8373            return true;
8374        }
8375
8376        enforceCrossUserPermission(Binder.getCallingUid(), userId,
8377                true /* requireFullPermission */, true /* checkShell */,
8378                "setInstantAppCookie");
8379        if (!isCallerSameApp(packageName, Binder.getCallingUid())) {
8380            return false;
8381        }
8382        synchronized (mPackages) {
8383            return mInstantAppRegistry.setInstantAppCookieLPw(
8384                    packageName, cookie, userId);
8385        }
8386    }
8387
8388    @Override
8389    public Bitmap getInstantAppIcon(String packageName, int userId) {
8390        if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) {
8391            return null;
8392        }
8393
8394        mContext.enforceCallingOrSelfPermission(Manifest.permission.ACCESS_INSTANT_APPS,
8395                "getInstantAppIcon");
8396
8397        enforceCrossUserPermission(Binder.getCallingUid(), userId,
8398                true /* requireFullPermission */, false /* checkShell */,
8399                "getInstantAppIcon");
8400
8401        synchronized (mPackages) {
8402            return mInstantAppRegistry.getInstantAppIconLPw(
8403                    packageName, userId);
8404        }
8405    }
8406
8407    private boolean isCallerSameApp(String packageName, int uid) {
8408        PackageParser.Package pkg = mPackages.get(packageName);
8409        return pkg != null
8410                && UserHandle.getAppId(uid) == pkg.applicationInfo.uid;
8411    }
8412
8413    @Override
8414    public @NonNull ParceledListSlice<ApplicationInfo> getPersistentApplications(int flags) {
8415        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
8416            return ParceledListSlice.emptyList();
8417        }
8418        return new ParceledListSlice<>(getPersistentApplicationsInternal(flags));
8419    }
8420
8421    private @NonNull List<ApplicationInfo> getPersistentApplicationsInternal(int flags) {
8422        final ArrayList<ApplicationInfo> finalList = new ArrayList<ApplicationInfo>();
8423
8424        // reader
8425        synchronized (mPackages) {
8426            final Iterator<PackageParser.Package> i = mPackages.values().iterator();
8427            final int userId = UserHandle.getCallingUserId();
8428            while (i.hasNext()) {
8429                final PackageParser.Package p = i.next();
8430                if (p.applicationInfo == null) continue;
8431
8432                final boolean matchesUnaware = ((flags & MATCH_DIRECT_BOOT_UNAWARE) != 0)
8433                        && !p.applicationInfo.isDirectBootAware();
8434                final boolean matchesAware = ((flags & MATCH_DIRECT_BOOT_AWARE) != 0)
8435                        && p.applicationInfo.isDirectBootAware();
8436
8437                if ((p.applicationInfo.flags & ApplicationInfo.FLAG_PERSISTENT) != 0
8438                        && (!mSafeMode || isSystemApp(p))
8439                        && (matchesUnaware || matchesAware)) {
8440                    PackageSetting ps = mSettings.mPackages.get(p.packageName);
8441                    if (ps != null) {
8442                        ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags,
8443                                ps.readUserState(userId), userId);
8444                        if (ai != null) {
8445                            finalList.add(ai);
8446                        }
8447                    }
8448                }
8449            }
8450        }
8451
8452        return finalList;
8453    }
8454
8455    @Override
8456    public ProviderInfo resolveContentProvider(String name, int flags, int userId) {
8457        if (!sUserManager.exists(userId)) return null;
8458        flags = updateFlagsForComponent(flags, userId, name);
8459        final String instantAppPkgName = getInstantAppPackageName(Binder.getCallingUid());
8460        // reader
8461        synchronized (mPackages) {
8462            final PackageParser.Provider provider = mProvidersByAuthority.get(name);
8463            PackageSetting ps = provider != null
8464                    ? mSettings.mPackages.get(provider.owner.packageName)
8465                    : null;
8466            if (ps != null) {
8467                final boolean isInstantApp = ps.getInstantApp(userId);
8468                // normal application; filter out instant application provider
8469                if (instantAppPkgName == null && isInstantApp) {
8470                    return null;
8471                }
8472                // instant application; filter out other instant applications
8473                if (instantAppPkgName != null
8474                        && isInstantApp
8475                        && !provider.owner.packageName.equals(instantAppPkgName)) {
8476                    return null;
8477                }
8478                // instant application; filter out non-exposed provider
8479                if (instantAppPkgName != null
8480                        && !isInstantApp
8481                        && (provider.info.flags & ProviderInfo.FLAG_VISIBLE_TO_INSTANT_APP) == 0) {
8482                    return null;
8483                }
8484                // provider not enabled
8485                if (!mSettings.isEnabledAndMatchLPr(provider.info, flags, userId)) {
8486                    return null;
8487                }
8488                return PackageParser.generateProviderInfo(
8489                        provider, flags, ps.readUserState(userId), userId);
8490            }
8491            return null;
8492        }
8493    }
8494
8495    /**
8496     * @deprecated
8497     */
8498    @Deprecated
8499    public void querySyncProviders(List<String> outNames, List<ProviderInfo> outInfo) {
8500        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
8501            return;
8502        }
8503        // reader
8504        synchronized (mPackages) {
8505            final Iterator<Map.Entry<String, PackageParser.Provider>> i = mProvidersByAuthority
8506                    .entrySet().iterator();
8507            final int userId = UserHandle.getCallingUserId();
8508            while (i.hasNext()) {
8509                Map.Entry<String, PackageParser.Provider> entry = i.next();
8510                PackageParser.Provider p = entry.getValue();
8511                PackageSetting ps = mSettings.mPackages.get(p.owner.packageName);
8512
8513                if (ps != null && p.syncable
8514                        && (!mSafeMode || (p.info.applicationInfo.flags
8515                                &ApplicationInfo.FLAG_SYSTEM) != 0)) {
8516                    ProviderInfo info = PackageParser.generateProviderInfo(p, 0,
8517                            ps.readUserState(userId), userId);
8518                    if (info != null) {
8519                        outNames.add(entry.getKey());
8520                        outInfo.add(info);
8521                    }
8522                }
8523            }
8524        }
8525    }
8526
8527    @Override
8528    public @NonNull ParceledListSlice<ProviderInfo> queryContentProviders(String processName,
8529            int uid, int flags, String metaDataKey) {
8530        final int callingUid = Binder.getCallingUid();
8531        final int userId = processName != null ? UserHandle.getUserId(uid)
8532                : UserHandle.getCallingUserId();
8533        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
8534        flags = updateFlagsForComponent(flags, userId, processName);
8535        ArrayList<ProviderInfo> finalList = null;
8536        // reader
8537        synchronized (mPackages) {
8538            final Iterator<PackageParser.Provider> i = mProviders.mProviders.values().iterator();
8539            while (i.hasNext()) {
8540                final PackageParser.Provider p = i.next();
8541                PackageSetting ps = mSettings.mPackages.get(p.owner.packageName);
8542                if (ps != null && p.info.authority != null
8543                        && (processName == null
8544                                || (p.info.processName.equals(processName)
8545                                        && UserHandle.isSameApp(p.info.applicationInfo.uid, uid)))
8546                        && mSettings.isEnabledAndMatchLPr(p.info, flags, userId)) {
8547
8548                    // See PM.queryContentProviders()'s javadoc for why we have the metaData
8549                    // parameter.
8550                    if (metaDataKey != null
8551                            && (p.metaData == null || !p.metaData.containsKey(metaDataKey))) {
8552                        continue;
8553                    }
8554                    final ComponentName component =
8555                            new ComponentName(p.info.packageName, p.info.name);
8556                    if (filterAppAccessLPr(ps, callingUid, component, TYPE_PROVIDER, userId)) {
8557                        continue;
8558                    }
8559                    if (finalList == null) {
8560                        finalList = new ArrayList<ProviderInfo>(3);
8561                    }
8562                    ProviderInfo info = PackageParser.generateProviderInfo(p, flags,
8563                            ps.readUserState(userId), userId);
8564                    if (info != null) {
8565                        finalList.add(info);
8566                    }
8567                }
8568            }
8569        }
8570
8571        if (finalList != null) {
8572            Collections.sort(finalList, mProviderInitOrderSorter);
8573            return new ParceledListSlice<ProviderInfo>(finalList);
8574        }
8575
8576        return ParceledListSlice.emptyList();
8577    }
8578
8579    @Override
8580    public InstrumentationInfo getInstrumentationInfo(ComponentName component, int flags) {
8581        // reader
8582        synchronized (mPackages) {
8583            final int callingUid = Binder.getCallingUid();
8584            final int callingUserId = UserHandle.getUserId(callingUid);
8585            final PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
8586            if (ps == null) return null;
8587            if (filterAppAccessLPr(ps, callingUid, component, TYPE_UNKNOWN, callingUserId)) {
8588                return null;
8589            }
8590            final PackageParser.Instrumentation i = mInstrumentation.get(component);
8591            return PackageParser.generateInstrumentationInfo(i, flags);
8592        }
8593    }
8594
8595    @Override
8596    public @NonNull ParceledListSlice<InstrumentationInfo> queryInstrumentation(
8597            String targetPackage, int flags) {
8598        final int callingUid = Binder.getCallingUid();
8599        final int callingUserId = UserHandle.getUserId(callingUid);
8600        final PackageSetting ps = mSettings.mPackages.get(targetPackage);
8601        if (filterAppAccessLPr(ps, callingUid, callingUserId)) {
8602            return ParceledListSlice.emptyList();
8603        }
8604        return new ParceledListSlice<>(queryInstrumentationInternal(targetPackage, flags));
8605    }
8606
8607    private @NonNull List<InstrumentationInfo> queryInstrumentationInternal(String targetPackage,
8608            int flags) {
8609        ArrayList<InstrumentationInfo> finalList = new ArrayList<InstrumentationInfo>();
8610
8611        // reader
8612        synchronized (mPackages) {
8613            final Iterator<PackageParser.Instrumentation> i = mInstrumentation.values().iterator();
8614            while (i.hasNext()) {
8615                final PackageParser.Instrumentation p = i.next();
8616                if (targetPackage == null
8617                        || targetPackage.equals(p.info.targetPackage)) {
8618                    InstrumentationInfo ii = PackageParser.generateInstrumentationInfo(p,
8619                            flags);
8620                    if (ii != null) {
8621                        finalList.add(ii);
8622                    }
8623                }
8624            }
8625        }
8626
8627        return finalList;
8628    }
8629
8630    private void scanDirTracedLI(File dir, final int parseFlags, int scanFlags, long currentTime) {
8631        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanDir [" + dir.getAbsolutePath() + "]");
8632        try {
8633            scanDirLI(dir, parseFlags, scanFlags, currentTime);
8634        } finally {
8635            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
8636        }
8637    }
8638
8639    private void scanDirLI(File dir, int parseFlags, int scanFlags, long currentTime) {
8640        final File[] files = dir.listFiles();
8641        if (ArrayUtils.isEmpty(files)) {
8642            Log.d(TAG, "No files in app dir " + dir);
8643            return;
8644        }
8645
8646        if (DEBUG_PACKAGE_SCANNING) {
8647            Log.d(TAG, "Scanning app dir " + dir + " scanFlags=" + scanFlags
8648                    + " flags=0x" + Integer.toHexString(parseFlags));
8649        }
8650        ParallelPackageParser parallelPackageParser = new ParallelPackageParser(
8651                mSeparateProcesses, mOnlyCore, mMetrics, mCacheDir,
8652                mParallelPackageParserCallback);
8653
8654        // Submit files for parsing in parallel
8655        int fileCount = 0;
8656        for (File file : files) {
8657            final boolean isPackage = (isApkFile(file) || file.isDirectory())
8658                    && !PackageInstallerService.isStageName(file.getName());
8659            if (!isPackage) {
8660                // Ignore entries which are not packages
8661                continue;
8662            }
8663            parallelPackageParser.submit(file, parseFlags);
8664            fileCount++;
8665        }
8666
8667        // Process results one by one
8668        for (; fileCount > 0; fileCount--) {
8669            ParallelPackageParser.ParseResult parseResult = parallelPackageParser.take();
8670            Throwable throwable = parseResult.throwable;
8671            int errorCode = PackageManager.INSTALL_SUCCEEDED;
8672
8673            if (throwable == null) {
8674                // Static shared libraries have synthetic package names
8675                if (parseResult.pkg.applicationInfo.isStaticSharedLibrary()) {
8676                    renameStaticSharedLibraryPackage(parseResult.pkg);
8677                }
8678                try {
8679                    if (errorCode == PackageManager.INSTALL_SUCCEEDED) {
8680                        scanPackageLI(parseResult.pkg, parseResult.scanFile, parseFlags, scanFlags,
8681                                currentTime, null);
8682                    }
8683                } catch (PackageManagerException e) {
8684                    errorCode = e.error;
8685                    Slog.w(TAG, "Failed to scan " + parseResult.scanFile + ": " + e.getMessage());
8686                }
8687            } else if (throwable instanceof PackageParser.PackageParserException) {
8688                PackageParser.PackageParserException e = (PackageParser.PackageParserException)
8689                        throwable;
8690                errorCode = e.error;
8691                Slog.w(TAG, "Failed to parse " + parseResult.scanFile + ": " + e.getMessage());
8692            } else {
8693                throw new IllegalStateException("Unexpected exception occurred while parsing "
8694                        + parseResult.scanFile, throwable);
8695            }
8696
8697            // Delete invalid userdata apps
8698            if ((parseFlags & PackageParser.PARSE_IS_SYSTEM) == 0 &&
8699                    errorCode == PackageManager.INSTALL_FAILED_INVALID_APK) {
8700                logCriticalInfo(Log.WARN,
8701                        "Deleting invalid package at " + parseResult.scanFile);
8702                removeCodePathLI(parseResult.scanFile);
8703            }
8704        }
8705        parallelPackageParser.close();
8706    }
8707
8708    private static File getSettingsProblemFile() {
8709        File dataDir = Environment.getDataDirectory();
8710        File systemDir = new File(dataDir, "system");
8711        File fname = new File(systemDir, "uiderrors.txt");
8712        return fname;
8713    }
8714
8715    static void reportSettingsProblem(int priority, String msg) {
8716        logCriticalInfo(priority, msg);
8717    }
8718
8719    public static void logCriticalInfo(int priority, String msg) {
8720        Slog.println(priority, TAG, msg);
8721        EventLogTags.writePmCriticalInfo(msg);
8722        try {
8723            File fname = getSettingsProblemFile();
8724            FileOutputStream out = new FileOutputStream(fname, true);
8725            PrintWriter pw = new FastPrintWriter(out);
8726            SimpleDateFormat formatter = new SimpleDateFormat();
8727            String dateString = formatter.format(new Date(System.currentTimeMillis()));
8728            pw.println(dateString + ": " + msg);
8729            pw.close();
8730            FileUtils.setPermissions(
8731                    fname.toString(),
8732                    FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IROTH,
8733                    -1, -1);
8734        } catch (java.io.IOException e) {
8735        }
8736    }
8737
8738    private long getLastModifiedTime(PackageParser.Package pkg, File srcFile) {
8739        if (srcFile.isDirectory()) {
8740            final File baseFile = new File(pkg.baseCodePath);
8741            long maxModifiedTime = baseFile.lastModified();
8742            if (pkg.splitCodePaths != null) {
8743                for (int i = pkg.splitCodePaths.length - 1; i >=0; --i) {
8744                    final File splitFile = new File(pkg.splitCodePaths[i]);
8745                    maxModifiedTime = Math.max(maxModifiedTime, splitFile.lastModified());
8746                }
8747            }
8748            return maxModifiedTime;
8749        }
8750        return srcFile.lastModified();
8751    }
8752
8753    private void collectCertificatesLI(PackageSetting ps, PackageParser.Package pkg, File srcFile,
8754            final int policyFlags) throws PackageManagerException {
8755        // When upgrading from pre-N MR1, verify the package time stamp using the package
8756        // directory and not the APK file.
8757        final long lastModifiedTime = mIsPreNMR1Upgrade
8758                ? new File(pkg.codePath).lastModified() : getLastModifiedTime(pkg, srcFile);
8759        if (ps != null
8760                && ps.codePath.equals(srcFile)
8761                && ps.timeStamp == lastModifiedTime
8762                && !isCompatSignatureUpdateNeeded(pkg)
8763                && !isRecoverSignatureUpdateNeeded(pkg)) {
8764            long mSigningKeySetId = ps.keySetData.getProperSigningKeySet();
8765            KeySetManagerService ksms = mSettings.mKeySetManagerService;
8766            ArraySet<PublicKey> signingKs;
8767            synchronized (mPackages) {
8768                signingKs = ksms.getPublicKeysFromKeySetLPr(mSigningKeySetId);
8769            }
8770            if (ps.signatures.mSignatures != null
8771                    && ps.signatures.mSignatures.length != 0
8772                    && signingKs != null) {
8773                // Optimization: reuse the existing cached certificates
8774                // if the package appears to be unchanged.
8775                pkg.mSignatures = ps.signatures.mSignatures;
8776                pkg.mSigningKeys = signingKs;
8777                return;
8778            }
8779
8780            Slog.w(TAG, "PackageSetting for " + ps.name
8781                    + " is missing signatures.  Collecting certs again to recover them.");
8782        } else {
8783            Slog.i(TAG, srcFile.toString() + " changed; collecting certs");
8784        }
8785
8786        try {
8787            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "collectCertificates");
8788            PackageParser.collectCertificates(pkg, policyFlags);
8789        } catch (PackageParserException e) {
8790            throw PackageManagerException.from(e);
8791        } finally {
8792            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
8793        }
8794    }
8795
8796    /**
8797     *  Traces a package scan.
8798     *  @see #scanPackageLI(File, int, int, long, UserHandle)
8799     */
8800    private PackageParser.Package scanPackageTracedLI(File scanFile, final int parseFlags,
8801            int scanFlags, long currentTime, UserHandle user) throws PackageManagerException {
8802        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage [" + scanFile.toString() + "]");
8803        try {
8804            return scanPackageLI(scanFile, parseFlags, scanFlags, currentTime, user);
8805        } finally {
8806            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
8807        }
8808    }
8809
8810    /**
8811     *  Scans a package and returns the newly parsed package.
8812     *  Returns {@code null} in case of errors and the error code is stored in mLastScanError
8813     */
8814    private PackageParser.Package scanPackageLI(File scanFile, int parseFlags, int scanFlags,
8815            long currentTime, UserHandle user) throws PackageManagerException {
8816        if (DEBUG_INSTALL) Slog.d(TAG, "Parsing: " + scanFile);
8817        PackageParser pp = new PackageParser();
8818        pp.setSeparateProcesses(mSeparateProcesses);
8819        pp.setOnlyCoreApps(mOnlyCore);
8820        pp.setDisplayMetrics(mMetrics);
8821        pp.setCallback(mPackageParserCallback);
8822
8823        if ((scanFlags & SCAN_TRUSTED_OVERLAY) != 0) {
8824            parseFlags |= PackageParser.PARSE_TRUSTED_OVERLAY;
8825        }
8826
8827        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "parsePackage");
8828        final PackageParser.Package pkg;
8829        try {
8830            pkg = pp.parsePackage(scanFile, parseFlags);
8831        } catch (PackageParserException e) {
8832            throw PackageManagerException.from(e);
8833        } finally {
8834            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
8835        }
8836
8837        // Static shared libraries have synthetic package names
8838        if (pkg.applicationInfo.isStaticSharedLibrary()) {
8839            renameStaticSharedLibraryPackage(pkg);
8840        }
8841
8842        return scanPackageLI(pkg, scanFile, parseFlags, scanFlags, currentTime, user);
8843    }
8844
8845    /**
8846     *  Scans a package and returns the newly parsed package.
8847     *  @throws PackageManagerException on a parse error.
8848     */
8849    private PackageParser.Package scanPackageLI(PackageParser.Package pkg, File scanFile,
8850            final int policyFlags, int scanFlags, long currentTime, @Nullable UserHandle user)
8851            throws PackageManagerException {
8852        // If the package has children and this is the first dive in the function
8853        // we scan the package with the SCAN_CHECK_ONLY flag set to see whether all
8854        // packages (parent and children) would be successfully scanned before the
8855        // actual scan since scanning mutates internal state and we want to atomically
8856        // install the package and its children.
8857        if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
8858            if (pkg.childPackages != null && pkg.childPackages.size() > 0) {
8859                scanFlags |= SCAN_CHECK_ONLY;
8860            }
8861        } else {
8862            scanFlags &= ~SCAN_CHECK_ONLY;
8863        }
8864
8865        // Scan the parent
8866        PackageParser.Package scannedPkg = scanPackageInternalLI(pkg, scanFile, policyFlags,
8867                scanFlags, currentTime, user);
8868
8869        // Scan the children
8870        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
8871        for (int i = 0; i < childCount; i++) {
8872            PackageParser.Package childPackage = pkg.childPackages.get(i);
8873            scanPackageInternalLI(childPackage, scanFile, policyFlags, scanFlags,
8874                    currentTime, user);
8875        }
8876
8877
8878        if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
8879            return scanPackageLI(pkg, scanFile, policyFlags, scanFlags, currentTime, user);
8880        }
8881
8882        return scannedPkg;
8883    }
8884
8885    /**
8886     *  Scans a package and returns the newly parsed package.
8887     *  @throws PackageManagerException on a parse error.
8888     */
8889    private PackageParser.Package scanPackageInternalLI(PackageParser.Package pkg, File scanFile,
8890            int policyFlags, int scanFlags, long currentTime, @Nullable UserHandle user)
8891            throws PackageManagerException {
8892        PackageSetting ps = null;
8893        PackageSetting updatedPkg;
8894        // reader
8895        synchronized (mPackages) {
8896            // Look to see if we already know about this package.
8897            String oldName = mSettings.getRenamedPackageLPr(pkg.packageName);
8898            if (pkg.mOriginalPackages != null && pkg.mOriginalPackages.contains(oldName)) {
8899                // This package has been renamed to its original name.  Let's
8900                // use that.
8901                ps = mSettings.getPackageLPr(oldName);
8902            }
8903            // If there was no original package, see one for the real package name.
8904            if (ps == null) {
8905                ps = mSettings.getPackageLPr(pkg.packageName);
8906            }
8907            // Check to see if this package could be hiding/updating a system
8908            // package.  Must look for it either under the original or real
8909            // package name depending on our state.
8910            updatedPkg = mSettings.getDisabledSystemPkgLPr(ps != null ? ps.name : pkg.packageName);
8911            if (DEBUG_INSTALL && updatedPkg != null) Slog.d(TAG, "updatedPkg = " + updatedPkg);
8912
8913            // If this is a package we don't know about on the system partition, we
8914            // may need to remove disabled child packages on the system partition
8915            // or may need to not add child packages if the parent apk is updated
8916            // on the data partition and no longer defines this child package.
8917            if ((policyFlags & PackageParser.PARSE_IS_SYSTEM) != 0) {
8918                // If this is a parent package for an updated system app and this system
8919                // app got an OTA update which no longer defines some of the child packages
8920                // we have to prune them from the disabled system packages.
8921                PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(pkg.packageName);
8922                if (disabledPs != null) {
8923                    final int scannedChildCount = (pkg.childPackages != null)
8924                            ? pkg.childPackages.size() : 0;
8925                    final int disabledChildCount = disabledPs.childPackageNames != null
8926                            ? disabledPs.childPackageNames.size() : 0;
8927                    for (int i = 0; i < disabledChildCount; i++) {
8928                        String disabledChildPackageName = disabledPs.childPackageNames.get(i);
8929                        boolean disabledPackageAvailable = false;
8930                        for (int j = 0; j < scannedChildCount; j++) {
8931                            PackageParser.Package childPkg = pkg.childPackages.get(j);
8932                            if (childPkg.packageName.equals(disabledChildPackageName)) {
8933                                disabledPackageAvailable = true;
8934                                break;
8935                            }
8936                         }
8937                         if (!disabledPackageAvailable) {
8938                             mSettings.removeDisabledSystemPackageLPw(disabledChildPackageName);
8939                         }
8940                    }
8941                }
8942            }
8943        }
8944
8945        final boolean isUpdatedPkg = updatedPkg != null;
8946        final boolean isUpdatedSystemPkg = isUpdatedPkg
8947                && (policyFlags & PackageParser.PARSE_IS_SYSTEM) != 0;
8948        boolean isUpdatedPkgBetter = false;
8949        // First check if this is a system package that may involve an update
8950        if (isUpdatedSystemPkg) {
8951            // If new package is not located in "/system/priv-app" (e.g. due to an OTA),
8952            // it needs to drop FLAG_PRIVILEGED.
8953            if (locationIsPrivileged(scanFile)) {
8954                updatedPkg.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
8955            } else {
8956                updatedPkg.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
8957            }
8958
8959            if (ps != null && !ps.codePath.equals(scanFile)) {
8960                // The path has changed from what was last scanned...  check the
8961                // version of the new path against what we have stored to determine
8962                // what to do.
8963                if (DEBUG_INSTALL) Slog.d(TAG, "Path changing from " + ps.codePath);
8964                if (pkg.mVersionCode <= ps.versionCode) {
8965                    // The system package has been updated and the code path does not match
8966                    // Ignore entry. Skip it.
8967                    if (DEBUG_INSTALL) Slog.i(TAG, "Package " + ps.name + " at " + scanFile
8968                            + " ignored: updated version " + ps.versionCode
8969                            + " better than this " + pkg.mVersionCode);
8970                    if (!updatedPkg.codePath.equals(scanFile)) {
8971                        Slog.w(PackageManagerService.TAG, "Code path for hidden system pkg "
8972                                + ps.name + " changing from " + updatedPkg.codePathString
8973                                + " to " + scanFile);
8974                        updatedPkg.codePath = scanFile;
8975                        updatedPkg.codePathString = scanFile.toString();
8976                        updatedPkg.resourcePath = scanFile;
8977                        updatedPkg.resourcePathString = scanFile.toString();
8978                    }
8979                    updatedPkg.pkg = pkg;
8980                    updatedPkg.versionCode = pkg.mVersionCode;
8981
8982                    // Update the disabled system child packages to point to the package too.
8983                    final int childCount = updatedPkg.childPackageNames != null
8984                            ? updatedPkg.childPackageNames.size() : 0;
8985                    for (int i = 0; i < childCount; i++) {
8986                        String childPackageName = updatedPkg.childPackageNames.get(i);
8987                        PackageSetting updatedChildPkg = mSettings.getDisabledSystemPkgLPr(
8988                                childPackageName);
8989                        if (updatedChildPkg != null) {
8990                            updatedChildPkg.pkg = pkg;
8991                            updatedChildPkg.versionCode = pkg.mVersionCode;
8992                        }
8993                    }
8994                } else {
8995                    // The current app on the system partition is better than
8996                    // what we have updated to on the data partition; switch
8997                    // back to the system partition version.
8998                    // At this point, its safely assumed that package installation for
8999                    // apps in system partition will go through. If not there won't be a working
9000                    // version of the app
9001                    // writer
9002                    synchronized (mPackages) {
9003                        // Just remove the loaded entries from package lists.
9004                        mPackages.remove(ps.name);
9005                    }
9006
9007                    logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile
9008                            + " reverting from " + ps.codePathString
9009                            + ": new version " + pkg.mVersionCode
9010                            + " better than installed " + ps.versionCode);
9011
9012                    InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
9013                            ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
9014                    synchronized (mInstallLock) {
9015                        args.cleanUpResourcesLI();
9016                    }
9017                    synchronized (mPackages) {
9018                        mSettings.enableSystemPackageLPw(ps.name);
9019                    }
9020                    isUpdatedPkgBetter = true;
9021                }
9022            }
9023        }
9024
9025        String resourcePath = null;
9026        String baseResourcePath = null;
9027        if ((policyFlags & PackageParser.PARSE_FORWARD_LOCK) != 0 && !isUpdatedPkgBetter) {
9028            if (ps != null && ps.resourcePathString != null) {
9029                resourcePath = ps.resourcePathString;
9030                baseResourcePath = ps.resourcePathString;
9031            } else {
9032                // Should not happen at all. Just log an error.
9033                Slog.e(TAG, "Resource path not set for package " + pkg.packageName);
9034            }
9035        } else {
9036            resourcePath = pkg.codePath;
9037            baseResourcePath = pkg.baseCodePath;
9038        }
9039
9040        // Set application objects path explicitly.
9041        pkg.setApplicationVolumeUuid(pkg.volumeUuid);
9042        pkg.setApplicationInfoCodePath(pkg.codePath);
9043        pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
9044        pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
9045        pkg.setApplicationInfoResourcePath(resourcePath);
9046        pkg.setApplicationInfoBaseResourcePath(baseResourcePath);
9047        pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
9048
9049        // throw an exception if we have an update to a system application, but, it's not more
9050        // recent than the package we've already scanned
9051        if (isUpdatedSystemPkg && !isUpdatedPkgBetter) {
9052            throw new PackageManagerException(Log.WARN, "Package " + ps.name + " at "
9053                    + scanFile + " ignored: updated version " + ps.versionCode
9054                    + " better than this " + pkg.mVersionCode);
9055        }
9056
9057        if (isUpdatedPkg) {
9058            // An updated system app will not have the PARSE_IS_SYSTEM flag set
9059            // initially
9060            policyFlags |= PackageParser.PARSE_IS_SYSTEM;
9061
9062            // An updated privileged app will not have the PARSE_IS_PRIVILEGED
9063            // flag set initially
9064            if ((updatedPkg.pkgPrivateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0) {
9065                policyFlags |= PackageParser.PARSE_IS_PRIVILEGED;
9066            }
9067        }
9068
9069        // Verify certificates against what was last scanned
9070        collectCertificatesLI(ps, pkg, scanFile, policyFlags);
9071
9072        /*
9073         * A new system app appeared, but we already had a non-system one of the
9074         * same name installed earlier.
9075         */
9076        boolean shouldHideSystemApp = false;
9077        if (!isUpdatedPkg && ps != null
9078                && (policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0 && !isSystemApp(ps)) {
9079            /*
9080             * Check to make sure the signatures match first. If they don't,
9081             * wipe the installed application and its data.
9082             */
9083            if (compareSignatures(ps.signatures.mSignatures, pkg.mSignatures)
9084                    != PackageManager.SIGNATURE_MATCH) {
9085                logCriticalInfo(Log.WARN, "Package " + ps.name + " appeared on system, but"
9086                        + " signatures don't match existing userdata copy; removing");
9087                try (PackageFreezer freezer = freezePackage(pkg.packageName,
9088                        "scanPackageInternalLI")) {
9089                    deletePackageLIF(pkg.packageName, null, true, null, 0, null, false, null);
9090                }
9091                ps = null;
9092            } else {
9093                /*
9094                 * If the newly-added system app is an older version than the
9095                 * already installed version, hide it. It will be scanned later
9096                 * and re-added like an update.
9097                 */
9098                if (pkg.mVersionCode <= ps.versionCode) {
9099                    shouldHideSystemApp = true;
9100                    logCriticalInfo(Log.INFO, "Package " + ps.name + " appeared at " + scanFile
9101                            + " but new version " + pkg.mVersionCode + " better than installed "
9102                            + ps.versionCode + "; hiding system");
9103                } else {
9104                    /*
9105                     * The newly found system app is a newer version that the
9106                     * one previously installed. Simply remove the
9107                     * already-installed application and replace it with our own
9108                     * while keeping the application data.
9109                     */
9110                    logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile
9111                            + " reverting from " + ps.codePathString + ": new version "
9112                            + pkg.mVersionCode + " better than installed " + ps.versionCode);
9113                    InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
9114                            ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
9115                    synchronized (mInstallLock) {
9116                        args.cleanUpResourcesLI();
9117                    }
9118                }
9119            }
9120        }
9121
9122        // The apk is forward locked (not public) if its code and resources
9123        // are kept in different files. (except for app in either system or
9124        // vendor path).
9125        // TODO grab this value from PackageSettings
9126        if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
9127            if (ps != null && !ps.codePath.equals(ps.resourcePath)) {
9128                policyFlags |= PackageParser.PARSE_FORWARD_LOCK;
9129            }
9130        }
9131
9132        final int userId = ((user == null) ? 0 : user.getIdentifier());
9133        if (ps != null && ps.getInstantApp(userId)) {
9134            scanFlags |= SCAN_AS_INSTANT_APP;
9135        }
9136
9137        // Note that we invoke the following method only if we are about to unpack an application
9138        PackageParser.Package scannedPkg = scanPackageLI(pkg, policyFlags, scanFlags
9139                | SCAN_UPDATE_SIGNATURE, currentTime, user);
9140
9141        /*
9142         * If the system app should be overridden by a previously installed
9143         * data, hide the system app now and let the /data/app scan pick it up
9144         * again.
9145         */
9146        if (shouldHideSystemApp) {
9147            synchronized (mPackages) {
9148                mSettings.disableSystemPackageLPw(pkg.packageName, true);
9149            }
9150        }
9151
9152        return scannedPkg;
9153    }
9154
9155    private void renameStaticSharedLibraryPackage(PackageParser.Package pkg) {
9156        // Derive the new package synthetic package name
9157        pkg.setPackageName(pkg.packageName + STATIC_SHARED_LIB_DELIMITER
9158                + pkg.staticSharedLibVersion);
9159    }
9160
9161    private static String fixProcessName(String defProcessName,
9162            String processName) {
9163        if (processName == null) {
9164            return defProcessName;
9165        }
9166        return processName;
9167    }
9168
9169    private void verifySignaturesLP(PackageSetting pkgSetting, PackageParser.Package pkg)
9170            throws PackageManagerException {
9171        if (pkgSetting.signatures.mSignatures != null) {
9172            // Already existing package. Make sure signatures match
9173            boolean match = compareSignatures(pkgSetting.signatures.mSignatures, pkg.mSignatures)
9174                    == PackageManager.SIGNATURE_MATCH;
9175            if (!match) {
9176                match = compareSignaturesCompat(pkgSetting.signatures, pkg)
9177                        == PackageManager.SIGNATURE_MATCH;
9178            }
9179            if (!match) {
9180                match = compareSignaturesRecover(pkgSetting.signatures, pkg)
9181                        == PackageManager.SIGNATURE_MATCH;
9182            }
9183            if (!match) {
9184                throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package "
9185                        + pkg.packageName + " signatures do not match the "
9186                        + "previously installed version; ignoring!");
9187            }
9188        }
9189
9190        // Check for shared user signatures
9191        if (pkgSetting.sharedUser != null && pkgSetting.sharedUser.signatures.mSignatures != null) {
9192            // Already existing package. Make sure signatures match
9193            boolean match = compareSignatures(pkgSetting.sharedUser.signatures.mSignatures,
9194                    pkg.mSignatures) == PackageManager.SIGNATURE_MATCH;
9195            if (!match) {
9196                match = compareSignaturesCompat(pkgSetting.sharedUser.signatures, pkg)
9197                        == PackageManager.SIGNATURE_MATCH;
9198            }
9199            if (!match) {
9200                match = compareSignaturesRecover(pkgSetting.sharedUser.signatures, pkg)
9201                        == PackageManager.SIGNATURE_MATCH;
9202            }
9203            if (!match) {
9204                throw new PackageManagerException(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE,
9205                        "Package " + pkg.packageName
9206                        + " has no signatures that match those in shared user "
9207                        + pkgSetting.sharedUser.name + "; ignoring!");
9208            }
9209        }
9210    }
9211
9212    /**
9213     * Enforces that only the system UID or root's UID can call a method exposed
9214     * via Binder.
9215     *
9216     * @param message used as message if SecurityException is thrown
9217     * @throws SecurityException if the caller is not system or root
9218     */
9219    private static final void enforceSystemOrRoot(String message) {
9220        final int uid = Binder.getCallingUid();
9221        if (uid != Process.SYSTEM_UID && uid != Process.ROOT_UID) {
9222            throw new SecurityException(message);
9223        }
9224    }
9225
9226    @Override
9227    public void performFstrimIfNeeded() {
9228        enforceSystemOrRoot("Only the system can request fstrim");
9229
9230        // Before everything else, see whether we need to fstrim.
9231        try {
9232            IStorageManager sm = PackageHelper.getStorageManager();
9233            if (sm != null) {
9234                boolean doTrim = false;
9235                final long interval = android.provider.Settings.Global.getLong(
9236                        mContext.getContentResolver(),
9237                        android.provider.Settings.Global.FSTRIM_MANDATORY_INTERVAL,
9238                        DEFAULT_MANDATORY_FSTRIM_INTERVAL);
9239                if (interval > 0) {
9240                    final long timeSinceLast = System.currentTimeMillis() - sm.lastMaintenance();
9241                    if (timeSinceLast > interval) {
9242                        doTrim = true;
9243                        Slog.w(TAG, "No disk maintenance in " + timeSinceLast
9244                                + "; running immediately");
9245                    }
9246                }
9247                if (doTrim) {
9248                    final boolean dexOptDialogShown;
9249                    synchronized (mPackages) {
9250                        dexOptDialogShown = mDexOptDialogShown;
9251                    }
9252                    if (!isFirstBoot() && dexOptDialogShown) {
9253                        try {
9254                            ActivityManager.getService().showBootMessage(
9255                                    mContext.getResources().getString(
9256                                            R.string.android_upgrading_fstrim), true);
9257                        } catch (RemoteException e) {
9258                        }
9259                    }
9260                    sm.runMaintenance();
9261                }
9262            } else {
9263                Slog.e(TAG, "storageManager service unavailable!");
9264            }
9265        } catch (RemoteException e) {
9266            // Can't happen; StorageManagerService is local
9267        }
9268    }
9269
9270    @Override
9271    public void updatePackagesIfNeeded() {
9272        enforceSystemOrRoot("Only the system can request package update");
9273
9274        // We need to re-extract after an OTA.
9275        boolean causeUpgrade = isUpgrade();
9276
9277        // First boot or factory reset.
9278        // Note: we also handle devices that are upgrading to N right now as if it is their
9279        //       first boot, as they do not have profile data.
9280        boolean causeFirstBoot = isFirstBoot() || mIsPreNUpgrade;
9281
9282        // We need to re-extract after a pruned cache, as AoT-ed files will be out of date.
9283        boolean causePrunedCache = VMRuntime.didPruneDalvikCache();
9284
9285        if (!causeUpgrade && !causeFirstBoot && !causePrunedCache) {
9286            return;
9287        }
9288
9289        List<PackageParser.Package> pkgs;
9290        synchronized (mPackages) {
9291            pkgs = PackageManagerServiceUtils.getPackagesForDexopt(mPackages.values(), this);
9292        }
9293
9294        final long startTime = System.nanoTime();
9295        final int[] stats = performDexOptUpgrade(pkgs, mIsPreNUpgrade /* showDialog */,
9296                    getCompilerFilterForReason(causeFirstBoot ? REASON_FIRST_BOOT : REASON_BOOT),
9297                    false /* bootComplete */);
9298
9299        final int elapsedTimeSeconds =
9300                (int) TimeUnit.NANOSECONDS.toSeconds(System.nanoTime() - startTime);
9301
9302        MetricsLogger.histogram(mContext, "opt_dialog_num_dexopted", stats[0]);
9303        MetricsLogger.histogram(mContext, "opt_dialog_num_skipped", stats[1]);
9304        MetricsLogger.histogram(mContext, "opt_dialog_num_failed", stats[2]);
9305        MetricsLogger.histogram(mContext, "opt_dialog_num_total", getOptimizablePackages().size());
9306        MetricsLogger.histogram(mContext, "opt_dialog_time_s", elapsedTimeSeconds);
9307    }
9308
9309    /*
9310     * Return the prebuilt profile path given a package base code path.
9311     */
9312    private static String getPrebuildProfilePath(PackageParser.Package pkg) {
9313        return pkg.baseCodePath + ".prof";
9314    }
9315
9316    /**
9317     * Performs dexopt on the set of packages in {@code packages} and returns an int array
9318     * containing statistics about the invocation. The array consists of three elements,
9319     * which are (in order) {@code numberOfPackagesOptimized}, {@code numberOfPackagesSkipped}
9320     * and {@code numberOfPackagesFailed}.
9321     */
9322    private int[] performDexOptUpgrade(List<PackageParser.Package> pkgs, boolean showDialog,
9323            String compilerFilter, boolean bootComplete) {
9324
9325        int numberOfPackagesVisited = 0;
9326        int numberOfPackagesOptimized = 0;
9327        int numberOfPackagesSkipped = 0;
9328        int numberOfPackagesFailed = 0;
9329        final int numberOfPackagesToDexopt = pkgs.size();
9330
9331        for (PackageParser.Package pkg : pkgs) {
9332            numberOfPackagesVisited++;
9333
9334            if ((isFirstBoot() || isUpgrade()) && isSystemApp(pkg)) {
9335                // Copy over initial preopt profiles since we won't get any JIT samples for methods
9336                // that are already compiled.
9337                File profileFile = new File(getPrebuildProfilePath(pkg));
9338                // Copy profile if it exists.
9339                if (profileFile.exists()) {
9340                    try {
9341                        // We could also do this lazily before calling dexopt in
9342                        // PackageDexOptimizer to prevent this happening on first boot. The issue
9343                        // is that we don't have a good way to say "do this only once".
9344                        if (!mInstaller.copySystemProfile(profileFile.getAbsolutePath(),
9345                                pkg.applicationInfo.uid, pkg.packageName)) {
9346                            Log.e(TAG, "Installer failed to copy system profile!");
9347                        }
9348                    } catch (Exception e) {
9349                        Log.e(TAG, "Failed to copy profile " + profileFile.getAbsolutePath() + " ",
9350                                e);
9351                    }
9352                }
9353            }
9354
9355            if (!PackageDexOptimizer.canOptimizePackage(pkg)) {
9356                if (DEBUG_DEXOPT) {
9357                    Log.i(TAG, "Skipping update of of non-optimizable app " + pkg.packageName);
9358                }
9359                numberOfPackagesSkipped++;
9360                continue;
9361            }
9362
9363            if (DEBUG_DEXOPT) {
9364                Log.i(TAG, "Updating app " + numberOfPackagesVisited + " of " +
9365                        numberOfPackagesToDexopt + ": " + pkg.packageName);
9366            }
9367
9368            if (showDialog) {
9369                try {
9370                    ActivityManager.getService().showBootMessage(
9371                            mContext.getResources().getString(R.string.android_upgrading_apk,
9372                                    numberOfPackagesVisited, numberOfPackagesToDexopt), true);
9373                } catch (RemoteException e) {
9374                }
9375                synchronized (mPackages) {
9376                    mDexOptDialogShown = true;
9377                }
9378            }
9379
9380            // If the OTA updates a system app which was previously preopted to a non-preopted state
9381            // the app might end up being verified at runtime. That's because by default the apps
9382            // are verify-profile but for preopted apps there's no profile.
9383            // Do a hacky check to ensure that if we have no profiles (a reasonable indication
9384            // that before the OTA the app was preopted) the app gets compiled with a non-profile
9385            // filter (by default 'quicken').
9386            // Note that at this stage unused apps are already filtered.
9387            if (isSystemApp(pkg) &&
9388                    DexFile.isProfileGuidedCompilerFilter(compilerFilter) &&
9389                    !Environment.getReferenceProfile(pkg.packageName).exists()) {
9390                compilerFilter = getNonProfileGuidedCompilerFilter(compilerFilter);
9391            }
9392
9393            // checkProfiles is false to avoid merging profiles during boot which
9394            // might interfere with background compilation (b/28612421).
9395            // Unfortunately this will also means that "pm.dexopt.boot=speed-profile" will
9396            // behave differently than "pm.dexopt.bg-dexopt=speed-profile" but that's a
9397            // trade-off worth doing to save boot time work.
9398            int dexoptFlags = bootComplete ? DexoptOptions.DEXOPT_BOOT_COMPLETE : 0;
9399            int primaryDexOptStaus = performDexOptTraced(new DexoptOptions(
9400                    pkg.packageName,
9401                    compilerFilter,
9402                    dexoptFlags));
9403
9404            boolean secondaryDexOptStatus = true;
9405            if (pkg.isSystemApp()) {
9406                // Only dexopt shared secondary dex files belonging to system apps to not slow down
9407                // too much boot after an OTA.
9408                int secondaryDexoptFlags = dexoptFlags |
9409                        DexoptOptions.DEXOPT_ONLY_SECONDARY_DEX |
9410                        DexoptOptions.DEXOPT_ONLY_SHARED_DEX;
9411                mDexManager.dexoptSecondaryDex(new DexoptOptions(
9412                        pkg.packageName,
9413                        compilerFilter,
9414                        secondaryDexoptFlags));
9415            }
9416
9417            if (secondaryDexOptStatus) {
9418                switch (primaryDexOptStaus) {
9419                    case PackageDexOptimizer.DEX_OPT_PERFORMED:
9420                        numberOfPackagesOptimized++;
9421                        break;
9422                    case PackageDexOptimizer.DEX_OPT_SKIPPED:
9423                        numberOfPackagesSkipped++;
9424                        break;
9425                    case PackageDexOptimizer.DEX_OPT_FAILED:
9426                        numberOfPackagesFailed++;
9427                        break;
9428                    default:
9429                        Log.e(TAG, "Unexpected dexopt return code " + primaryDexOptStaus);
9430                        break;
9431                }
9432            } else {
9433                numberOfPackagesFailed++;
9434            }
9435        }
9436
9437        return new int[] { numberOfPackagesOptimized, numberOfPackagesSkipped,
9438                numberOfPackagesFailed };
9439    }
9440
9441    @Override
9442    public void notifyPackageUse(String packageName, int reason) {
9443        synchronized (mPackages) {
9444            final int callingUid = Binder.getCallingUid();
9445            final int callingUserId = UserHandle.getUserId(callingUid);
9446            if (getInstantAppPackageName(callingUid) != null) {
9447                if (!isCallerSameApp(packageName, callingUid)) {
9448                    return;
9449                }
9450            } else {
9451                if (isInstantApp(packageName, callingUserId)) {
9452                    return;
9453                }
9454            }
9455            final PackageParser.Package p = mPackages.get(packageName);
9456            if (p == null) {
9457                return;
9458            }
9459            p.mLastPackageUsageTimeInMills[reason] = System.currentTimeMillis();
9460        }
9461    }
9462
9463    @Override
9464    public void notifyDexLoad(String loadingPackageName, List<String> dexPaths, String loaderIsa) {
9465        int userId = UserHandle.getCallingUserId();
9466        ApplicationInfo ai = getApplicationInfo(loadingPackageName, /*flags*/ 0, userId);
9467        if (ai == null) {
9468            Slog.w(TAG, "Loading a package that does not exist for the calling user. package="
9469                + loadingPackageName + ", user=" + userId);
9470            return;
9471        }
9472        mDexManager.notifyDexLoad(ai, dexPaths, loaderIsa, userId);
9473    }
9474
9475    @Override
9476    public void registerDexModule(String packageName, String dexModulePath, boolean isSharedModule,
9477            IDexModuleRegisterCallback callback) {
9478        int userId = UserHandle.getCallingUserId();
9479        ApplicationInfo ai = getApplicationInfo(packageName, /*flags*/ 0, userId);
9480        DexManager.RegisterDexModuleResult result;
9481        if (ai == null) {
9482            Slog.w(TAG, "Registering a dex module for a package that does not exist for the" +
9483                     " calling user. package=" + packageName + ", user=" + userId);
9484            result = new DexManager.RegisterDexModuleResult(false, "Package not installed");
9485        } else {
9486            result = mDexManager.registerDexModule(ai, dexModulePath, isSharedModule, userId);
9487        }
9488
9489        if (callback != null) {
9490            mHandler.post(() -> {
9491                try {
9492                    callback.onDexModuleRegistered(dexModulePath, result.success, result.message);
9493                } catch (RemoteException e) {
9494                    Slog.w(TAG, "Failed to callback after module registration " + dexModulePath, e);
9495                }
9496            });
9497        }
9498    }
9499
9500    /**
9501     * Ask the package manager to perform a dex-opt with the given compiler filter.
9502     *
9503     * Note: exposed only for the shell command to allow moving packages explicitly to a
9504     *       definite state.
9505     */
9506    @Override
9507    public boolean performDexOptMode(String packageName,
9508            boolean checkProfiles, String targetCompilerFilter, boolean force,
9509            boolean bootComplete) {
9510        int flags = (checkProfiles ? DexoptOptions.DEXOPT_CHECK_FOR_PROFILES_UPDATES : 0) |
9511                (force ? DexoptOptions.DEXOPT_FORCE : 0) |
9512                (bootComplete ? DexoptOptions.DEXOPT_BOOT_COMPLETE : 0);
9513        return performDexOpt(new DexoptOptions(packageName, targetCompilerFilter, flags));
9514    }
9515
9516    /**
9517     * Ask the package manager to perform a dex-opt with the given compiler filter on the
9518     * secondary dex files belonging to the given package.
9519     *
9520     * Note: exposed only for the shell command to allow moving packages explicitly to a
9521     *       definite state.
9522     */
9523    @Override
9524    public boolean performDexOptSecondary(String packageName, String compilerFilter,
9525            boolean force) {
9526        int flags = DexoptOptions.DEXOPT_ONLY_SECONDARY_DEX |
9527                DexoptOptions.DEXOPT_CHECK_FOR_PROFILES_UPDATES |
9528                DexoptOptions.DEXOPT_BOOT_COMPLETE |
9529                (force ? DexoptOptions.DEXOPT_FORCE : 0);
9530        return performDexOpt(new DexoptOptions(packageName, compilerFilter, flags));
9531    }
9532
9533    /*package*/ boolean performDexOpt(DexoptOptions options) {
9534        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
9535            return false;
9536        } else if (isInstantApp(options.getPackageName(), UserHandle.getCallingUserId())) {
9537            return false;
9538        }
9539
9540        if (options.isDexoptOnlySecondaryDex()) {
9541            return mDexManager.dexoptSecondaryDex(options);
9542        } else {
9543            int dexoptStatus = performDexOptWithStatus(options);
9544            return dexoptStatus != PackageDexOptimizer.DEX_OPT_FAILED;
9545        }
9546    }
9547
9548    /**
9549     * Perform dexopt on the given package and return one of following result:
9550     *  {@link PackageDexOptimizer#DEX_OPT_SKIPPED}
9551     *  {@link PackageDexOptimizer#DEX_OPT_PERFORMED}
9552     *  {@link PackageDexOptimizer#DEX_OPT_FAILED}
9553     */
9554    /* package */ int performDexOptWithStatus(DexoptOptions options) {
9555        return performDexOptTraced(options);
9556    }
9557
9558    private int performDexOptTraced(DexoptOptions options) {
9559        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt");
9560        try {
9561            return performDexOptInternal(options);
9562        } finally {
9563            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
9564        }
9565    }
9566
9567    // Run dexopt on a given package. Returns true if dexopt did not fail, i.e.
9568    // if the package can now be considered up to date for the given filter.
9569    private int performDexOptInternal(DexoptOptions options) {
9570        PackageParser.Package p;
9571        synchronized (mPackages) {
9572            p = mPackages.get(options.getPackageName());
9573            if (p == null) {
9574                // Package could not be found. Report failure.
9575                return PackageDexOptimizer.DEX_OPT_FAILED;
9576            }
9577            mPackageUsage.maybeWriteAsync(mPackages);
9578            mCompilerStats.maybeWriteAsync();
9579        }
9580        long callingId = Binder.clearCallingIdentity();
9581        try {
9582            synchronized (mInstallLock) {
9583                return performDexOptInternalWithDependenciesLI(p, options);
9584            }
9585        } finally {
9586            Binder.restoreCallingIdentity(callingId);
9587        }
9588    }
9589
9590    public ArraySet<String> getOptimizablePackages() {
9591        ArraySet<String> pkgs = new ArraySet<String>();
9592        synchronized (mPackages) {
9593            for (PackageParser.Package p : mPackages.values()) {
9594                if (PackageDexOptimizer.canOptimizePackage(p)) {
9595                    pkgs.add(p.packageName);
9596                }
9597            }
9598        }
9599        return pkgs;
9600    }
9601
9602    private int performDexOptInternalWithDependenciesLI(PackageParser.Package p,
9603            DexoptOptions options) {
9604        // Select the dex optimizer based on the force parameter.
9605        // Note: The force option is rarely used (cmdline input for testing, mostly), so it's OK to
9606        //       allocate an object here.
9607        PackageDexOptimizer pdo = options.isForce()
9608                ? new PackageDexOptimizer.ForcedUpdatePackageDexOptimizer(mPackageDexOptimizer)
9609                : mPackageDexOptimizer;
9610
9611        // Dexopt all dependencies first. Note: we ignore the return value and march on
9612        // on errors.
9613        // Note that we are going to call performDexOpt on those libraries as many times as
9614        // they are referenced in packages. When we do a batch of performDexOpt (for example
9615        // at boot, or background job), the passed 'targetCompilerFilter' stays the same,
9616        // and the first package that uses the library will dexopt it. The
9617        // others will see that the compiled code for the library is up to date.
9618        Collection<PackageParser.Package> deps = findSharedNonSystemLibraries(p);
9619        final String[] instructionSets = getAppDexInstructionSets(p.applicationInfo);
9620        if (!deps.isEmpty()) {
9621            for (PackageParser.Package depPackage : deps) {
9622                // TODO: Analyze and investigate if we (should) profile libraries.
9623                pdo.performDexOpt(depPackage, null /* sharedLibraries */, instructionSets,
9624                        getOrCreateCompilerPackageStats(depPackage),
9625                        true /* isUsedByOtherApps */,
9626                        options);
9627            }
9628        }
9629        return pdo.performDexOpt(p, p.usesLibraryFiles, instructionSets,
9630                getOrCreateCompilerPackageStats(p),
9631                mDexManager.isUsedByOtherApps(p.packageName), options);
9632    }
9633
9634    /**
9635     * Reconcile the information we have about the secondary dex files belonging to
9636     * {@code packagName} and the actual dex files. For all dex files that were
9637     * deleted, update the internal records and delete the generated oat files.
9638     */
9639    @Override
9640    public void reconcileSecondaryDexFiles(String packageName) {
9641        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
9642            return;
9643        } else if (isInstantApp(packageName, UserHandle.getCallingUserId())) {
9644            return;
9645        }
9646        mDexManager.reconcileSecondaryDexFiles(packageName);
9647    }
9648
9649    // TODO(calin): this is only needed for BackgroundDexOptService. Find a cleaner way to inject
9650    // a reference there.
9651    /*package*/ DexManager getDexManager() {
9652        return mDexManager;
9653    }
9654
9655    /**
9656     * Execute the background dexopt job immediately.
9657     */
9658    @Override
9659    public boolean runBackgroundDexoptJob() {
9660        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
9661            return false;
9662        }
9663        return BackgroundDexOptService.runIdleOptimizationsNow(this, mContext);
9664    }
9665
9666    List<PackageParser.Package> findSharedNonSystemLibraries(PackageParser.Package p) {
9667        if (p.usesLibraries != null || p.usesOptionalLibraries != null
9668                || p.usesStaticLibraries != null) {
9669            ArrayList<PackageParser.Package> retValue = new ArrayList<>();
9670            Set<String> collectedNames = new HashSet<>();
9671            findSharedNonSystemLibrariesRecursive(p, retValue, collectedNames);
9672
9673            retValue.remove(p);
9674
9675            return retValue;
9676        } else {
9677            return Collections.emptyList();
9678        }
9679    }
9680
9681    private void findSharedNonSystemLibrariesRecursive(PackageParser.Package p,
9682            ArrayList<PackageParser.Package> collected, Set<String> collectedNames) {
9683        if (!collectedNames.contains(p.packageName)) {
9684            collectedNames.add(p.packageName);
9685            collected.add(p);
9686
9687            if (p.usesLibraries != null) {
9688                findSharedNonSystemLibrariesRecursive(p.usesLibraries,
9689                        null, collected, collectedNames);
9690            }
9691            if (p.usesOptionalLibraries != null) {
9692                findSharedNonSystemLibrariesRecursive(p.usesOptionalLibraries,
9693                        null, collected, collectedNames);
9694            }
9695            if (p.usesStaticLibraries != null) {
9696                findSharedNonSystemLibrariesRecursive(p.usesStaticLibraries,
9697                        p.usesStaticLibrariesVersions, collected, collectedNames);
9698            }
9699        }
9700    }
9701
9702    private void findSharedNonSystemLibrariesRecursive(ArrayList<String> libs, int[] versions,
9703            ArrayList<PackageParser.Package> collected, Set<String> collectedNames) {
9704        final int libNameCount = libs.size();
9705        for (int i = 0; i < libNameCount; i++) {
9706            String libName = libs.get(i);
9707            int version = (versions != null && versions.length == libNameCount)
9708                    ? versions[i] : PackageManager.VERSION_CODE_HIGHEST;
9709            PackageParser.Package libPkg = findSharedNonSystemLibrary(libName, version);
9710            if (libPkg != null) {
9711                findSharedNonSystemLibrariesRecursive(libPkg, collected, collectedNames);
9712            }
9713        }
9714    }
9715
9716    private PackageParser.Package findSharedNonSystemLibrary(String name, int version) {
9717        synchronized (mPackages) {
9718            SharedLibraryEntry libEntry = getSharedLibraryEntryLPr(name, version);
9719            if (libEntry != null) {
9720                return mPackages.get(libEntry.apk);
9721            }
9722            return null;
9723        }
9724    }
9725
9726    private SharedLibraryEntry getSharedLibraryEntryLPr(String name, int version) {
9727        SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(name);
9728        if (versionedLib == null) {
9729            return null;
9730        }
9731        return versionedLib.get(version);
9732    }
9733
9734    private SharedLibraryEntry getLatestSharedLibraVersionLPr(PackageParser.Package pkg) {
9735        SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(
9736                pkg.staticSharedLibName);
9737        if (versionedLib == null) {
9738            return null;
9739        }
9740        int previousLibVersion = -1;
9741        final int versionCount = versionedLib.size();
9742        for (int i = 0; i < versionCount; i++) {
9743            final int libVersion = versionedLib.keyAt(i);
9744            if (libVersion < pkg.staticSharedLibVersion) {
9745                previousLibVersion = Math.max(previousLibVersion, libVersion);
9746            }
9747        }
9748        if (previousLibVersion >= 0) {
9749            return versionedLib.get(previousLibVersion);
9750        }
9751        return null;
9752    }
9753
9754    public void shutdown() {
9755        mPackageUsage.writeNow(mPackages);
9756        mCompilerStats.writeNow();
9757    }
9758
9759    @Override
9760    public void dumpProfiles(String packageName) {
9761        PackageParser.Package pkg;
9762        synchronized (mPackages) {
9763            pkg = mPackages.get(packageName);
9764            if (pkg == null) {
9765                throw new IllegalArgumentException("Unknown package: " + packageName);
9766            }
9767        }
9768        /* Only the shell, root, or the app user should be able to dump profiles. */
9769        int callingUid = Binder.getCallingUid();
9770        if (callingUid != Process.SHELL_UID &&
9771            callingUid != Process.ROOT_UID &&
9772            callingUid != pkg.applicationInfo.uid) {
9773            throw new SecurityException("dumpProfiles");
9774        }
9775
9776        synchronized (mInstallLock) {
9777            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dump profiles");
9778            final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid);
9779            try {
9780                List<String> allCodePaths = pkg.getAllCodePathsExcludingResourceOnly();
9781                String codePaths = TextUtils.join(";", allCodePaths);
9782                mInstaller.dumpProfiles(sharedGid, packageName, codePaths);
9783            } catch (InstallerException e) {
9784                Slog.w(TAG, "Failed to dump profiles", e);
9785            }
9786            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
9787        }
9788    }
9789
9790    @Override
9791    public void forceDexOpt(String packageName) {
9792        enforceSystemOrRoot("forceDexOpt");
9793
9794        PackageParser.Package pkg;
9795        synchronized (mPackages) {
9796            pkg = mPackages.get(packageName);
9797            if (pkg == null) {
9798                throw new IllegalArgumentException("Unknown package: " + packageName);
9799            }
9800        }
9801
9802        synchronized (mInstallLock) {
9803            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt");
9804
9805            // Whoever is calling forceDexOpt wants a compiled package.
9806            // Don't use profiles since that may cause compilation to be skipped.
9807            final int res = performDexOptInternalWithDependenciesLI(
9808                    pkg,
9809                    new DexoptOptions(packageName,
9810                            getDefaultCompilerFilter(),
9811                            DexoptOptions.DEXOPT_FORCE | DexoptOptions.DEXOPT_BOOT_COMPLETE));
9812
9813            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
9814            if (res != PackageDexOptimizer.DEX_OPT_PERFORMED) {
9815                throw new IllegalStateException("Failed to dexopt: " + res);
9816            }
9817        }
9818    }
9819
9820    private boolean verifyPackageUpdateLPr(PackageSetting oldPkg, PackageParser.Package newPkg) {
9821        if ((oldPkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) {
9822            Slog.w(TAG, "Unable to update from " + oldPkg.name
9823                    + " to " + newPkg.packageName
9824                    + ": old package not in system partition");
9825            return false;
9826        } else if (mPackages.get(oldPkg.name) != null) {
9827            Slog.w(TAG, "Unable to update from " + oldPkg.name
9828                    + " to " + newPkg.packageName
9829                    + ": old package still exists");
9830            return false;
9831        }
9832        return true;
9833    }
9834
9835    void removeCodePathLI(File codePath) {
9836        if (codePath.isDirectory()) {
9837            try {
9838                mInstaller.rmPackageDir(codePath.getAbsolutePath());
9839            } catch (InstallerException e) {
9840                Slog.w(TAG, "Failed to remove code path", e);
9841            }
9842        } else {
9843            codePath.delete();
9844        }
9845    }
9846
9847    private int[] resolveUserIds(int userId) {
9848        return (userId == UserHandle.USER_ALL) ? sUserManager.getUserIds() : new int[] { userId };
9849    }
9850
9851    private void clearAppDataLIF(PackageParser.Package pkg, int userId, int flags) {
9852        if (pkg == null) {
9853            Slog.wtf(TAG, "Package was null!", new Throwable());
9854            return;
9855        }
9856        clearAppDataLeafLIF(pkg, userId, flags);
9857        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
9858        for (int i = 0; i < childCount; i++) {
9859            clearAppDataLeafLIF(pkg.childPackages.get(i), userId, flags);
9860        }
9861    }
9862
9863    private void clearAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) {
9864        final PackageSetting ps;
9865        synchronized (mPackages) {
9866            ps = mSettings.mPackages.get(pkg.packageName);
9867        }
9868        for (int realUserId : resolveUserIds(userId)) {
9869            final long ceDataInode = (ps != null) ? ps.getCeDataInode(realUserId) : 0;
9870            try {
9871                mInstaller.clearAppData(pkg.volumeUuid, pkg.packageName, realUserId, flags,
9872                        ceDataInode);
9873            } catch (InstallerException e) {
9874                Slog.w(TAG, String.valueOf(e));
9875            }
9876        }
9877    }
9878
9879    private void destroyAppDataLIF(PackageParser.Package pkg, int userId, int flags) {
9880        if (pkg == null) {
9881            Slog.wtf(TAG, "Package was null!", new Throwable());
9882            return;
9883        }
9884        destroyAppDataLeafLIF(pkg, userId, flags);
9885        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
9886        for (int i = 0; i < childCount; i++) {
9887            destroyAppDataLeafLIF(pkg.childPackages.get(i), userId, flags);
9888        }
9889    }
9890
9891    private void destroyAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) {
9892        final PackageSetting ps;
9893        synchronized (mPackages) {
9894            ps = mSettings.mPackages.get(pkg.packageName);
9895        }
9896        for (int realUserId : resolveUserIds(userId)) {
9897            final long ceDataInode = (ps != null) ? ps.getCeDataInode(realUserId) : 0;
9898            try {
9899                mInstaller.destroyAppData(pkg.volumeUuid, pkg.packageName, realUserId, flags,
9900                        ceDataInode);
9901            } catch (InstallerException e) {
9902                Slog.w(TAG, String.valueOf(e));
9903            }
9904            mDexManager.notifyPackageDataDestroyed(pkg.packageName, userId);
9905        }
9906    }
9907
9908    private void destroyAppProfilesLIF(PackageParser.Package pkg, int userId) {
9909        if (pkg == null) {
9910            Slog.wtf(TAG, "Package was null!", new Throwable());
9911            return;
9912        }
9913        destroyAppProfilesLeafLIF(pkg);
9914        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
9915        for (int i = 0; i < childCount; i++) {
9916            destroyAppProfilesLeafLIF(pkg.childPackages.get(i));
9917        }
9918    }
9919
9920    private void destroyAppProfilesLeafLIF(PackageParser.Package pkg) {
9921        try {
9922            mInstaller.destroyAppProfiles(pkg.packageName);
9923        } catch (InstallerException e) {
9924            Slog.w(TAG, String.valueOf(e));
9925        }
9926    }
9927
9928    private void clearAppProfilesLIF(PackageParser.Package pkg, int userId) {
9929        if (pkg == null) {
9930            Slog.wtf(TAG, "Package was null!", new Throwable());
9931            return;
9932        }
9933        clearAppProfilesLeafLIF(pkg);
9934        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
9935        for (int i = 0; i < childCount; i++) {
9936            clearAppProfilesLeafLIF(pkg.childPackages.get(i));
9937        }
9938    }
9939
9940    private void clearAppProfilesLeafLIF(PackageParser.Package pkg) {
9941        try {
9942            mInstaller.clearAppProfiles(pkg.packageName);
9943        } catch (InstallerException e) {
9944            Slog.w(TAG, String.valueOf(e));
9945        }
9946    }
9947
9948    private void setInstallAndUpdateTime(PackageParser.Package pkg, long firstInstallTime,
9949            long lastUpdateTime) {
9950        // Set parent install/update time
9951        PackageSetting ps = (PackageSetting) pkg.mExtras;
9952        if (ps != null) {
9953            ps.firstInstallTime = firstInstallTime;
9954            ps.lastUpdateTime = lastUpdateTime;
9955        }
9956        // Set children install/update time
9957        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
9958        for (int i = 0; i < childCount; i++) {
9959            PackageParser.Package childPkg = pkg.childPackages.get(i);
9960            ps = (PackageSetting) childPkg.mExtras;
9961            if (ps != null) {
9962                ps.firstInstallTime = firstInstallTime;
9963                ps.lastUpdateTime = lastUpdateTime;
9964            }
9965        }
9966    }
9967
9968    private void addSharedLibraryLPr(Set<String> usesLibraryFiles,
9969            SharedLibraryEntry file,
9970            PackageParser.Package changingLib) {
9971        if (file.path != null) {
9972            usesLibraryFiles.add(file.path);
9973            return;
9974        }
9975        PackageParser.Package p = mPackages.get(file.apk);
9976        if (changingLib != null && changingLib.packageName.equals(file.apk)) {
9977            // If we are doing this while in the middle of updating a library apk,
9978            // then we need to make sure to use that new apk for determining the
9979            // dependencies here.  (We haven't yet finished committing the new apk
9980            // to the package manager state.)
9981            if (p == null || p.packageName.equals(changingLib.packageName)) {
9982                p = changingLib;
9983            }
9984        }
9985        if (p != null) {
9986            usesLibraryFiles.addAll(p.getAllCodePaths());
9987            if (p.usesLibraryFiles != null) {
9988                Collections.addAll(usesLibraryFiles, p.usesLibraryFiles);
9989            }
9990        }
9991    }
9992
9993    private void updateSharedLibrariesLPr(PackageParser.Package pkg,
9994            PackageParser.Package changingLib) throws PackageManagerException {
9995        if (pkg == null) {
9996            return;
9997        }
9998        // The collection used here must maintain the order of addition (so
9999        // that libraries are searched in the correct order) and must have no
10000        // duplicates.
10001        Set<String> usesLibraryFiles = null;
10002        if (pkg.usesLibraries != null) {
10003            usesLibraryFiles = addSharedLibrariesLPw(pkg.usesLibraries,
10004                    null, null, pkg.packageName, changingLib, true, null);
10005        }
10006        if (pkg.usesStaticLibraries != null) {
10007            usesLibraryFiles = addSharedLibrariesLPw(pkg.usesStaticLibraries,
10008                    pkg.usesStaticLibrariesVersions, pkg.usesStaticLibrariesCertDigests,
10009                    pkg.packageName, changingLib, true, usesLibraryFiles);
10010        }
10011        if (pkg.usesOptionalLibraries != null) {
10012            usesLibraryFiles = addSharedLibrariesLPw(pkg.usesOptionalLibraries,
10013                    null, null, pkg.packageName, changingLib, false, usesLibraryFiles);
10014        }
10015        if (!ArrayUtils.isEmpty(usesLibraryFiles)) {
10016            pkg.usesLibraryFiles = usesLibraryFiles.toArray(new String[usesLibraryFiles.size()]);
10017        } else {
10018            pkg.usesLibraryFiles = null;
10019        }
10020    }
10021
10022    private Set<String> addSharedLibrariesLPw(@NonNull List<String> requestedLibraries,
10023            @Nullable int[] requiredVersions, @Nullable String[] requiredCertDigests,
10024            @NonNull String packageName, @Nullable PackageParser.Package changingLib,
10025            boolean required, @Nullable Set<String> outUsedLibraries)
10026            throws PackageManagerException {
10027        final int libCount = requestedLibraries.size();
10028        for (int i = 0; i < libCount; i++) {
10029            final String libName = requestedLibraries.get(i);
10030            final int libVersion = requiredVersions != null ? requiredVersions[i]
10031                    : SharedLibraryInfo.VERSION_UNDEFINED;
10032            final SharedLibraryEntry libEntry = getSharedLibraryEntryLPr(libName, libVersion);
10033            if (libEntry == null) {
10034                if (required) {
10035                    throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY,
10036                            "Package " + packageName + " requires unavailable shared library "
10037                                    + libName + "; failing!");
10038                } else if (DEBUG_SHARED_LIBRARIES) {
10039                    Slog.i(TAG, "Package " + packageName
10040                            + " desires unavailable shared library "
10041                            + libName + "; ignoring!");
10042                }
10043            } else {
10044                if (requiredVersions != null && requiredCertDigests != null) {
10045                    if (libEntry.info.getVersion() != requiredVersions[i]) {
10046                        throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY,
10047                            "Package " + packageName + " requires unavailable static shared"
10048                                    + " library " + libName + " version "
10049                                    + libEntry.info.getVersion() + "; failing!");
10050                    }
10051
10052                    PackageParser.Package libPkg = mPackages.get(libEntry.apk);
10053                    if (libPkg == null) {
10054                        throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY,
10055                                "Package " + packageName + " requires unavailable static shared"
10056                                        + " library; failing!");
10057                    }
10058
10059                    String expectedCertDigest = requiredCertDigests[i];
10060                    String libCertDigest = PackageUtils.computeCertSha256Digest(
10061                                libPkg.mSignatures[0]);
10062                    if (!libCertDigest.equalsIgnoreCase(expectedCertDigest)) {
10063                        throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY,
10064                                "Package " + packageName + " requires differently signed" +
10065                                        " static shared library; failing!");
10066                    }
10067                }
10068
10069                if (outUsedLibraries == null) {
10070                    // Use LinkedHashSet to preserve the order of files added to
10071                    // usesLibraryFiles while eliminating duplicates.
10072                    outUsedLibraries = new LinkedHashSet<>();
10073                }
10074                addSharedLibraryLPr(outUsedLibraries, libEntry, changingLib);
10075            }
10076        }
10077        return outUsedLibraries;
10078    }
10079
10080    private static boolean hasString(List<String> list, List<String> which) {
10081        if (list == null) {
10082            return false;
10083        }
10084        for (int i=list.size()-1; i>=0; i--) {
10085            for (int j=which.size()-1; j>=0; j--) {
10086                if (which.get(j).equals(list.get(i))) {
10087                    return true;
10088                }
10089            }
10090        }
10091        return false;
10092    }
10093
10094    private ArrayList<PackageParser.Package> updateAllSharedLibrariesLPw(
10095            PackageParser.Package changingPkg) {
10096        ArrayList<PackageParser.Package> res = null;
10097        for (PackageParser.Package pkg : mPackages.values()) {
10098            if (changingPkg != null
10099                    && !hasString(pkg.usesLibraries, changingPkg.libraryNames)
10100                    && !hasString(pkg.usesOptionalLibraries, changingPkg.libraryNames)
10101                    && !ArrayUtils.contains(pkg.usesStaticLibraries,
10102                            changingPkg.staticSharedLibName)) {
10103                return null;
10104            }
10105            if (res == null) {
10106                res = new ArrayList<>();
10107            }
10108            res.add(pkg);
10109            try {
10110                updateSharedLibrariesLPr(pkg, changingPkg);
10111            } catch (PackageManagerException e) {
10112                // If a system app update or an app and a required lib missing we
10113                // delete the package and for updated system apps keep the data as
10114                // it is better for the user to reinstall than to be in an limbo
10115                // state. Also libs disappearing under an app should never happen
10116                // - just in case.
10117                if (!pkg.isSystemApp() || pkg.isUpdatedSystemApp()) {
10118                    final int flags = pkg.isUpdatedSystemApp()
10119                            ? PackageManager.DELETE_KEEP_DATA : 0;
10120                    deletePackageLIF(pkg.packageName, null, true, sUserManager.getUserIds(),
10121                            flags , null, true, null);
10122                }
10123                Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
10124            }
10125        }
10126        return res;
10127    }
10128
10129    /**
10130     * Derive the value of the {@code cpuAbiOverride} based on the provided
10131     * value and an optional stored value from the package settings.
10132     */
10133    private static String deriveAbiOverride(String abiOverride, PackageSetting settings) {
10134        String cpuAbiOverride = null;
10135
10136        if (NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(abiOverride)) {
10137            cpuAbiOverride = null;
10138        } else if (abiOverride != null) {
10139            cpuAbiOverride = abiOverride;
10140        } else if (settings != null) {
10141            cpuAbiOverride = settings.cpuAbiOverrideString;
10142        }
10143
10144        return cpuAbiOverride;
10145    }
10146
10147    private PackageParser.Package scanPackageTracedLI(PackageParser.Package pkg,
10148            final int policyFlags, int scanFlags, long currentTime, @Nullable UserHandle user)
10149                    throws PackageManagerException {
10150        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage");
10151        // If the package has children and this is the first dive in the function
10152        // we recursively scan the package with the SCAN_CHECK_ONLY flag set to see
10153        // whether all packages (parent and children) would be successfully scanned
10154        // before the actual scan since scanning mutates internal state and we want
10155        // to atomically install the package and its children.
10156        if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
10157            if (pkg.childPackages != null && pkg.childPackages.size() > 0) {
10158                scanFlags |= SCAN_CHECK_ONLY;
10159            }
10160        } else {
10161            scanFlags &= ~SCAN_CHECK_ONLY;
10162        }
10163
10164        final PackageParser.Package scannedPkg;
10165        try {
10166            // Scan the parent
10167            scannedPkg = scanPackageLI(pkg, policyFlags, scanFlags, currentTime, user);
10168            // Scan the children
10169            final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
10170            for (int i = 0; i < childCount; i++) {
10171                PackageParser.Package childPkg = pkg.childPackages.get(i);
10172                scanPackageLI(childPkg, policyFlags,
10173                        scanFlags, currentTime, user);
10174            }
10175        } finally {
10176            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
10177        }
10178
10179        if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
10180            return scanPackageTracedLI(pkg, policyFlags, scanFlags, currentTime, user);
10181        }
10182
10183        return scannedPkg;
10184    }
10185
10186    private PackageParser.Package scanPackageLI(PackageParser.Package pkg, final int policyFlags,
10187            int scanFlags, long currentTime, @Nullable UserHandle user)
10188                    throws PackageManagerException {
10189        boolean success = false;
10190        try {
10191            final PackageParser.Package res = scanPackageDirtyLI(pkg, policyFlags, scanFlags,
10192                    currentTime, user);
10193            success = true;
10194            return res;
10195        } finally {
10196            if (!success && (scanFlags & SCAN_DELETE_DATA_ON_FAILURES) != 0) {
10197                // DELETE_DATA_ON_FAILURES is only used by frozen paths
10198                destroyAppDataLIF(pkg, UserHandle.USER_ALL,
10199                        StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
10200                destroyAppProfilesLIF(pkg, UserHandle.USER_ALL);
10201            }
10202        }
10203    }
10204
10205    /**
10206     * Returns {@code true} if the given file contains code. Otherwise {@code false}.
10207     */
10208    private static boolean apkHasCode(String fileName) {
10209        StrictJarFile jarFile = null;
10210        try {
10211            jarFile = new StrictJarFile(fileName,
10212                    false /*verify*/, false /*signatureSchemeRollbackProtectionsEnforced*/);
10213            return jarFile.findEntry("classes.dex") != null;
10214        } catch (IOException ignore) {
10215        } finally {
10216            try {
10217                if (jarFile != null) {
10218                    jarFile.close();
10219                }
10220            } catch (IOException ignore) {}
10221        }
10222        return false;
10223    }
10224
10225    /**
10226     * Enforces code policy for the package. This ensures that if an APK has
10227     * declared hasCode="true" in its manifest that the APK actually contains
10228     * code.
10229     *
10230     * @throws PackageManagerException If bytecode could not be found when it should exist
10231     */
10232    private static void assertCodePolicy(PackageParser.Package pkg)
10233            throws PackageManagerException {
10234        final boolean shouldHaveCode =
10235                (pkg.applicationInfo.flags & ApplicationInfo.FLAG_HAS_CODE) != 0;
10236        if (shouldHaveCode && !apkHasCode(pkg.baseCodePath)) {
10237            throw new PackageManagerException(INSTALL_FAILED_INVALID_APK,
10238                    "Package " + pkg.baseCodePath + " code is missing");
10239        }
10240
10241        if (!ArrayUtils.isEmpty(pkg.splitCodePaths)) {
10242            for (int i = 0; i < pkg.splitCodePaths.length; i++) {
10243                final boolean splitShouldHaveCode =
10244                        (pkg.splitFlags[i] & ApplicationInfo.FLAG_HAS_CODE) != 0;
10245                if (splitShouldHaveCode && !apkHasCode(pkg.splitCodePaths[i])) {
10246                    throw new PackageManagerException(INSTALL_FAILED_INVALID_APK,
10247                            "Package " + pkg.splitCodePaths[i] + " code is missing");
10248                }
10249            }
10250        }
10251    }
10252
10253    private PackageParser.Package scanPackageDirtyLI(PackageParser.Package pkg,
10254            final int policyFlags, final int scanFlags, long currentTime, @Nullable UserHandle user)
10255                    throws PackageManagerException {
10256        if (DEBUG_PACKAGE_SCANNING) {
10257            if ((policyFlags & PackageParser.PARSE_CHATTY) != 0)
10258                Log.d(TAG, "Scanning package " + pkg.packageName);
10259        }
10260
10261        applyPolicy(pkg, policyFlags);
10262
10263        assertPackageIsValid(pkg, policyFlags, scanFlags);
10264
10265        if (Build.IS_DEBUGGABLE &&
10266                pkg.isPrivilegedApp() &&
10267                !SystemProperties.getBoolean("pm.dexopt.priv-apps", true)) {
10268            PackageManagerServiceUtils.logPackageHasUncompressedCode(pkg);
10269        }
10270
10271        // Initialize package source and resource directories
10272        final File scanFile = new File(pkg.codePath);
10273        final File destCodeFile = new File(pkg.applicationInfo.getCodePath());
10274        final File destResourceFile = new File(pkg.applicationInfo.getResourcePath());
10275
10276        SharedUserSetting suid = null;
10277        PackageSetting pkgSetting = null;
10278
10279        // Getting the package setting may have a side-effect, so if we
10280        // are only checking if scan would succeed, stash a copy of the
10281        // old setting to restore at the end.
10282        PackageSetting nonMutatedPs = null;
10283
10284        // We keep references to the derived CPU Abis from settings in oder to reuse
10285        // them in the case where we're not upgrading or booting for the first time.
10286        String primaryCpuAbiFromSettings = null;
10287        String secondaryCpuAbiFromSettings = null;
10288
10289        // writer
10290        synchronized (mPackages) {
10291            if (pkg.mSharedUserId != null) {
10292                // SIDE EFFECTS; may potentially allocate a new shared user
10293                suid = mSettings.getSharedUserLPw(
10294                        pkg.mSharedUserId, 0 /*pkgFlags*/, 0 /*pkgPrivateFlags*/, true /*create*/);
10295                if (DEBUG_PACKAGE_SCANNING) {
10296                    if ((policyFlags & PackageParser.PARSE_CHATTY) != 0)
10297                        Log.d(TAG, "Shared UserID " + pkg.mSharedUserId + " (uid=" + suid.userId
10298                                + "): packages=" + suid.packages);
10299                }
10300            }
10301
10302            // Check if we are renaming from an original package name.
10303            PackageSetting origPackage = null;
10304            String realName = null;
10305            if (pkg.mOriginalPackages != null) {
10306                // This package may need to be renamed to a previously
10307                // installed name.  Let's check on that...
10308                final String renamed = mSettings.getRenamedPackageLPr(pkg.mRealPackage);
10309                if (pkg.mOriginalPackages.contains(renamed)) {
10310                    // This package had originally been installed as the
10311                    // original name, and we have already taken care of
10312                    // transitioning to the new one.  Just update the new
10313                    // one to continue using the old name.
10314                    realName = pkg.mRealPackage;
10315                    if (!pkg.packageName.equals(renamed)) {
10316                        // Callers into this function may have already taken
10317                        // care of renaming the package; only do it here if
10318                        // it is not already done.
10319                        pkg.setPackageName(renamed);
10320                    }
10321                } else {
10322                    for (int i=pkg.mOriginalPackages.size()-1; i>=0; i--) {
10323                        if ((origPackage = mSettings.getPackageLPr(
10324                                pkg.mOriginalPackages.get(i))) != null) {
10325                            // We do have the package already installed under its
10326                            // original name...  should we use it?
10327                            if (!verifyPackageUpdateLPr(origPackage, pkg)) {
10328                                // New package is not compatible with original.
10329                                origPackage = null;
10330                                continue;
10331                            } else if (origPackage.sharedUser != null) {
10332                                // Make sure uid is compatible between packages.
10333                                if (!origPackage.sharedUser.name.equals(pkg.mSharedUserId)) {
10334                                    Slog.w(TAG, "Unable to migrate data from " + origPackage.name
10335                                            + " to " + pkg.packageName + ": old uid "
10336                                            + origPackage.sharedUser.name
10337                                            + " differs from " + pkg.mSharedUserId);
10338                                    origPackage = null;
10339                                    continue;
10340                                }
10341                                // TODO: Add case when shared user id is added [b/28144775]
10342                            } else {
10343                                if (DEBUG_UPGRADE) Log.v(TAG, "Renaming new package "
10344                                        + pkg.packageName + " to old name " + origPackage.name);
10345                            }
10346                            break;
10347                        }
10348                    }
10349                }
10350            }
10351
10352            if (mTransferedPackages.contains(pkg.packageName)) {
10353                Slog.w(TAG, "Package " + pkg.packageName
10354                        + " was transferred to another, but its .apk remains");
10355            }
10356
10357            // See comments in nonMutatedPs declaration
10358            if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
10359                PackageSetting foundPs = mSettings.getPackageLPr(pkg.packageName);
10360                if (foundPs != null) {
10361                    nonMutatedPs = new PackageSetting(foundPs);
10362                }
10363            }
10364
10365            if ((scanFlags & SCAN_FIRST_BOOT_OR_UPGRADE) == 0) {
10366                PackageSetting foundPs = mSettings.getPackageLPr(pkg.packageName);
10367                if (foundPs != null) {
10368                    primaryCpuAbiFromSettings = foundPs.primaryCpuAbiString;
10369                    secondaryCpuAbiFromSettings = foundPs.secondaryCpuAbiString;
10370                }
10371            }
10372
10373            pkgSetting = mSettings.getPackageLPr(pkg.packageName);
10374            if (pkgSetting != null && pkgSetting.sharedUser != suid) {
10375                PackageManagerService.reportSettingsProblem(Log.WARN,
10376                        "Package " + pkg.packageName + " shared user changed from "
10377                                + (pkgSetting.sharedUser != null
10378                                        ? pkgSetting.sharedUser.name : "<nothing>")
10379                                + " to "
10380                                + (suid != null ? suid.name : "<nothing>")
10381                                + "; replacing with new");
10382                pkgSetting = null;
10383            }
10384            final PackageSetting oldPkgSetting =
10385                    pkgSetting == null ? null : new PackageSetting(pkgSetting);
10386            final PackageSetting disabledPkgSetting =
10387                    mSettings.getDisabledSystemPkgLPr(pkg.packageName);
10388
10389            String[] usesStaticLibraries = null;
10390            if (pkg.usesStaticLibraries != null) {
10391                usesStaticLibraries = new String[pkg.usesStaticLibraries.size()];
10392                pkg.usesStaticLibraries.toArray(usesStaticLibraries);
10393            }
10394
10395            if (pkgSetting == null) {
10396                final String parentPackageName = (pkg.parentPackage != null)
10397                        ? pkg.parentPackage.packageName : null;
10398                final boolean instantApp = (scanFlags & SCAN_AS_INSTANT_APP) != 0;
10399                // REMOVE SharedUserSetting from method; update in a separate call
10400                pkgSetting = Settings.createNewSetting(pkg.packageName, origPackage,
10401                        disabledPkgSetting, realName, suid, destCodeFile, destResourceFile,
10402                        pkg.applicationInfo.nativeLibraryRootDir, pkg.applicationInfo.primaryCpuAbi,
10403                        pkg.applicationInfo.secondaryCpuAbi, pkg.mVersionCode,
10404                        pkg.applicationInfo.flags, pkg.applicationInfo.privateFlags, user,
10405                        true /*allowInstall*/, instantApp, parentPackageName,
10406                        pkg.getChildPackageNames(), UserManagerService.getInstance(),
10407                        usesStaticLibraries, pkg.usesStaticLibrariesVersions);
10408                // SIDE EFFECTS; updates system state; move elsewhere
10409                if (origPackage != null) {
10410                    mSettings.addRenamedPackageLPw(pkg.packageName, origPackage.name);
10411                }
10412                mSettings.addUserToSettingLPw(pkgSetting);
10413            } else {
10414                // REMOVE SharedUserSetting from method; update in a separate call.
10415                //
10416                // TODO(narayan): This update is bogus. nativeLibraryDir & primaryCpuAbi,
10417                // secondaryCpuAbi are not known at this point so we always update them
10418                // to null here, only to reset them at a later point.
10419                Settings.updatePackageSetting(pkgSetting, disabledPkgSetting, suid, destCodeFile,
10420                        pkg.applicationInfo.nativeLibraryDir, pkg.applicationInfo.primaryCpuAbi,
10421                        pkg.applicationInfo.secondaryCpuAbi, pkg.applicationInfo.flags,
10422                        pkg.applicationInfo.privateFlags, pkg.getChildPackageNames(),
10423                        UserManagerService.getInstance(), usesStaticLibraries,
10424                        pkg.usesStaticLibrariesVersions);
10425            }
10426            // SIDE EFFECTS; persists system state to files on disk; move elsewhere
10427            mSettings.writeUserRestrictionsLPw(pkgSetting, oldPkgSetting);
10428
10429            // SIDE EFFECTS; modifies system state; move elsewhere
10430            if (pkgSetting.origPackage != null) {
10431                // If we are first transitioning from an original package,
10432                // fix up the new package's name now.  We need to do this after
10433                // looking up the package under its new name, so getPackageLP
10434                // can take care of fiddling things correctly.
10435                pkg.setPackageName(origPackage.name);
10436
10437                // File a report about this.
10438                String msg = "New package " + pkgSetting.realName
10439                        + " renamed to replace old package " + pkgSetting.name;
10440                reportSettingsProblem(Log.WARN, msg);
10441
10442                // Make a note of it.
10443                if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
10444                    mTransferedPackages.add(origPackage.name);
10445                }
10446
10447                // No longer need to retain this.
10448                pkgSetting.origPackage = null;
10449            }
10450
10451            // SIDE EFFECTS; modifies system state; move elsewhere
10452            if ((scanFlags & SCAN_CHECK_ONLY) == 0 && realName != null) {
10453                // Make a note of it.
10454                mTransferedPackages.add(pkg.packageName);
10455            }
10456
10457            if (mSettings.isDisabledSystemPackageLPr(pkg.packageName)) {
10458                pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
10459            }
10460
10461            if ((scanFlags & SCAN_BOOTING) == 0
10462                    && (policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
10463                // Check all shared libraries and map to their actual file path.
10464                // We only do this here for apps not on a system dir, because those
10465                // are the only ones that can fail an install due to this.  We
10466                // will take care of the system apps by updating all of their
10467                // library paths after the scan is done. Also during the initial
10468                // scan don't update any libs as we do this wholesale after all
10469                // apps are scanned to avoid dependency based scanning.
10470                updateSharedLibrariesLPr(pkg, null);
10471            }
10472
10473            if (mFoundPolicyFile) {
10474                SELinuxMMAC.assignSeInfoValue(pkg);
10475            }
10476            pkg.applicationInfo.uid = pkgSetting.appId;
10477            pkg.mExtras = pkgSetting;
10478
10479
10480            // Static shared libs have same package with different versions where
10481            // we internally use a synthetic package name to allow multiple versions
10482            // of the same package, therefore we need to compare signatures against
10483            // the package setting for the latest library version.
10484            PackageSetting signatureCheckPs = pkgSetting;
10485            if (pkg.applicationInfo.isStaticSharedLibrary()) {
10486                SharedLibraryEntry libraryEntry = getLatestSharedLibraVersionLPr(pkg);
10487                if (libraryEntry != null) {
10488                    signatureCheckPs = mSettings.getPackageLPr(libraryEntry.apk);
10489                }
10490            }
10491
10492            if (shouldCheckUpgradeKeySetLP(signatureCheckPs, scanFlags)) {
10493                if (checkUpgradeKeySetLP(signatureCheckPs, pkg)) {
10494                    // We just determined the app is signed correctly, so bring
10495                    // over the latest parsed certs.
10496                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
10497                } else {
10498                    if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
10499                        throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
10500                                "Package " + pkg.packageName + " upgrade keys do not match the "
10501                                + "previously installed version");
10502                    } else {
10503                        pkgSetting.signatures.mSignatures = pkg.mSignatures;
10504                        String msg = "System package " + pkg.packageName
10505                                + " signature changed; retaining data.";
10506                        reportSettingsProblem(Log.WARN, msg);
10507                    }
10508                }
10509            } else {
10510                try {
10511                    // SIDE EFFECTS; compareSignaturesCompat() changes KeysetManagerService
10512                    verifySignaturesLP(signatureCheckPs, pkg);
10513                    // We just determined the app is signed correctly, so bring
10514                    // over the latest parsed certs.
10515                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
10516                } catch (PackageManagerException e) {
10517                    if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
10518                        throw e;
10519                    }
10520                    // The signature has changed, but this package is in the system
10521                    // image...  let's recover!
10522                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
10523                    // However...  if this package is part of a shared user, but it
10524                    // doesn't match the signature of the shared user, let's fail.
10525                    // What this means is that you can't change the signatures
10526                    // associated with an overall shared user, which doesn't seem all
10527                    // that unreasonable.
10528                    if (signatureCheckPs.sharedUser != null) {
10529                        if (compareSignatures(signatureCheckPs.sharedUser.signatures.mSignatures,
10530                                pkg.mSignatures) != PackageManager.SIGNATURE_MATCH) {
10531                            throw new PackageManagerException(
10532                                    INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES,
10533                                    "Signature mismatch for shared user: "
10534                                            + pkgSetting.sharedUser);
10535                        }
10536                    }
10537                    // File a report about this.
10538                    String msg = "System package " + pkg.packageName
10539                            + " signature changed; retaining data.";
10540                    reportSettingsProblem(Log.WARN, msg);
10541                }
10542            }
10543
10544            if ((scanFlags & SCAN_CHECK_ONLY) == 0 && pkg.mAdoptPermissions != null) {
10545                // This package wants to adopt ownership of permissions from
10546                // another package.
10547                for (int i = pkg.mAdoptPermissions.size() - 1; i >= 0; i--) {
10548                    final String origName = pkg.mAdoptPermissions.get(i);
10549                    final PackageSetting orig = mSettings.getPackageLPr(origName);
10550                    if (orig != null) {
10551                        if (verifyPackageUpdateLPr(orig, pkg)) {
10552                            Slog.i(TAG, "Adopting permissions from " + origName + " to "
10553                                    + pkg.packageName);
10554                            // SIDE EFFECTS; updates permissions system state; move elsewhere
10555                            mSettings.transferPermissionsLPw(origName, pkg.packageName);
10556                        }
10557                    }
10558                }
10559            }
10560        }
10561
10562        pkg.applicationInfo.processName = fixProcessName(
10563                pkg.applicationInfo.packageName,
10564                pkg.applicationInfo.processName);
10565
10566        if (pkg != mPlatformPackage) {
10567            // Get all of our default paths setup
10568            pkg.applicationInfo.initForUser(UserHandle.USER_SYSTEM);
10569        }
10570
10571        final String cpuAbiOverride = deriveAbiOverride(pkg.cpuAbiOverride, pkgSetting);
10572
10573        if ((scanFlags & SCAN_NEW_INSTALL) == 0) {
10574            if ((scanFlags & SCAN_FIRST_BOOT_OR_UPGRADE) != 0) {
10575                Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "derivePackageAbi");
10576                final boolean extractNativeLibs = !pkg.isLibrary();
10577                derivePackageAbi(pkg, scanFile, cpuAbiOverride, extractNativeLibs,
10578                        mAppLib32InstallDir);
10579                Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
10580
10581                // Some system apps still use directory structure for native libraries
10582                // in which case we might end up not detecting abi solely based on apk
10583                // structure. Try to detect abi based on directory structure.
10584                if (isSystemApp(pkg) && !pkg.isUpdatedSystemApp() &&
10585                        pkg.applicationInfo.primaryCpuAbi == null) {
10586                    setBundledAppAbisAndRoots(pkg, pkgSetting);
10587                    setNativeLibraryPaths(pkg, mAppLib32InstallDir);
10588                }
10589            } else {
10590                // This is not a first boot or an upgrade, don't bother deriving the
10591                // ABI during the scan. Instead, trust the value that was stored in the
10592                // package setting.
10593                pkg.applicationInfo.primaryCpuAbi = primaryCpuAbiFromSettings;
10594                pkg.applicationInfo.secondaryCpuAbi = secondaryCpuAbiFromSettings;
10595
10596                setNativeLibraryPaths(pkg, mAppLib32InstallDir);
10597
10598                if (DEBUG_ABI_SELECTION) {
10599                    Slog.i(TAG, "Using ABIS and native lib paths from settings : " +
10600                        pkg.packageName + " " + pkg.applicationInfo.primaryCpuAbi + ", " +
10601                        pkg.applicationInfo.secondaryCpuAbi);
10602                }
10603            }
10604        } else {
10605            if ((scanFlags & SCAN_MOVE) != 0) {
10606                // We haven't run dex-opt for this move (since we've moved the compiled output too)
10607                // but we already have this packages package info in the PackageSetting. We just
10608                // use that and derive the native library path based on the new codepath.
10609                pkg.applicationInfo.primaryCpuAbi = pkgSetting.primaryCpuAbiString;
10610                pkg.applicationInfo.secondaryCpuAbi = pkgSetting.secondaryCpuAbiString;
10611            }
10612
10613            // Set native library paths again. For moves, the path will be updated based on the
10614            // ABIs we've determined above. For non-moves, the path will be updated based on the
10615            // ABIs we determined during compilation, but the path will depend on the final
10616            // package path (after the rename away from the stage path).
10617            setNativeLibraryPaths(pkg, mAppLib32InstallDir);
10618        }
10619
10620        // This is a special case for the "system" package, where the ABI is
10621        // dictated by the zygote configuration (and init.rc). We should keep track
10622        // of this ABI so that we can deal with "normal" applications that run under
10623        // the same UID correctly.
10624        if (mPlatformPackage == pkg) {
10625            pkg.applicationInfo.primaryCpuAbi = VMRuntime.getRuntime().is64Bit() ?
10626                    Build.SUPPORTED_64_BIT_ABIS[0] : Build.SUPPORTED_32_BIT_ABIS[0];
10627        }
10628
10629        // If there's a mismatch between the abi-override in the package setting
10630        // and the abiOverride specified for the install. Warn about this because we
10631        // would've already compiled the app without taking the package setting into
10632        // account.
10633        if ((scanFlags & SCAN_NO_DEX) == 0 && (scanFlags & SCAN_NEW_INSTALL) != 0) {
10634            if (cpuAbiOverride == null && pkgSetting.cpuAbiOverrideString != null) {
10635                Slog.w(TAG, "Ignoring persisted ABI override " + cpuAbiOverride +
10636                        " for package " + pkg.packageName);
10637            }
10638        }
10639
10640        pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi;
10641        pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi;
10642        pkgSetting.cpuAbiOverrideString = cpuAbiOverride;
10643
10644        // Copy the derived override back to the parsed package, so that we can
10645        // update the package settings accordingly.
10646        pkg.cpuAbiOverride = cpuAbiOverride;
10647
10648        if (DEBUG_ABI_SELECTION) {
10649            Slog.d(TAG, "Resolved nativeLibraryRoot for " + pkg.applicationInfo.packageName
10650                    + " to root=" + pkg.applicationInfo.nativeLibraryRootDir + ", isa="
10651                    + pkg.applicationInfo.nativeLibraryRootRequiresIsa);
10652        }
10653
10654        // Push the derived path down into PackageSettings so we know what to
10655        // clean up at uninstall time.
10656        pkgSetting.legacyNativeLibraryPathString = pkg.applicationInfo.nativeLibraryRootDir;
10657
10658        if (DEBUG_ABI_SELECTION) {
10659            Log.d(TAG, "Abis for package[" + pkg.packageName + "] are" +
10660                    " primary=" + pkg.applicationInfo.primaryCpuAbi +
10661                    " secondary=" + pkg.applicationInfo.secondaryCpuAbi);
10662        }
10663
10664        // SIDE EFFECTS; removes DEX files from disk; move elsewhere
10665        if ((scanFlags & SCAN_BOOTING) == 0 && pkgSetting.sharedUser != null) {
10666            // We don't do this here during boot because we can do it all
10667            // at once after scanning all existing packages.
10668            //
10669            // We also do this *before* we perform dexopt on this package, so that
10670            // we can avoid redundant dexopts, and also to make sure we've got the
10671            // code and package path correct.
10672            adjustCpuAbisForSharedUserLPw(pkgSetting.sharedUser.packages, pkg);
10673        }
10674
10675        if (mFactoryTest && pkg.requestedPermissions.contains(
10676                android.Manifest.permission.FACTORY_TEST)) {
10677            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_FACTORY_TEST;
10678        }
10679
10680        if (isSystemApp(pkg)) {
10681            pkgSetting.isOrphaned = true;
10682        }
10683
10684        // Take care of first install / last update times.
10685        final long scanFileTime = getLastModifiedTime(pkg, scanFile);
10686        if (currentTime != 0) {
10687            if (pkgSetting.firstInstallTime == 0) {
10688                pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = currentTime;
10689            } else if ((scanFlags & SCAN_UPDATE_TIME) != 0) {
10690                pkgSetting.lastUpdateTime = currentTime;
10691            }
10692        } else if (pkgSetting.firstInstallTime == 0) {
10693            // We need *something*.  Take time time stamp of the file.
10694            pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = scanFileTime;
10695        } else if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0) {
10696            if (scanFileTime != pkgSetting.timeStamp) {
10697                // A package on the system image has changed; consider this
10698                // to be an update.
10699                pkgSetting.lastUpdateTime = scanFileTime;
10700            }
10701        }
10702        pkgSetting.setTimeStamp(scanFileTime);
10703
10704        if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
10705            if (nonMutatedPs != null) {
10706                synchronized (mPackages) {
10707                    mSettings.mPackages.put(nonMutatedPs.name, nonMutatedPs);
10708                }
10709            }
10710        } else {
10711            final int userId = user == null ? 0 : user.getIdentifier();
10712            // Modify state for the given package setting
10713            commitPackageSettings(pkg, pkgSetting, user, scanFlags,
10714                    (policyFlags & PackageParser.PARSE_CHATTY) != 0 /*chatty*/);
10715            if (pkgSetting.getInstantApp(userId)) {
10716                mInstantAppRegistry.addInstantAppLPw(userId, pkgSetting.appId);
10717            }
10718        }
10719        return pkg;
10720    }
10721
10722    /**
10723     * Applies policy to the parsed package based upon the given policy flags.
10724     * Ensures the package is in a good state.
10725     * <p>
10726     * Implementation detail: This method must NOT have any side effect. It would
10727     * ideally be static, but, it requires locks to read system state.
10728     */
10729    private void applyPolicy(PackageParser.Package pkg, int policyFlags) {
10730        if ((policyFlags&PackageParser.PARSE_IS_SYSTEM) != 0) {
10731            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_SYSTEM;
10732            if (pkg.applicationInfo.isDirectBootAware()) {
10733                // we're direct boot aware; set for all components
10734                for (PackageParser.Service s : pkg.services) {
10735                    s.info.encryptionAware = s.info.directBootAware = true;
10736                }
10737                for (PackageParser.Provider p : pkg.providers) {
10738                    p.info.encryptionAware = p.info.directBootAware = true;
10739                }
10740                for (PackageParser.Activity a : pkg.activities) {
10741                    a.info.encryptionAware = a.info.directBootAware = true;
10742                }
10743                for (PackageParser.Activity r : pkg.receivers) {
10744                    r.info.encryptionAware = r.info.directBootAware = true;
10745                }
10746            }
10747        } else {
10748            // Only allow system apps to be flagged as core apps.
10749            pkg.coreApp = false;
10750            // clear flags not applicable to regular apps
10751            pkg.applicationInfo.privateFlags &=
10752                    ~ApplicationInfo.PRIVATE_FLAG_DEFAULT_TO_DEVICE_PROTECTED_STORAGE;
10753            pkg.applicationInfo.privateFlags &=
10754                    ~ApplicationInfo.PRIVATE_FLAG_DIRECT_BOOT_AWARE;
10755        }
10756        pkg.mTrustedOverlay = (policyFlags&PackageParser.PARSE_TRUSTED_OVERLAY) != 0;
10757
10758        if ((policyFlags&PackageParser.PARSE_IS_PRIVILEGED) != 0) {
10759            pkg.applicationInfo.privateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
10760        }
10761
10762        if (!isSystemApp(pkg)) {
10763            // Only system apps can use these features.
10764            pkg.mOriginalPackages = null;
10765            pkg.mRealPackage = null;
10766            pkg.mAdoptPermissions = null;
10767        }
10768    }
10769
10770    /**
10771     * Asserts the parsed package is valid according to the given policy. If the
10772     * package is invalid, for whatever reason, throws {@link PackageManagerException}.
10773     * <p>
10774     * Implementation detail: This method must NOT have any side effects. It would
10775     * ideally be static, but, it requires locks to read system state.
10776     *
10777     * @throws PackageManagerException If the package fails any of the validation checks
10778     */
10779    private void assertPackageIsValid(PackageParser.Package pkg, int policyFlags, int scanFlags)
10780            throws PackageManagerException {
10781        if ((policyFlags & PackageParser.PARSE_ENFORCE_CODE) != 0) {
10782            assertCodePolicy(pkg);
10783        }
10784
10785        if (pkg.applicationInfo.getCodePath() == null ||
10786                pkg.applicationInfo.getResourcePath() == null) {
10787            // Bail out. The resource and code paths haven't been set.
10788            throw new PackageManagerException(INSTALL_FAILED_INVALID_APK,
10789                    "Code and resource paths haven't been set correctly");
10790        }
10791
10792        // Make sure we're not adding any bogus keyset info
10793        KeySetManagerService ksms = mSettings.mKeySetManagerService;
10794        ksms.assertScannedPackageValid(pkg);
10795
10796        synchronized (mPackages) {
10797            // The special "android" package can only be defined once
10798            if (pkg.packageName.equals("android")) {
10799                if (mAndroidApplication != null) {
10800                    Slog.w(TAG, "*************************************************");
10801                    Slog.w(TAG, "Core android package being redefined.  Skipping.");
10802                    Slog.w(TAG, " codePath=" + pkg.codePath);
10803                    Slog.w(TAG, "*************************************************");
10804                    throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE,
10805                            "Core android package being redefined.  Skipping.");
10806                }
10807            }
10808
10809            // A package name must be unique; don't allow duplicates
10810            if (mPackages.containsKey(pkg.packageName)) {
10811                throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE,
10812                        "Application package " + pkg.packageName
10813                        + " already installed.  Skipping duplicate.");
10814            }
10815
10816            if (pkg.applicationInfo.isStaticSharedLibrary()) {
10817                // Static libs have a synthetic package name containing the version
10818                // but we still want the base name to be unique.
10819                if (mPackages.containsKey(pkg.manifestPackageName)) {
10820                    throw new PackageManagerException(
10821                            "Duplicate static shared lib provider package");
10822                }
10823
10824                // Static shared libraries should have at least O target SDK
10825                if (pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.O) {
10826                    throw new PackageManagerException(
10827                            "Packages declaring static-shared libs must target O SDK or higher");
10828                }
10829
10830                // Package declaring static a shared lib cannot be instant apps
10831                if ((scanFlags & SCAN_AS_INSTANT_APP) != 0) {
10832                    throw new PackageManagerException(
10833                            "Packages declaring static-shared libs cannot be instant apps");
10834                }
10835
10836                // Package declaring static a shared lib cannot be renamed since the package
10837                // name is synthetic and apps can't code around package manager internals.
10838                if (!ArrayUtils.isEmpty(pkg.mOriginalPackages)) {
10839                    throw new PackageManagerException(
10840                            "Packages declaring static-shared libs cannot be renamed");
10841                }
10842
10843                // Package declaring static a shared lib cannot declare child packages
10844                if (!ArrayUtils.isEmpty(pkg.childPackages)) {
10845                    throw new PackageManagerException(
10846                            "Packages declaring static-shared libs cannot have child packages");
10847                }
10848
10849                // Package declaring static a shared lib cannot declare dynamic libs
10850                if (!ArrayUtils.isEmpty(pkg.libraryNames)) {
10851                    throw new PackageManagerException(
10852                            "Packages declaring static-shared libs cannot declare dynamic libs");
10853                }
10854
10855                // Package declaring static a shared lib cannot declare shared users
10856                if (pkg.mSharedUserId != null) {
10857                    throw new PackageManagerException(
10858                            "Packages declaring static-shared libs cannot declare shared users");
10859                }
10860
10861                // Static shared libs cannot declare activities
10862                if (!pkg.activities.isEmpty()) {
10863                    throw new PackageManagerException(
10864                            "Static shared libs cannot declare activities");
10865                }
10866
10867                // Static shared libs cannot declare services
10868                if (!pkg.services.isEmpty()) {
10869                    throw new PackageManagerException(
10870                            "Static shared libs cannot declare services");
10871                }
10872
10873                // Static shared libs cannot declare providers
10874                if (!pkg.providers.isEmpty()) {
10875                    throw new PackageManagerException(
10876                            "Static shared libs cannot declare content providers");
10877                }
10878
10879                // Static shared libs cannot declare receivers
10880                if (!pkg.receivers.isEmpty()) {
10881                    throw new PackageManagerException(
10882                            "Static shared libs cannot declare broadcast receivers");
10883                }
10884
10885                // Static shared libs cannot declare permission groups
10886                if (!pkg.permissionGroups.isEmpty()) {
10887                    throw new PackageManagerException(
10888                            "Static shared libs cannot declare permission groups");
10889                }
10890
10891                // Static shared libs cannot declare permissions
10892                if (!pkg.permissions.isEmpty()) {
10893                    throw new PackageManagerException(
10894                            "Static shared libs cannot declare permissions");
10895                }
10896
10897                // Static shared libs cannot declare protected broadcasts
10898                if (pkg.protectedBroadcasts != null) {
10899                    throw new PackageManagerException(
10900                            "Static shared libs cannot declare protected broadcasts");
10901                }
10902
10903                // Static shared libs cannot be overlay targets
10904                if (pkg.mOverlayTarget != null) {
10905                    throw new PackageManagerException(
10906                            "Static shared libs cannot be overlay targets");
10907                }
10908
10909                // The version codes must be ordered as lib versions
10910                int minVersionCode = Integer.MIN_VALUE;
10911                int maxVersionCode = Integer.MAX_VALUE;
10912
10913                SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(
10914                        pkg.staticSharedLibName);
10915                if (versionedLib != null) {
10916                    final int versionCount = versionedLib.size();
10917                    for (int i = 0; i < versionCount; i++) {
10918                        SharedLibraryInfo libInfo = versionedLib.valueAt(i).info;
10919                        final int libVersionCode = libInfo.getDeclaringPackage()
10920                                .getVersionCode();
10921                        if (libInfo.getVersion() <  pkg.staticSharedLibVersion) {
10922                            minVersionCode = Math.max(minVersionCode, libVersionCode + 1);
10923                        } else if (libInfo.getVersion() >  pkg.staticSharedLibVersion) {
10924                            maxVersionCode = Math.min(maxVersionCode, libVersionCode - 1);
10925                        } else {
10926                            minVersionCode = maxVersionCode = libVersionCode;
10927                            break;
10928                        }
10929                    }
10930                }
10931                if (pkg.mVersionCode < minVersionCode || pkg.mVersionCode > maxVersionCode) {
10932                    throw new PackageManagerException("Static shared"
10933                            + " lib version codes must be ordered as lib versions");
10934                }
10935            }
10936
10937            // Only privileged apps and updated privileged apps can add child packages.
10938            if (pkg.childPackages != null && !pkg.childPackages.isEmpty()) {
10939                if ((policyFlags & PARSE_IS_PRIVILEGED) == 0) {
10940                    throw new PackageManagerException("Only privileged apps can add child "
10941                            + "packages. Ignoring package " + pkg.packageName);
10942                }
10943                final int childCount = pkg.childPackages.size();
10944                for (int i = 0; i < childCount; i++) {
10945                    PackageParser.Package childPkg = pkg.childPackages.get(i);
10946                    if (mSettings.hasOtherDisabledSystemPkgWithChildLPr(pkg.packageName,
10947                            childPkg.packageName)) {
10948                        throw new PackageManagerException("Can't override child of "
10949                                + "another disabled app. Ignoring package " + pkg.packageName);
10950                    }
10951                }
10952            }
10953
10954            // If we're only installing presumed-existing packages, require that the
10955            // scanned APK is both already known and at the path previously established
10956            // for it.  Previously unknown packages we pick up normally, but if we have an
10957            // a priori expectation about this package's install presence, enforce it.
10958            // With a singular exception for new system packages. When an OTA contains
10959            // a new system package, we allow the codepath to change from a system location
10960            // to the user-installed location. If we don't allow this change, any newer,
10961            // user-installed version of the application will be ignored.
10962            if ((scanFlags & SCAN_REQUIRE_KNOWN) != 0) {
10963                if (mExpectingBetter.containsKey(pkg.packageName)) {
10964                    logCriticalInfo(Log.WARN,
10965                            "Relax SCAN_REQUIRE_KNOWN requirement for package " + pkg.packageName);
10966                } else {
10967                    PackageSetting known = mSettings.getPackageLPr(pkg.packageName);
10968                    if (known != null) {
10969                        if (DEBUG_PACKAGE_SCANNING) {
10970                            Log.d(TAG, "Examining " + pkg.codePath
10971                                    + " and requiring known paths " + known.codePathString
10972                                    + " & " + known.resourcePathString);
10973                        }
10974                        if (!pkg.applicationInfo.getCodePath().equals(known.codePathString)
10975                                || !pkg.applicationInfo.getResourcePath().equals(
10976                                        known.resourcePathString)) {
10977                            throw new PackageManagerException(INSTALL_FAILED_PACKAGE_CHANGED,
10978                                    "Application package " + pkg.packageName
10979                                    + " found at " + pkg.applicationInfo.getCodePath()
10980                                    + " but expected at " + known.codePathString
10981                                    + "; ignoring.");
10982                        }
10983                    }
10984                }
10985            }
10986
10987            // Verify that this new package doesn't have any content providers
10988            // that conflict with existing packages.  Only do this if the
10989            // package isn't already installed, since we don't want to break
10990            // things that are installed.
10991            if ((scanFlags & SCAN_NEW_INSTALL) != 0) {
10992                final int N = pkg.providers.size();
10993                int i;
10994                for (i=0; i<N; i++) {
10995                    PackageParser.Provider p = pkg.providers.get(i);
10996                    if (p.info.authority != null) {
10997                        String names[] = p.info.authority.split(";");
10998                        for (int j = 0; j < names.length; j++) {
10999                            if (mProvidersByAuthority.containsKey(names[j])) {
11000                                PackageParser.Provider other = mProvidersByAuthority.get(names[j]);
11001                                final String otherPackageName =
11002                                        ((other != null && other.getComponentName() != null) ?
11003                                                other.getComponentName().getPackageName() : "?");
11004                                throw new PackageManagerException(
11005                                        INSTALL_FAILED_CONFLICTING_PROVIDER,
11006                                        "Can't install because provider name " + names[j]
11007                                                + " (in package " + pkg.applicationInfo.packageName
11008                                                + ") is already used by " + otherPackageName);
11009                            }
11010                        }
11011                    }
11012                }
11013            }
11014        }
11015    }
11016
11017    private boolean addSharedLibraryLPw(String path, String apk, String name, int version,
11018            int type, String declaringPackageName, int declaringVersionCode) {
11019        SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(name);
11020        if (versionedLib == null) {
11021            versionedLib = new SparseArray<>();
11022            mSharedLibraries.put(name, versionedLib);
11023            if (type == SharedLibraryInfo.TYPE_STATIC) {
11024                mStaticLibsByDeclaringPackage.put(declaringPackageName, versionedLib);
11025            }
11026        } else if (versionedLib.indexOfKey(version) >= 0) {
11027            return false;
11028        }
11029        SharedLibraryEntry libEntry = new SharedLibraryEntry(path, apk, name,
11030                version, type, declaringPackageName, declaringVersionCode);
11031        versionedLib.put(version, libEntry);
11032        return true;
11033    }
11034
11035    private boolean removeSharedLibraryLPw(String name, int version) {
11036        SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(name);
11037        if (versionedLib == null) {
11038            return false;
11039        }
11040        final int libIdx = versionedLib.indexOfKey(version);
11041        if (libIdx < 0) {
11042            return false;
11043        }
11044        SharedLibraryEntry libEntry = versionedLib.valueAt(libIdx);
11045        versionedLib.remove(version);
11046        if (versionedLib.size() <= 0) {
11047            mSharedLibraries.remove(name);
11048            if (libEntry.info.getType() == SharedLibraryInfo.TYPE_STATIC) {
11049                mStaticLibsByDeclaringPackage.remove(libEntry.info.getDeclaringPackage()
11050                        .getPackageName());
11051            }
11052        }
11053        return true;
11054    }
11055
11056    /**
11057     * Adds a scanned package to the system. When this method is finished, the package will
11058     * be available for query, resolution, etc...
11059     */
11060    private void commitPackageSettings(PackageParser.Package pkg, PackageSetting pkgSetting,
11061            UserHandle user, int scanFlags, boolean chatty) throws PackageManagerException {
11062        final String pkgName = pkg.packageName;
11063        if (mCustomResolverComponentName != null &&
11064                mCustomResolverComponentName.getPackageName().equals(pkg.packageName)) {
11065            setUpCustomResolverActivity(pkg);
11066        }
11067
11068        if (pkg.packageName.equals("android")) {
11069            synchronized (mPackages) {
11070                if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
11071                    // Set up information for our fall-back user intent resolution activity.
11072                    mPlatformPackage = pkg;
11073                    pkg.mVersionCode = mSdkVersion;
11074                    mAndroidApplication = pkg.applicationInfo;
11075                    if (!mResolverReplaced) {
11076                        mResolveActivity.applicationInfo = mAndroidApplication;
11077                        mResolveActivity.name = ResolverActivity.class.getName();
11078                        mResolveActivity.packageName = mAndroidApplication.packageName;
11079                        mResolveActivity.processName = "system:ui";
11080                        mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
11081                        mResolveActivity.documentLaunchMode = ActivityInfo.DOCUMENT_LAUNCH_NEVER;
11082                        mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS;
11083                        mResolveActivity.theme = R.style.Theme_Material_Dialog_Alert;
11084                        mResolveActivity.exported = true;
11085                        mResolveActivity.enabled = true;
11086                        mResolveActivity.resizeMode = ActivityInfo.RESIZE_MODE_RESIZEABLE;
11087                        mResolveActivity.configChanges = ActivityInfo.CONFIG_SCREEN_SIZE
11088                                | ActivityInfo.CONFIG_SMALLEST_SCREEN_SIZE
11089                                | ActivityInfo.CONFIG_SCREEN_LAYOUT
11090                                | ActivityInfo.CONFIG_ORIENTATION
11091                                | ActivityInfo.CONFIG_KEYBOARD
11092                                | ActivityInfo.CONFIG_KEYBOARD_HIDDEN;
11093                        mResolveInfo.activityInfo = mResolveActivity;
11094                        mResolveInfo.priority = 0;
11095                        mResolveInfo.preferredOrder = 0;
11096                        mResolveInfo.match = 0;
11097                        mResolveComponentName = new ComponentName(
11098                                mAndroidApplication.packageName, mResolveActivity.name);
11099                    }
11100                }
11101            }
11102        }
11103
11104        ArrayList<PackageParser.Package> clientLibPkgs = null;
11105        // writer
11106        synchronized (mPackages) {
11107            boolean hasStaticSharedLibs = false;
11108
11109            // Any app can add new static shared libraries
11110            if (pkg.staticSharedLibName != null) {
11111                // Static shared libs don't allow renaming as they have synthetic package
11112                // names to allow install of multiple versions, so use name from manifest.
11113                if (addSharedLibraryLPw(null, pkg.packageName, pkg.staticSharedLibName,
11114                        pkg.staticSharedLibVersion, SharedLibraryInfo.TYPE_STATIC,
11115                        pkg.manifestPackageName, pkg.mVersionCode)) {
11116                    hasStaticSharedLibs = true;
11117                } else {
11118                    Slog.w(TAG, "Package " + pkg.packageName + " library "
11119                                + pkg.staticSharedLibName + " already exists; skipping");
11120                }
11121                // Static shared libs cannot be updated once installed since they
11122                // use synthetic package name which includes the version code, so
11123                // not need to update other packages's shared lib dependencies.
11124            }
11125
11126            if (!hasStaticSharedLibs
11127                    && (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
11128                // Only system apps can add new dynamic shared libraries.
11129                if (pkg.libraryNames != null) {
11130                    for (int i = 0; i < pkg.libraryNames.size(); i++) {
11131                        String name = pkg.libraryNames.get(i);
11132                        boolean allowed = false;
11133                        if (pkg.isUpdatedSystemApp()) {
11134                            // New library entries can only be added through the
11135                            // system image.  This is important to get rid of a lot
11136                            // of nasty edge cases: for example if we allowed a non-
11137                            // system update of the app to add a library, then uninstalling
11138                            // the update would make the library go away, and assumptions
11139                            // we made such as through app install filtering would now
11140                            // have allowed apps on the device which aren't compatible
11141                            // with it.  Better to just have the restriction here, be
11142                            // conservative, and create many fewer cases that can negatively
11143                            // impact the user experience.
11144                            final PackageSetting sysPs = mSettings
11145                                    .getDisabledSystemPkgLPr(pkg.packageName);
11146                            if (sysPs.pkg != null && sysPs.pkg.libraryNames != null) {
11147                                for (int j = 0; j < sysPs.pkg.libraryNames.size(); j++) {
11148                                    if (name.equals(sysPs.pkg.libraryNames.get(j))) {
11149                                        allowed = true;
11150                                        break;
11151                                    }
11152                                }
11153                            }
11154                        } else {
11155                            allowed = true;
11156                        }
11157                        if (allowed) {
11158                            if (!addSharedLibraryLPw(null, pkg.packageName, name,
11159                                    SharedLibraryInfo.VERSION_UNDEFINED,
11160                                    SharedLibraryInfo.TYPE_DYNAMIC,
11161                                    pkg.packageName, pkg.mVersionCode)) {
11162                                Slog.w(TAG, "Package " + pkg.packageName + " library "
11163                                        + name + " already exists; skipping");
11164                            }
11165                        } else {
11166                            Slog.w(TAG, "Package " + pkg.packageName + " declares lib "
11167                                    + name + " that is not declared on system image; skipping");
11168                        }
11169                    }
11170
11171                    if ((scanFlags & SCAN_BOOTING) == 0) {
11172                        // If we are not booting, we need to update any applications
11173                        // that are clients of our shared library.  If we are booting,
11174                        // this will all be done once the scan is complete.
11175                        clientLibPkgs = updateAllSharedLibrariesLPw(pkg);
11176                    }
11177                }
11178            }
11179        }
11180
11181        if ((scanFlags & SCAN_BOOTING) != 0) {
11182            // No apps can run during boot scan, so they don't need to be frozen
11183        } else if ((scanFlags & SCAN_DONT_KILL_APP) != 0) {
11184            // Caller asked to not kill app, so it's probably not frozen
11185        } else if ((scanFlags & SCAN_IGNORE_FROZEN) != 0) {
11186            // Caller asked us to ignore frozen check for some reason; they
11187            // probably didn't know the package name
11188        } else {
11189            // We're doing major surgery on this package, so it better be frozen
11190            // right now to keep it from launching
11191            checkPackageFrozen(pkgName);
11192        }
11193
11194        // Also need to kill any apps that are dependent on the library.
11195        if (clientLibPkgs != null) {
11196            for (int i=0; i<clientLibPkgs.size(); i++) {
11197                PackageParser.Package clientPkg = clientLibPkgs.get(i);
11198                killApplication(clientPkg.applicationInfo.packageName,
11199                        clientPkg.applicationInfo.uid, "update lib");
11200            }
11201        }
11202
11203        // writer
11204        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings");
11205
11206        synchronized (mPackages) {
11207            // We don't expect installation to fail beyond this point
11208
11209            // Add the new setting to mSettings
11210            mSettings.insertPackageSettingLPw(pkgSetting, pkg);
11211            // Add the new setting to mPackages
11212            mPackages.put(pkg.applicationInfo.packageName, pkg);
11213            // Make sure we don't accidentally delete its data.
11214            final Iterator<PackageCleanItem> iter = mSettings.mPackagesToBeCleaned.iterator();
11215            while (iter.hasNext()) {
11216                PackageCleanItem item = iter.next();
11217                if (pkgName.equals(item.packageName)) {
11218                    iter.remove();
11219                }
11220            }
11221
11222            // Add the package's KeySets to the global KeySetManagerService
11223            KeySetManagerService ksms = mSettings.mKeySetManagerService;
11224            ksms.addScannedPackageLPw(pkg);
11225
11226            int N = pkg.providers.size();
11227            StringBuilder r = null;
11228            int i;
11229            for (i=0; i<N; i++) {
11230                PackageParser.Provider p = pkg.providers.get(i);
11231                p.info.processName = fixProcessName(pkg.applicationInfo.processName,
11232                        p.info.processName);
11233                mProviders.addProvider(p);
11234                p.syncable = p.info.isSyncable;
11235                if (p.info.authority != null) {
11236                    String names[] = p.info.authority.split(";");
11237                    p.info.authority = null;
11238                    for (int j = 0; j < names.length; j++) {
11239                        if (j == 1 && p.syncable) {
11240                            // We only want the first authority for a provider to possibly be
11241                            // syncable, so if we already added this provider using a different
11242                            // authority clear the syncable flag. We copy the provider before
11243                            // changing it because the mProviders object contains a reference
11244                            // to a provider that we don't want to change.
11245                            // Only do this for the second authority since the resulting provider
11246                            // object can be the same for all future authorities for this provider.
11247                            p = new PackageParser.Provider(p);
11248                            p.syncable = false;
11249                        }
11250                        if (!mProvidersByAuthority.containsKey(names[j])) {
11251                            mProvidersByAuthority.put(names[j], p);
11252                            if (p.info.authority == null) {
11253                                p.info.authority = names[j];
11254                            } else {
11255                                p.info.authority = p.info.authority + ";" + names[j];
11256                            }
11257                            if (DEBUG_PACKAGE_SCANNING) {
11258                                if (chatty)
11259                                    Log.d(TAG, "Registered content provider: " + names[j]
11260                                            + ", className = " + p.info.name + ", isSyncable = "
11261                                            + p.info.isSyncable);
11262                            }
11263                        } else {
11264                            PackageParser.Provider other = mProvidersByAuthority.get(names[j]);
11265                            Slog.w(TAG, "Skipping provider name " + names[j] +
11266                                    " (in package " + pkg.applicationInfo.packageName +
11267                                    "): name already used by "
11268                                    + ((other != null && other.getComponentName() != null)
11269                                            ? other.getComponentName().getPackageName() : "?"));
11270                        }
11271                    }
11272                }
11273                if (chatty) {
11274                    if (r == null) {
11275                        r = new StringBuilder(256);
11276                    } else {
11277                        r.append(' ');
11278                    }
11279                    r.append(p.info.name);
11280                }
11281            }
11282            if (r != null) {
11283                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Providers: " + r);
11284            }
11285
11286            N = pkg.services.size();
11287            r = null;
11288            for (i=0; i<N; i++) {
11289                PackageParser.Service s = pkg.services.get(i);
11290                s.info.processName = fixProcessName(pkg.applicationInfo.processName,
11291                        s.info.processName);
11292                mServices.addService(s);
11293                if (chatty) {
11294                    if (r == null) {
11295                        r = new StringBuilder(256);
11296                    } else {
11297                        r.append(' ');
11298                    }
11299                    r.append(s.info.name);
11300                }
11301            }
11302            if (r != null) {
11303                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Services: " + r);
11304            }
11305
11306            N = pkg.receivers.size();
11307            r = null;
11308            for (i=0; i<N; i++) {
11309                PackageParser.Activity a = pkg.receivers.get(i);
11310                a.info.processName = fixProcessName(pkg.applicationInfo.processName,
11311                        a.info.processName);
11312                mReceivers.addActivity(a, "receiver");
11313                if (chatty) {
11314                    if (r == null) {
11315                        r = new StringBuilder(256);
11316                    } else {
11317                        r.append(' ');
11318                    }
11319                    r.append(a.info.name);
11320                }
11321            }
11322            if (r != null) {
11323                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Receivers: " + r);
11324            }
11325
11326            N = pkg.activities.size();
11327            r = null;
11328            for (i=0; i<N; i++) {
11329                PackageParser.Activity a = pkg.activities.get(i);
11330                a.info.processName = fixProcessName(pkg.applicationInfo.processName,
11331                        a.info.processName);
11332                mActivities.addActivity(a, "activity");
11333                if (chatty) {
11334                    if (r == null) {
11335                        r = new StringBuilder(256);
11336                    } else {
11337                        r.append(' ');
11338                    }
11339                    r.append(a.info.name);
11340                }
11341            }
11342            if (r != null) {
11343                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Activities: " + r);
11344            }
11345
11346            N = pkg.permissionGroups.size();
11347            r = null;
11348            for (i=0; i<N; i++) {
11349                PackageParser.PermissionGroup pg = pkg.permissionGroups.get(i);
11350                PackageParser.PermissionGroup cur = mPermissionGroups.get(pg.info.name);
11351                final String curPackageName = cur == null ? null : cur.info.packageName;
11352                // Dont allow ephemeral apps to define new permission groups.
11353                if ((scanFlags & SCAN_AS_INSTANT_APP) != 0) {
11354                    Slog.w(TAG, "Permission group " + pg.info.name + " from package "
11355                            + pg.info.packageName
11356                            + " ignored: instant apps cannot define new permission groups.");
11357                    continue;
11358                }
11359                final boolean isPackageUpdate = pg.info.packageName.equals(curPackageName);
11360                if (cur == null || isPackageUpdate) {
11361                    mPermissionGroups.put(pg.info.name, pg);
11362                    if (chatty) {
11363                        if (r == null) {
11364                            r = new StringBuilder(256);
11365                        } else {
11366                            r.append(' ');
11367                        }
11368                        if (isPackageUpdate) {
11369                            r.append("UPD:");
11370                        }
11371                        r.append(pg.info.name);
11372                    }
11373                } else {
11374                    Slog.w(TAG, "Permission group " + pg.info.name + " from package "
11375                            + pg.info.packageName + " ignored: original from "
11376                            + cur.info.packageName);
11377                    if (chatty) {
11378                        if (r == null) {
11379                            r = new StringBuilder(256);
11380                        } else {
11381                            r.append(' ');
11382                        }
11383                        r.append("DUP:");
11384                        r.append(pg.info.name);
11385                    }
11386                }
11387            }
11388            if (r != null) {
11389                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Permission Groups: " + r);
11390            }
11391
11392            N = pkg.permissions.size();
11393            r = null;
11394            for (i=0; i<N; i++) {
11395                PackageParser.Permission p = pkg.permissions.get(i);
11396
11397                // Dont allow ephemeral apps to define new permissions.
11398                if ((scanFlags & SCAN_AS_INSTANT_APP) != 0) {
11399                    Slog.w(TAG, "Permission " + p.info.name + " from package "
11400                            + p.info.packageName
11401                            + " ignored: instant apps cannot define new permissions.");
11402                    continue;
11403                }
11404
11405                // Assume by default that we did not install this permission into the system.
11406                p.info.flags &= ~PermissionInfo.FLAG_INSTALLED;
11407
11408                // Now that permission groups have a special meaning, we ignore permission
11409                // groups for legacy apps to prevent unexpected behavior. In particular,
11410                // permissions for one app being granted to someone just because they happen
11411                // to be in a group defined by another app (before this had no implications).
11412                if (pkg.applicationInfo.targetSdkVersion > Build.VERSION_CODES.LOLLIPOP_MR1) {
11413                    p.group = mPermissionGroups.get(p.info.group);
11414                    // Warn for a permission in an unknown group.
11415                    if (DEBUG_PERMISSIONS && p.info.group != null && p.group == null) {
11416                        Slog.i(TAG, "Permission " + p.info.name + " from package "
11417                                + p.info.packageName + " in an unknown group " + p.info.group);
11418                    }
11419                }
11420
11421                ArrayMap<String, BasePermission> permissionMap =
11422                        p.tree ? mSettings.mPermissionTrees
11423                                : mSettings.mPermissions;
11424                BasePermission bp = permissionMap.get(p.info.name);
11425
11426                // Allow system apps to redefine non-system permissions
11427                if (bp != null && !Objects.equals(bp.sourcePackage, p.info.packageName)) {
11428                    final boolean currentOwnerIsSystem = (bp.perm != null
11429                            && isSystemApp(bp.perm.owner));
11430                    if (isSystemApp(p.owner)) {
11431                        if (bp.type == BasePermission.TYPE_BUILTIN && bp.perm == null) {
11432                            // It's a built-in permission and no owner, take ownership now
11433                            bp.packageSetting = pkgSetting;
11434                            bp.perm = p;
11435                            bp.uid = pkg.applicationInfo.uid;
11436                            bp.sourcePackage = p.info.packageName;
11437                            p.info.flags |= PermissionInfo.FLAG_INSTALLED;
11438                        } else if (!currentOwnerIsSystem) {
11439                            String msg = "New decl " + p.owner + " of permission  "
11440                                    + p.info.name + " is system; overriding " + bp.sourcePackage;
11441                            reportSettingsProblem(Log.WARN, msg);
11442                            bp = null;
11443                        }
11444                    }
11445                }
11446
11447                if (bp == null) {
11448                    bp = new BasePermission(p.info.name, p.info.packageName,
11449                            BasePermission.TYPE_NORMAL);
11450                    permissionMap.put(p.info.name, bp);
11451                }
11452
11453                if (bp.perm == null) {
11454                    if (bp.sourcePackage == null
11455                            || bp.sourcePackage.equals(p.info.packageName)) {
11456                        BasePermission tree = findPermissionTreeLP(p.info.name);
11457                        if (tree == null
11458                                || tree.sourcePackage.equals(p.info.packageName)) {
11459                            bp.packageSetting = pkgSetting;
11460                            bp.perm = p;
11461                            bp.uid = pkg.applicationInfo.uid;
11462                            bp.sourcePackage = p.info.packageName;
11463                            p.info.flags |= PermissionInfo.FLAG_INSTALLED;
11464                            if (chatty) {
11465                                if (r == null) {
11466                                    r = new StringBuilder(256);
11467                                } else {
11468                                    r.append(' ');
11469                                }
11470                                r.append(p.info.name);
11471                            }
11472                        } else {
11473                            Slog.w(TAG, "Permission " + p.info.name + " from package "
11474                                    + p.info.packageName + " ignored: base tree "
11475                                    + tree.name + " is from package "
11476                                    + tree.sourcePackage);
11477                        }
11478                    } else {
11479                        Slog.w(TAG, "Permission " + p.info.name + " from package "
11480                                + p.info.packageName + " ignored: original from "
11481                                + bp.sourcePackage);
11482                    }
11483                } else if (chatty) {
11484                    if (r == null) {
11485                        r = new StringBuilder(256);
11486                    } else {
11487                        r.append(' ');
11488                    }
11489                    r.append("DUP:");
11490                    r.append(p.info.name);
11491                }
11492                if (bp.perm == p) {
11493                    bp.protectionLevel = p.info.protectionLevel;
11494                }
11495            }
11496
11497            if (r != null) {
11498                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Permissions: " + r);
11499            }
11500
11501            N = pkg.instrumentation.size();
11502            r = null;
11503            for (i=0; i<N; i++) {
11504                PackageParser.Instrumentation a = pkg.instrumentation.get(i);
11505                a.info.packageName = pkg.applicationInfo.packageName;
11506                a.info.sourceDir = pkg.applicationInfo.sourceDir;
11507                a.info.publicSourceDir = pkg.applicationInfo.publicSourceDir;
11508                a.info.splitNames = pkg.splitNames;
11509                a.info.splitSourceDirs = pkg.applicationInfo.splitSourceDirs;
11510                a.info.splitPublicSourceDirs = pkg.applicationInfo.splitPublicSourceDirs;
11511                a.info.splitDependencies = pkg.applicationInfo.splitDependencies;
11512                a.info.dataDir = pkg.applicationInfo.dataDir;
11513                a.info.deviceProtectedDataDir = pkg.applicationInfo.deviceProtectedDataDir;
11514                a.info.credentialProtectedDataDir = pkg.applicationInfo.credentialProtectedDataDir;
11515                a.info.nativeLibraryDir = pkg.applicationInfo.nativeLibraryDir;
11516                a.info.secondaryNativeLibraryDir = pkg.applicationInfo.secondaryNativeLibraryDir;
11517                mInstrumentation.put(a.getComponentName(), a);
11518                if (chatty) {
11519                    if (r == null) {
11520                        r = new StringBuilder(256);
11521                    } else {
11522                        r.append(' ');
11523                    }
11524                    r.append(a.info.name);
11525                }
11526            }
11527            if (r != null) {
11528                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Instrumentation: " + r);
11529            }
11530
11531            if (pkg.protectedBroadcasts != null) {
11532                N = pkg.protectedBroadcasts.size();
11533                for (i=0; i<N; i++) {
11534                    mProtectedBroadcasts.add(pkg.protectedBroadcasts.get(i));
11535                }
11536            }
11537        }
11538
11539        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
11540    }
11541
11542    /**
11543     * Derive the ABI of a non-system package located at {@code scanFile}. This information
11544     * is derived purely on the basis of the contents of {@code scanFile} and
11545     * {@code cpuAbiOverride}.
11546     *
11547     * If {@code extractLibs} is true, native libraries are extracted from the app if required.
11548     */
11549    private static void derivePackageAbi(PackageParser.Package pkg, File scanFile,
11550                                 String cpuAbiOverride, boolean extractLibs,
11551                                 File appLib32InstallDir)
11552            throws PackageManagerException {
11553        // Give ourselves some initial paths; we'll come back for another
11554        // pass once we've determined ABI below.
11555        setNativeLibraryPaths(pkg, appLib32InstallDir);
11556
11557        // We would never need to extract libs for forward-locked and external packages,
11558        // since the container service will do it for us. We shouldn't attempt to
11559        // extract libs from system app when it was not updated.
11560        if (pkg.isForwardLocked() || pkg.applicationInfo.isExternalAsec() ||
11561                (isSystemApp(pkg) && !pkg.isUpdatedSystemApp())) {
11562            extractLibs = false;
11563        }
11564
11565        final String nativeLibraryRootStr = pkg.applicationInfo.nativeLibraryRootDir;
11566        final boolean useIsaSpecificSubdirs = pkg.applicationInfo.nativeLibraryRootRequiresIsa;
11567
11568        NativeLibraryHelper.Handle handle = null;
11569        try {
11570            handle = NativeLibraryHelper.Handle.create(pkg);
11571            // TODO(multiArch): This can be null for apps that didn't go through the
11572            // usual installation process. We can calculate it again, like we
11573            // do during install time.
11574            //
11575            // TODO(multiArch): Why do we need to rescan ASEC apps again ? It seems totally
11576            // unnecessary.
11577            final File nativeLibraryRoot = new File(nativeLibraryRootStr);
11578
11579            // Null out the abis so that they can be recalculated.
11580            pkg.applicationInfo.primaryCpuAbi = null;
11581            pkg.applicationInfo.secondaryCpuAbi = null;
11582            if (isMultiArch(pkg.applicationInfo)) {
11583                // Warn if we've set an abiOverride for multi-lib packages..
11584                // By definition, we need to copy both 32 and 64 bit libraries for
11585                // such packages.
11586                if (pkg.cpuAbiOverride != null
11587                        && !NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(pkg.cpuAbiOverride)) {
11588                    Slog.w(TAG, "Ignoring abiOverride for multi arch application.");
11589                }
11590
11591                int abi32 = PackageManager.NO_NATIVE_LIBRARIES;
11592                int abi64 = PackageManager.NO_NATIVE_LIBRARIES;
11593                if (Build.SUPPORTED_32_BIT_ABIS.length > 0) {
11594                    if (extractLibs) {
11595                        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyNativeBinaries");
11596                        abi32 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
11597                                nativeLibraryRoot, Build.SUPPORTED_32_BIT_ABIS,
11598                                useIsaSpecificSubdirs);
11599                    } else {
11600                        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "findSupportedAbi");
11601                        abi32 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_32_BIT_ABIS);
11602                    }
11603                    Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
11604                }
11605
11606                // Shared library native code should be in the APK zip aligned
11607                if (abi32 >= 0 && pkg.isLibrary() && extractLibs) {
11608                    throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR,
11609                            "Shared library native lib extraction not supported");
11610                }
11611
11612                maybeThrowExceptionForMultiArchCopy(
11613                        "Error unpackaging 32 bit native libs for multiarch app.", abi32);
11614
11615                if (Build.SUPPORTED_64_BIT_ABIS.length > 0) {
11616                    if (extractLibs) {
11617                        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyNativeBinaries");
11618                        abi64 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
11619                                nativeLibraryRoot, Build.SUPPORTED_64_BIT_ABIS,
11620                                useIsaSpecificSubdirs);
11621                    } else {
11622                        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "findSupportedAbi");
11623                        abi64 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_64_BIT_ABIS);
11624                    }
11625                    Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
11626                }
11627
11628                maybeThrowExceptionForMultiArchCopy(
11629                        "Error unpackaging 64 bit native libs for multiarch app.", abi64);
11630
11631                if (abi64 >= 0) {
11632                    // Shared library native libs should be in the APK zip aligned
11633                    if (extractLibs && pkg.isLibrary()) {
11634                        throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR,
11635                                "Shared library native lib extraction not supported");
11636                    }
11637                    pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[abi64];
11638                }
11639
11640                if (abi32 >= 0) {
11641                    final String abi = Build.SUPPORTED_32_BIT_ABIS[abi32];
11642                    if (abi64 >= 0) {
11643                        if (pkg.use32bitAbi) {
11644                            pkg.applicationInfo.secondaryCpuAbi = pkg.applicationInfo.primaryCpuAbi;
11645                            pkg.applicationInfo.primaryCpuAbi = abi;
11646                        } else {
11647                            pkg.applicationInfo.secondaryCpuAbi = abi;
11648                        }
11649                    } else {
11650                        pkg.applicationInfo.primaryCpuAbi = abi;
11651                    }
11652                }
11653            } else {
11654                String[] abiList = (cpuAbiOverride != null) ?
11655                        new String[] { cpuAbiOverride } : Build.SUPPORTED_ABIS;
11656
11657                // Enable gross and lame hacks for apps that are built with old
11658                // SDK tools. We must scan their APKs for renderscript bitcode and
11659                // not launch them if it's present. Don't bother checking on devices
11660                // that don't have 64 bit support.
11661                boolean needsRenderScriptOverride = false;
11662                if (Build.SUPPORTED_64_BIT_ABIS.length > 0 && cpuAbiOverride == null &&
11663                        NativeLibraryHelper.hasRenderscriptBitcode(handle)) {
11664                    abiList = Build.SUPPORTED_32_BIT_ABIS;
11665                    needsRenderScriptOverride = true;
11666                }
11667
11668                final int copyRet;
11669                if (extractLibs) {
11670                    Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyNativeBinaries");
11671                    copyRet = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
11672                            nativeLibraryRoot, abiList, useIsaSpecificSubdirs);
11673                } else {
11674                    Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "findSupportedAbi");
11675                    copyRet = NativeLibraryHelper.findSupportedAbi(handle, abiList);
11676                }
11677                Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
11678
11679                if (copyRet < 0 && copyRet != PackageManager.NO_NATIVE_LIBRARIES) {
11680                    throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR,
11681                            "Error unpackaging native libs for app, errorCode=" + copyRet);
11682                }
11683
11684                if (copyRet >= 0) {
11685                    // Shared libraries that have native libs must be multi-architecture
11686                    if (pkg.isLibrary()) {
11687                        throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR,
11688                                "Shared library with native libs must be multiarch");
11689                    }
11690                    pkg.applicationInfo.primaryCpuAbi = abiList[copyRet];
11691                } else if (copyRet == PackageManager.NO_NATIVE_LIBRARIES && cpuAbiOverride != null) {
11692                    pkg.applicationInfo.primaryCpuAbi = cpuAbiOverride;
11693                } else if (needsRenderScriptOverride) {
11694                    pkg.applicationInfo.primaryCpuAbi = abiList[0];
11695                }
11696            }
11697        } catch (IOException ioe) {
11698            Slog.e(TAG, "Unable to get canonical file " + ioe.toString());
11699        } finally {
11700            IoUtils.closeQuietly(handle);
11701        }
11702
11703        // Now that we've calculated the ABIs and determined if it's an internal app,
11704        // we will go ahead and populate the nativeLibraryPath.
11705        setNativeLibraryPaths(pkg, appLib32InstallDir);
11706    }
11707
11708    /**
11709     * Adjusts ABIs for a set of packages belonging to a shared user so that they all match.
11710     * i.e, so that all packages can be run inside a single process if required.
11711     *
11712     * Optionally, callers can pass in a parsed package via {@code newPackage} in which case
11713     * this function will either try and make the ABI for all packages in {@code packagesForUser}
11714     * match {@code scannedPackage} or will update the ABI of {@code scannedPackage} to match
11715     * the ABI selected for {@code packagesForUser}. This variant is used when installing or
11716     * updating a package that belongs to a shared user.
11717     *
11718     * NOTE: We currently only match for the primary CPU abi string. Matching the secondary
11719     * adds unnecessary complexity.
11720     */
11721    private void adjustCpuAbisForSharedUserLPw(Set<PackageSetting> packagesForUser,
11722            PackageParser.Package scannedPackage) {
11723        String requiredInstructionSet = null;
11724        if (scannedPackage != null && scannedPackage.applicationInfo.primaryCpuAbi != null) {
11725            requiredInstructionSet = VMRuntime.getInstructionSet(
11726                     scannedPackage.applicationInfo.primaryCpuAbi);
11727        }
11728
11729        PackageSetting requirer = null;
11730        for (PackageSetting ps : packagesForUser) {
11731            // If packagesForUser contains scannedPackage, we skip it. This will happen
11732            // when scannedPackage is an update of an existing package. Without this check,
11733            // we will never be able to change the ABI of any package belonging to a shared
11734            // user, even if it's compatible with other packages.
11735            if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) {
11736                if (ps.primaryCpuAbiString == null) {
11737                    continue;
11738                }
11739
11740                final String instructionSet = VMRuntime.getInstructionSet(ps.primaryCpuAbiString);
11741                if (requiredInstructionSet != null && !instructionSet.equals(requiredInstructionSet)) {
11742                    // We have a mismatch between instruction sets (say arm vs arm64) warn about
11743                    // this but there's not much we can do.
11744                    String errorMessage = "Instruction set mismatch, "
11745                            + ((requirer == null) ? "[caller]" : requirer)
11746                            + " requires " + requiredInstructionSet + " whereas " + ps
11747                            + " requires " + instructionSet;
11748                    Slog.w(TAG, errorMessage);
11749                }
11750
11751                if (requiredInstructionSet == null) {
11752                    requiredInstructionSet = instructionSet;
11753                    requirer = ps;
11754                }
11755            }
11756        }
11757
11758        if (requiredInstructionSet != null) {
11759            String adjustedAbi;
11760            if (requirer != null) {
11761                // requirer != null implies that either scannedPackage was null or that scannedPackage
11762                // did not require an ABI, in which case we have to adjust scannedPackage to match
11763                // the ABI of the set (which is the same as requirer's ABI)
11764                adjustedAbi = requirer.primaryCpuAbiString;
11765                if (scannedPackage != null) {
11766                    scannedPackage.applicationInfo.primaryCpuAbi = adjustedAbi;
11767                }
11768            } else {
11769                // requirer == null implies that we're updating all ABIs in the set to
11770                // match scannedPackage.
11771                adjustedAbi =  scannedPackage.applicationInfo.primaryCpuAbi;
11772            }
11773
11774            for (PackageSetting ps : packagesForUser) {
11775                if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) {
11776                    if (ps.primaryCpuAbiString != null) {
11777                        continue;
11778                    }
11779
11780                    ps.primaryCpuAbiString = adjustedAbi;
11781                    if (ps.pkg != null && ps.pkg.applicationInfo != null &&
11782                            !TextUtils.equals(adjustedAbi, ps.pkg.applicationInfo.primaryCpuAbi)) {
11783                        ps.pkg.applicationInfo.primaryCpuAbi = adjustedAbi;
11784                        if (DEBUG_ABI_SELECTION) {
11785                            Slog.i(TAG, "Adjusting ABI for " + ps.name + " to " + adjustedAbi
11786                                    + " (requirer="
11787                                    + (requirer != null ? requirer.pkg : "null")
11788                                    + ", scannedPackage="
11789                                    + (scannedPackage != null ? scannedPackage : "null")
11790                                    + ")");
11791                        }
11792                        try {
11793                            mInstaller.rmdex(ps.codePathString,
11794                                    getDexCodeInstructionSet(getPreferredInstructionSet()));
11795                        } catch (InstallerException ignored) {
11796                        }
11797                    }
11798                }
11799            }
11800        }
11801    }
11802
11803    private void setUpCustomResolverActivity(PackageParser.Package pkg) {
11804        synchronized (mPackages) {
11805            mResolverReplaced = true;
11806            // Set up information for custom user intent resolution activity.
11807            mResolveActivity.applicationInfo = pkg.applicationInfo;
11808            mResolveActivity.name = mCustomResolverComponentName.getClassName();
11809            mResolveActivity.packageName = pkg.applicationInfo.packageName;
11810            mResolveActivity.processName = pkg.applicationInfo.packageName;
11811            mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
11812            mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS |
11813                    ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS;
11814            mResolveActivity.theme = 0;
11815            mResolveActivity.exported = true;
11816            mResolveActivity.enabled = true;
11817            mResolveInfo.activityInfo = mResolveActivity;
11818            mResolveInfo.priority = 0;
11819            mResolveInfo.preferredOrder = 0;
11820            mResolveInfo.match = 0;
11821            mResolveComponentName = mCustomResolverComponentName;
11822            Slog.i(TAG, "Replacing default ResolverActivity with custom activity: " +
11823                    mResolveComponentName);
11824        }
11825    }
11826
11827    private void setUpInstantAppInstallerActivityLP(ActivityInfo installerActivity) {
11828        if (installerActivity == null) {
11829            if (DEBUG_EPHEMERAL) {
11830                Slog.d(TAG, "Clear ephemeral installer activity");
11831            }
11832            mInstantAppInstallerActivity = null;
11833            return;
11834        }
11835
11836        if (DEBUG_EPHEMERAL) {
11837            Slog.d(TAG, "Set ephemeral installer activity: "
11838                    + installerActivity.getComponentName());
11839        }
11840        // Set up information for ephemeral installer activity
11841        mInstantAppInstallerActivity = installerActivity;
11842        mInstantAppInstallerActivity.flags |= ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS
11843                | ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS;
11844        mInstantAppInstallerActivity.exported = true;
11845        mInstantAppInstallerActivity.enabled = true;
11846        mInstantAppInstallerInfo.activityInfo = mInstantAppInstallerActivity;
11847        mInstantAppInstallerInfo.priority = 0;
11848        mInstantAppInstallerInfo.preferredOrder = 1;
11849        mInstantAppInstallerInfo.isDefault = true;
11850        mInstantAppInstallerInfo.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART
11851                | IntentFilter.MATCH_ADJUSTMENT_NORMAL;
11852    }
11853
11854    private static String calculateBundledApkRoot(final String codePathString) {
11855        final File codePath = new File(codePathString);
11856        final File codeRoot;
11857        if (FileUtils.contains(Environment.getRootDirectory(), codePath)) {
11858            codeRoot = Environment.getRootDirectory();
11859        } else if (FileUtils.contains(Environment.getOemDirectory(), codePath)) {
11860            codeRoot = Environment.getOemDirectory();
11861        } else if (FileUtils.contains(Environment.getVendorDirectory(), codePath)) {
11862            codeRoot = Environment.getVendorDirectory();
11863        } else {
11864            // Unrecognized code path; take its top real segment as the apk root:
11865            // e.g. /something/app/blah.apk => /something
11866            try {
11867                File f = codePath.getCanonicalFile();
11868                File parent = f.getParentFile();    // non-null because codePath is a file
11869                File tmp;
11870                while ((tmp = parent.getParentFile()) != null) {
11871                    f = parent;
11872                    parent = tmp;
11873                }
11874                codeRoot = f;
11875                Slog.w(TAG, "Unrecognized code path "
11876                        + codePath + " - using " + codeRoot);
11877            } catch (IOException e) {
11878                // Can't canonicalize the code path -- shenanigans?
11879                Slog.w(TAG, "Can't canonicalize code path " + codePath);
11880                return Environment.getRootDirectory().getPath();
11881            }
11882        }
11883        return codeRoot.getPath();
11884    }
11885
11886    /**
11887     * Derive and set the location of native libraries for the given package,
11888     * which varies depending on where and how the package was installed.
11889     */
11890    private static void setNativeLibraryPaths(PackageParser.Package pkg, File appLib32InstallDir) {
11891        final ApplicationInfo info = pkg.applicationInfo;
11892        final String codePath = pkg.codePath;
11893        final File codeFile = new File(codePath);
11894        final boolean bundledApp = info.isSystemApp() && !info.isUpdatedSystemApp();
11895        final boolean asecApp = info.isForwardLocked() || info.isExternalAsec();
11896
11897        info.nativeLibraryRootDir = null;
11898        info.nativeLibraryRootRequiresIsa = false;
11899        info.nativeLibraryDir = null;
11900        info.secondaryNativeLibraryDir = null;
11901
11902        if (isApkFile(codeFile)) {
11903            // Monolithic install
11904            if (bundledApp) {
11905                // If "/system/lib64/apkname" exists, assume that is the per-package
11906                // native library directory to use; otherwise use "/system/lib/apkname".
11907                final String apkRoot = calculateBundledApkRoot(info.sourceDir);
11908                final boolean is64Bit = VMRuntime.is64BitInstructionSet(
11909                        getPrimaryInstructionSet(info));
11910
11911                // This is a bundled system app so choose the path based on the ABI.
11912                // if it's a 64 bit abi, use lib64 otherwise use lib32. Note that this
11913                // is just the default path.
11914                final String apkName = deriveCodePathName(codePath);
11915                final String libDir = is64Bit ? LIB64_DIR_NAME : LIB_DIR_NAME;
11916                info.nativeLibraryRootDir = Environment.buildPath(new File(apkRoot), libDir,
11917                        apkName).getAbsolutePath();
11918
11919                if (info.secondaryCpuAbi != null) {
11920                    final String secondaryLibDir = is64Bit ? LIB_DIR_NAME : LIB64_DIR_NAME;
11921                    info.secondaryNativeLibraryDir = Environment.buildPath(new File(apkRoot),
11922                            secondaryLibDir, apkName).getAbsolutePath();
11923                }
11924            } else if (asecApp) {
11925                info.nativeLibraryRootDir = new File(codeFile.getParentFile(), LIB_DIR_NAME)
11926                        .getAbsolutePath();
11927            } else {
11928                final String apkName = deriveCodePathName(codePath);
11929                info.nativeLibraryRootDir = new File(appLib32InstallDir, apkName)
11930                        .getAbsolutePath();
11931            }
11932
11933            info.nativeLibraryRootRequiresIsa = false;
11934            info.nativeLibraryDir = info.nativeLibraryRootDir;
11935        } else {
11936            // Cluster install
11937            info.nativeLibraryRootDir = new File(codeFile, LIB_DIR_NAME).getAbsolutePath();
11938            info.nativeLibraryRootRequiresIsa = true;
11939
11940            info.nativeLibraryDir = new File(info.nativeLibraryRootDir,
11941                    getPrimaryInstructionSet(info)).getAbsolutePath();
11942
11943            if (info.secondaryCpuAbi != null) {
11944                info.secondaryNativeLibraryDir = new File(info.nativeLibraryRootDir,
11945                        VMRuntime.getInstructionSet(info.secondaryCpuAbi)).getAbsolutePath();
11946            }
11947        }
11948    }
11949
11950    /**
11951     * Calculate the abis and roots for a bundled app. These can uniquely
11952     * be determined from the contents of the system partition, i.e whether
11953     * it contains 64 or 32 bit shared libraries etc. We do not validate any
11954     * of this information, and instead assume that the system was built
11955     * sensibly.
11956     */
11957    private static void setBundledAppAbisAndRoots(PackageParser.Package pkg,
11958                                           PackageSetting pkgSetting) {
11959        final String apkName = deriveCodePathName(pkg.applicationInfo.getCodePath());
11960
11961        // If "/system/lib64/apkname" exists, assume that is the per-package
11962        // native library directory to use; otherwise use "/system/lib/apkname".
11963        final String apkRoot = calculateBundledApkRoot(pkg.applicationInfo.sourceDir);
11964        setBundledAppAbi(pkg, apkRoot, apkName);
11965        // pkgSetting might be null during rescan following uninstall of updates
11966        // to a bundled app, so accommodate that possibility.  The settings in
11967        // that case will be established later from the parsed package.
11968        //
11969        // If the settings aren't null, sync them up with what we've just derived.
11970        // note that apkRoot isn't stored in the package settings.
11971        if (pkgSetting != null) {
11972            pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi;
11973            pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi;
11974        }
11975    }
11976
11977    /**
11978     * Deduces the ABI of a bundled app and sets the relevant fields on the
11979     * parsed pkg object.
11980     *
11981     * @param apkRoot the root of the installed apk, something like {@code /system} or {@code /oem}
11982     *        under which system libraries are installed.
11983     * @param apkName the name of the installed package.
11984     */
11985    private static void setBundledAppAbi(PackageParser.Package pkg, String apkRoot, String apkName) {
11986        final File codeFile = new File(pkg.codePath);
11987
11988        final boolean has64BitLibs;
11989        final boolean has32BitLibs;
11990        if (isApkFile(codeFile)) {
11991            // Monolithic install
11992            has64BitLibs = (new File(apkRoot, new File(LIB64_DIR_NAME, apkName).getPath())).exists();
11993            has32BitLibs = (new File(apkRoot, new File(LIB_DIR_NAME, apkName).getPath())).exists();
11994        } else {
11995            // Cluster install
11996            final File rootDir = new File(codeFile, LIB_DIR_NAME);
11997            if (!ArrayUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS)
11998                    && !TextUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS[0])) {
11999                final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_64_BIT_ABIS[0]);
12000                has64BitLibs = (new File(rootDir, isa)).exists();
12001            } else {
12002                has64BitLibs = false;
12003            }
12004            if (!ArrayUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS)
12005                    && !TextUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS[0])) {
12006                final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_32_BIT_ABIS[0]);
12007                has32BitLibs = (new File(rootDir, isa)).exists();
12008            } else {
12009                has32BitLibs = false;
12010            }
12011        }
12012
12013        if (has64BitLibs && !has32BitLibs) {
12014            // The package has 64 bit libs, but not 32 bit libs. Its primary
12015            // ABI should be 64 bit. We can safely assume here that the bundled
12016            // native libraries correspond to the most preferred ABI in the list.
12017
12018            pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
12019            pkg.applicationInfo.secondaryCpuAbi = null;
12020        } else if (has32BitLibs && !has64BitLibs) {
12021            // The package has 32 bit libs but not 64 bit libs. Its primary
12022            // ABI should be 32 bit.
12023
12024            pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
12025            pkg.applicationInfo.secondaryCpuAbi = null;
12026        } else if (has32BitLibs && has64BitLibs) {
12027            // The application has both 64 and 32 bit bundled libraries. We check
12028            // here that the app declares multiArch support, and warn if it doesn't.
12029            //
12030            // We will be lenient here and record both ABIs. The primary will be the
12031            // ABI that's higher on the list, i.e, a device that's configured to prefer
12032            // 64 bit apps will see a 64 bit primary ABI,
12033
12034            if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_MULTIARCH) == 0) {
12035                Slog.e(TAG, "Package " + pkg + " has multiple bundled libs, but is not multiarch.");
12036            }
12037
12038            if (VMRuntime.is64BitInstructionSet(getPreferredInstructionSet())) {
12039                pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
12040                pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
12041            } else {
12042                pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
12043                pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
12044            }
12045        } else {
12046            pkg.applicationInfo.primaryCpuAbi = null;
12047            pkg.applicationInfo.secondaryCpuAbi = null;
12048        }
12049    }
12050
12051    private void killApplication(String pkgName, int appId, String reason) {
12052        killApplication(pkgName, appId, UserHandle.USER_ALL, reason);
12053    }
12054
12055    private void killApplication(String pkgName, int appId, int userId, String reason) {
12056        // Request the ActivityManager to kill the process(only for existing packages)
12057        // so that we do not end up in a confused state while the user is still using the older
12058        // version of the application while the new one gets installed.
12059        final long token = Binder.clearCallingIdentity();
12060        try {
12061            IActivityManager am = ActivityManager.getService();
12062            if (am != null) {
12063                try {
12064                    am.killApplication(pkgName, appId, userId, reason);
12065                } catch (RemoteException e) {
12066                }
12067            }
12068        } finally {
12069            Binder.restoreCallingIdentity(token);
12070        }
12071    }
12072
12073    private void removePackageLI(PackageParser.Package pkg, boolean chatty) {
12074        // Remove the parent package setting
12075        PackageSetting ps = (PackageSetting) pkg.mExtras;
12076        if (ps != null) {
12077            removePackageLI(ps, chatty);
12078        }
12079        // Remove the child package setting
12080        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
12081        for (int i = 0; i < childCount; i++) {
12082            PackageParser.Package childPkg = pkg.childPackages.get(i);
12083            ps = (PackageSetting) childPkg.mExtras;
12084            if (ps != null) {
12085                removePackageLI(ps, chatty);
12086            }
12087        }
12088    }
12089
12090    void removePackageLI(PackageSetting ps, boolean chatty) {
12091        if (DEBUG_INSTALL) {
12092            if (chatty)
12093                Log.d(TAG, "Removing package " + ps.name);
12094        }
12095
12096        // writer
12097        synchronized (mPackages) {
12098            mPackages.remove(ps.name);
12099            final PackageParser.Package pkg = ps.pkg;
12100            if (pkg != null) {
12101                cleanPackageDataStructuresLILPw(pkg, chatty);
12102            }
12103        }
12104    }
12105
12106    void removeInstalledPackageLI(PackageParser.Package pkg, boolean chatty) {
12107        if (DEBUG_INSTALL) {
12108            if (chatty)
12109                Log.d(TAG, "Removing package " + pkg.applicationInfo.packageName);
12110        }
12111
12112        // writer
12113        synchronized (mPackages) {
12114            // Remove the parent package
12115            mPackages.remove(pkg.applicationInfo.packageName);
12116            cleanPackageDataStructuresLILPw(pkg, chatty);
12117
12118            // Remove the child packages
12119            final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
12120            for (int i = 0; i < childCount; i++) {
12121                PackageParser.Package childPkg = pkg.childPackages.get(i);
12122                mPackages.remove(childPkg.applicationInfo.packageName);
12123                cleanPackageDataStructuresLILPw(childPkg, chatty);
12124            }
12125        }
12126    }
12127
12128    void cleanPackageDataStructuresLILPw(PackageParser.Package pkg, boolean chatty) {
12129        int N = pkg.providers.size();
12130        StringBuilder r = null;
12131        int i;
12132        for (i=0; i<N; i++) {
12133            PackageParser.Provider p = pkg.providers.get(i);
12134            mProviders.removeProvider(p);
12135            if (p.info.authority == null) {
12136
12137                /* There was another ContentProvider with this authority when
12138                 * this app was installed so this authority is null,
12139                 * Ignore it as we don't have to unregister the provider.
12140                 */
12141                continue;
12142            }
12143            String names[] = p.info.authority.split(";");
12144            for (int j = 0; j < names.length; j++) {
12145                if (mProvidersByAuthority.get(names[j]) == p) {
12146                    mProvidersByAuthority.remove(names[j]);
12147                    if (DEBUG_REMOVE) {
12148                        if (chatty)
12149                            Log.d(TAG, "Unregistered content provider: " + names[j]
12150                                    + ", className = " + p.info.name + ", isSyncable = "
12151                                    + p.info.isSyncable);
12152                    }
12153                }
12154            }
12155            if (DEBUG_REMOVE && chatty) {
12156                if (r == null) {
12157                    r = new StringBuilder(256);
12158                } else {
12159                    r.append(' ');
12160                }
12161                r.append(p.info.name);
12162            }
12163        }
12164        if (r != null) {
12165            if (DEBUG_REMOVE) Log.d(TAG, "  Providers: " + r);
12166        }
12167
12168        N = pkg.services.size();
12169        r = null;
12170        for (i=0; i<N; i++) {
12171            PackageParser.Service s = pkg.services.get(i);
12172            mServices.removeService(s);
12173            if (chatty) {
12174                if (r == null) {
12175                    r = new StringBuilder(256);
12176                } else {
12177                    r.append(' ');
12178                }
12179                r.append(s.info.name);
12180            }
12181        }
12182        if (r != null) {
12183            if (DEBUG_REMOVE) Log.d(TAG, "  Services: " + r);
12184        }
12185
12186        N = pkg.receivers.size();
12187        r = null;
12188        for (i=0; i<N; i++) {
12189            PackageParser.Activity a = pkg.receivers.get(i);
12190            mReceivers.removeActivity(a, "receiver");
12191            if (DEBUG_REMOVE && chatty) {
12192                if (r == null) {
12193                    r = new StringBuilder(256);
12194                } else {
12195                    r.append(' ');
12196                }
12197                r.append(a.info.name);
12198            }
12199        }
12200        if (r != null) {
12201            if (DEBUG_REMOVE) Log.d(TAG, "  Receivers: " + r);
12202        }
12203
12204        N = pkg.activities.size();
12205        r = null;
12206        for (i=0; i<N; i++) {
12207            PackageParser.Activity a = pkg.activities.get(i);
12208            mActivities.removeActivity(a, "activity");
12209            if (DEBUG_REMOVE && chatty) {
12210                if (r == null) {
12211                    r = new StringBuilder(256);
12212                } else {
12213                    r.append(' ');
12214                }
12215                r.append(a.info.name);
12216            }
12217        }
12218        if (r != null) {
12219            if (DEBUG_REMOVE) Log.d(TAG, "  Activities: " + r);
12220        }
12221
12222        N = pkg.permissions.size();
12223        r = null;
12224        for (i=0; i<N; i++) {
12225            PackageParser.Permission p = pkg.permissions.get(i);
12226            BasePermission bp = mSettings.mPermissions.get(p.info.name);
12227            if (bp == null) {
12228                bp = mSettings.mPermissionTrees.get(p.info.name);
12229            }
12230            if (bp != null && bp.perm == p) {
12231                bp.perm = null;
12232                if (DEBUG_REMOVE && chatty) {
12233                    if (r == null) {
12234                        r = new StringBuilder(256);
12235                    } else {
12236                        r.append(' ');
12237                    }
12238                    r.append(p.info.name);
12239                }
12240            }
12241            if ((p.info.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
12242                ArraySet<String> appOpPkgs = mAppOpPermissionPackages.get(p.info.name);
12243                if (appOpPkgs != null) {
12244                    appOpPkgs.remove(pkg.packageName);
12245                }
12246            }
12247        }
12248        if (r != null) {
12249            if (DEBUG_REMOVE) Log.d(TAG, "  Permissions: " + r);
12250        }
12251
12252        N = pkg.requestedPermissions.size();
12253        r = null;
12254        for (i=0; i<N; i++) {
12255            String perm = pkg.requestedPermissions.get(i);
12256            BasePermission bp = mSettings.mPermissions.get(perm);
12257            if (bp != null && (bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
12258                ArraySet<String> appOpPkgs = mAppOpPermissionPackages.get(perm);
12259                if (appOpPkgs != null) {
12260                    appOpPkgs.remove(pkg.packageName);
12261                    if (appOpPkgs.isEmpty()) {
12262                        mAppOpPermissionPackages.remove(perm);
12263                    }
12264                }
12265            }
12266        }
12267        if (r != null) {
12268            if (DEBUG_REMOVE) Log.d(TAG, "  Permissions: " + r);
12269        }
12270
12271        N = pkg.instrumentation.size();
12272        r = null;
12273        for (i=0; i<N; i++) {
12274            PackageParser.Instrumentation a = pkg.instrumentation.get(i);
12275            mInstrumentation.remove(a.getComponentName());
12276            if (DEBUG_REMOVE && chatty) {
12277                if (r == null) {
12278                    r = new StringBuilder(256);
12279                } else {
12280                    r.append(' ');
12281                }
12282                r.append(a.info.name);
12283            }
12284        }
12285        if (r != null) {
12286            if (DEBUG_REMOVE) Log.d(TAG, "  Instrumentation: " + r);
12287        }
12288
12289        r = null;
12290        if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) {
12291            // Only system apps can hold shared libraries.
12292            if (pkg.libraryNames != null) {
12293                for (i = 0; i < pkg.libraryNames.size(); i++) {
12294                    String name = pkg.libraryNames.get(i);
12295                    if (removeSharedLibraryLPw(name, 0)) {
12296                        if (DEBUG_REMOVE && chatty) {
12297                            if (r == null) {
12298                                r = new StringBuilder(256);
12299                            } else {
12300                                r.append(' ');
12301                            }
12302                            r.append(name);
12303                        }
12304                    }
12305                }
12306            }
12307        }
12308
12309        r = null;
12310
12311        // Any package can hold static shared libraries.
12312        if (pkg.staticSharedLibName != null) {
12313            if (removeSharedLibraryLPw(pkg.staticSharedLibName, pkg.staticSharedLibVersion)) {
12314                if (DEBUG_REMOVE && chatty) {
12315                    if (r == null) {
12316                        r = new StringBuilder(256);
12317                    } else {
12318                        r.append(' ');
12319                    }
12320                    r.append(pkg.staticSharedLibName);
12321                }
12322            }
12323        }
12324
12325        if (r != null) {
12326            if (DEBUG_REMOVE) Log.d(TAG, "  Libraries: " + r);
12327        }
12328    }
12329
12330    private static boolean hasPermission(PackageParser.Package pkgInfo, String perm) {
12331        for (int i=pkgInfo.permissions.size()-1; i>=0; i--) {
12332            if (pkgInfo.permissions.get(i).info.name.equals(perm)) {
12333                return true;
12334            }
12335        }
12336        return false;
12337    }
12338
12339    static final int UPDATE_PERMISSIONS_ALL = 1<<0;
12340    static final int UPDATE_PERMISSIONS_REPLACE_PKG = 1<<1;
12341    static final int UPDATE_PERMISSIONS_REPLACE_ALL = 1<<2;
12342
12343    private void updatePermissionsLPw(PackageParser.Package pkg, int flags) {
12344        // Update the parent permissions
12345        updatePermissionsLPw(pkg.packageName, pkg, flags);
12346        // Update the child permissions
12347        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
12348        for (int i = 0; i < childCount; i++) {
12349            PackageParser.Package childPkg = pkg.childPackages.get(i);
12350            updatePermissionsLPw(childPkg.packageName, childPkg, flags);
12351        }
12352    }
12353
12354    private void updatePermissionsLPw(String changingPkg, PackageParser.Package pkgInfo,
12355            int flags) {
12356        final String volumeUuid = (pkgInfo != null) ? getVolumeUuidForPackage(pkgInfo) : null;
12357        updatePermissionsLPw(changingPkg, pkgInfo, volumeUuid, flags);
12358    }
12359
12360    private void updatePermissionsLPw(String changingPkg,
12361            PackageParser.Package pkgInfo, String replaceVolumeUuid, int flags) {
12362        // Make sure there are no dangling permission trees.
12363        Iterator<BasePermission> it = mSettings.mPermissionTrees.values().iterator();
12364        while (it.hasNext()) {
12365            final BasePermission bp = it.next();
12366            if (bp.packageSetting == null) {
12367                // We may not yet have parsed the package, so just see if
12368                // we still know about its settings.
12369                bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage);
12370            }
12371            if (bp.packageSetting == null) {
12372                Slog.w(TAG, "Removing dangling permission tree: " + bp.name
12373                        + " from package " + bp.sourcePackage);
12374                it.remove();
12375            } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) {
12376                if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) {
12377                    Slog.i(TAG, "Removing old permission tree: " + bp.name
12378                            + " from package " + bp.sourcePackage);
12379                    flags |= UPDATE_PERMISSIONS_ALL;
12380                    it.remove();
12381                }
12382            }
12383        }
12384
12385        // Make sure all dynamic permissions have been assigned to a package,
12386        // and make sure there are no dangling permissions.
12387        it = mSettings.mPermissions.values().iterator();
12388        while (it.hasNext()) {
12389            final BasePermission bp = it.next();
12390            if (bp.type == BasePermission.TYPE_DYNAMIC) {
12391                if (DEBUG_SETTINGS) Log.v(TAG, "Dynamic permission: name="
12392                        + bp.name + " pkg=" + bp.sourcePackage
12393                        + " info=" + bp.pendingInfo);
12394                if (bp.packageSetting == null && bp.pendingInfo != null) {
12395                    final BasePermission tree = findPermissionTreeLP(bp.name);
12396                    if (tree != null && tree.perm != null) {
12397                        bp.packageSetting = tree.packageSetting;
12398                        bp.perm = new PackageParser.Permission(tree.perm.owner,
12399                                new PermissionInfo(bp.pendingInfo));
12400                        bp.perm.info.packageName = tree.perm.info.packageName;
12401                        bp.perm.info.name = bp.name;
12402                        bp.uid = tree.uid;
12403                    }
12404                }
12405            }
12406            if (bp.packageSetting == null) {
12407                // We may not yet have parsed the package, so just see if
12408                // we still know about its settings.
12409                bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage);
12410            }
12411            if (bp.packageSetting == null) {
12412                Slog.w(TAG, "Removing dangling permission: " + bp.name
12413                        + " from package " + bp.sourcePackage);
12414                it.remove();
12415            } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) {
12416                if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) {
12417                    Slog.i(TAG, "Removing old permission: " + bp.name
12418                            + " from package " + bp.sourcePackage);
12419                    flags |= UPDATE_PERMISSIONS_ALL;
12420                    it.remove();
12421                }
12422            }
12423        }
12424
12425        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "grantPermissions");
12426        // Now update the permissions for all packages, in particular
12427        // replace the granted permissions of the system packages.
12428        if ((flags&UPDATE_PERMISSIONS_ALL) != 0) {
12429            for (PackageParser.Package pkg : mPackages.values()) {
12430                if (pkg != pkgInfo) {
12431                    // Only replace for packages on requested volume
12432                    final String volumeUuid = getVolumeUuidForPackage(pkg);
12433                    final boolean replace = ((flags & UPDATE_PERMISSIONS_REPLACE_ALL) != 0)
12434                            && Objects.equals(replaceVolumeUuid, volumeUuid);
12435                    grantPermissionsLPw(pkg, replace, changingPkg);
12436                }
12437            }
12438        }
12439
12440        if (pkgInfo != null) {
12441            // Only replace for packages on requested volume
12442            final String volumeUuid = getVolumeUuidForPackage(pkgInfo);
12443            final boolean replace = ((flags & UPDATE_PERMISSIONS_REPLACE_PKG) != 0)
12444                    && Objects.equals(replaceVolumeUuid, volumeUuid);
12445            grantPermissionsLPw(pkgInfo, replace, changingPkg);
12446        }
12447        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
12448    }
12449
12450    private void grantPermissionsLPw(PackageParser.Package pkg, boolean replace,
12451            String packageOfInterest) {
12452        // IMPORTANT: There are two types of permissions: install and runtime.
12453        // Install time permissions are granted when the app is installed to
12454        // all device users and users added in the future. Runtime permissions
12455        // are granted at runtime explicitly to specific users. Normal and signature
12456        // protected permissions are install time permissions. Dangerous permissions
12457        // are install permissions if the app's target SDK is Lollipop MR1 or older,
12458        // otherwise they are runtime permissions. This function does not manage
12459        // runtime permissions except for the case an app targeting Lollipop MR1
12460        // being upgraded to target a newer SDK, in which case dangerous permissions
12461        // are transformed from install time to runtime ones.
12462
12463        final PackageSetting ps = (PackageSetting) pkg.mExtras;
12464        if (ps == null) {
12465            return;
12466        }
12467
12468        PermissionsState permissionsState = ps.getPermissionsState();
12469        PermissionsState origPermissions = permissionsState;
12470
12471        final int[] currentUserIds = UserManagerService.getInstance().getUserIds();
12472
12473        boolean runtimePermissionsRevoked = false;
12474        int[] changedRuntimePermissionUserIds = EMPTY_INT_ARRAY;
12475
12476        boolean changedInstallPermission = false;
12477
12478        if (replace) {
12479            ps.installPermissionsFixed = false;
12480            if (!ps.isSharedUser()) {
12481                origPermissions = new PermissionsState(permissionsState);
12482                permissionsState.reset();
12483            } else {
12484                // We need to know only about runtime permission changes since the
12485                // calling code always writes the install permissions state but
12486                // the runtime ones are written only if changed. The only cases of
12487                // changed runtime permissions here are promotion of an install to
12488                // runtime and revocation of a runtime from a shared user.
12489                changedRuntimePermissionUserIds = revokeUnusedSharedUserPermissionsLPw(
12490                        ps.sharedUser, UserManagerService.getInstance().getUserIds());
12491                if (!ArrayUtils.isEmpty(changedRuntimePermissionUserIds)) {
12492                    runtimePermissionsRevoked = true;
12493                }
12494            }
12495        }
12496
12497        permissionsState.setGlobalGids(mGlobalGids);
12498
12499        final int N = pkg.requestedPermissions.size();
12500        for (int i=0; i<N; i++) {
12501            final String name = pkg.requestedPermissions.get(i);
12502            final BasePermission bp = mSettings.mPermissions.get(name);
12503            final boolean appSupportsRuntimePermissions = pkg.applicationInfo.targetSdkVersion
12504                    >= Build.VERSION_CODES.M;
12505
12506            if (DEBUG_INSTALL) {
12507                Log.i(TAG, "Package " + pkg.packageName + " checking " + name + ": " + bp);
12508            }
12509
12510            if (bp == null || bp.packageSetting == null) {
12511                if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) {
12512                    if (DEBUG_PERMISSIONS) {
12513                        Slog.i(TAG, "Unknown permission " + name
12514                                + " in package " + pkg.packageName);
12515                    }
12516                }
12517                continue;
12518            }
12519
12520
12521            // Limit ephemeral apps to ephemeral allowed permissions.
12522            if (pkg.applicationInfo.isInstantApp() && !bp.isInstant()) {
12523                if (DEBUG_PERMISSIONS) {
12524                    Log.i(TAG, "Denying non-ephemeral permission " + bp.name + " for package "
12525                            + pkg.packageName);
12526                }
12527                continue;
12528            }
12529
12530            if (bp.isRuntimeOnly() && !appSupportsRuntimePermissions) {
12531                if (DEBUG_PERMISSIONS) {
12532                    Log.i(TAG, "Denying runtime-only permission " + bp.name + " for package "
12533                            + pkg.packageName);
12534                }
12535                continue;
12536            }
12537
12538            final String perm = bp.name;
12539            boolean allowedSig = false;
12540            int grant = GRANT_DENIED;
12541
12542            // Keep track of app op permissions.
12543            if ((bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
12544                ArraySet<String> pkgs = mAppOpPermissionPackages.get(bp.name);
12545                if (pkgs == null) {
12546                    pkgs = new ArraySet<>();
12547                    mAppOpPermissionPackages.put(bp.name, pkgs);
12548                }
12549                pkgs.add(pkg.packageName);
12550            }
12551
12552            final int level = bp.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE;
12553            switch (level) {
12554                case PermissionInfo.PROTECTION_NORMAL: {
12555                    // For all apps normal permissions are install time ones.
12556                    grant = GRANT_INSTALL;
12557                } break;
12558
12559                case PermissionInfo.PROTECTION_DANGEROUS: {
12560                    // If a permission review is required for legacy apps we represent
12561                    // their permissions as always granted runtime ones since we need
12562                    // to keep the review required permission flag per user while an
12563                    // install permission's state is shared across all users.
12564                    if (!appSupportsRuntimePermissions && !mPermissionReviewRequired) {
12565                        // For legacy apps dangerous permissions are install time ones.
12566                        grant = GRANT_INSTALL;
12567                    } else if (origPermissions.hasInstallPermission(bp.name)) {
12568                        // For legacy apps that became modern, install becomes runtime.
12569                        grant = GRANT_UPGRADE;
12570                    } else if (mPromoteSystemApps
12571                            && isSystemApp(ps)
12572                            && mExistingSystemPackages.contains(ps.name)) {
12573                        // For legacy system apps, install becomes runtime.
12574                        // We cannot check hasInstallPermission() for system apps since those
12575                        // permissions were granted implicitly and not persisted pre-M.
12576                        grant = GRANT_UPGRADE;
12577                    } else {
12578                        // For modern apps keep runtime permissions unchanged.
12579                        grant = GRANT_RUNTIME;
12580                    }
12581                } break;
12582
12583                case PermissionInfo.PROTECTION_SIGNATURE: {
12584                    // For all apps signature permissions are install time ones.
12585                    allowedSig = grantSignaturePermission(perm, pkg, bp, origPermissions);
12586                    if (allowedSig) {
12587                        grant = GRANT_INSTALL;
12588                    }
12589                } break;
12590            }
12591
12592            if (DEBUG_PERMISSIONS) {
12593                Slog.i(TAG, "Granting permission " + perm + " to package " + pkg.packageName);
12594            }
12595
12596            if (grant != GRANT_DENIED) {
12597                if (!isSystemApp(ps) && ps.installPermissionsFixed) {
12598                    // If this is an existing, non-system package, then
12599                    // we can't add any new permissions to it.
12600                    if (!allowedSig && !origPermissions.hasInstallPermission(perm)) {
12601                        // Except...  if this is a permission that was added
12602                        // to the platform (note: need to only do this when
12603                        // updating the platform).
12604                        if (!isNewPlatformPermissionForPackage(perm, pkg)) {
12605                            grant = GRANT_DENIED;
12606                        }
12607                    }
12608                }
12609
12610                switch (grant) {
12611                    case GRANT_INSTALL: {
12612                        // Revoke this as runtime permission to handle the case of
12613                        // a runtime permission being downgraded to an install one.
12614                        // Also in permission review mode we keep dangerous permissions
12615                        // for legacy apps
12616                        for (int userId : UserManagerService.getInstance().getUserIds()) {
12617                            if (origPermissions.getRuntimePermissionState(
12618                                    bp.name, userId) != null) {
12619                                // Revoke the runtime permission and clear the flags.
12620                                origPermissions.revokeRuntimePermission(bp, userId);
12621                                origPermissions.updatePermissionFlags(bp, userId,
12622                                      PackageManager.MASK_PERMISSION_FLAGS, 0);
12623                                // If we revoked a permission permission, we have to write.
12624                                changedRuntimePermissionUserIds = ArrayUtils.appendInt(
12625                                        changedRuntimePermissionUserIds, userId);
12626                            }
12627                        }
12628                        // Grant an install permission.
12629                        if (permissionsState.grantInstallPermission(bp) !=
12630                                PermissionsState.PERMISSION_OPERATION_FAILURE) {
12631                            changedInstallPermission = true;
12632                        }
12633                    } break;
12634
12635                    case GRANT_RUNTIME: {
12636                        // Grant previously granted runtime permissions.
12637                        for (int userId : UserManagerService.getInstance().getUserIds()) {
12638                            PermissionState permissionState = origPermissions
12639                                    .getRuntimePermissionState(bp.name, userId);
12640                            int flags = permissionState != null
12641                                    ? permissionState.getFlags() : 0;
12642                            if (origPermissions.hasRuntimePermission(bp.name, userId)) {
12643                                // Don't propagate the permission in a permission review mode if
12644                                // the former was revoked, i.e. marked to not propagate on upgrade.
12645                                // Note that in a permission review mode install permissions are
12646                                // represented as constantly granted runtime ones since we need to
12647                                // keep a per user state associated with the permission. Also the
12648                                // revoke on upgrade flag is no longer applicable and is reset.
12649                                final boolean revokeOnUpgrade = (flags & PackageManager
12650                                        .FLAG_PERMISSION_REVOKE_ON_UPGRADE) != 0;
12651                                if (revokeOnUpgrade) {
12652                                    flags &= ~PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE;
12653                                    // Since we changed the flags, we have to write.
12654                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
12655                                            changedRuntimePermissionUserIds, userId);
12656                                }
12657                                if (!mPermissionReviewRequired || !revokeOnUpgrade) {
12658                                    if (permissionsState.grantRuntimePermission(bp, userId) ==
12659                                            PermissionsState.PERMISSION_OPERATION_FAILURE) {
12660                                        // If we cannot put the permission as it was,
12661                                        // we have to write.
12662                                        changedRuntimePermissionUserIds = ArrayUtils.appendInt(
12663                                                changedRuntimePermissionUserIds, userId);
12664                                    }
12665                                }
12666
12667                                // If the app supports runtime permissions no need for a review.
12668                                if (mPermissionReviewRequired
12669                                        && appSupportsRuntimePermissions
12670                                        && (flags & PackageManager
12671                                                .FLAG_PERMISSION_REVIEW_REQUIRED) != 0) {
12672                                    flags &= ~PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED;
12673                                    // Since we changed the flags, we have to write.
12674                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
12675                                            changedRuntimePermissionUserIds, userId);
12676                                }
12677                            } else if (mPermissionReviewRequired
12678                                    && !appSupportsRuntimePermissions) {
12679                                // For legacy apps that need a permission review, every new
12680                                // runtime permission is granted but it is pending a review.
12681                                // We also need to review only platform defined runtime
12682                                // permissions as these are the only ones the platform knows
12683                                // how to disable the API to simulate revocation as legacy
12684                                // apps don't expect to run with revoked permissions.
12685                                if (PLATFORM_PACKAGE_NAME.equals(bp.sourcePackage)) {
12686                                    if ((flags & FLAG_PERMISSION_REVIEW_REQUIRED) == 0) {
12687                                        flags |= FLAG_PERMISSION_REVIEW_REQUIRED;
12688                                        // We changed the flags, hence have to write.
12689                                        changedRuntimePermissionUserIds = ArrayUtils.appendInt(
12690                                                changedRuntimePermissionUserIds, userId);
12691                                    }
12692                                }
12693                                if (permissionsState.grantRuntimePermission(bp, userId)
12694                                        != PermissionsState.PERMISSION_OPERATION_FAILURE) {
12695                                    // We changed the permission, hence have to write.
12696                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
12697                                            changedRuntimePermissionUserIds, userId);
12698                                }
12699                            }
12700                            // Propagate the permission flags.
12701                            permissionsState.updatePermissionFlags(bp, userId, flags, flags);
12702                        }
12703                    } break;
12704
12705                    case GRANT_UPGRADE: {
12706                        // Grant runtime permissions for a previously held install permission.
12707                        PermissionState permissionState = origPermissions
12708                                .getInstallPermissionState(bp.name);
12709                        final int flags = permissionState != null ? permissionState.getFlags() : 0;
12710
12711                        if (origPermissions.revokeInstallPermission(bp)
12712                                != PermissionsState.PERMISSION_OPERATION_FAILURE) {
12713                            // We will be transferring the permission flags, so clear them.
12714                            origPermissions.updatePermissionFlags(bp, UserHandle.USER_ALL,
12715                                    PackageManager.MASK_PERMISSION_FLAGS, 0);
12716                            changedInstallPermission = true;
12717                        }
12718
12719                        // If the permission is not to be promoted to runtime we ignore it and
12720                        // also its other flags as they are not applicable to install permissions.
12721                        if ((flags & PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE) == 0) {
12722                            for (int userId : currentUserIds) {
12723                                if (permissionsState.grantRuntimePermission(bp, userId) !=
12724                                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
12725                                    // Transfer the permission flags.
12726                                    permissionsState.updatePermissionFlags(bp, userId,
12727                                            flags, flags);
12728                                    // If we granted the permission, we have to write.
12729                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
12730                                            changedRuntimePermissionUserIds, userId);
12731                                }
12732                            }
12733                        }
12734                    } break;
12735
12736                    default: {
12737                        if (packageOfInterest == null
12738                                || packageOfInterest.equals(pkg.packageName)) {
12739                            if (DEBUG_PERMISSIONS) {
12740                                Slog.i(TAG, "Not granting permission " + perm
12741                                        + " to package " + pkg.packageName
12742                                        + " because it was previously installed without");
12743                            }
12744                        }
12745                    } break;
12746                }
12747            } else {
12748                if (permissionsState.revokeInstallPermission(bp) !=
12749                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
12750                    // Also drop the permission flags.
12751                    permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL,
12752                            PackageManager.MASK_PERMISSION_FLAGS, 0);
12753                    changedInstallPermission = true;
12754                    Slog.i(TAG, "Un-granting permission " + perm
12755                            + " from package " + pkg.packageName
12756                            + " (protectionLevel=" + bp.protectionLevel
12757                            + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
12758                            + ")");
12759                } else if ((bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) == 0) {
12760                    // Don't print warning for app op permissions, since it is fine for them
12761                    // not to be granted, there is a UI for the user to decide.
12762                    if (DEBUG_PERMISSIONS
12763                            && (packageOfInterest == null
12764                                    || packageOfInterest.equals(pkg.packageName))) {
12765                        Slog.i(TAG, "Not granting permission " + perm
12766                                + " to package " + pkg.packageName
12767                                + " (protectionLevel=" + bp.protectionLevel
12768                                + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
12769                                + ")");
12770                    }
12771                }
12772            }
12773        }
12774
12775        if ((changedInstallPermission || replace) && !ps.installPermissionsFixed &&
12776                !isSystemApp(ps) || isUpdatedSystemApp(ps)){
12777            // This is the first that we have heard about this package, so the
12778            // permissions we have now selected are fixed until explicitly
12779            // changed.
12780            ps.installPermissionsFixed = true;
12781        }
12782
12783        // Persist the runtime permissions state for users with changes. If permissions
12784        // were revoked because no app in the shared user declares them we have to
12785        // write synchronously to avoid losing runtime permissions state.
12786        for (int userId : changedRuntimePermissionUserIds) {
12787            mSettings.writeRuntimePermissionsForUserLPr(userId, runtimePermissionsRevoked);
12788        }
12789    }
12790
12791    private boolean isNewPlatformPermissionForPackage(String perm, PackageParser.Package pkg) {
12792        boolean allowed = false;
12793        final int NP = PackageParser.NEW_PERMISSIONS.length;
12794        for (int ip=0; ip<NP; ip++) {
12795            final PackageParser.NewPermissionInfo npi
12796                    = PackageParser.NEW_PERMISSIONS[ip];
12797            if (npi.name.equals(perm)
12798                    && pkg.applicationInfo.targetSdkVersion < npi.sdkVersion) {
12799                allowed = true;
12800                Log.i(TAG, "Auto-granting " + perm + " to old pkg "
12801                        + pkg.packageName);
12802                break;
12803            }
12804        }
12805        return allowed;
12806    }
12807
12808    private boolean grantSignaturePermission(String perm, PackageParser.Package pkg,
12809            BasePermission bp, PermissionsState origPermissions) {
12810        boolean privilegedPermission = (bp.protectionLevel
12811                & PermissionInfo.PROTECTION_FLAG_PRIVILEGED) != 0;
12812        boolean privappPermissionsDisable =
12813                RoSystemProperties.CONTROL_PRIVAPP_PERMISSIONS_DISABLE;
12814        boolean platformPermission = PLATFORM_PACKAGE_NAME.equals(bp.sourcePackage);
12815        boolean platformPackage = PLATFORM_PACKAGE_NAME.equals(pkg.packageName);
12816        if (!privappPermissionsDisable && privilegedPermission && pkg.isPrivilegedApp()
12817                && !platformPackage && platformPermission) {
12818            ArraySet<String> wlPermissions = SystemConfig.getInstance()
12819                    .getPrivAppPermissions(pkg.packageName);
12820            boolean whitelisted = wlPermissions != null && wlPermissions.contains(perm);
12821            if (!whitelisted) {
12822                Slog.w(TAG, "Privileged permission " + perm + " for package "
12823                        + pkg.packageName + " - not in privapp-permissions whitelist");
12824                // Only report violations for apps on system image
12825                if (!mSystemReady && !pkg.isUpdatedSystemApp()) {
12826                    if (mPrivappPermissionsViolations == null) {
12827                        mPrivappPermissionsViolations = new ArraySet<>();
12828                    }
12829                    mPrivappPermissionsViolations.add(pkg.packageName + ": " + perm);
12830                }
12831                if (RoSystemProperties.CONTROL_PRIVAPP_PERMISSIONS_ENFORCE) {
12832                    return false;
12833                }
12834            }
12835        }
12836        boolean allowed = (compareSignatures(
12837                bp.packageSetting.signatures.mSignatures, pkg.mSignatures)
12838                        == PackageManager.SIGNATURE_MATCH)
12839                || (compareSignatures(mPlatformPackage.mSignatures, pkg.mSignatures)
12840                        == PackageManager.SIGNATURE_MATCH);
12841        if (!allowed && privilegedPermission) {
12842            if (isSystemApp(pkg)) {
12843                // For updated system applications, a system permission
12844                // is granted only if it had been defined by the original application.
12845                if (pkg.isUpdatedSystemApp()) {
12846                    final PackageSetting sysPs = mSettings
12847                            .getDisabledSystemPkgLPr(pkg.packageName);
12848                    if (sysPs != null && sysPs.getPermissionsState().hasInstallPermission(perm)) {
12849                        // If the original was granted this permission, we take
12850                        // that grant decision as read and propagate it to the
12851                        // update.
12852                        if (sysPs.isPrivileged()) {
12853                            allowed = true;
12854                        }
12855                    } else {
12856                        // The system apk may have been updated with an older
12857                        // version of the one on the data partition, but which
12858                        // granted a new system permission that it didn't have
12859                        // before.  In this case we do want to allow the app to
12860                        // now get the new permission if the ancestral apk is
12861                        // privileged to get it.
12862                        if (sysPs != null && sysPs.pkg != null && sysPs.isPrivileged()) {
12863                            for (int j = 0; j < sysPs.pkg.requestedPermissions.size(); j++) {
12864                                if (perm.equals(sysPs.pkg.requestedPermissions.get(j))) {
12865                                    allowed = true;
12866                                    break;
12867                                }
12868                            }
12869                        }
12870                        // Also if a privileged parent package on the system image or any of
12871                        // its children requested a privileged permission, the updated child
12872                        // packages can also get the permission.
12873                        if (pkg.parentPackage != null) {
12874                            final PackageSetting disabledSysParentPs = mSettings
12875                                    .getDisabledSystemPkgLPr(pkg.parentPackage.packageName);
12876                            if (disabledSysParentPs != null && disabledSysParentPs.pkg != null
12877                                    && disabledSysParentPs.isPrivileged()) {
12878                                if (isPackageRequestingPermission(disabledSysParentPs.pkg, perm)) {
12879                                    allowed = true;
12880                                } else if (disabledSysParentPs.pkg.childPackages != null) {
12881                                    final int count = disabledSysParentPs.pkg.childPackages.size();
12882                                    for (int i = 0; i < count; i++) {
12883                                        PackageParser.Package disabledSysChildPkg =
12884                                                disabledSysParentPs.pkg.childPackages.get(i);
12885                                        if (isPackageRequestingPermission(disabledSysChildPkg,
12886                                                perm)) {
12887                                            allowed = true;
12888                                            break;
12889                                        }
12890                                    }
12891                                }
12892                            }
12893                        }
12894                    }
12895                } else {
12896                    allowed = isPrivilegedApp(pkg);
12897                }
12898            }
12899        }
12900        if (!allowed) {
12901            if (!allowed && (bp.protectionLevel
12902                    & PermissionInfo.PROTECTION_FLAG_PRE23) != 0
12903                    && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) {
12904                // If this was a previously normal/dangerous permission that got moved
12905                // to a system permission as part of the runtime permission redesign, then
12906                // we still want to blindly grant it to old apps.
12907                allowed = true;
12908            }
12909            if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_INSTALLER) != 0
12910                    && pkg.packageName.equals(mRequiredInstallerPackage)) {
12911                // If this permission is to be granted to the system installer and
12912                // this app is an installer, then it gets the permission.
12913                allowed = true;
12914            }
12915            if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_VERIFIER) != 0
12916                    && pkg.packageName.equals(mRequiredVerifierPackage)) {
12917                // If this permission is to be granted to the system verifier and
12918                // this app is a verifier, then it gets the permission.
12919                allowed = true;
12920            }
12921            if (!allowed && (bp.protectionLevel
12922                    & PermissionInfo.PROTECTION_FLAG_PREINSTALLED) != 0
12923                    && isSystemApp(pkg)) {
12924                // Any pre-installed system app is allowed to get this permission.
12925                allowed = true;
12926            }
12927            if (!allowed && (bp.protectionLevel
12928                    & PermissionInfo.PROTECTION_FLAG_DEVELOPMENT) != 0) {
12929                // For development permissions, a development permission
12930                // is granted only if it was already granted.
12931                allowed = origPermissions.hasInstallPermission(perm);
12932            }
12933            if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_SETUP) != 0
12934                    && pkg.packageName.equals(mSetupWizardPackage)) {
12935                // If this permission is to be granted to the system setup wizard and
12936                // this app is a setup wizard, then it gets the permission.
12937                allowed = true;
12938            }
12939        }
12940        return allowed;
12941    }
12942
12943    private boolean isPackageRequestingPermission(PackageParser.Package pkg, String permission) {
12944        final int permCount = pkg.requestedPermissions.size();
12945        for (int j = 0; j < permCount; j++) {
12946            String requestedPermission = pkg.requestedPermissions.get(j);
12947            if (permission.equals(requestedPermission)) {
12948                return true;
12949            }
12950        }
12951        return false;
12952    }
12953
12954    final class ActivityIntentResolver
12955            extends IntentResolver<PackageParser.ActivityIntentInfo, ResolveInfo> {
12956        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
12957                boolean defaultOnly, int userId) {
12958            if (!sUserManager.exists(userId)) return null;
12959            mFlags = (defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0);
12960            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
12961        }
12962
12963        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
12964                int userId) {
12965            if (!sUserManager.exists(userId)) return null;
12966            mFlags = flags;
12967            return super.queryIntent(intent, resolvedType,
12968                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0,
12969                    userId);
12970        }
12971
12972        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
12973                int flags, ArrayList<PackageParser.Activity> packageActivities, int userId) {
12974            if (!sUserManager.exists(userId)) return null;
12975            if (packageActivities == null) {
12976                return null;
12977            }
12978            mFlags = flags;
12979            final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0;
12980            final int N = packageActivities.size();
12981            ArrayList<PackageParser.ActivityIntentInfo[]> listCut =
12982                new ArrayList<PackageParser.ActivityIntentInfo[]>(N);
12983
12984            ArrayList<PackageParser.ActivityIntentInfo> intentFilters;
12985            for (int i = 0; i < N; ++i) {
12986                intentFilters = packageActivities.get(i).intents;
12987                if (intentFilters != null && intentFilters.size() > 0) {
12988                    PackageParser.ActivityIntentInfo[] array =
12989                            new PackageParser.ActivityIntentInfo[intentFilters.size()];
12990                    intentFilters.toArray(array);
12991                    listCut.add(array);
12992                }
12993            }
12994            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
12995        }
12996
12997        /**
12998         * Finds a privileged activity that matches the specified activity names.
12999         */
13000        private PackageParser.Activity findMatchingActivity(
13001                List<PackageParser.Activity> activityList, ActivityInfo activityInfo) {
13002            for (PackageParser.Activity sysActivity : activityList) {
13003                if (sysActivity.info.name.equals(activityInfo.name)) {
13004                    return sysActivity;
13005                }
13006                if (sysActivity.info.name.equals(activityInfo.targetActivity)) {
13007                    return sysActivity;
13008                }
13009                if (sysActivity.info.targetActivity != null) {
13010                    if (sysActivity.info.targetActivity.equals(activityInfo.name)) {
13011                        return sysActivity;
13012                    }
13013                    if (sysActivity.info.targetActivity.equals(activityInfo.targetActivity)) {
13014                        return sysActivity;
13015                    }
13016                }
13017            }
13018            return null;
13019        }
13020
13021        public class IterGenerator<E> {
13022            public Iterator<E> generate(ActivityIntentInfo info) {
13023                return null;
13024            }
13025        }
13026
13027        public class ActionIterGenerator extends IterGenerator<String> {
13028            @Override
13029            public Iterator<String> generate(ActivityIntentInfo info) {
13030                return info.actionsIterator();
13031            }
13032        }
13033
13034        public class CategoriesIterGenerator extends IterGenerator<String> {
13035            @Override
13036            public Iterator<String> generate(ActivityIntentInfo info) {
13037                return info.categoriesIterator();
13038            }
13039        }
13040
13041        public class SchemesIterGenerator extends IterGenerator<String> {
13042            @Override
13043            public Iterator<String> generate(ActivityIntentInfo info) {
13044                return info.schemesIterator();
13045            }
13046        }
13047
13048        public class AuthoritiesIterGenerator extends IterGenerator<IntentFilter.AuthorityEntry> {
13049            @Override
13050            public Iterator<IntentFilter.AuthorityEntry> generate(ActivityIntentInfo info) {
13051                return info.authoritiesIterator();
13052            }
13053        }
13054
13055        /**
13056         * <em>WARNING</em> for performance reasons, the passed in intentList WILL BE
13057         * MODIFIED. Do not pass in a list that should not be changed.
13058         */
13059        private <T> void getIntentListSubset(List<ActivityIntentInfo> intentList,
13060                IterGenerator<T> generator, Iterator<T> searchIterator) {
13061            // loop through the set of actions; every one must be found in the intent filter
13062            while (searchIterator.hasNext()) {
13063                // we must have at least one filter in the list to consider a match
13064                if (intentList.size() == 0) {
13065                    break;
13066                }
13067
13068                final T searchAction = searchIterator.next();
13069
13070                // loop through the set of intent filters
13071                final Iterator<ActivityIntentInfo> intentIter = intentList.iterator();
13072                while (intentIter.hasNext()) {
13073                    final ActivityIntentInfo intentInfo = intentIter.next();
13074                    boolean selectionFound = false;
13075
13076                    // loop through the intent filter's selection criteria; at least one
13077                    // of them must match the searched criteria
13078                    final Iterator<T> intentSelectionIter = generator.generate(intentInfo);
13079                    while (intentSelectionIter != null && intentSelectionIter.hasNext()) {
13080                        final T intentSelection = intentSelectionIter.next();
13081                        if (intentSelection != null && intentSelection.equals(searchAction)) {
13082                            selectionFound = true;
13083                            break;
13084                        }
13085                    }
13086
13087                    // the selection criteria wasn't found in this filter's set; this filter
13088                    // is not a potential match
13089                    if (!selectionFound) {
13090                        intentIter.remove();
13091                    }
13092                }
13093            }
13094        }
13095
13096        private boolean isProtectedAction(ActivityIntentInfo filter) {
13097            final Iterator<String> actionsIter = filter.actionsIterator();
13098            while (actionsIter != null && actionsIter.hasNext()) {
13099                final String filterAction = actionsIter.next();
13100                if (PROTECTED_ACTIONS.contains(filterAction)) {
13101                    return true;
13102                }
13103            }
13104            return false;
13105        }
13106
13107        /**
13108         * Adjusts the priority of the given intent filter according to policy.
13109         * <p>
13110         * <ul>
13111         * <li>The priority for non privileged applications is capped to '0'</li>
13112         * <li>The priority for protected actions on privileged applications is capped to '0'</li>
13113         * <li>The priority for unbundled updates to privileged applications is capped to the
13114         *      priority defined on the system partition</li>
13115         * </ul>
13116         * <p>
13117         * <em>NOTE:</em> There is one exception. For security reasons, the setup wizard is
13118         * allowed to obtain any priority on any action.
13119         */
13120        private void adjustPriority(
13121                List<PackageParser.Activity> systemActivities, ActivityIntentInfo intent) {
13122            // nothing to do; priority is fine as-is
13123            if (intent.getPriority() <= 0) {
13124                return;
13125            }
13126
13127            final ActivityInfo activityInfo = intent.activity.info;
13128            final ApplicationInfo applicationInfo = activityInfo.applicationInfo;
13129
13130            final boolean privilegedApp =
13131                    ((applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0);
13132            if (!privilegedApp) {
13133                // non-privileged applications can never define a priority >0
13134                if (DEBUG_FILTERS) {
13135                    Slog.i(TAG, "Non-privileged app; cap priority to 0;"
13136                            + " package: " + applicationInfo.packageName
13137                            + " activity: " + intent.activity.className
13138                            + " origPrio: " + intent.getPriority());
13139                }
13140                intent.setPriority(0);
13141                return;
13142            }
13143
13144            if (systemActivities == null) {
13145                // the system package is not disabled; we're parsing the system partition
13146                if (isProtectedAction(intent)) {
13147                    if (mDeferProtectedFilters) {
13148                        // We can't deal with these just yet. No component should ever obtain a
13149                        // >0 priority for a protected actions, with ONE exception -- the setup
13150                        // wizard. The setup wizard, however, cannot be known until we're able to
13151                        // query it for the category CATEGORY_SETUP_WIZARD. Which we can't do
13152                        // until all intent filters have been processed. Chicken, meet egg.
13153                        // Let the filter temporarily have a high priority and rectify the
13154                        // priorities after all system packages have been scanned.
13155                        mProtectedFilters.add(intent);
13156                        if (DEBUG_FILTERS) {
13157                            Slog.i(TAG, "Protected action; save for later;"
13158                                    + " package: " + applicationInfo.packageName
13159                                    + " activity: " + intent.activity.className
13160                                    + " origPrio: " + intent.getPriority());
13161                        }
13162                        return;
13163                    } else {
13164                        if (DEBUG_FILTERS && mSetupWizardPackage == null) {
13165                            Slog.i(TAG, "No setup wizard;"
13166                                + " All protected intents capped to priority 0");
13167                        }
13168                        if (intent.activity.info.packageName.equals(mSetupWizardPackage)) {
13169                            if (DEBUG_FILTERS) {
13170                                Slog.i(TAG, "Found setup wizard;"
13171                                    + " allow priority " + intent.getPriority() + ";"
13172                                    + " package: " + intent.activity.info.packageName
13173                                    + " activity: " + intent.activity.className
13174                                    + " priority: " + intent.getPriority());
13175                            }
13176                            // setup wizard gets whatever it wants
13177                            return;
13178                        }
13179                        if (DEBUG_FILTERS) {
13180                            Slog.i(TAG, "Protected action; cap priority to 0;"
13181                                    + " package: " + intent.activity.info.packageName
13182                                    + " activity: " + intent.activity.className
13183                                    + " origPrio: " + intent.getPriority());
13184                        }
13185                        intent.setPriority(0);
13186                        return;
13187                    }
13188                }
13189                // privileged apps on the system image get whatever priority they request
13190                return;
13191            }
13192
13193            // privileged app unbundled update ... try to find the same activity
13194            final PackageParser.Activity foundActivity =
13195                    findMatchingActivity(systemActivities, activityInfo);
13196            if (foundActivity == null) {
13197                // this is a new activity; it cannot obtain >0 priority
13198                if (DEBUG_FILTERS) {
13199                    Slog.i(TAG, "New activity; cap priority to 0;"
13200                            + " package: " + applicationInfo.packageName
13201                            + " activity: " + intent.activity.className
13202                            + " origPrio: " + intent.getPriority());
13203                }
13204                intent.setPriority(0);
13205                return;
13206            }
13207
13208            // found activity, now check for filter equivalence
13209
13210            // a shallow copy is enough; we modify the list, not its contents
13211            final List<ActivityIntentInfo> intentListCopy =
13212                    new ArrayList<>(foundActivity.intents);
13213            final List<ActivityIntentInfo> foundFilters = findFilters(intent);
13214
13215            // find matching action subsets
13216            final Iterator<String> actionsIterator = intent.actionsIterator();
13217            if (actionsIterator != null) {
13218                getIntentListSubset(
13219                        intentListCopy, new ActionIterGenerator(), actionsIterator);
13220                if (intentListCopy.size() == 0) {
13221                    // no more intents to match; we're not equivalent
13222                    if (DEBUG_FILTERS) {
13223                        Slog.i(TAG, "Mismatched action; cap priority to 0;"
13224                                + " package: " + applicationInfo.packageName
13225                                + " activity: " + intent.activity.className
13226                                + " origPrio: " + intent.getPriority());
13227                    }
13228                    intent.setPriority(0);
13229                    return;
13230                }
13231            }
13232
13233            // find matching category subsets
13234            final Iterator<String> categoriesIterator = intent.categoriesIterator();
13235            if (categoriesIterator != null) {
13236                getIntentListSubset(intentListCopy, new CategoriesIterGenerator(),
13237                        categoriesIterator);
13238                if (intentListCopy.size() == 0) {
13239                    // no more intents to match; we're not equivalent
13240                    if (DEBUG_FILTERS) {
13241                        Slog.i(TAG, "Mismatched category; cap priority to 0;"
13242                                + " package: " + applicationInfo.packageName
13243                                + " activity: " + intent.activity.className
13244                                + " origPrio: " + intent.getPriority());
13245                    }
13246                    intent.setPriority(0);
13247                    return;
13248                }
13249            }
13250
13251            // find matching schemes subsets
13252            final Iterator<String> schemesIterator = intent.schemesIterator();
13253            if (schemesIterator != null) {
13254                getIntentListSubset(intentListCopy, new SchemesIterGenerator(),
13255                        schemesIterator);
13256                if (intentListCopy.size() == 0) {
13257                    // no more intents to match; we're not equivalent
13258                    if (DEBUG_FILTERS) {
13259                        Slog.i(TAG, "Mismatched scheme; cap priority to 0;"
13260                                + " package: " + applicationInfo.packageName
13261                                + " activity: " + intent.activity.className
13262                                + " origPrio: " + intent.getPriority());
13263                    }
13264                    intent.setPriority(0);
13265                    return;
13266                }
13267            }
13268
13269            // find matching authorities subsets
13270            final Iterator<IntentFilter.AuthorityEntry>
13271                    authoritiesIterator = intent.authoritiesIterator();
13272            if (authoritiesIterator != null) {
13273                getIntentListSubset(intentListCopy,
13274                        new AuthoritiesIterGenerator(),
13275                        authoritiesIterator);
13276                if (intentListCopy.size() == 0) {
13277                    // no more intents to match; we're not equivalent
13278                    if (DEBUG_FILTERS) {
13279                        Slog.i(TAG, "Mismatched authority; cap priority to 0;"
13280                                + " package: " + applicationInfo.packageName
13281                                + " activity: " + intent.activity.className
13282                                + " origPrio: " + intent.getPriority());
13283                    }
13284                    intent.setPriority(0);
13285                    return;
13286                }
13287            }
13288
13289            // we found matching filter(s); app gets the max priority of all intents
13290            int cappedPriority = 0;
13291            for (int i = intentListCopy.size() - 1; i >= 0; --i) {
13292                cappedPriority = Math.max(cappedPriority, intentListCopy.get(i).getPriority());
13293            }
13294            if (intent.getPriority() > cappedPriority) {
13295                if (DEBUG_FILTERS) {
13296                    Slog.i(TAG, "Found matching filter(s);"
13297                            + " cap priority to " + cappedPriority + ";"
13298                            + " package: " + applicationInfo.packageName
13299                            + " activity: " + intent.activity.className
13300                            + " origPrio: " + intent.getPriority());
13301                }
13302                intent.setPriority(cappedPriority);
13303                return;
13304            }
13305            // all this for nothing; the requested priority was <= what was on the system
13306        }
13307
13308        public final void addActivity(PackageParser.Activity a, String type) {
13309            mActivities.put(a.getComponentName(), a);
13310            if (DEBUG_SHOW_INFO)
13311                Log.v(
13312                TAG, "  " + type + " " +
13313                (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":");
13314            if (DEBUG_SHOW_INFO)
13315                Log.v(TAG, "    Class=" + a.info.name);
13316            final int NI = a.intents.size();
13317            for (int j=0; j<NI; j++) {
13318                PackageParser.ActivityIntentInfo intent = a.intents.get(j);
13319                if ("activity".equals(type)) {
13320                    final PackageSetting ps =
13321                            mSettings.getDisabledSystemPkgLPr(intent.activity.info.packageName);
13322                    final List<PackageParser.Activity> systemActivities =
13323                            ps != null && ps.pkg != null ? ps.pkg.activities : null;
13324                    adjustPriority(systemActivities, intent);
13325                }
13326                if (DEBUG_SHOW_INFO) {
13327                    Log.v(TAG, "    IntentFilter:");
13328                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
13329                }
13330                if (!intent.debugCheck()) {
13331                    Log.w(TAG, "==> For Activity " + a.info.name);
13332                }
13333                addFilter(intent);
13334            }
13335        }
13336
13337        public final void removeActivity(PackageParser.Activity a, String type) {
13338            mActivities.remove(a.getComponentName());
13339            if (DEBUG_SHOW_INFO) {
13340                Log.v(TAG, "  " + type + " "
13341                        + (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel
13342                                : a.info.name) + ":");
13343                Log.v(TAG, "    Class=" + a.info.name);
13344            }
13345            final int NI = a.intents.size();
13346            for (int j=0; j<NI; j++) {
13347                PackageParser.ActivityIntentInfo intent = a.intents.get(j);
13348                if (DEBUG_SHOW_INFO) {
13349                    Log.v(TAG, "    IntentFilter:");
13350                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
13351                }
13352                removeFilter(intent);
13353            }
13354        }
13355
13356        @Override
13357        protected boolean allowFilterResult(
13358                PackageParser.ActivityIntentInfo filter, List<ResolveInfo> dest) {
13359            ActivityInfo filterAi = filter.activity.info;
13360            for (int i=dest.size()-1; i>=0; i--) {
13361                ActivityInfo destAi = dest.get(i).activityInfo;
13362                if (destAi.name == filterAi.name
13363                        && destAi.packageName == filterAi.packageName) {
13364                    return false;
13365                }
13366            }
13367            return true;
13368        }
13369
13370        @Override
13371        protected ActivityIntentInfo[] newArray(int size) {
13372            return new ActivityIntentInfo[size];
13373        }
13374
13375        @Override
13376        protected boolean isFilterStopped(PackageParser.ActivityIntentInfo filter, int userId) {
13377            if (!sUserManager.exists(userId)) return true;
13378            PackageParser.Package p = filter.activity.owner;
13379            if (p != null) {
13380                PackageSetting ps = (PackageSetting)p.mExtras;
13381                if (ps != null) {
13382                    // System apps are never considered stopped for purposes of
13383                    // filtering, because there may be no way for the user to
13384                    // actually re-launch them.
13385                    return (ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0
13386                            && ps.getStopped(userId);
13387                }
13388            }
13389            return false;
13390        }
13391
13392        @Override
13393        protected boolean isPackageForFilter(String packageName,
13394                PackageParser.ActivityIntentInfo info) {
13395            return packageName.equals(info.activity.owner.packageName);
13396        }
13397
13398        @Override
13399        protected ResolveInfo newResult(PackageParser.ActivityIntentInfo info,
13400                int match, int userId) {
13401            if (!sUserManager.exists(userId)) return null;
13402            if (!mSettings.isEnabledAndMatchLPr(info.activity.info, mFlags, userId)) {
13403                return null;
13404            }
13405            final PackageParser.Activity activity = info.activity;
13406            PackageSetting ps = (PackageSetting) activity.owner.mExtras;
13407            if (ps == null) {
13408                return null;
13409            }
13410            final PackageUserState userState = ps.readUserState(userId);
13411            ActivityInfo ai =
13412                    PackageParser.generateActivityInfo(activity, mFlags, userState, userId);
13413            if (ai == null) {
13414                return null;
13415            }
13416            final boolean matchExplicitlyVisibleOnly =
13417                    (mFlags & PackageManager.MATCH_EXPLICITLY_VISIBLE_ONLY) != 0;
13418            final boolean matchVisibleToInstantApp =
13419                    (mFlags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
13420            final boolean componentVisible =
13421                    matchVisibleToInstantApp
13422                    && info.isVisibleToInstantApp()
13423                    && (!matchExplicitlyVisibleOnly || info.isExplicitlyVisibleToInstantApp());
13424            final boolean matchInstantApp = (mFlags & PackageManager.MATCH_INSTANT) != 0;
13425            // throw out filters that aren't visible to ephemeral apps
13426            if (matchVisibleToInstantApp && !(componentVisible || userState.instantApp)) {
13427                return null;
13428            }
13429            // throw out instant app filters if we're not explicitly requesting them
13430            if (!matchInstantApp && userState.instantApp) {
13431                return null;
13432            }
13433            // throw out instant app filters if updates are available; will trigger
13434            // instant app resolution
13435            if (userState.instantApp && ps.isUpdateAvailable()) {
13436                return null;
13437            }
13438            final ResolveInfo res = new ResolveInfo();
13439            res.activityInfo = ai;
13440            if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
13441                res.filter = info;
13442            }
13443            if (info != null) {
13444                res.handleAllWebDataURI = info.handleAllWebDataURI();
13445            }
13446            res.priority = info.getPriority();
13447            res.preferredOrder = activity.owner.mPreferredOrder;
13448            //System.out.println("Result: " + res.activityInfo.className +
13449            //                   " = " + res.priority);
13450            res.match = match;
13451            res.isDefault = info.hasDefault;
13452            res.labelRes = info.labelRes;
13453            res.nonLocalizedLabel = info.nonLocalizedLabel;
13454            if (userNeedsBadging(userId)) {
13455                res.noResourceId = true;
13456            } else {
13457                res.icon = info.icon;
13458            }
13459            res.iconResourceId = info.icon;
13460            res.system = res.activityInfo.applicationInfo.isSystemApp();
13461            res.isInstantAppAvailable = userState.instantApp;
13462            return res;
13463        }
13464
13465        @Override
13466        protected void sortResults(List<ResolveInfo> results) {
13467            Collections.sort(results, mResolvePrioritySorter);
13468        }
13469
13470        @Override
13471        protected void dumpFilter(PrintWriter out, String prefix,
13472                PackageParser.ActivityIntentInfo filter) {
13473            out.print(prefix); out.print(
13474                    Integer.toHexString(System.identityHashCode(filter.activity)));
13475                    out.print(' ');
13476                    filter.activity.printComponentShortName(out);
13477                    out.print(" filter ");
13478                    out.println(Integer.toHexString(System.identityHashCode(filter)));
13479        }
13480
13481        @Override
13482        protected Object filterToLabel(PackageParser.ActivityIntentInfo filter) {
13483            return filter.activity;
13484        }
13485
13486        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
13487            PackageParser.Activity activity = (PackageParser.Activity)label;
13488            out.print(prefix); out.print(
13489                    Integer.toHexString(System.identityHashCode(activity)));
13490                    out.print(' ');
13491                    activity.printComponentShortName(out);
13492            if (count > 1) {
13493                out.print(" ("); out.print(count); out.print(" filters)");
13494            }
13495            out.println();
13496        }
13497
13498        // Keys are String (activity class name), values are Activity.
13499        private final ArrayMap<ComponentName, PackageParser.Activity> mActivities
13500                = new ArrayMap<ComponentName, PackageParser.Activity>();
13501        private int mFlags;
13502    }
13503
13504    private final class ServiceIntentResolver
13505            extends IntentResolver<PackageParser.ServiceIntentInfo, ResolveInfo> {
13506        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
13507                boolean defaultOnly, int userId) {
13508            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
13509            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
13510        }
13511
13512        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
13513                int userId) {
13514            if (!sUserManager.exists(userId)) return null;
13515            mFlags = flags;
13516            return super.queryIntent(intent, resolvedType,
13517                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0,
13518                    userId);
13519        }
13520
13521        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
13522                int flags, ArrayList<PackageParser.Service> packageServices, int userId) {
13523            if (!sUserManager.exists(userId)) return null;
13524            if (packageServices == null) {
13525                return null;
13526            }
13527            mFlags = flags;
13528            final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0;
13529            final int N = packageServices.size();
13530            ArrayList<PackageParser.ServiceIntentInfo[]> listCut =
13531                new ArrayList<PackageParser.ServiceIntentInfo[]>(N);
13532
13533            ArrayList<PackageParser.ServiceIntentInfo> intentFilters;
13534            for (int i = 0; i < N; ++i) {
13535                intentFilters = packageServices.get(i).intents;
13536                if (intentFilters != null && intentFilters.size() > 0) {
13537                    PackageParser.ServiceIntentInfo[] array =
13538                            new PackageParser.ServiceIntentInfo[intentFilters.size()];
13539                    intentFilters.toArray(array);
13540                    listCut.add(array);
13541                }
13542            }
13543            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
13544        }
13545
13546        public final void addService(PackageParser.Service s) {
13547            mServices.put(s.getComponentName(), s);
13548            if (DEBUG_SHOW_INFO) {
13549                Log.v(TAG, "  "
13550                        + (s.info.nonLocalizedLabel != null
13551                        ? s.info.nonLocalizedLabel : s.info.name) + ":");
13552                Log.v(TAG, "    Class=" + s.info.name);
13553            }
13554            final int NI = s.intents.size();
13555            int j;
13556            for (j=0; j<NI; j++) {
13557                PackageParser.ServiceIntentInfo intent = s.intents.get(j);
13558                if (DEBUG_SHOW_INFO) {
13559                    Log.v(TAG, "    IntentFilter:");
13560                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
13561                }
13562                if (!intent.debugCheck()) {
13563                    Log.w(TAG, "==> For Service " + s.info.name);
13564                }
13565                addFilter(intent);
13566            }
13567        }
13568
13569        public final void removeService(PackageParser.Service s) {
13570            mServices.remove(s.getComponentName());
13571            if (DEBUG_SHOW_INFO) {
13572                Log.v(TAG, "  " + (s.info.nonLocalizedLabel != null
13573                        ? s.info.nonLocalizedLabel : s.info.name) + ":");
13574                Log.v(TAG, "    Class=" + s.info.name);
13575            }
13576            final int NI = s.intents.size();
13577            int j;
13578            for (j=0; j<NI; j++) {
13579                PackageParser.ServiceIntentInfo intent = s.intents.get(j);
13580                if (DEBUG_SHOW_INFO) {
13581                    Log.v(TAG, "    IntentFilter:");
13582                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
13583                }
13584                removeFilter(intent);
13585            }
13586        }
13587
13588        @Override
13589        protected boolean allowFilterResult(
13590                PackageParser.ServiceIntentInfo filter, List<ResolveInfo> dest) {
13591            ServiceInfo filterSi = filter.service.info;
13592            for (int i=dest.size()-1; i>=0; i--) {
13593                ServiceInfo destAi = dest.get(i).serviceInfo;
13594                if (destAi.name == filterSi.name
13595                        && destAi.packageName == filterSi.packageName) {
13596                    return false;
13597                }
13598            }
13599            return true;
13600        }
13601
13602        @Override
13603        protected PackageParser.ServiceIntentInfo[] newArray(int size) {
13604            return new PackageParser.ServiceIntentInfo[size];
13605        }
13606
13607        @Override
13608        protected boolean isFilterStopped(PackageParser.ServiceIntentInfo filter, int userId) {
13609            if (!sUserManager.exists(userId)) return true;
13610            PackageParser.Package p = filter.service.owner;
13611            if (p != null) {
13612                PackageSetting ps = (PackageSetting)p.mExtras;
13613                if (ps != null) {
13614                    // System apps are never considered stopped for purposes of
13615                    // filtering, because there may be no way for the user to
13616                    // actually re-launch them.
13617                    return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0
13618                            && ps.getStopped(userId);
13619                }
13620            }
13621            return false;
13622        }
13623
13624        @Override
13625        protected boolean isPackageForFilter(String packageName,
13626                PackageParser.ServiceIntentInfo info) {
13627            return packageName.equals(info.service.owner.packageName);
13628        }
13629
13630        @Override
13631        protected ResolveInfo newResult(PackageParser.ServiceIntentInfo filter,
13632                int match, int userId) {
13633            if (!sUserManager.exists(userId)) return null;
13634            final PackageParser.ServiceIntentInfo info = (PackageParser.ServiceIntentInfo)filter;
13635            if (!mSettings.isEnabledAndMatchLPr(info.service.info, mFlags, userId)) {
13636                return null;
13637            }
13638            final PackageParser.Service service = info.service;
13639            PackageSetting ps = (PackageSetting) service.owner.mExtras;
13640            if (ps == null) {
13641                return null;
13642            }
13643            final PackageUserState userState = ps.readUserState(userId);
13644            ServiceInfo si = PackageParser.generateServiceInfo(service, mFlags,
13645                    userState, userId);
13646            if (si == null) {
13647                return null;
13648            }
13649            final boolean matchVisibleToInstantApp =
13650                    (mFlags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
13651            final boolean isInstantApp = (mFlags & PackageManager.MATCH_INSTANT) != 0;
13652            // throw out filters that aren't visible to ephemeral apps
13653            if (matchVisibleToInstantApp
13654                    && !(info.isVisibleToInstantApp() || userState.instantApp)) {
13655                return null;
13656            }
13657            // throw out ephemeral filters if we're not explicitly requesting them
13658            if (!isInstantApp && userState.instantApp) {
13659                return null;
13660            }
13661            // throw out instant app filters if updates are available; will trigger
13662            // instant app resolution
13663            if (userState.instantApp && ps.isUpdateAvailable()) {
13664                return null;
13665            }
13666            final ResolveInfo res = new ResolveInfo();
13667            res.serviceInfo = si;
13668            if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
13669                res.filter = filter;
13670            }
13671            res.priority = info.getPriority();
13672            res.preferredOrder = service.owner.mPreferredOrder;
13673            res.match = match;
13674            res.isDefault = info.hasDefault;
13675            res.labelRes = info.labelRes;
13676            res.nonLocalizedLabel = info.nonLocalizedLabel;
13677            res.icon = info.icon;
13678            res.system = res.serviceInfo.applicationInfo.isSystemApp();
13679            return res;
13680        }
13681
13682        @Override
13683        protected void sortResults(List<ResolveInfo> results) {
13684            Collections.sort(results, mResolvePrioritySorter);
13685        }
13686
13687        @Override
13688        protected void dumpFilter(PrintWriter out, String prefix,
13689                PackageParser.ServiceIntentInfo filter) {
13690            out.print(prefix); out.print(
13691                    Integer.toHexString(System.identityHashCode(filter.service)));
13692                    out.print(' ');
13693                    filter.service.printComponentShortName(out);
13694                    out.print(" filter ");
13695                    out.println(Integer.toHexString(System.identityHashCode(filter)));
13696        }
13697
13698        @Override
13699        protected Object filterToLabel(PackageParser.ServiceIntentInfo filter) {
13700            return filter.service;
13701        }
13702
13703        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
13704            PackageParser.Service service = (PackageParser.Service)label;
13705            out.print(prefix); out.print(
13706                    Integer.toHexString(System.identityHashCode(service)));
13707                    out.print(' ');
13708                    service.printComponentShortName(out);
13709            if (count > 1) {
13710                out.print(" ("); out.print(count); out.print(" filters)");
13711            }
13712            out.println();
13713        }
13714
13715//        List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) {
13716//            final Iterator<ResolveInfo> i = resolveInfoList.iterator();
13717//            final List<ResolveInfo> retList = Lists.newArrayList();
13718//            while (i.hasNext()) {
13719//                final ResolveInfo resolveInfo = (ResolveInfo) i;
13720//                if (isEnabledLP(resolveInfo.serviceInfo)) {
13721//                    retList.add(resolveInfo);
13722//                }
13723//            }
13724//            return retList;
13725//        }
13726
13727        // Keys are String (activity class name), values are Activity.
13728        private final ArrayMap<ComponentName, PackageParser.Service> mServices
13729                = new ArrayMap<ComponentName, PackageParser.Service>();
13730        private int mFlags;
13731    }
13732
13733    private final class ProviderIntentResolver
13734            extends IntentResolver<PackageParser.ProviderIntentInfo, ResolveInfo> {
13735        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
13736                boolean defaultOnly, int userId) {
13737            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
13738            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
13739        }
13740
13741        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
13742                int userId) {
13743            if (!sUserManager.exists(userId))
13744                return null;
13745            mFlags = flags;
13746            return super.queryIntent(intent, resolvedType,
13747                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0,
13748                    userId);
13749        }
13750
13751        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
13752                int flags, ArrayList<PackageParser.Provider> packageProviders, int userId) {
13753            if (!sUserManager.exists(userId))
13754                return null;
13755            if (packageProviders == null) {
13756                return null;
13757            }
13758            mFlags = flags;
13759            final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0;
13760            final int N = packageProviders.size();
13761            ArrayList<PackageParser.ProviderIntentInfo[]> listCut =
13762                    new ArrayList<PackageParser.ProviderIntentInfo[]>(N);
13763
13764            ArrayList<PackageParser.ProviderIntentInfo> intentFilters;
13765            for (int i = 0; i < N; ++i) {
13766                intentFilters = packageProviders.get(i).intents;
13767                if (intentFilters != null && intentFilters.size() > 0) {
13768                    PackageParser.ProviderIntentInfo[] array =
13769                            new PackageParser.ProviderIntentInfo[intentFilters.size()];
13770                    intentFilters.toArray(array);
13771                    listCut.add(array);
13772                }
13773            }
13774            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
13775        }
13776
13777        public final void addProvider(PackageParser.Provider p) {
13778            if (mProviders.containsKey(p.getComponentName())) {
13779                Slog.w(TAG, "Provider " + p.getComponentName() + " already defined; ignoring");
13780                return;
13781            }
13782
13783            mProviders.put(p.getComponentName(), p);
13784            if (DEBUG_SHOW_INFO) {
13785                Log.v(TAG, "  "
13786                        + (p.info.nonLocalizedLabel != null
13787                                ? p.info.nonLocalizedLabel : p.info.name) + ":");
13788                Log.v(TAG, "    Class=" + p.info.name);
13789            }
13790            final int NI = p.intents.size();
13791            int j;
13792            for (j = 0; j < NI; j++) {
13793                PackageParser.ProviderIntentInfo intent = p.intents.get(j);
13794                if (DEBUG_SHOW_INFO) {
13795                    Log.v(TAG, "    IntentFilter:");
13796                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
13797                }
13798                if (!intent.debugCheck()) {
13799                    Log.w(TAG, "==> For Provider " + p.info.name);
13800                }
13801                addFilter(intent);
13802            }
13803        }
13804
13805        public final void removeProvider(PackageParser.Provider p) {
13806            mProviders.remove(p.getComponentName());
13807            if (DEBUG_SHOW_INFO) {
13808                Log.v(TAG, "  " + (p.info.nonLocalizedLabel != null
13809                        ? p.info.nonLocalizedLabel : p.info.name) + ":");
13810                Log.v(TAG, "    Class=" + p.info.name);
13811            }
13812            final int NI = p.intents.size();
13813            int j;
13814            for (j = 0; j < NI; j++) {
13815                PackageParser.ProviderIntentInfo intent = p.intents.get(j);
13816                if (DEBUG_SHOW_INFO) {
13817                    Log.v(TAG, "    IntentFilter:");
13818                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
13819                }
13820                removeFilter(intent);
13821            }
13822        }
13823
13824        @Override
13825        protected boolean allowFilterResult(
13826                PackageParser.ProviderIntentInfo filter, List<ResolveInfo> dest) {
13827            ProviderInfo filterPi = filter.provider.info;
13828            for (int i = dest.size() - 1; i >= 0; i--) {
13829                ProviderInfo destPi = dest.get(i).providerInfo;
13830                if (destPi.name == filterPi.name
13831                        && destPi.packageName == filterPi.packageName) {
13832                    return false;
13833                }
13834            }
13835            return true;
13836        }
13837
13838        @Override
13839        protected PackageParser.ProviderIntentInfo[] newArray(int size) {
13840            return new PackageParser.ProviderIntentInfo[size];
13841        }
13842
13843        @Override
13844        protected boolean isFilterStopped(PackageParser.ProviderIntentInfo filter, int userId) {
13845            if (!sUserManager.exists(userId))
13846                return true;
13847            PackageParser.Package p = filter.provider.owner;
13848            if (p != null) {
13849                PackageSetting ps = (PackageSetting) p.mExtras;
13850                if (ps != null) {
13851                    // System apps are never considered stopped for purposes of
13852                    // filtering, because there may be no way for the user to
13853                    // actually re-launch them.
13854                    return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0
13855                            && ps.getStopped(userId);
13856                }
13857            }
13858            return false;
13859        }
13860
13861        @Override
13862        protected boolean isPackageForFilter(String packageName,
13863                PackageParser.ProviderIntentInfo info) {
13864            return packageName.equals(info.provider.owner.packageName);
13865        }
13866
13867        @Override
13868        protected ResolveInfo newResult(PackageParser.ProviderIntentInfo filter,
13869                int match, int userId) {
13870            if (!sUserManager.exists(userId))
13871                return null;
13872            final PackageParser.ProviderIntentInfo info = filter;
13873            if (!mSettings.isEnabledAndMatchLPr(info.provider.info, mFlags, userId)) {
13874                return null;
13875            }
13876            final PackageParser.Provider provider = info.provider;
13877            PackageSetting ps = (PackageSetting) provider.owner.mExtras;
13878            if (ps == null) {
13879                return null;
13880            }
13881            final PackageUserState userState = ps.readUserState(userId);
13882            final boolean matchVisibleToInstantApp =
13883                    (mFlags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
13884            final boolean isInstantApp = (mFlags & PackageManager.MATCH_INSTANT) != 0;
13885            // throw out filters that aren't visible to instant applications
13886            if (matchVisibleToInstantApp
13887                    && !(info.isVisibleToInstantApp() || userState.instantApp)) {
13888                return null;
13889            }
13890            // throw out instant application filters if we're not explicitly requesting them
13891            if (!isInstantApp && userState.instantApp) {
13892                return null;
13893            }
13894            // throw out instant application filters if updates are available; will trigger
13895            // instant application resolution
13896            if (userState.instantApp && ps.isUpdateAvailable()) {
13897                return null;
13898            }
13899            ProviderInfo pi = PackageParser.generateProviderInfo(provider, mFlags,
13900                    userState, userId);
13901            if (pi == null) {
13902                return null;
13903            }
13904            final ResolveInfo res = new ResolveInfo();
13905            res.providerInfo = pi;
13906            if ((mFlags & PackageManager.GET_RESOLVED_FILTER) != 0) {
13907                res.filter = filter;
13908            }
13909            res.priority = info.getPriority();
13910            res.preferredOrder = provider.owner.mPreferredOrder;
13911            res.match = match;
13912            res.isDefault = info.hasDefault;
13913            res.labelRes = info.labelRes;
13914            res.nonLocalizedLabel = info.nonLocalizedLabel;
13915            res.icon = info.icon;
13916            res.system = res.providerInfo.applicationInfo.isSystemApp();
13917            return res;
13918        }
13919
13920        @Override
13921        protected void sortResults(List<ResolveInfo> results) {
13922            Collections.sort(results, mResolvePrioritySorter);
13923        }
13924
13925        @Override
13926        protected void dumpFilter(PrintWriter out, String prefix,
13927                PackageParser.ProviderIntentInfo filter) {
13928            out.print(prefix);
13929            out.print(
13930                    Integer.toHexString(System.identityHashCode(filter.provider)));
13931            out.print(' ');
13932            filter.provider.printComponentShortName(out);
13933            out.print(" filter ");
13934            out.println(Integer.toHexString(System.identityHashCode(filter)));
13935        }
13936
13937        @Override
13938        protected Object filterToLabel(PackageParser.ProviderIntentInfo filter) {
13939            return filter.provider;
13940        }
13941
13942        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
13943            PackageParser.Provider provider = (PackageParser.Provider)label;
13944            out.print(prefix); out.print(
13945                    Integer.toHexString(System.identityHashCode(provider)));
13946                    out.print(' ');
13947                    provider.printComponentShortName(out);
13948            if (count > 1) {
13949                out.print(" ("); out.print(count); out.print(" filters)");
13950            }
13951            out.println();
13952        }
13953
13954        private final ArrayMap<ComponentName, PackageParser.Provider> mProviders
13955                = new ArrayMap<ComponentName, PackageParser.Provider>();
13956        private int mFlags;
13957    }
13958
13959    static final class EphemeralIntentResolver
13960            extends IntentResolver<AuxiliaryResolveInfo, AuxiliaryResolveInfo> {
13961        /**
13962         * The result that has the highest defined order. Ordering applies on a
13963         * per-package basis. Mapping is from package name to Pair of order and
13964         * EphemeralResolveInfo.
13965         * <p>
13966         * NOTE: This is implemented as a field variable for convenience and efficiency.
13967         * By having a field variable, we're able to track filter ordering as soon as
13968         * a non-zero order is defined. Otherwise, multiple loops across the result set
13969         * would be needed to apply ordering. If the intent resolver becomes re-entrant,
13970         * this needs to be contained entirely within {@link #filterResults}.
13971         */
13972        final ArrayMap<String, Pair<Integer, InstantAppResolveInfo>> mOrderResult = new ArrayMap<>();
13973
13974        @Override
13975        protected AuxiliaryResolveInfo[] newArray(int size) {
13976            return new AuxiliaryResolveInfo[size];
13977        }
13978
13979        @Override
13980        protected boolean isPackageForFilter(String packageName, AuxiliaryResolveInfo responseObj) {
13981            return true;
13982        }
13983
13984        @Override
13985        protected AuxiliaryResolveInfo newResult(AuxiliaryResolveInfo responseObj, int match,
13986                int userId) {
13987            if (!sUserManager.exists(userId)) {
13988                return null;
13989            }
13990            final String packageName = responseObj.resolveInfo.getPackageName();
13991            final Integer order = responseObj.getOrder();
13992            final Pair<Integer, InstantAppResolveInfo> lastOrderResult =
13993                    mOrderResult.get(packageName);
13994            // ordering is enabled and this item's order isn't high enough
13995            if (lastOrderResult != null && lastOrderResult.first >= order) {
13996                return null;
13997            }
13998            final InstantAppResolveInfo res = responseObj.resolveInfo;
13999            if (order > 0) {
14000                // non-zero order, enable ordering
14001                mOrderResult.put(packageName, new Pair<>(order, res));
14002            }
14003            return responseObj;
14004        }
14005
14006        @Override
14007        protected void filterResults(List<AuxiliaryResolveInfo> results) {
14008            // only do work if ordering is enabled [most of the time it won't be]
14009            if (mOrderResult.size() == 0) {
14010                return;
14011            }
14012            int resultSize = results.size();
14013            for (int i = 0; i < resultSize; i++) {
14014                final InstantAppResolveInfo info = results.get(i).resolveInfo;
14015                final String packageName = info.getPackageName();
14016                final Pair<Integer, InstantAppResolveInfo> savedInfo = mOrderResult.get(packageName);
14017                if (savedInfo == null) {
14018                    // package doesn't having ordering
14019                    continue;
14020                }
14021                if (savedInfo.second == info) {
14022                    // circled back to the highest ordered item; remove from order list
14023                    mOrderResult.remove(savedInfo);
14024                    if (mOrderResult.size() == 0) {
14025                        // no more ordered items
14026                        break;
14027                    }
14028                    continue;
14029                }
14030                // item has a worse order, remove it from the result list
14031                results.remove(i);
14032                resultSize--;
14033                i--;
14034            }
14035        }
14036    }
14037
14038    private static final Comparator<ResolveInfo> mResolvePrioritySorter =
14039            new Comparator<ResolveInfo>() {
14040        public int compare(ResolveInfo r1, ResolveInfo r2) {
14041            int v1 = r1.priority;
14042            int v2 = r2.priority;
14043            //System.out.println("Comparing: q1=" + q1 + " q2=" + q2);
14044            if (v1 != v2) {
14045                return (v1 > v2) ? -1 : 1;
14046            }
14047            v1 = r1.preferredOrder;
14048            v2 = r2.preferredOrder;
14049            if (v1 != v2) {
14050                return (v1 > v2) ? -1 : 1;
14051            }
14052            if (r1.isDefault != r2.isDefault) {
14053                return r1.isDefault ? -1 : 1;
14054            }
14055            v1 = r1.match;
14056            v2 = r2.match;
14057            //System.out.println("Comparing: m1=" + m1 + " m2=" + m2);
14058            if (v1 != v2) {
14059                return (v1 > v2) ? -1 : 1;
14060            }
14061            if (r1.system != r2.system) {
14062                return r1.system ? -1 : 1;
14063            }
14064            if (r1.activityInfo != null) {
14065                return r1.activityInfo.packageName.compareTo(r2.activityInfo.packageName);
14066            }
14067            if (r1.serviceInfo != null) {
14068                return r1.serviceInfo.packageName.compareTo(r2.serviceInfo.packageName);
14069            }
14070            if (r1.providerInfo != null) {
14071                return r1.providerInfo.packageName.compareTo(r2.providerInfo.packageName);
14072            }
14073            return 0;
14074        }
14075    };
14076
14077    private static final Comparator<ProviderInfo> mProviderInitOrderSorter =
14078            new Comparator<ProviderInfo>() {
14079        public int compare(ProviderInfo p1, ProviderInfo p2) {
14080            final int v1 = p1.initOrder;
14081            final int v2 = p2.initOrder;
14082            return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0);
14083        }
14084    };
14085
14086    public void sendPackageBroadcast(final String action, final String pkg, final Bundle extras,
14087            final int flags, final String targetPkg, final IIntentReceiver finishedReceiver,
14088            final int[] userIds) {
14089        mHandler.post(new Runnable() {
14090            @Override
14091            public void run() {
14092                try {
14093                    final IActivityManager am = ActivityManager.getService();
14094                    if (am == null) return;
14095                    final int[] resolvedUserIds;
14096                    if (userIds == null) {
14097                        resolvedUserIds = am.getRunningUserIds();
14098                    } else {
14099                        resolvedUserIds = userIds;
14100                    }
14101                    for (int id : resolvedUserIds) {
14102                        final Intent intent = new Intent(action,
14103                                pkg != null ? Uri.fromParts(PACKAGE_SCHEME, pkg, null) : null);
14104                        if (extras != null) {
14105                            intent.putExtras(extras);
14106                        }
14107                        if (targetPkg != null) {
14108                            intent.setPackage(targetPkg);
14109                        }
14110                        // Modify the UID when posting to other users
14111                        int uid = intent.getIntExtra(Intent.EXTRA_UID, -1);
14112                        if (uid > 0 && UserHandle.getUserId(uid) != id) {
14113                            uid = UserHandle.getUid(id, UserHandle.getAppId(uid));
14114                            intent.putExtra(Intent.EXTRA_UID, uid);
14115                        }
14116                        intent.putExtra(Intent.EXTRA_USER_HANDLE, id);
14117                        intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT | flags);
14118                        if (DEBUG_BROADCASTS) {
14119                            RuntimeException here = new RuntimeException("here");
14120                            here.fillInStackTrace();
14121                            Slog.d(TAG, "Sending to user " + id + ": "
14122                                    + intent.toShortString(false, true, false, false)
14123                                    + " " + intent.getExtras(), here);
14124                        }
14125                        am.broadcastIntent(null, intent, null, finishedReceiver,
14126                                0, null, null, null, android.app.AppOpsManager.OP_NONE,
14127                                null, finishedReceiver != null, false, id);
14128                    }
14129                } catch (RemoteException ex) {
14130                }
14131            }
14132        });
14133    }
14134
14135    /**
14136     * Check if the external storage media is available. This is true if there
14137     * is a mounted external storage medium or if the external storage is
14138     * emulated.
14139     */
14140    private boolean isExternalMediaAvailable() {
14141        return mMediaMounted || Environment.isExternalStorageEmulated();
14142    }
14143
14144    @Override
14145    public PackageCleanItem nextPackageToClean(PackageCleanItem lastPackage) {
14146        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
14147            return null;
14148        }
14149        // writer
14150        synchronized (mPackages) {
14151            if (!isExternalMediaAvailable()) {
14152                // If the external storage is no longer mounted at this point,
14153                // the caller may not have been able to delete all of this
14154                // packages files and can not delete any more.  Bail.
14155                return null;
14156            }
14157            final ArrayList<PackageCleanItem> pkgs = mSettings.mPackagesToBeCleaned;
14158            if (lastPackage != null) {
14159                pkgs.remove(lastPackage);
14160            }
14161            if (pkgs.size() > 0) {
14162                return pkgs.get(0);
14163            }
14164        }
14165        return null;
14166    }
14167
14168    void schedulePackageCleaning(String packageName, int userId, boolean andCode) {
14169        final Message msg = mHandler.obtainMessage(START_CLEANING_PACKAGE,
14170                userId, andCode ? 1 : 0, packageName);
14171        if (mSystemReady) {
14172            msg.sendToTarget();
14173        } else {
14174            if (mPostSystemReadyMessages == null) {
14175                mPostSystemReadyMessages = new ArrayList<>();
14176            }
14177            mPostSystemReadyMessages.add(msg);
14178        }
14179    }
14180
14181    void startCleaningPackages() {
14182        // reader
14183        if (!isExternalMediaAvailable()) {
14184            return;
14185        }
14186        synchronized (mPackages) {
14187            if (mSettings.mPackagesToBeCleaned.isEmpty()) {
14188                return;
14189            }
14190        }
14191        Intent intent = new Intent(PackageManager.ACTION_CLEAN_EXTERNAL_STORAGE);
14192        intent.setComponent(DEFAULT_CONTAINER_COMPONENT);
14193        IActivityManager am = ActivityManager.getService();
14194        if (am != null) {
14195            int dcsUid = -1;
14196            synchronized (mPackages) {
14197                if (!mDefaultContainerWhitelisted) {
14198                    mDefaultContainerWhitelisted = true;
14199                    PackageSetting ps = mSettings.mPackages.get(DEFAULT_CONTAINER_PACKAGE);
14200                    dcsUid = UserHandle.getUid(UserHandle.USER_SYSTEM, ps.appId);
14201                }
14202            }
14203            try {
14204                if (dcsUid > 0) {
14205                    am.backgroundWhitelistUid(dcsUid);
14206                }
14207                am.startService(null, intent, null, false, mContext.getOpPackageName(),
14208                        UserHandle.USER_SYSTEM);
14209            } catch (RemoteException e) {
14210            }
14211        }
14212    }
14213
14214    @Override
14215    public void installPackageAsUser(String originPath, IPackageInstallObserver2 observer,
14216            int installFlags, String installerPackageName, int userId) {
14217        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, null);
14218
14219        final int callingUid = Binder.getCallingUid();
14220        enforceCrossUserPermission(callingUid, userId,
14221                true /* requireFullPermission */, true /* checkShell */, "installPackageAsUser");
14222
14223        if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) {
14224            try {
14225                if (observer != null) {
14226                    observer.onPackageInstalled("", INSTALL_FAILED_USER_RESTRICTED, null, null);
14227                }
14228            } catch (RemoteException re) {
14229            }
14230            return;
14231        }
14232
14233        if ((callingUid == Process.SHELL_UID) || (callingUid == Process.ROOT_UID)) {
14234            installFlags |= PackageManager.INSTALL_FROM_ADB;
14235
14236        } else {
14237            // Caller holds INSTALL_PACKAGES permission, so we're less strict
14238            // about installerPackageName.
14239
14240            installFlags &= ~PackageManager.INSTALL_FROM_ADB;
14241            installFlags &= ~PackageManager.INSTALL_ALL_USERS;
14242        }
14243
14244        UserHandle user;
14245        if ((installFlags & PackageManager.INSTALL_ALL_USERS) != 0) {
14246            user = UserHandle.ALL;
14247        } else {
14248            user = new UserHandle(userId);
14249        }
14250
14251        // Only system components can circumvent runtime permissions when installing.
14252        if ((installFlags & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0
14253                && mContext.checkCallingOrSelfPermission(Manifest.permission
14254                .INSTALL_GRANT_RUNTIME_PERMISSIONS) == PackageManager.PERMISSION_DENIED) {
14255            throw new SecurityException("You need the "
14256                    + "android.permission.INSTALL_GRANT_RUNTIME_PERMISSIONS permission "
14257                    + "to use the PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS flag");
14258        }
14259
14260        if ((installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0
14261                || (installFlags & PackageManager.INSTALL_EXTERNAL) != 0) {
14262            throw new IllegalArgumentException(
14263                    "New installs into ASEC containers no longer supported");
14264        }
14265
14266        final File originFile = new File(originPath);
14267        final OriginInfo origin = OriginInfo.fromUntrustedFile(originFile);
14268
14269        final Message msg = mHandler.obtainMessage(INIT_COPY);
14270        final VerificationInfo verificationInfo = new VerificationInfo(
14271                null /*originatingUri*/, null /*referrer*/, -1 /*originatingUid*/, callingUid);
14272        final InstallParams params = new InstallParams(origin, null /*moveInfo*/, observer,
14273                installFlags, installerPackageName, null /*volumeUuid*/, verificationInfo, user,
14274                null /*packageAbiOverride*/, null /*grantedPermissions*/,
14275                null /*certificates*/, PackageManager.INSTALL_REASON_UNKNOWN);
14276        params.setTraceMethod("installAsUser").setTraceCookie(System.identityHashCode(params));
14277        msg.obj = params;
14278
14279        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "installAsUser",
14280                System.identityHashCode(msg.obj));
14281        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
14282                System.identityHashCode(msg.obj));
14283
14284        mHandler.sendMessage(msg);
14285    }
14286
14287
14288    /**
14289     * Ensure that the install reason matches what we know about the package installer (e.g. whether
14290     * it is acting on behalf on an enterprise or the user).
14291     *
14292     * Note that the ordering of the conditionals in this method is important. The checks we perform
14293     * are as follows, in this order:
14294     *
14295     * 1) If the install is being performed by a system app, we can trust the app to have set the
14296     *    install reason correctly. Thus, we pass through the install reason unchanged, no matter
14297     *    what it is.
14298     * 2) If the install is being performed by a device or profile owner app, the install reason
14299     *    should be enterprise policy. However, we cannot be sure that the device or profile owner
14300     *    set the install reason correctly. If the app targets an older SDK version where install
14301     *    reasons did not exist yet, or if the app author simply forgot, the install reason may be
14302     *    unset or wrong. Thus, we force the install reason to be enterprise policy.
14303     * 3) In all other cases, the install is being performed by a regular app that is neither part
14304     *    of the system nor a device or profile owner. We have no reason to believe that this app is
14305     *    acting on behalf of the enterprise admin. Thus, we check whether the install reason was
14306     *    set to enterprise policy and if so, change it to unknown instead.
14307     */
14308    private int fixUpInstallReason(String installerPackageName, int installerUid,
14309            int installReason) {
14310        if (checkUidPermission(android.Manifest.permission.INSTALL_PACKAGES, installerUid)
14311                == PERMISSION_GRANTED) {
14312            // If the install is being performed by a system app, we trust that app to have set the
14313            // install reason correctly.
14314            return installReason;
14315        }
14316
14317        final IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface(
14318            ServiceManager.getService(Context.DEVICE_POLICY_SERVICE));
14319        if (dpm != null) {
14320            ComponentName owner = null;
14321            try {
14322                owner = dpm.getDeviceOwnerComponent(true /* callingUserOnly */);
14323                if (owner == null) {
14324                    owner = dpm.getProfileOwner(UserHandle.getUserId(installerUid));
14325                }
14326            } catch (RemoteException e) {
14327            }
14328            if (owner != null && owner.getPackageName().equals(installerPackageName)) {
14329                // If the install is being performed by a device or profile owner, the install
14330                // reason should be enterprise policy.
14331                return PackageManager.INSTALL_REASON_POLICY;
14332            }
14333        }
14334
14335        if (installReason == PackageManager.INSTALL_REASON_POLICY) {
14336            // If the install is being performed by a regular app (i.e. neither system app nor
14337            // device or profile owner), we have no reason to believe that the app is acting on
14338            // behalf of an enterprise. If the app set the install reason to enterprise policy,
14339            // change it to unknown instead.
14340            return PackageManager.INSTALL_REASON_UNKNOWN;
14341        }
14342
14343        // If the install is being performed by a regular app and the install reason was set to any
14344        // value but enterprise policy, leave the install reason unchanged.
14345        return installReason;
14346    }
14347
14348    void installStage(String packageName, File stagedDir, String stagedCid,
14349            IPackageInstallObserver2 observer, PackageInstaller.SessionParams sessionParams,
14350            String installerPackageName, int installerUid, UserHandle user,
14351            Certificate[][] certificates) {
14352        if (DEBUG_EPHEMERAL) {
14353            if ((sessionParams.installFlags & PackageManager.INSTALL_INSTANT_APP) != 0) {
14354                Slog.d(TAG, "Ephemeral install of " + packageName);
14355            }
14356        }
14357        final VerificationInfo verificationInfo = new VerificationInfo(
14358                sessionParams.originatingUri, sessionParams.referrerUri,
14359                sessionParams.originatingUid, installerUid);
14360
14361        final OriginInfo origin;
14362        if (stagedDir != null) {
14363            origin = OriginInfo.fromStagedFile(stagedDir);
14364        } else {
14365            origin = OriginInfo.fromStagedContainer(stagedCid);
14366        }
14367
14368        final Message msg = mHandler.obtainMessage(INIT_COPY);
14369        final int installReason = fixUpInstallReason(installerPackageName, installerUid,
14370                sessionParams.installReason);
14371        final InstallParams params = new InstallParams(origin, null, observer,
14372                sessionParams.installFlags, installerPackageName, sessionParams.volumeUuid,
14373                verificationInfo, user, sessionParams.abiOverride,
14374                sessionParams.grantedRuntimePermissions, certificates, installReason);
14375        params.setTraceMethod("installStage").setTraceCookie(System.identityHashCode(params));
14376        msg.obj = params;
14377
14378        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "installStage",
14379                System.identityHashCode(msg.obj));
14380        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
14381                System.identityHashCode(msg.obj));
14382
14383        mHandler.sendMessage(msg);
14384    }
14385
14386    private void sendPackageAddedForUser(String packageName, PackageSetting pkgSetting,
14387            int userId) {
14388        final boolean isSystem = isSystemApp(pkgSetting) || isUpdatedSystemApp(pkgSetting);
14389        sendPackageAddedForNewUsers(packageName, isSystem, pkgSetting.appId, userId);
14390
14391        // Send a session commit broadcast
14392        final PackageInstaller.SessionInfo info = new PackageInstaller.SessionInfo();
14393        info.installReason = pkgSetting.getInstallReason(userId);
14394        info.appPackageName = packageName;
14395        sendSessionCommitBroadcast(info, userId);
14396    }
14397
14398    public void sendPackageAddedForNewUsers(String packageName, boolean isSystem, int appId, int... userIds) {
14399        if (ArrayUtils.isEmpty(userIds)) {
14400            return;
14401        }
14402        Bundle extras = new Bundle(1);
14403        // Set to UID of the first user, EXTRA_UID is automatically updated in sendPackageBroadcast
14404        extras.putInt(Intent.EXTRA_UID, UserHandle.getUid(userIds[0], appId));
14405
14406        sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
14407                packageName, extras, 0, null, null, userIds);
14408        if (isSystem) {
14409            mHandler.post(() -> {
14410                        for (int userId : userIds) {
14411                            sendBootCompletedBroadcastToSystemApp(packageName, userId);
14412                        }
14413                    }
14414            );
14415        }
14416    }
14417
14418    /**
14419     * The just-installed/enabled app is bundled on the system, so presumed to be able to run
14420     * automatically without needing an explicit launch.
14421     * Send it a LOCKED_BOOT_COMPLETED/BOOT_COMPLETED if it would ordinarily have gotten ones.
14422     */
14423    private void sendBootCompletedBroadcastToSystemApp(String packageName, int userId) {
14424        // If user is not running, the app didn't miss any broadcast
14425        if (!mUserManagerInternal.isUserRunning(userId)) {
14426            return;
14427        }
14428        final IActivityManager am = ActivityManager.getService();
14429        try {
14430            // Deliver LOCKED_BOOT_COMPLETED first
14431            Intent lockedBcIntent = new Intent(Intent.ACTION_LOCKED_BOOT_COMPLETED)
14432                    .setPackage(packageName);
14433            final String[] requiredPermissions = {Manifest.permission.RECEIVE_BOOT_COMPLETED};
14434            am.broadcastIntent(null, lockedBcIntent, null, null, 0, null, null, requiredPermissions,
14435                    android.app.AppOpsManager.OP_NONE, null, false, false, userId);
14436
14437            // Deliver BOOT_COMPLETED only if user is unlocked
14438            if (mUserManagerInternal.isUserUnlockingOrUnlocked(userId)) {
14439                Intent bcIntent = new Intent(Intent.ACTION_BOOT_COMPLETED).setPackage(packageName);
14440                am.broadcastIntent(null, bcIntent, null, null, 0, null, null, requiredPermissions,
14441                        android.app.AppOpsManager.OP_NONE, null, false, false, userId);
14442            }
14443        } catch (RemoteException e) {
14444            throw e.rethrowFromSystemServer();
14445        }
14446    }
14447
14448    @Override
14449    public boolean setApplicationHiddenSettingAsUser(String packageName, boolean hidden,
14450            int userId) {
14451        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
14452        PackageSetting pkgSetting;
14453        final int callingUid = Binder.getCallingUid();
14454        enforceCrossUserPermission(callingUid, userId,
14455                true /* requireFullPermission */, true /* checkShell */,
14456                "setApplicationHiddenSetting for user " + userId);
14457
14458        if (hidden && isPackageDeviceAdmin(packageName, userId)) {
14459            Slog.w(TAG, "Not hiding package " + packageName + ": has active device admin");
14460            return false;
14461        }
14462
14463        long callingId = Binder.clearCallingIdentity();
14464        try {
14465            boolean sendAdded = false;
14466            boolean sendRemoved = false;
14467            // writer
14468            synchronized (mPackages) {
14469                pkgSetting = mSettings.mPackages.get(packageName);
14470                if (pkgSetting == null) {
14471                    return false;
14472                }
14473                if (filterAppAccessLPr(pkgSetting, callingUid, userId)) {
14474                    return false;
14475                }
14476                // Do not allow "android" is being disabled
14477                if ("android".equals(packageName)) {
14478                    Slog.w(TAG, "Cannot hide package: android");
14479                    return false;
14480                }
14481                // Cannot hide static shared libs as they are considered
14482                // a part of the using app (emulating static linking). Also
14483                // static libs are installed always on internal storage.
14484                PackageParser.Package pkg = mPackages.get(packageName);
14485                if (pkg != null && pkg.staticSharedLibName != null) {
14486                    Slog.w(TAG, "Cannot hide package: " + packageName
14487                            + " providing static shared library: "
14488                            + pkg.staticSharedLibName);
14489                    return false;
14490                }
14491                // Only allow protected packages to hide themselves.
14492                if (hidden && !UserHandle.isSameApp(callingUid, pkgSetting.appId)
14493                        && mProtectedPackages.isPackageStateProtected(userId, packageName)) {
14494                    Slog.w(TAG, "Not hiding protected package: " + packageName);
14495                    return false;
14496                }
14497
14498                if (pkgSetting.getHidden(userId) != hidden) {
14499                    pkgSetting.setHidden(hidden, userId);
14500                    mSettings.writePackageRestrictionsLPr(userId);
14501                    if (hidden) {
14502                        sendRemoved = true;
14503                    } else {
14504                        sendAdded = true;
14505                    }
14506                }
14507            }
14508            if (sendAdded) {
14509                sendPackageAddedForUser(packageName, pkgSetting, userId);
14510                return true;
14511            }
14512            if (sendRemoved) {
14513                killApplication(packageName, UserHandle.getUid(userId, pkgSetting.appId),
14514                        "hiding pkg");
14515                sendApplicationHiddenForUser(packageName, pkgSetting, userId);
14516                return true;
14517            }
14518        } finally {
14519            Binder.restoreCallingIdentity(callingId);
14520        }
14521        return false;
14522    }
14523
14524    private void sendApplicationHiddenForUser(String packageName, PackageSetting pkgSetting,
14525            int userId) {
14526        final PackageRemovedInfo info = new PackageRemovedInfo(this);
14527        info.removedPackage = packageName;
14528        info.installerPackageName = pkgSetting.installerPackageName;
14529        info.removedUsers = new int[] {userId};
14530        info.broadcastUsers = new int[] {userId};
14531        info.uid = UserHandle.getUid(userId, pkgSetting.appId);
14532        info.sendPackageRemovedBroadcasts(true /*killApp*/);
14533    }
14534
14535    private void sendPackagesSuspendedForUser(String[] pkgList, int userId, boolean suspended) {
14536        if (pkgList.length > 0) {
14537            Bundle extras = new Bundle(1);
14538            extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList);
14539
14540            sendPackageBroadcast(
14541                    suspended ? Intent.ACTION_PACKAGES_SUSPENDED
14542                            : Intent.ACTION_PACKAGES_UNSUSPENDED,
14543                    null, extras, Intent.FLAG_RECEIVER_REGISTERED_ONLY, null, null,
14544                    new int[] {userId});
14545        }
14546    }
14547
14548    /**
14549     * Returns true if application is not found or there was an error. Otherwise it returns
14550     * the hidden state of the package for the given user.
14551     */
14552    @Override
14553    public boolean getApplicationHiddenSettingAsUser(String packageName, int userId) {
14554        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
14555        final int callingUid = Binder.getCallingUid();
14556        enforceCrossUserPermission(callingUid, userId,
14557                true /* requireFullPermission */, false /* checkShell */,
14558                "getApplicationHidden for user " + userId);
14559        PackageSetting ps;
14560        long callingId = Binder.clearCallingIdentity();
14561        try {
14562            // writer
14563            synchronized (mPackages) {
14564                ps = mSettings.mPackages.get(packageName);
14565                if (ps == null) {
14566                    return true;
14567                }
14568                if (filterAppAccessLPr(ps, callingUid, userId)) {
14569                    return true;
14570                }
14571                return ps.getHidden(userId);
14572            }
14573        } finally {
14574            Binder.restoreCallingIdentity(callingId);
14575        }
14576    }
14577
14578    /**
14579     * @hide
14580     */
14581    @Override
14582    public int installExistingPackageAsUser(String packageName, int userId, int installFlags,
14583            int installReason) {
14584        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES,
14585                null);
14586        PackageSetting pkgSetting;
14587        final int callingUid = Binder.getCallingUid();
14588        enforceCrossUserPermission(callingUid, userId,
14589                true /* requireFullPermission */, true /* checkShell */,
14590                "installExistingPackage for user " + userId);
14591        if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) {
14592            return PackageManager.INSTALL_FAILED_USER_RESTRICTED;
14593        }
14594
14595        long callingId = Binder.clearCallingIdentity();
14596        try {
14597            boolean installed = false;
14598            final boolean instantApp =
14599                    (installFlags & PackageManager.INSTALL_INSTANT_APP) != 0;
14600            final boolean fullApp =
14601                    (installFlags & PackageManager.INSTALL_FULL_APP) != 0;
14602
14603            // writer
14604            synchronized (mPackages) {
14605                pkgSetting = mSettings.mPackages.get(packageName);
14606                if (pkgSetting == null) {
14607                    return PackageManager.INSTALL_FAILED_INVALID_URI;
14608                }
14609                if (!canViewInstantApps(callingUid, UserHandle.getUserId(callingUid))) {
14610                    // only allow the existing package to be used if it's installed as a full
14611                    // application for at least one user
14612                    boolean installAllowed = false;
14613                    for (int checkUserId : sUserManager.getUserIds()) {
14614                        installAllowed = !pkgSetting.getInstantApp(checkUserId);
14615                        if (installAllowed) {
14616                            break;
14617                        }
14618                    }
14619                    if (!installAllowed) {
14620                        return PackageManager.INSTALL_FAILED_INVALID_URI;
14621                    }
14622                }
14623                if (!pkgSetting.getInstalled(userId)) {
14624                    pkgSetting.setInstalled(true, userId);
14625                    pkgSetting.setHidden(false, userId);
14626                    pkgSetting.setInstallReason(installReason, userId);
14627                    mSettings.writePackageRestrictionsLPr(userId);
14628                    mSettings.writeKernelMappingLPr(pkgSetting);
14629                    installed = true;
14630                } else if (fullApp && pkgSetting.getInstantApp(userId)) {
14631                    // upgrade app from instant to full; we don't allow app downgrade
14632                    installed = true;
14633                }
14634                setInstantAppForUser(pkgSetting, userId, instantApp, fullApp);
14635            }
14636
14637            if (installed) {
14638                if (pkgSetting.pkg != null) {
14639                    synchronized (mInstallLock) {
14640                        // We don't need to freeze for a brand new install
14641                        prepareAppDataAfterInstallLIF(pkgSetting.pkg);
14642                    }
14643                }
14644                sendPackageAddedForUser(packageName, pkgSetting, userId);
14645                synchronized (mPackages) {
14646                    updateSequenceNumberLP(pkgSetting, new int[]{ userId });
14647                }
14648            }
14649        } finally {
14650            Binder.restoreCallingIdentity(callingId);
14651        }
14652
14653        return PackageManager.INSTALL_SUCCEEDED;
14654    }
14655
14656    void setInstantAppForUser(PackageSetting pkgSetting, int userId,
14657            boolean instantApp, boolean fullApp) {
14658        // no state specified; do nothing
14659        if (!instantApp && !fullApp) {
14660            return;
14661        }
14662        if (userId != UserHandle.USER_ALL) {
14663            if (instantApp && !pkgSetting.getInstantApp(userId)) {
14664                pkgSetting.setInstantApp(true /*instantApp*/, userId);
14665            } else if (fullApp && pkgSetting.getInstantApp(userId)) {
14666                pkgSetting.setInstantApp(false /*instantApp*/, userId);
14667            }
14668        } else {
14669            for (int currentUserId : sUserManager.getUserIds()) {
14670                if (instantApp && !pkgSetting.getInstantApp(currentUserId)) {
14671                    pkgSetting.setInstantApp(true /*instantApp*/, currentUserId);
14672                } else if (fullApp && pkgSetting.getInstantApp(currentUserId)) {
14673                    pkgSetting.setInstantApp(false /*instantApp*/, currentUserId);
14674                }
14675            }
14676        }
14677    }
14678
14679    boolean isUserRestricted(int userId, String restrictionKey) {
14680        Bundle restrictions = sUserManager.getUserRestrictions(userId);
14681        if (restrictions.getBoolean(restrictionKey, false)) {
14682            Log.w(TAG, "User is restricted: " + restrictionKey);
14683            return true;
14684        }
14685        return false;
14686    }
14687
14688    @Override
14689    public String[] setPackagesSuspendedAsUser(String[] packageNames, boolean suspended,
14690            int userId) {
14691        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
14692        final int callingUid = Binder.getCallingUid();
14693        enforceCrossUserPermission(callingUid, userId,
14694                true /* requireFullPermission */, true /* checkShell */,
14695                "setPackagesSuspended for user " + userId);
14696
14697        if (ArrayUtils.isEmpty(packageNames)) {
14698            return packageNames;
14699        }
14700
14701        // List of package names for whom the suspended state has changed.
14702        List<String> changedPackages = new ArrayList<>(packageNames.length);
14703        // List of package names for whom the suspended state is not set as requested in this
14704        // method.
14705        List<String> unactionedPackages = new ArrayList<>(packageNames.length);
14706        long callingId = Binder.clearCallingIdentity();
14707        try {
14708            for (int i = 0; i < packageNames.length; i++) {
14709                String packageName = packageNames[i];
14710                boolean changed = false;
14711                final int appId;
14712                synchronized (mPackages) {
14713                    final PackageSetting pkgSetting = mSettings.mPackages.get(packageName);
14714                    if (pkgSetting == null
14715                            || filterAppAccessLPr(pkgSetting, callingUid, userId)) {
14716                        Slog.w(TAG, "Could not find package setting for package \"" + packageName
14717                                + "\". Skipping suspending/un-suspending.");
14718                        unactionedPackages.add(packageName);
14719                        continue;
14720                    }
14721                    appId = pkgSetting.appId;
14722                    if (pkgSetting.getSuspended(userId) != suspended) {
14723                        if (!canSuspendPackageForUserLocked(packageName, userId)) {
14724                            unactionedPackages.add(packageName);
14725                            continue;
14726                        }
14727                        pkgSetting.setSuspended(suspended, userId);
14728                        mSettings.writePackageRestrictionsLPr(userId);
14729                        changed = true;
14730                        changedPackages.add(packageName);
14731                    }
14732                }
14733
14734                if (changed && suspended) {
14735                    killApplication(packageName, UserHandle.getUid(userId, appId),
14736                            "suspending package");
14737                }
14738            }
14739        } finally {
14740            Binder.restoreCallingIdentity(callingId);
14741        }
14742
14743        if (!changedPackages.isEmpty()) {
14744            sendPackagesSuspendedForUser(changedPackages.toArray(
14745                    new String[changedPackages.size()]), userId, suspended);
14746        }
14747
14748        return unactionedPackages.toArray(new String[unactionedPackages.size()]);
14749    }
14750
14751    @Override
14752    public boolean isPackageSuspendedForUser(String packageName, int userId) {
14753        final int callingUid = Binder.getCallingUid();
14754        enforceCrossUserPermission(callingUid, userId,
14755                true /* requireFullPermission */, false /* checkShell */,
14756                "isPackageSuspendedForUser for user " + userId);
14757        synchronized (mPackages) {
14758            final PackageSetting ps = mSettings.mPackages.get(packageName);
14759            if (ps == null || filterAppAccessLPr(ps, callingUid, userId)) {
14760                throw new IllegalArgumentException("Unknown target package: " + packageName);
14761            }
14762            return ps.getSuspended(userId);
14763        }
14764    }
14765
14766    private boolean canSuspendPackageForUserLocked(String packageName, int userId) {
14767        if (isPackageDeviceAdmin(packageName, userId)) {
14768            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
14769                    + "\": has an active device admin");
14770            return false;
14771        }
14772
14773        String activeLauncherPackageName = getActiveLauncherPackageName(userId);
14774        if (packageName.equals(activeLauncherPackageName)) {
14775            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
14776                    + "\": contains the active launcher");
14777            return false;
14778        }
14779
14780        if (packageName.equals(mRequiredInstallerPackage)) {
14781            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
14782                    + "\": required for package installation");
14783            return false;
14784        }
14785
14786        if (packageName.equals(mRequiredUninstallerPackage)) {
14787            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
14788                    + "\": required for package uninstallation");
14789            return false;
14790        }
14791
14792        if (packageName.equals(mRequiredVerifierPackage)) {
14793            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
14794                    + "\": required for package verification");
14795            return false;
14796        }
14797
14798        if (packageName.equals(getDefaultDialerPackageName(userId))) {
14799            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
14800                    + "\": is the default dialer");
14801            return false;
14802        }
14803
14804        if (mProtectedPackages.isPackageStateProtected(userId, packageName)) {
14805            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
14806                    + "\": protected package");
14807            return false;
14808        }
14809
14810        // Cannot suspend static shared libs as they are considered
14811        // a part of the using app (emulating static linking). Also
14812        // static libs are installed always on internal storage.
14813        PackageParser.Package pkg = mPackages.get(packageName);
14814        if (pkg != null && pkg.applicationInfo.isStaticSharedLibrary()) {
14815            Slog.w(TAG, "Cannot suspend package: " + packageName
14816                    + " providing static shared library: "
14817                    + pkg.staticSharedLibName);
14818            return false;
14819        }
14820
14821        return true;
14822    }
14823
14824    private String getActiveLauncherPackageName(int userId) {
14825        Intent intent = new Intent(Intent.ACTION_MAIN);
14826        intent.addCategory(Intent.CATEGORY_HOME);
14827        ResolveInfo resolveInfo = resolveIntent(
14828                intent,
14829                intent.resolveTypeIfNeeded(mContext.getContentResolver()),
14830                PackageManager.MATCH_DEFAULT_ONLY,
14831                userId);
14832
14833        return resolveInfo == null ? null : resolveInfo.activityInfo.packageName;
14834    }
14835
14836    private String getDefaultDialerPackageName(int userId) {
14837        synchronized (mPackages) {
14838            return mSettings.getDefaultDialerPackageNameLPw(userId);
14839        }
14840    }
14841
14842    @Override
14843    public void verifyPendingInstall(int id, int verificationCode) throws RemoteException {
14844        mContext.enforceCallingOrSelfPermission(
14845                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
14846                "Only package verification agents can verify applications");
14847
14848        final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED);
14849        final PackageVerificationResponse response = new PackageVerificationResponse(
14850                verificationCode, Binder.getCallingUid());
14851        msg.arg1 = id;
14852        msg.obj = response;
14853        mHandler.sendMessage(msg);
14854    }
14855
14856    @Override
14857    public void extendVerificationTimeout(int id, int verificationCodeAtTimeout,
14858            long millisecondsToDelay) {
14859        mContext.enforceCallingOrSelfPermission(
14860                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
14861                "Only package verification agents can extend verification timeouts");
14862
14863        final PackageVerificationState state = mPendingVerification.get(id);
14864        final PackageVerificationResponse response = new PackageVerificationResponse(
14865                verificationCodeAtTimeout, Binder.getCallingUid());
14866
14867        if (millisecondsToDelay > PackageManager.MAXIMUM_VERIFICATION_TIMEOUT) {
14868            millisecondsToDelay = PackageManager.MAXIMUM_VERIFICATION_TIMEOUT;
14869        }
14870        if (millisecondsToDelay < 0) {
14871            millisecondsToDelay = 0;
14872        }
14873        if ((verificationCodeAtTimeout != PackageManager.VERIFICATION_ALLOW)
14874                && (verificationCodeAtTimeout != PackageManager.VERIFICATION_REJECT)) {
14875            verificationCodeAtTimeout = PackageManager.VERIFICATION_REJECT;
14876        }
14877
14878        if ((state != null) && !state.timeoutExtended()) {
14879            state.extendTimeout();
14880
14881            final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED);
14882            msg.arg1 = id;
14883            msg.obj = response;
14884            mHandler.sendMessageDelayed(msg, millisecondsToDelay);
14885        }
14886    }
14887
14888    private void broadcastPackageVerified(int verificationId, Uri packageUri,
14889            int verificationCode, UserHandle user) {
14890        final Intent intent = new Intent(Intent.ACTION_PACKAGE_VERIFIED);
14891        intent.setDataAndType(packageUri, PACKAGE_MIME_TYPE);
14892        intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
14893        intent.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId);
14894        intent.putExtra(PackageManager.EXTRA_VERIFICATION_RESULT, verificationCode);
14895
14896        mContext.sendBroadcastAsUser(intent, user,
14897                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT);
14898    }
14899
14900    private ComponentName matchComponentForVerifier(String packageName,
14901            List<ResolveInfo> receivers) {
14902        ActivityInfo targetReceiver = null;
14903
14904        final int NR = receivers.size();
14905        for (int i = 0; i < NR; i++) {
14906            final ResolveInfo info = receivers.get(i);
14907            if (info.activityInfo == null) {
14908                continue;
14909            }
14910
14911            if (packageName.equals(info.activityInfo.packageName)) {
14912                targetReceiver = info.activityInfo;
14913                break;
14914            }
14915        }
14916
14917        if (targetReceiver == null) {
14918            return null;
14919        }
14920
14921        return new ComponentName(targetReceiver.packageName, targetReceiver.name);
14922    }
14923
14924    private List<ComponentName> matchVerifiers(PackageInfoLite pkgInfo,
14925            List<ResolveInfo> receivers, final PackageVerificationState verificationState) {
14926        if (pkgInfo.verifiers.length == 0) {
14927            return null;
14928        }
14929
14930        final int N = pkgInfo.verifiers.length;
14931        final List<ComponentName> sufficientVerifiers = new ArrayList<ComponentName>(N + 1);
14932        for (int i = 0; i < N; i++) {
14933            final VerifierInfo verifierInfo = pkgInfo.verifiers[i];
14934
14935            final ComponentName comp = matchComponentForVerifier(verifierInfo.packageName,
14936                    receivers);
14937            if (comp == null) {
14938                continue;
14939            }
14940
14941            final int verifierUid = getUidForVerifier(verifierInfo);
14942            if (verifierUid == -1) {
14943                continue;
14944            }
14945
14946            if (DEBUG_VERIFY) {
14947                Slog.d(TAG, "Added sufficient verifier " + verifierInfo.packageName
14948                        + " with the correct signature");
14949            }
14950            sufficientVerifiers.add(comp);
14951            verificationState.addSufficientVerifier(verifierUid);
14952        }
14953
14954        return sufficientVerifiers;
14955    }
14956
14957    private int getUidForVerifier(VerifierInfo verifierInfo) {
14958        synchronized (mPackages) {
14959            final PackageParser.Package pkg = mPackages.get(verifierInfo.packageName);
14960            if (pkg == null) {
14961                return -1;
14962            } else if (pkg.mSignatures.length != 1) {
14963                Slog.i(TAG, "Verifier package " + verifierInfo.packageName
14964                        + " has more than one signature; ignoring");
14965                return -1;
14966            }
14967
14968            /*
14969             * If the public key of the package's signature does not match
14970             * our expected public key, then this is a different package and
14971             * we should skip.
14972             */
14973
14974            final byte[] expectedPublicKey;
14975            try {
14976                final Signature verifierSig = pkg.mSignatures[0];
14977                final PublicKey publicKey = verifierSig.getPublicKey();
14978                expectedPublicKey = publicKey.getEncoded();
14979            } catch (CertificateException e) {
14980                return -1;
14981            }
14982
14983            final byte[] actualPublicKey = verifierInfo.publicKey.getEncoded();
14984
14985            if (!Arrays.equals(actualPublicKey, expectedPublicKey)) {
14986                Slog.i(TAG, "Verifier package " + verifierInfo.packageName
14987                        + " does not have the expected public key; ignoring");
14988                return -1;
14989            }
14990
14991            return pkg.applicationInfo.uid;
14992        }
14993    }
14994
14995    @Override
14996    public void finishPackageInstall(int token, boolean didLaunch) {
14997        enforceSystemOrRoot("Only the system is allowed to finish installs");
14998
14999        if (DEBUG_INSTALL) {
15000            Slog.v(TAG, "BM finishing package install for " + token);
15001        }
15002        Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "restore", token);
15003
15004        final Message msg = mHandler.obtainMessage(POST_INSTALL, token, didLaunch ? 1 : 0);
15005        mHandler.sendMessage(msg);
15006    }
15007
15008    /**
15009     * Get the verification agent timeout.  Used for both the APK verifier and the
15010     * intent filter verifier.
15011     *
15012     * @return verification timeout in milliseconds
15013     */
15014    private long getVerificationTimeout() {
15015        return android.provider.Settings.Global.getLong(mContext.getContentResolver(),
15016                android.provider.Settings.Global.PACKAGE_VERIFIER_TIMEOUT,
15017                DEFAULT_VERIFICATION_TIMEOUT);
15018    }
15019
15020    /**
15021     * Get the default verification agent response code.
15022     *
15023     * @return default verification response code
15024     */
15025    private int getDefaultVerificationResponse(UserHandle user) {
15026        if (sUserManager.hasUserRestriction(UserManager.ENSURE_VERIFY_APPS, user.getIdentifier())) {
15027            return PackageManager.VERIFICATION_REJECT;
15028        }
15029        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
15030                android.provider.Settings.Global.PACKAGE_VERIFIER_DEFAULT_RESPONSE,
15031                DEFAULT_VERIFICATION_RESPONSE);
15032    }
15033
15034    /**
15035     * Check whether or not package verification has been enabled.
15036     *
15037     * @return true if verification should be performed
15038     */
15039    private boolean isVerificationEnabled(int userId, int installFlags, int installerUid) {
15040        if (!DEFAULT_VERIFY_ENABLE) {
15041            return false;
15042        }
15043
15044        boolean ensureVerifyAppsEnabled = isUserRestricted(userId, UserManager.ENSURE_VERIFY_APPS);
15045
15046        // Check if installing from ADB
15047        if ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0) {
15048            // Do not run verification in a test harness environment
15049            if (ActivityManager.isRunningInTestHarness()) {
15050                return false;
15051            }
15052            if (ensureVerifyAppsEnabled) {
15053                return true;
15054            }
15055            // Check if the developer does not want package verification for ADB installs
15056            if (android.provider.Settings.Global.getInt(mContext.getContentResolver(),
15057                    android.provider.Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB, 1) == 0) {
15058                return false;
15059            }
15060        } else {
15061            // only when not installed from ADB, skip verification for instant apps when
15062            // the installer and verifier are the same.
15063            if ((installFlags & PackageManager.INSTALL_INSTANT_APP) != 0) {
15064                if (mInstantAppInstallerActivity != null
15065                        && mInstantAppInstallerActivity.packageName.equals(
15066                                mRequiredVerifierPackage)) {
15067                    try {
15068                        mContext.getSystemService(AppOpsManager.class)
15069                                .checkPackage(installerUid, mRequiredVerifierPackage);
15070                        if (DEBUG_VERIFY) {
15071                            Slog.i(TAG, "disable verification for instant app");
15072                        }
15073                        return false;
15074                    } catch (SecurityException ignore) { }
15075                }
15076            }
15077        }
15078
15079        if (ensureVerifyAppsEnabled) {
15080            return true;
15081        }
15082
15083        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
15084                android.provider.Settings.Global.PACKAGE_VERIFIER_ENABLE, 1) == 1;
15085    }
15086
15087    @Override
15088    public void verifyIntentFilter(int id, int verificationCode, List<String> failedDomains)
15089            throws RemoteException {
15090        mContext.enforceCallingOrSelfPermission(
15091                Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT,
15092                "Only intentfilter verification agents can verify applications");
15093
15094        final Message msg = mHandler.obtainMessage(INTENT_FILTER_VERIFIED);
15095        final IntentFilterVerificationResponse response = new IntentFilterVerificationResponse(
15096                Binder.getCallingUid(), verificationCode, failedDomains);
15097        msg.arg1 = id;
15098        msg.obj = response;
15099        mHandler.sendMessage(msg);
15100    }
15101
15102    @Override
15103    public int getIntentVerificationStatus(String packageName, int userId) {
15104        final int callingUid = Binder.getCallingUid();
15105        if (getInstantAppPackageName(callingUid) != null) {
15106            return INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED;
15107        }
15108        synchronized (mPackages) {
15109            final PackageSetting ps = mSettings.mPackages.get(packageName);
15110            if (ps == null
15111                    || filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
15112                return INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED;
15113            }
15114            return mSettings.getIntentFilterVerificationStatusLPr(packageName, userId);
15115        }
15116    }
15117
15118    @Override
15119    public boolean updateIntentVerificationStatus(String packageName, int status, int userId) {
15120        mContext.enforceCallingOrSelfPermission(
15121                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
15122
15123        boolean result = false;
15124        synchronized (mPackages) {
15125            final PackageSetting ps = mSettings.mPackages.get(packageName);
15126            if (filterAppAccessLPr(ps, Binder.getCallingUid(), UserHandle.getCallingUserId())) {
15127                return false;
15128            }
15129            result = mSettings.updateIntentFilterVerificationStatusLPw(packageName, status, userId);
15130        }
15131        if (result) {
15132            scheduleWritePackageRestrictionsLocked(userId);
15133        }
15134        return result;
15135    }
15136
15137    @Override
15138    public @NonNull ParceledListSlice<IntentFilterVerificationInfo> getIntentFilterVerifications(
15139            String packageName) {
15140        final int callingUid = Binder.getCallingUid();
15141        if (getInstantAppPackageName(callingUid) != null) {
15142            return ParceledListSlice.emptyList();
15143        }
15144        synchronized (mPackages) {
15145            final PackageSetting ps = mSettings.mPackages.get(packageName);
15146            if (filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
15147                return ParceledListSlice.emptyList();
15148            }
15149            return new ParceledListSlice<>(mSettings.getIntentFilterVerificationsLPr(packageName));
15150        }
15151    }
15152
15153    @Override
15154    public @NonNull ParceledListSlice<IntentFilter> getAllIntentFilters(String packageName) {
15155        if (TextUtils.isEmpty(packageName)) {
15156            return ParceledListSlice.emptyList();
15157        }
15158        final int callingUid = Binder.getCallingUid();
15159        final int callingUserId = UserHandle.getUserId(callingUid);
15160        synchronized (mPackages) {
15161            PackageParser.Package pkg = mPackages.get(packageName);
15162            if (pkg == null || pkg.activities == null) {
15163                return ParceledListSlice.emptyList();
15164            }
15165            if (pkg.mExtras == null) {
15166                return ParceledListSlice.emptyList();
15167            }
15168            final PackageSetting ps = (PackageSetting) pkg.mExtras;
15169            if (filterAppAccessLPr(ps, callingUid, callingUserId)) {
15170                return ParceledListSlice.emptyList();
15171            }
15172            final int count = pkg.activities.size();
15173            ArrayList<IntentFilter> result = new ArrayList<>();
15174            for (int n=0; n<count; n++) {
15175                PackageParser.Activity activity = pkg.activities.get(n);
15176                if (activity.intents != null && activity.intents.size() > 0) {
15177                    result.addAll(activity.intents);
15178                }
15179            }
15180            return new ParceledListSlice<>(result);
15181        }
15182    }
15183
15184    @Override
15185    public boolean setDefaultBrowserPackageName(String packageName, int userId) {
15186        mContext.enforceCallingOrSelfPermission(
15187                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
15188
15189        synchronized (mPackages) {
15190            boolean result = mSettings.setDefaultBrowserPackageNameLPw(packageName, userId);
15191            if (packageName != null) {
15192                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultBrowserLPr(
15193                        packageName, userId);
15194            }
15195            return result;
15196        }
15197    }
15198
15199    @Override
15200    public String getDefaultBrowserPackageName(int userId) {
15201        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
15202            return null;
15203        }
15204        synchronized (mPackages) {
15205            return mSettings.getDefaultBrowserPackageNameLPw(userId);
15206        }
15207    }
15208
15209    /**
15210     * Get the "allow unknown sources" setting.
15211     *
15212     * @return the current "allow unknown sources" setting
15213     */
15214    private int getUnknownSourcesSettings() {
15215        return android.provider.Settings.Secure.getInt(mContext.getContentResolver(),
15216                android.provider.Settings.Secure.INSTALL_NON_MARKET_APPS,
15217                -1);
15218    }
15219
15220    @Override
15221    public void setInstallerPackageName(String targetPackage, String installerPackageName) {
15222        final int callingUid = Binder.getCallingUid();
15223        if (getInstantAppPackageName(callingUid) != null) {
15224            return;
15225        }
15226        // writer
15227        synchronized (mPackages) {
15228            PackageSetting targetPackageSetting = mSettings.mPackages.get(targetPackage);
15229            if (targetPackageSetting == null
15230                    || filterAppAccessLPr(
15231                            targetPackageSetting, callingUid, UserHandle.getUserId(callingUid))) {
15232                throw new IllegalArgumentException("Unknown target package: " + targetPackage);
15233            }
15234
15235            PackageSetting installerPackageSetting;
15236            if (installerPackageName != null) {
15237                installerPackageSetting = mSettings.mPackages.get(installerPackageName);
15238                if (installerPackageSetting == null) {
15239                    throw new IllegalArgumentException("Unknown installer package: "
15240                            + installerPackageName);
15241                }
15242            } else {
15243                installerPackageSetting = null;
15244            }
15245
15246            Signature[] callerSignature;
15247            Object obj = mSettings.getUserIdLPr(callingUid);
15248            if (obj != null) {
15249                if (obj instanceof SharedUserSetting) {
15250                    callerSignature = ((SharedUserSetting)obj).signatures.mSignatures;
15251                } else if (obj instanceof PackageSetting) {
15252                    callerSignature = ((PackageSetting)obj).signatures.mSignatures;
15253                } else {
15254                    throw new SecurityException("Bad object " + obj + " for uid " + callingUid);
15255                }
15256            } else {
15257                throw new SecurityException("Unknown calling UID: " + callingUid);
15258            }
15259
15260            // Verify: can't set installerPackageName to a package that is
15261            // not signed with the same cert as the caller.
15262            if (installerPackageSetting != null) {
15263                if (compareSignatures(callerSignature,
15264                        installerPackageSetting.signatures.mSignatures)
15265                        != PackageManager.SIGNATURE_MATCH) {
15266                    throw new SecurityException(
15267                            "Caller does not have same cert as new installer package "
15268                            + installerPackageName);
15269                }
15270            }
15271
15272            // Verify: if target already has an installer package, it must
15273            // be signed with the same cert as the caller.
15274            if (targetPackageSetting.installerPackageName != null) {
15275                PackageSetting setting = mSettings.mPackages.get(
15276                        targetPackageSetting.installerPackageName);
15277                // If the currently set package isn't valid, then it's always
15278                // okay to change it.
15279                if (setting != null) {
15280                    if (compareSignatures(callerSignature,
15281                            setting.signatures.mSignatures)
15282                            != PackageManager.SIGNATURE_MATCH) {
15283                        throw new SecurityException(
15284                                "Caller does not have same cert as old installer package "
15285                                + targetPackageSetting.installerPackageName);
15286                    }
15287                }
15288            }
15289
15290            // Okay!
15291            targetPackageSetting.installerPackageName = installerPackageName;
15292            if (installerPackageName != null) {
15293                mSettings.mInstallerPackages.add(installerPackageName);
15294            }
15295            scheduleWriteSettingsLocked();
15296        }
15297    }
15298
15299    @Override
15300    public void setApplicationCategoryHint(String packageName, int categoryHint,
15301            String callerPackageName) {
15302        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
15303            throw new SecurityException("Instant applications don't have access to this method");
15304        }
15305        mContext.getSystemService(AppOpsManager.class).checkPackage(Binder.getCallingUid(),
15306                callerPackageName);
15307        synchronized (mPackages) {
15308            PackageSetting ps = mSettings.mPackages.get(packageName);
15309            if (ps == null) {
15310                throw new IllegalArgumentException("Unknown target package " + packageName);
15311            }
15312            if (filterAppAccessLPr(ps, Binder.getCallingUid(), UserHandle.getCallingUserId())) {
15313                throw new IllegalArgumentException("Unknown target package " + packageName);
15314            }
15315            if (!Objects.equals(callerPackageName, ps.installerPackageName)) {
15316                throw new IllegalArgumentException("Calling package " + callerPackageName
15317                        + " is not installer for " + packageName);
15318            }
15319
15320            if (ps.categoryHint != categoryHint) {
15321                ps.categoryHint = categoryHint;
15322                scheduleWriteSettingsLocked();
15323            }
15324        }
15325    }
15326
15327    private void processPendingInstall(final InstallArgs args, final int currentStatus) {
15328        // Queue up an async operation since the package installation may take a little while.
15329        mHandler.post(new Runnable() {
15330            public void run() {
15331                mHandler.removeCallbacks(this);
15332                 // Result object to be returned
15333                PackageInstalledInfo res = new PackageInstalledInfo();
15334                res.setReturnCode(currentStatus);
15335                res.uid = -1;
15336                res.pkg = null;
15337                res.removedInfo = null;
15338                if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
15339                    args.doPreInstall(res.returnCode);
15340                    synchronized (mInstallLock) {
15341                        installPackageTracedLI(args, res);
15342                    }
15343                    args.doPostInstall(res.returnCode, res.uid);
15344                }
15345
15346                // A restore should be performed at this point if (a) the install
15347                // succeeded, (b) the operation is not an update, and (c) the new
15348                // package has not opted out of backup participation.
15349                final boolean update = res.removedInfo != null
15350                        && res.removedInfo.removedPackage != null;
15351                final int flags = (res.pkg == null) ? 0 : res.pkg.applicationInfo.flags;
15352                boolean doRestore = !update
15353                        && ((flags & ApplicationInfo.FLAG_ALLOW_BACKUP) != 0);
15354
15355                // Set up the post-install work request bookkeeping.  This will be used
15356                // and cleaned up by the post-install event handling regardless of whether
15357                // there's a restore pass performed.  Token values are >= 1.
15358                int token;
15359                if (mNextInstallToken < 0) mNextInstallToken = 1;
15360                token = mNextInstallToken++;
15361
15362                PostInstallData data = new PostInstallData(args, res);
15363                mRunningInstalls.put(token, data);
15364                if (DEBUG_INSTALL) Log.v(TAG, "+ starting restore round-trip " + token);
15365
15366                if (res.returnCode == PackageManager.INSTALL_SUCCEEDED && doRestore) {
15367                    // Pass responsibility to the Backup Manager.  It will perform a
15368                    // restore if appropriate, then pass responsibility back to the
15369                    // Package Manager to run the post-install observer callbacks
15370                    // and broadcasts.
15371                    IBackupManager bm = IBackupManager.Stub.asInterface(
15372                            ServiceManager.getService(Context.BACKUP_SERVICE));
15373                    if (bm != null) {
15374                        if (DEBUG_INSTALL) Log.v(TAG, "token " + token
15375                                + " to BM for possible restore");
15376                        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "restore", token);
15377                        try {
15378                            // TODO: http://b/22388012
15379                            if (bm.isBackupServiceActive(UserHandle.USER_SYSTEM)) {
15380                                bm.restoreAtInstall(res.pkg.applicationInfo.packageName, token);
15381                            } else {
15382                                doRestore = false;
15383                            }
15384                        } catch (RemoteException e) {
15385                            // can't happen; the backup manager is local
15386                        } catch (Exception e) {
15387                            Slog.e(TAG, "Exception trying to enqueue restore", e);
15388                            doRestore = false;
15389                        }
15390                    } else {
15391                        Slog.e(TAG, "Backup Manager not found!");
15392                        doRestore = false;
15393                    }
15394                }
15395
15396                if (!doRestore) {
15397                    // No restore possible, or the Backup Manager was mysteriously not
15398                    // available -- just fire the post-install work request directly.
15399                    if (DEBUG_INSTALL) Log.v(TAG, "No restore - queue post-install for " + token);
15400
15401                    Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "postInstall", token);
15402
15403                    Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0);
15404                    mHandler.sendMessage(msg);
15405                }
15406            }
15407        });
15408    }
15409
15410    /**
15411     * Callback from PackageSettings whenever an app is first transitioned out of the
15412     * 'stopped' state.  Normally we just issue the broadcast, but we can't do that if
15413     * the app was "launched" for a restoreAtInstall operation.  Therefore we check
15414     * here whether the app is the target of an ongoing install, and only send the
15415     * broadcast immediately if it is not in that state.  If it *is* undergoing a restore,
15416     * the first-launch broadcast will be sent implicitly on that basis in POST_INSTALL
15417     * handling.
15418     */
15419    void notifyFirstLaunch(final String pkgName, final String installerPackage, final int userId) {
15420        // Serialize this with the rest of the install-process message chain.  In the
15421        // restore-at-install case, this Runnable will necessarily run before the
15422        // POST_INSTALL message is processed, so the contents of mRunningInstalls
15423        // are coherent.  In the non-restore case, the app has already completed install
15424        // and been launched through some other means, so it is not in a problematic
15425        // state for observers to see the FIRST_LAUNCH signal.
15426        mHandler.post(new Runnable() {
15427            @Override
15428            public void run() {
15429                for (int i = 0; i < mRunningInstalls.size(); i++) {
15430                    final PostInstallData data = mRunningInstalls.valueAt(i);
15431                    if (data.res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
15432                        continue;
15433                    }
15434                    if (pkgName.equals(data.res.pkg.applicationInfo.packageName)) {
15435                        // right package; but is it for the right user?
15436                        for (int uIndex = 0; uIndex < data.res.newUsers.length; uIndex++) {
15437                            if (userId == data.res.newUsers[uIndex]) {
15438                                if (DEBUG_BACKUP) {
15439                                    Slog.i(TAG, "Package " + pkgName
15440                                            + " being restored so deferring FIRST_LAUNCH");
15441                                }
15442                                return;
15443                            }
15444                        }
15445                    }
15446                }
15447                // didn't find it, so not being restored
15448                if (DEBUG_BACKUP) {
15449                    Slog.i(TAG, "Package " + pkgName + " sending normal FIRST_LAUNCH");
15450                }
15451                sendFirstLaunchBroadcast(pkgName, installerPackage, new int[] {userId});
15452            }
15453        });
15454    }
15455
15456    private void sendFirstLaunchBroadcast(String pkgName, String installerPkg, int[] userIds) {
15457        sendPackageBroadcast(Intent.ACTION_PACKAGE_FIRST_LAUNCH, pkgName, null, 0,
15458                installerPkg, null, userIds);
15459    }
15460
15461    private abstract class HandlerParams {
15462        private static final int MAX_RETRIES = 4;
15463
15464        /**
15465         * Number of times startCopy() has been attempted and had a non-fatal
15466         * error.
15467         */
15468        private int mRetries = 0;
15469
15470        /** User handle for the user requesting the information or installation. */
15471        private final UserHandle mUser;
15472        String traceMethod;
15473        int traceCookie;
15474
15475        HandlerParams(UserHandle user) {
15476            mUser = user;
15477        }
15478
15479        UserHandle getUser() {
15480            return mUser;
15481        }
15482
15483        HandlerParams setTraceMethod(String traceMethod) {
15484            this.traceMethod = traceMethod;
15485            return this;
15486        }
15487
15488        HandlerParams setTraceCookie(int traceCookie) {
15489            this.traceCookie = traceCookie;
15490            return this;
15491        }
15492
15493        final boolean startCopy() {
15494            boolean res;
15495            try {
15496                if (DEBUG_INSTALL) Slog.i(TAG, "startCopy " + mUser + ": " + this);
15497
15498                if (++mRetries > MAX_RETRIES) {
15499                    Slog.w(TAG, "Failed to invoke remote methods on default container service. Giving up");
15500                    mHandler.sendEmptyMessage(MCS_GIVE_UP);
15501                    handleServiceError();
15502                    return false;
15503                } else {
15504                    handleStartCopy();
15505                    res = true;
15506                }
15507            } catch (RemoteException e) {
15508                if (DEBUG_INSTALL) Slog.i(TAG, "Posting install MCS_RECONNECT");
15509                mHandler.sendEmptyMessage(MCS_RECONNECT);
15510                res = false;
15511            }
15512            handleReturnCode();
15513            return res;
15514        }
15515
15516        final void serviceError() {
15517            if (DEBUG_INSTALL) Slog.i(TAG, "serviceError");
15518            handleServiceError();
15519            handleReturnCode();
15520        }
15521
15522        abstract void handleStartCopy() throws RemoteException;
15523        abstract void handleServiceError();
15524        abstract void handleReturnCode();
15525    }
15526
15527    private static void clearDirectory(IMediaContainerService mcs, File[] paths) {
15528        for (File path : paths) {
15529            try {
15530                mcs.clearDirectory(path.getAbsolutePath());
15531            } catch (RemoteException e) {
15532            }
15533        }
15534    }
15535
15536    static class OriginInfo {
15537        /**
15538         * Location where install is coming from, before it has been
15539         * copied/renamed into place. This could be a single monolithic APK
15540         * file, or a cluster directory. This location may be untrusted.
15541         */
15542        final File file;
15543        final String cid;
15544
15545        /**
15546         * Flag indicating that {@link #file} or {@link #cid} has already been
15547         * staged, meaning downstream users don't need to defensively copy the
15548         * contents.
15549         */
15550        final boolean staged;
15551
15552        /**
15553         * Flag indicating that {@link #file} or {@link #cid} is an already
15554         * installed app that is being moved.
15555         */
15556        final boolean existing;
15557
15558        final String resolvedPath;
15559        final File resolvedFile;
15560
15561        static OriginInfo fromNothing() {
15562            return new OriginInfo(null, null, false, false);
15563        }
15564
15565        static OriginInfo fromUntrustedFile(File file) {
15566            return new OriginInfo(file, null, false, false);
15567        }
15568
15569        static OriginInfo fromExistingFile(File file) {
15570            return new OriginInfo(file, null, false, true);
15571        }
15572
15573        static OriginInfo fromStagedFile(File file) {
15574            return new OriginInfo(file, null, true, false);
15575        }
15576
15577        static OriginInfo fromStagedContainer(String cid) {
15578            return new OriginInfo(null, cid, true, false);
15579        }
15580
15581        private OriginInfo(File file, String cid, boolean staged, boolean existing) {
15582            this.file = file;
15583            this.cid = cid;
15584            this.staged = staged;
15585            this.existing = existing;
15586
15587            if (cid != null) {
15588                resolvedPath = PackageHelper.getSdDir(cid);
15589                resolvedFile = new File(resolvedPath);
15590            } else if (file != null) {
15591                resolvedPath = file.getAbsolutePath();
15592                resolvedFile = file;
15593            } else {
15594                resolvedPath = null;
15595                resolvedFile = null;
15596            }
15597        }
15598    }
15599
15600    static class MoveInfo {
15601        final int moveId;
15602        final String fromUuid;
15603        final String toUuid;
15604        final String packageName;
15605        final String dataAppName;
15606        final int appId;
15607        final String seinfo;
15608        final int targetSdkVersion;
15609
15610        public MoveInfo(int moveId, String fromUuid, String toUuid, String packageName,
15611                String dataAppName, int appId, String seinfo, int targetSdkVersion) {
15612            this.moveId = moveId;
15613            this.fromUuid = fromUuid;
15614            this.toUuid = toUuid;
15615            this.packageName = packageName;
15616            this.dataAppName = dataAppName;
15617            this.appId = appId;
15618            this.seinfo = seinfo;
15619            this.targetSdkVersion = targetSdkVersion;
15620        }
15621    }
15622
15623    static class VerificationInfo {
15624        /** A constant used to indicate that a uid value is not present. */
15625        public static final int NO_UID = -1;
15626
15627        /** URI referencing where the package was downloaded from. */
15628        final Uri originatingUri;
15629
15630        /** HTTP referrer URI associated with the originatingURI. */
15631        final Uri referrer;
15632
15633        /** UID of the application that the install request originated from. */
15634        final int originatingUid;
15635
15636        /** UID of application requesting the install */
15637        final int installerUid;
15638
15639        VerificationInfo(Uri originatingUri, Uri referrer, int originatingUid, int installerUid) {
15640            this.originatingUri = originatingUri;
15641            this.referrer = referrer;
15642            this.originatingUid = originatingUid;
15643            this.installerUid = installerUid;
15644        }
15645    }
15646
15647    class InstallParams extends HandlerParams {
15648        final OriginInfo origin;
15649        final MoveInfo move;
15650        final IPackageInstallObserver2 observer;
15651        int installFlags;
15652        final String installerPackageName;
15653        final String volumeUuid;
15654        private InstallArgs mArgs;
15655        private int mRet;
15656        final String packageAbiOverride;
15657        final String[] grantedRuntimePermissions;
15658        final VerificationInfo verificationInfo;
15659        final Certificate[][] certificates;
15660        final int installReason;
15661
15662        InstallParams(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer,
15663                int installFlags, String installerPackageName, String volumeUuid,
15664                VerificationInfo verificationInfo, UserHandle user, String packageAbiOverride,
15665                String[] grantedPermissions, Certificate[][] certificates, int installReason) {
15666            super(user);
15667            this.origin = origin;
15668            this.move = move;
15669            this.observer = observer;
15670            this.installFlags = installFlags;
15671            this.installerPackageName = installerPackageName;
15672            this.volumeUuid = volumeUuid;
15673            this.verificationInfo = verificationInfo;
15674            this.packageAbiOverride = packageAbiOverride;
15675            this.grantedRuntimePermissions = grantedPermissions;
15676            this.certificates = certificates;
15677            this.installReason = installReason;
15678        }
15679
15680        @Override
15681        public String toString() {
15682            return "InstallParams{" + Integer.toHexString(System.identityHashCode(this))
15683                    + " file=" + origin.file + " cid=" + origin.cid + "}";
15684        }
15685
15686        private int installLocationPolicy(PackageInfoLite pkgLite) {
15687            String packageName = pkgLite.packageName;
15688            int installLocation = pkgLite.installLocation;
15689            boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
15690            // reader
15691            synchronized (mPackages) {
15692                // Currently installed package which the new package is attempting to replace or
15693                // null if no such package is installed.
15694                PackageParser.Package installedPkg = mPackages.get(packageName);
15695                // Package which currently owns the data which the new package will own if installed.
15696                // If an app is unstalled while keeping data (e.g., adb uninstall -k), installedPkg
15697                // will be null whereas dataOwnerPkg will contain information about the package
15698                // which was uninstalled while keeping its data.
15699                PackageParser.Package dataOwnerPkg = installedPkg;
15700                if (dataOwnerPkg  == null) {
15701                    PackageSetting ps = mSettings.mPackages.get(packageName);
15702                    if (ps != null) {
15703                        dataOwnerPkg = ps.pkg;
15704                    }
15705                }
15706
15707                if (dataOwnerPkg != null) {
15708                    // If installed, the package will get access to data left on the device by its
15709                    // predecessor. As a security measure, this is permited only if this is not a
15710                    // version downgrade or if the predecessor package is marked as debuggable and
15711                    // a downgrade is explicitly requested.
15712                    //
15713                    // On debuggable platform builds, downgrades are permitted even for
15714                    // non-debuggable packages to make testing easier. Debuggable platform builds do
15715                    // not offer security guarantees and thus it's OK to disable some security
15716                    // mechanisms to make debugging/testing easier on those builds. However, even on
15717                    // debuggable builds downgrades of packages are permitted only if requested via
15718                    // installFlags. This is because we aim to keep the behavior of debuggable
15719                    // platform builds as close as possible to the behavior of non-debuggable
15720                    // platform builds.
15721                    final boolean downgradeRequested =
15722                            (installFlags & PackageManager.INSTALL_ALLOW_DOWNGRADE) != 0;
15723                    final boolean packageDebuggable =
15724                                (dataOwnerPkg.applicationInfo.flags
15725                                        & ApplicationInfo.FLAG_DEBUGGABLE) != 0;
15726                    final boolean downgradePermitted =
15727                            (downgradeRequested) && ((Build.IS_DEBUGGABLE) || (packageDebuggable));
15728                    if (!downgradePermitted) {
15729                        try {
15730                            checkDowngrade(dataOwnerPkg, pkgLite);
15731                        } catch (PackageManagerException e) {
15732                            Slog.w(TAG, "Downgrade detected: " + e.getMessage());
15733                            return PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE;
15734                        }
15735                    }
15736                }
15737
15738                if (installedPkg != null) {
15739                    if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
15740                        // Check for updated system application.
15741                        if ((installedPkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
15742                            if (onSd) {
15743                                Slog.w(TAG, "Cannot install update to system app on sdcard");
15744                                return PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION;
15745                            }
15746                            return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
15747                        } else {
15748                            if (onSd) {
15749                                // Install flag overrides everything.
15750                                return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
15751                            }
15752                            // If current upgrade specifies particular preference
15753                            if (installLocation == PackageInfo.INSTALL_LOCATION_INTERNAL_ONLY) {
15754                                // Application explicitly specified internal.
15755                                return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
15756                            } else if (installLocation == PackageInfo.INSTALL_LOCATION_PREFER_EXTERNAL) {
15757                                // App explictly prefers external. Let policy decide
15758                            } else {
15759                                // Prefer previous location
15760                                if (isExternal(installedPkg)) {
15761                                    return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
15762                                }
15763                                return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
15764                            }
15765                        }
15766                    } else {
15767                        // Invalid install. Return error code
15768                        return PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS;
15769                    }
15770                }
15771            }
15772            // All the special cases have been taken care of.
15773            // Return result based on recommended install location.
15774            if (onSd) {
15775                return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
15776            }
15777            return pkgLite.recommendedInstallLocation;
15778        }
15779
15780        /*
15781         * Invoke remote method to get package information and install
15782         * location values. Override install location based on default
15783         * policy if needed and then create install arguments based
15784         * on the install location.
15785         */
15786        public void handleStartCopy() throws RemoteException {
15787            int ret = PackageManager.INSTALL_SUCCEEDED;
15788
15789            // If we're already staged, we've firmly committed to an install location
15790            if (origin.staged) {
15791                if (origin.file != null) {
15792                    installFlags |= PackageManager.INSTALL_INTERNAL;
15793                    installFlags &= ~PackageManager.INSTALL_EXTERNAL;
15794                } else if (origin.cid != null) {
15795                    installFlags |= PackageManager.INSTALL_EXTERNAL;
15796                    installFlags &= ~PackageManager.INSTALL_INTERNAL;
15797                } else {
15798                    throw new IllegalStateException("Invalid stage location");
15799                }
15800            }
15801
15802            final boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
15803            final boolean onInt = (installFlags & PackageManager.INSTALL_INTERNAL) != 0;
15804            final boolean ephemeral = (installFlags & PackageManager.INSTALL_INSTANT_APP) != 0;
15805            PackageInfoLite pkgLite = null;
15806
15807            if (onInt && onSd) {
15808                // Check if both bits are set.
15809                Slog.w(TAG, "Conflicting flags specified for installing on both internal and external");
15810                ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
15811            } else if (onSd && ephemeral) {
15812                Slog.w(TAG,  "Conflicting flags specified for installing ephemeral on external");
15813                ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
15814            } else {
15815                pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, installFlags,
15816                        packageAbiOverride);
15817
15818                if (DEBUG_EPHEMERAL && ephemeral) {
15819                    Slog.v(TAG, "pkgLite for install: " + pkgLite);
15820                }
15821
15822                /*
15823                 * If we have too little free space, try to free cache
15824                 * before giving up.
15825                 */
15826                if (!origin.staged && pkgLite.recommendedInstallLocation
15827                        == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) {
15828                    // TODO: focus freeing disk space on the target device
15829                    final StorageManager storage = StorageManager.from(mContext);
15830                    final long lowThreshold = storage.getStorageLowBytes(
15831                            Environment.getDataDirectory());
15832
15833                    final long sizeBytes = mContainerService.calculateInstalledSize(
15834                            origin.resolvedPath, isForwardLocked(), packageAbiOverride);
15835
15836                    try {
15837                        mInstaller.freeCache(null, sizeBytes + lowThreshold, 0, 0);
15838                        pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath,
15839                                installFlags, packageAbiOverride);
15840                    } catch (InstallerException e) {
15841                        Slog.w(TAG, "Failed to free cache", e);
15842                    }
15843
15844                    /*
15845                     * The cache free must have deleted the file we
15846                     * downloaded to install.
15847                     *
15848                     * TODO: fix the "freeCache" call to not delete
15849                     *       the file we care about.
15850                     */
15851                    if (pkgLite.recommendedInstallLocation
15852                            == PackageHelper.RECOMMEND_FAILED_INVALID_URI) {
15853                        pkgLite.recommendedInstallLocation
15854                            = PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE;
15855                    }
15856                }
15857            }
15858
15859            if (ret == PackageManager.INSTALL_SUCCEEDED) {
15860                int loc = pkgLite.recommendedInstallLocation;
15861                if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION) {
15862                    ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
15863                } else if (loc == PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS) {
15864                    ret = PackageManager.INSTALL_FAILED_ALREADY_EXISTS;
15865                } else if (loc == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) {
15866                    ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
15867                } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_APK) {
15868                    ret = PackageManager.INSTALL_FAILED_INVALID_APK;
15869                } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_URI) {
15870                    ret = PackageManager.INSTALL_FAILED_INVALID_URI;
15871                } else if (loc == PackageHelper.RECOMMEND_MEDIA_UNAVAILABLE) {
15872                    ret = PackageManager.INSTALL_FAILED_MEDIA_UNAVAILABLE;
15873                } else {
15874                    // Override with defaults if needed.
15875                    loc = installLocationPolicy(pkgLite);
15876                    if (loc == PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE) {
15877                        ret = PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE;
15878                    } else if (!onSd && !onInt) {
15879                        // Override install location with flags
15880                        if (loc == PackageHelper.RECOMMEND_INSTALL_EXTERNAL) {
15881                            // Set the flag to install on external media.
15882                            installFlags |= PackageManager.INSTALL_EXTERNAL;
15883                            installFlags &= ~PackageManager.INSTALL_INTERNAL;
15884                        } else if (loc == PackageHelper.RECOMMEND_INSTALL_EPHEMERAL) {
15885                            if (DEBUG_EPHEMERAL) {
15886                                Slog.v(TAG, "...setting INSTALL_EPHEMERAL install flag");
15887                            }
15888                            installFlags |= PackageManager.INSTALL_INSTANT_APP;
15889                            installFlags &= ~(PackageManager.INSTALL_EXTERNAL
15890                                    |PackageManager.INSTALL_INTERNAL);
15891                        } else {
15892                            // Make sure the flag for installing on external
15893                            // media is unset
15894                            installFlags |= PackageManager.INSTALL_INTERNAL;
15895                            installFlags &= ~PackageManager.INSTALL_EXTERNAL;
15896                        }
15897                    }
15898                }
15899            }
15900
15901            final InstallArgs args = createInstallArgs(this);
15902            mArgs = args;
15903
15904            if (ret == PackageManager.INSTALL_SUCCEEDED) {
15905                // TODO: http://b/22976637
15906                // Apps installed for "all" users use the device owner to verify the app
15907                UserHandle verifierUser = getUser();
15908                if (verifierUser == UserHandle.ALL) {
15909                    verifierUser = UserHandle.SYSTEM;
15910                }
15911
15912                /*
15913                 * Determine if we have any installed package verifiers. If we
15914                 * do, then we'll defer to them to verify the packages.
15915                 */
15916                final int requiredUid = mRequiredVerifierPackage == null ? -1
15917                        : getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING,
15918                                verifierUser.getIdentifier());
15919                final int installerUid =
15920                        verificationInfo == null ? -1 : verificationInfo.installerUid;
15921                if (!origin.existing && requiredUid != -1
15922                        && isVerificationEnabled(
15923                                verifierUser.getIdentifier(), installFlags, installerUid)) {
15924                    final Intent verification = new Intent(
15925                            Intent.ACTION_PACKAGE_NEEDS_VERIFICATION);
15926                    verification.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
15927                    verification.setDataAndType(Uri.fromFile(new File(origin.resolvedPath)),
15928                            PACKAGE_MIME_TYPE);
15929                    verification.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
15930
15931                    // Query all live verifiers based on current user state
15932                    final List<ResolveInfo> receivers = queryIntentReceiversInternal(verification,
15933                            PACKAGE_MIME_TYPE, 0, verifierUser.getIdentifier());
15934
15935                    if (DEBUG_VERIFY) {
15936                        Slog.d(TAG, "Found " + receivers.size() + " verifiers for intent "
15937                                + verification.toString() + " with " + pkgLite.verifiers.length
15938                                + " optional verifiers");
15939                    }
15940
15941                    final int verificationId = mPendingVerificationToken++;
15942
15943                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId);
15944
15945                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_PACKAGE,
15946                            installerPackageName);
15947
15948                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALL_FLAGS,
15949                            installFlags);
15950
15951                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_PACKAGE_NAME,
15952                            pkgLite.packageName);
15953
15954                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_VERSION_CODE,
15955                            pkgLite.versionCode);
15956
15957                    if (verificationInfo != null) {
15958                        if (verificationInfo.originatingUri != null) {
15959                            verification.putExtra(Intent.EXTRA_ORIGINATING_URI,
15960                                    verificationInfo.originatingUri);
15961                        }
15962                        if (verificationInfo.referrer != null) {
15963                            verification.putExtra(Intent.EXTRA_REFERRER,
15964                                    verificationInfo.referrer);
15965                        }
15966                        if (verificationInfo.originatingUid >= 0) {
15967                            verification.putExtra(Intent.EXTRA_ORIGINATING_UID,
15968                                    verificationInfo.originatingUid);
15969                        }
15970                        if (verificationInfo.installerUid >= 0) {
15971                            verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_UID,
15972                                    verificationInfo.installerUid);
15973                        }
15974                    }
15975
15976                    final PackageVerificationState verificationState = new PackageVerificationState(
15977                            requiredUid, args);
15978
15979                    mPendingVerification.append(verificationId, verificationState);
15980
15981                    final List<ComponentName> sufficientVerifiers = matchVerifiers(pkgLite,
15982                            receivers, verificationState);
15983
15984                    DeviceIdleController.LocalService idleController = getDeviceIdleController();
15985                    final long idleDuration = getVerificationTimeout();
15986
15987                    /*
15988                     * If any sufficient verifiers were listed in the package
15989                     * manifest, attempt to ask them.
15990                     */
15991                    if (sufficientVerifiers != null) {
15992                        final int N = sufficientVerifiers.size();
15993                        if (N == 0) {
15994                            Slog.i(TAG, "Additional verifiers required, but none installed.");
15995                            ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
15996                        } else {
15997                            for (int i = 0; i < N; i++) {
15998                                final ComponentName verifierComponent = sufficientVerifiers.get(i);
15999                                idleController.addPowerSaveTempWhitelistApp(Process.myUid(),
16000                                        verifierComponent.getPackageName(), idleDuration,
16001                                        verifierUser.getIdentifier(), false, "package verifier");
16002
16003                                final Intent sufficientIntent = new Intent(verification);
16004                                sufficientIntent.setComponent(verifierComponent);
16005                                mContext.sendBroadcastAsUser(sufficientIntent, verifierUser);
16006                            }
16007                        }
16008                    }
16009
16010                    final ComponentName requiredVerifierComponent = matchComponentForVerifier(
16011                            mRequiredVerifierPackage, receivers);
16012                    if (ret == PackageManager.INSTALL_SUCCEEDED
16013                            && mRequiredVerifierPackage != null) {
16014                        Trace.asyncTraceBegin(
16015                                TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId);
16016                        /*
16017                         * Send the intent to the required verification agent,
16018                         * but only start the verification timeout after the
16019                         * target BroadcastReceivers have run.
16020                         */
16021                        verification.setComponent(requiredVerifierComponent);
16022                        idleController.addPowerSaveTempWhitelistApp(Process.myUid(),
16023                                mRequiredVerifierPackage, idleDuration,
16024                                verifierUser.getIdentifier(), false, "package verifier");
16025                        mContext.sendOrderedBroadcastAsUser(verification, verifierUser,
16026                                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
16027                                new BroadcastReceiver() {
16028                                    @Override
16029                                    public void onReceive(Context context, Intent intent) {
16030                                        final Message msg = mHandler
16031                                                .obtainMessage(CHECK_PENDING_VERIFICATION);
16032                                        msg.arg1 = verificationId;
16033                                        mHandler.sendMessageDelayed(msg, getVerificationTimeout());
16034                                    }
16035                                }, null, 0, null, null);
16036
16037                        /*
16038                         * We don't want the copy to proceed until verification
16039                         * succeeds, so null out this field.
16040                         */
16041                        mArgs = null;
16042                    }
16043                } else {
16044                    /*
16045                     * No package verification is enabled, so immediately start
16046                     * the remote call to initiate copy using temporary file.
16047                     */
16048                    ret = args.copyApk(mContainerService, true);
16049                }
16050            }
16051
16052            mRet = ret;
16053        }
16054
16055        @Override
16056        void handleReturnCode() {
16057            // If mArgs is null, then MCS couldn't be reached. When it
16058            // reconnects, it will try again to install. At that point, this
16059            // will succeed.
16060            if (mArgs != null) {
16061                processPendingInstall(mArgs, mRet);
16062            }
16063        }
16064
16065        @Override
16066        void handleServiceError() {
16067            mArgs = createInstallArgs(this);
16068            mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
16069        }
16070
16071        public boolean isForwardLocked() {
16072            return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
16073        }
16074    }
16075
16076    /**
16077     * Used during creation of InstallArgs
16078     *
16079     * @param installFlags package installation flags
16080     * @return true if should be installed on external storage
16081     */
16082    private static boolean installOnExternalAsec(int installFlags) {
16083        if ((installFlags & PackageManager.INSTALL_INTERNAL) != 0) {
16084            return false;
16085        }
16086        if ((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) {
16087            return true;
16088        }
16089        return false;
16090    }
16091
16092    /**
16093     * Used during creation of InstallArgs
16094     *
16095     * @param installFlags package installation flags
16096     * @return true if should be installed as forward locked
16097     */
16098    private static boolean installForwardLocked(int installFlags) {
16099        return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
16100    }
16101
16102    private InstallArgs createInstallArgs(InstallParams params) {
16103        if (params.move != null) {
16104            return new MoveInstallArgs(params);
16105        } else if (installOnExternalAsec(params.installFlags) || params.isForwardLocked()) {
16106            return new AsecInstallArgs(params);
16107        } else {
16108            return new FileInstallArgs(params);
16109        }
16110    }
16111
16112    /**
16113     * Create args that describe an existing installed package. Typically used
16114     * when cleaning up old installs, or used as a move source.
16115     */
16116    private InstallArgs createInstallArgsForExisting(int installFlags, String codePath,
16117            String resourcePath, String[] instructionSets) {
16118        final boolean isInAsec;
16119        if (installOnExternalAsec(installFlags)) {
16120            /* Apps on SD card are always in ASEC containers. */
16121            isInAsec = true;
16122        } else if (installForwardLocked(installFlags)
16123                && !codePath.startsWith(mDrmAppPrivateInstallDir.getAbsolutePath())) {
16124            /*
16125             * Forward-locked apps are only in ASEC containers if they're the
16126             * new style
16127             */
16128            isInAsec = true;
16129        } else {
16130            isInAsec = false;
16131        }
16132
16133        if (isInAsec) {
16134            return new AsecInstallArgs(codePath, instructionSets,
16135                    installOnExternalAsec(installFlags), installForwardLocked(installFlags));
16136        } else {
16137            return new FileInstallArgs(codePath, resourcePath, instructionSets);
16138        }
16139    }
16140
16141    static abstract class InstallArgs {
16142        /** @see InstallParams#origin */
16143        final OriginInfo origin;
16144        /** @see InstallParams#move */
16145        final MoveInfo move;
16146
16147        final IPackageInstallObserver2 observer;
16148        // Always refers to PackageManager flags only
16149        final int installFlags;
16150        final String installerPackageName;
16151        final String volumeUuid;
16152        final UserHandle user;
16153        final String abiOverride;
16154        final String[] installGrantPermissions;
16155        /** If non-null, drop an async trace when the install completes */
16156        final String traceMethod;
16157        final int traceCookie;
16158        final Certificate[][] certificates;
16159        final int installReason;
16160
16161        // The list of instruction sets supported by this app. This is currently
16162        // only used during the rmdex() phase to clean up resources. We can get rid of this
16163        // if we move dex files under the common app path.
16164        /* nullable */ String[] instructionSets;
16165
16166        InstallArgs(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer,
16167                int installFlags, String installerPackageName, String volumeUuid,
16168                UserHandle user, String[] instructionSets,
16169                String abiOverride, String[] installGrantPermissions,
16170                String traceMethod, int traceCookie, Certificate[][] certificates,
16171                int installReason) {
16172            this.origin = origin;
16173            this.move = move;
16174            this.installFlags = installFlags;
16175            this.observer = observer;
16176            this.installerPackageName = installerPackageName;
16177            this.volumeUuid = volumeUuid;
16178            this.user = user;
16179            this.instructionSets = instructionSets;
16180            this.abiOverride = abiOverride;
16181            this.installGrantPermissions = installGrantPermissions;
16182            this.traceMethod = traceMethod;
16183            this.traceCookie = traceCookie;
16184            this.certificates = certificates;
16185            this.installReason = installReason;
16186        }
16187
16188        abstract int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException;
16189        abstract int doPreInstall(int status);
16190
16191        /**
16192         * Rename package into final resting place. All paths on the given
16193         * scanned package should be updated to reflect the rename.
16194         */
16195        abstract boolean doRename(int status, PackageParser.Package pkg, String oldCodePath);
16196        abstract int doPostInstall(int status, int uid);
16197
16198        /** @see PackageSettingBase#codePathString */
16199        abstract String getCodePath();
16200        /** @see PackageSettingBase#resourcePathString */
16201        abstract String getResourcePath();
16202
16203        // Need installer lock especially for dex file removal.
16204        abstract void cleanUpResourcesLI();
16205        abstract boolean doPostDeleteLI(boolean delete);
16206
16207        /**
16208         * Called before the source arguments are copied. This is used mostly
16209         * for MoveParams when it needs to read the source file to put it in the
16210         * destination.
16211         */
16212        int doPreCopy() {
16213            return PackageManager.INSTALL_SUCCEEDED;
16214        }
16215
16216        /**
16217         * Called after the source arguments are copied. This is used mostly for
16218         * MoveParams when it needs to read the source file to put it in the
16219         * destination.
16220         */
16221        int doPostCopy(int uid) {
16222            return PackageManager.INSTALL_SUCCEEDED;
16223        }
16224
16225        protected boolean isFwdLocked() {
16226            return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
16227        }
16228
16229        protected boolean isExternalAsec() {
16230            return (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
16231        }
16232
16233        protected boolean isEphemeral() {
16234            return (installFlags & PackageManager.INSTALL_INSTANT_APP) != 0;
16235        }
16236
16237        UserHandle getUser() {
16238            return user;
16239        }
16240    }
16241
16242    void removeDexFiles(List<String> allCodePaths, String[] instructionSets) {
16243        if (!allCodePaths.isEmpty()) {
16244            if (instructionSets == null) {
16245                throw new IllegalStateException("instructionSet == null");
16246            }
16247            String[] dexCodeInstructionSets = getDexCodeInstructionSets(instructionSets);
16248            for (String codePath : allCodePaths) {
16249                for (String dexCodeInstructionSet : dexCodeInstructionSets) {
16250                    try {
16251                        mInstaller.rmdex(codePath, dexCodeInstructionSet);
16252                    } catch (InstallerException ignored) {
16253                    }
16254                }
16255            }
16256        }
16257    }
16258
16259    /**
16260     * Logic to handle installation of non-ASEC applications, including copying
16261     * and renaming logic.
16262     */
16263    class FileInstallArgs extends InstallArgs {
16264        private File codeFile;
16265        private File resourceFile;
16266
16267        // Example topology:
16268        // /data/app/com.example/base.apk
16269        // /data/app/com.example/split_foo.apk
16270        // /data/app/com.example/lib/arm/libfoo.so
16271        // /data/app/com.example/lib/arm64/libfoo.so
16272        // /data/app/com.example/dalvik/arm/base.apk@classes.dex
16273
16274        /** New install */
16275        FileInstallArgs(InstallParams params) {
16276            super(params.origin, params.move, params.observer, params.installFlags,
16277                    params.installerPackageName, params.volumeUuid,
16278                    params.getUser(), null /*instructionSets*/, params.packageAbiOverride,
16279                    params.grantedRuntimePermissions,
16280                    params.traceMethod, params.traceCookie, params.certificates,
16281                    params.installReason);
16282            if (isFwdLocked()) {
16283                throw new IllegalArgumentException("Forward locking only supported in ASEC");
16284            }
16285        }
16286
16287        /** Existing install */
16288        FileInstallArgs(String codePath, String resourcePath, String[] instructionSets) {
16289            super(OriginInfo.fromNothing(), null, null, 0, null, null, null, instructionSets,
16290                    null, null, null, 0, null /*certificates*/,
16291                    PackageManager.INSTALL_REASON_UNKNOWN);
16292            this.codeFile = (codePath != null) ? new File(codePath) : null;
16293            this.resourceFile = (resourcePath != null) ? new File(resourcePath) : null;
16294        }
16295
16296        int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
16297            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyApk");
16298            try {
16299                return doCopyApk(imcs, temp);
16300            } finally {
16301                Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
16302            }
16303        }
16304
16305        private int doCopyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
16306            if (origin.staged) {
16307                if (DEBUG_INSTALL) Slog.d(TAG, origin.file + " already staged; skipping copy");
16308                codeFile = origin.file;
16309                resourceFile = origin.file;
16310                return PackageManager.INSTALL_SUCCEEDED;
16311            }
16312
16313            try {
16314                final boolean isEphemeral = (installFlags & PackageManager.INSTALL_INSTANT_APP) != 0;
16315                final File tempDir =
16316                        mInstallerService.allocateStageDirLegacy(volumeUuid, isEphemeral);
16317                codeFile = tempDir;
16318                resourceFile = tempDir;
16319            } catch (IOException e) {
16320                Slog.w(TAG, "Failed to create copy file: " + e);
16321                return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
16322            }
16323
16324            final IParcelFileDescriptorFactory target = new IParcelFileDescriptorFactory.Stub() {
16325                @Override
16326                public ParcelFileDescriptor open(String name, int mode) throws RemoteException {
16327                    if (!FileUtils.isValidExtFilename(name)) {
16328                        throw new IllegalArgumentException("Invalid filename: " + name);
16329                    }
16330                    try {
16331                        final File file = new File(codeFile, name);
16332                        final FileDescriptor fd = Os.open(file.getAbsolutePath(),
16333                                O_RDWR | O_CREAT, 0644);
16334                        Os.chmod(file.getAbsolutePath(), 0644);
16335                        return new ParcelFileDescriptor(fd);
16336                    } catch (ErrnoException e) {
16337                        throw new RemoteException("Failed to open: " + e.getMessage());
16338                    }
16339                }
16340            };
16341
16342            int ret = PackageManager.INSTALL_SUCCEEDED;
16343            ret = imcs.copyPackage(origin.file.getAbsolutePath(), target);
16344            if (ret != PackageManager.INSTALL_SUCCEEDED) {
16345                Slog.e(TAG, "Failed to copy package");
16346                return ret;
16347            }
16348
16349            final File libraryRoot = new File(codeFile, LIB_DIR_NAME);
16350            NativeLibraryHelper.Handle handle = null;
16351            try {
16352                handle = NativeLibraryHelper.Handle.create(codeFile);
16353                ret = NativeLibraryHelper.copyNativeBinariesWithOverride(handle, libraryRoot,
16354                        abiOverride);
16355            } catch (IOException e) {
16356                Slog.e(TAG, "Copying native libraries failed", e);
16357                ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
16358            } finally {
16359                IoUtils.closeQuietly(handle);
16360            }
16361
16362            return ret;
16363        }
16364
16365        int doPreInstall(int status) {
16366            if (status != PackageManager.INSTALL_SUCCEEDED) {
16367                cleanUp();
16368            }
16369            return status;
16370        }
16371
16372        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
16373            if (status != PackageManager.INSTALL_SUCCEEDED) {
16374                cleanUp();
16375                return false;
16376            }
16377
16378            final File targetDir = codeFile.getParentFile();
16379            final File beforeCodeFile = codeFile;
16380            final File afterCodeFile = getNextCodePath(targetDir, pkg.packageName);
16381
16382            if (DEBUG_INSTALL) Slog.d(TAG, "Renaming " + beforeCodeFile + " to " + afterCodeFile);
16383            try {
16384                Os.rename(beforeCodeFile.getAbsolutePath(), afterCodeFile.getAbsolutePath());
16385            } catch (ErrnoException e) {
16386                Slog.w(TAG, "Failed to rename", e);
16387                return false;
16388            }
16389
16390            if (!SELinux.restoreconRecursive(afterCodeFile)) {
16391                Slog.w(TAG, "Failed to restorecon");
16392                return false;
16393            }
16394
16395            // Reflect the rename internally
16396            codeFile = afterCodeFile;
16397            resourceFile = afterCodeFile;
16398
16399            // Reflect the rename in scanned details
16400            pkg.setCodePath(afterCodeFile.getAbsolutePath());
16401            pkg.setBaseCodePath(FileUtils.rewriteAfterRename(beforeCodeFile,
16402                    afterCodeFile, pkg.baseCodePath));
16403            pkg.setSplitCodePaths(FileUtils.rewriteAfterRename(beforeCodeFile,
16404                    afterCodeFile, pkg.splitCodePaths));
16405
16406            // Reflect the rename in app info
16407            pkg.setApplicationVolumeUuid(pkg.volumeUuid);
16408            pkg.setApplicationInfoCodePath(pkg.codePath);
16409            pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
16410            pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
16411            pkg.setApplicationInfoResourcePath(pkg.codePath);
16412            pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath);
16413            pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
16414
16415            return true;
16416        }
16417
16418        int doPostInstall(int status, int uid) {
16419            if (status != PackageManager.INSTALL_SUCCEEDED) {
16420                cleanUp();
16421            }
16422            return status;
16423        }
16424
16425        @Override
16426        String getCodePath() {
16427            return (codeFile != null) ? codeFile.getAbsolutePath() : null;
16428        }
16429
16430        @Override
16431        String getResourcePath() {
16432            return (resourceFile != null) ? resourceFile.getAbsolutePath() : null;
16433        }
16434
16435        private boolean cleanUp() {
16436            if (codeFile == null || !codeFile.exists()) {
16437                return false;
16438            }
16439
16440            removeCodePathLI(codeFile);
16441
16442            if (resourceFile != null && !FileUtils.contains(codeFile, resourceFile)) {
16443                resourceFile.delete();
16444            }
16445
16446            return true;
16447        }
16448
16449        void cleanUpResourcesLI() {
16450            // Try enumerating all code paths before deleting
16451            List<String> allCodePaths = Collections.EMPTY_LIST;
16452            if (codeFile != null && codeFile.exists()) {
16453                try {
16454                    final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0);
16455                    allCodePaths = pkg.getAllCodePaths();
16456                } catch (PackageParserException e) {
16457                    // Ignored; we tried our best
16458                }
16459            }
16460
16461            cleanUp();
16462            removeDexFiles(allCodePaths, instructionSets);
16463        }
16464
16465        boolean doPostDeleteLI(boolean delete) {
16466            // XXX err, shouldn't we respect the delete flag?
16467            cleanUpResourcesLI();
16468            return true;
16469        }
16470    }
16471
16472    private boolean isAsecExternal(String cid) {
16473        final String asecPath = PackageHelper.getSdFilesystem(cid);
16474        return !asecPath.startsWith(mAsecInternalPath);
16475    }
16476
16477    private static void maybeThrowExceptionForMultiArchCopy(String message, int copyRet) throws
16478            PackageManagerException {
16479        if (copyRet < 0) {
16480            if (copyRet != PackageManager.NO_NATIVE_LIBRARIES &&
16481                    copyRet != PackageManager.INSTALL_FAILED_NO_MATCHING_ABIS) {
16482                throw new PackageManagerException(copyRet, message);
16483            }
16484        }
16485    }
16486
16487    /**
16488     * Extract the StorageManagerService "container ID" from the full code path of an
16489     * .apk.
16490     */
16491    static String cidFromCodePath(String fullCodePath) {
16492        int eidx = fullCodePath.lastIndexOf("/");
16493        String subStr1 = fullCodePath.substring(0, eidx);
16494        int sidx = subStr1.lastIndexOf("/");
16495        return subStr1.substring(sidx+1, eidx);
16496    }
16497
16498    /**
16499     * Logic to handle installation of ASEC applications, including copying and
16500     * renaming logic.
16501     */
16502    class AsecInstallArgs extends InstallArgs {
16503        static final String RES_FILE_NAME = "pkg.apk";
16504        static final String PUBLIC_RES_FILE_NAME = "res.zip";
16505
16506        String cid;
16507        String packagePath;
16508        String resourcePath;
16509
16510        /** New install */
16511        AsecInstallArgs(InstallParams params) {
16512            super(params.origin, params.move, params.observer, params.installFlags,
16513                    params.installerPackageName, params.volumeUuid,
16514                    params.getUser(), null /* instruction sets */, params.packageAbiOverride,
16515                    params.grantedRuntimePermissions,
16516                    params.traceMethod, params.traceCookie, params.certificates,
16517                    params.installReason);
16518        }
16519
16520        /** Existing install */
16521        AsecInstallArgs(String fullCodePath, String[] instructionSets,
16522                        boolean isExternal, boolean isForwardLocked) {
16523            super(OriginInfo.fromNothing(), null, null, (isExternal ? INSTALL_EXTERNAL : 0)
16524                    | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null,
16525                    instructionSets, null, null, null, 0, null /*certificates*/,
16526                    PackageManager.INSTALL_REASON_UNKNOWN);
16527            // Hackily pretend we're still looking at a full code path
16528            if (!fullCodePath.endsWith(RES_FILE_NAME)) {
16529                fullCodePath = new File(fullCodePath, RES_FILE_NAME).getAbsolutePath();
16530            }
16531
16532            // Extract cid from fullCodePath
16533            int eidx = fullCodePath.lastIndexOf("/");
16534            String subStr1 = fullCodePath.substring(0, eidx);
16535            int sidx = subStr1.lastIndexOf("/");
16536            cid = subStr1.substring(sidx+1, eidx);
16537            setMountPath(subStr1);
16538        }
16539
16540        AsecInstallArgs(String cid, String[] instructionSets, boolean isForwardLocked) {
16541            super(OriginInfo.fromNothing(), null, null, (isAsecExternal(cid) ? INSTALL_EXTERNAL : 0)
16542                    | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null,
16543                    instructionSets, null, null, null, 0, null /*certificates*/,
16544                    PackageManager.INSTALL_REASON_UNKNOWN);
16545            this.cid = cid;
16546            setMountPath(PackageHelper.getSdDir(cid));
16547        }
16548
16549        void createCopyFile() {
16550            cid = mInstallerService.allocateExternalStageCidLegacy();
16551        }
16552
16553        int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
16554            if (origin.staged && origin.cid != null) {
16555                if (DEBUG_INSTALL) Slog.d(TAG, origin.cid + " already staged; skipping copy");
16556                cid = origin.cid;
16557                setMountPath(PackageHelper.getSdDir(cid));
16558                return PackageManager.INSTALL_SUCCEEDED;
16559            }
16560
16561            if (temp) {
16562                createCopyFile();
16563            } else {
16564                /*
16565                 * Pre-emptively destroy the container since it's destroyed if
16566                 * copying fails due to it existing anyway.
16567                 */
16568                PackageHelper.destroySdDir(cid);
16569            }
16570
16571            final String newMountPath = imcs.copyPackageToContainer(
16572                    origin.file.getAbsolutePath(), cid, getEncryptKey(), isExternalAsec(),
16573                    isFwdLocked(), deriveAbiOverride(abiOverride, null /* settings */));
16574
16575            if (newMountPath != null) {
16576                setMountPath(newMountPath);
16577                return PackageManager.INSTALL_SUCCEEDED;
16578            } else {
16579                return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
16580            }
16581        }
16582
16583        @Override
16584        String getCodePath() {
16585            return packagePath;
16586        }
16587
16588        @Override
16589        String getResourcePath() {
16590            return resourcePath;
16591        }
16592
16593        int doPreInstall(int status) {
16594            if (status != PackageManager.INSTALL_SUCCEEDED) {
16595                // Destroy container
16596                PackageHelper.destroySdDir(cid);
16597            } else {
16598                boolean mounted = PackageHelper.isContainerMounted(cid);
16599                if (!mounted) {
16600                    String newMountPath = PackageHelper.mountSdDir(cid, getEncryptKey(),
16601                            Process.SYSTEM_UID);
16602                    if (newMountPath != null) {
16603                        setMountPath(newMountPath);
16604                    } else {
16605                        return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
16606                    }
16607                }
16608            }
16609            return status;
16610        }
16611
16612        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
16613            String newCacheId = getNextCodePath(oldCodePath, pkg.packageName, "/" + RES_FILE_NAME);
16614            String newMountPath = null;
16615            if (PackageHelper.isContainerMounted(cid)) {
16616                // Unmount the container
16617                if (!PackageHelper.unMountSdDir(cid)) {
16618                    Slog.i(TAG, "Failed to unmount " + cid + " before renaming");
16619                    return false;
16620                }
16621            }
16622            if (!PackageHelper.renameSdDir(cid, newCacheId)) {
16623                Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId +
16624                        " which might be stale. Will try to clean up.");
16625                // Clean up the stale container and proceed to recreate.
16626                if (!PackageHelper.destroySdDir(newCacheId)) {
16627                    Slog.e(TAG, "Very strange. Cannot clean up stale container " + newCacheId);
16628                    return false;
16629                }
16630                // Successfully cleaned up stale container. Try to rename again.
16631                if (!PackageHelper.renameSdDir(cid, newCacheId)) {
16632                    Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId
16633                            + " inspite of cleaning it up.");
16634                    return false;
16635                }
16636            }
16637            if (!PackageHelper.isContainerMounted(newCacheId)) {
16638                Slog.w(TAG, "Mounting container " + newCacheId);
16639                newMountPath = PackageHelper.mountSdDir(newCacheId,
16640                        getEncryptKey(), Process.SYSTEM_UID);
16641            } else {
16642                newMountPath = PackageHelper.getSdDir(newCacheId);
16643            }
16644            if (newMountPath == null) {
16645                Slog.w(TAG, "Failed to get cache path for  " + newCacheId);
16646                return false;
16647            }
16648            Log.i(TAG, "Succesfully renamed " + cid +
16649                    " to " + newCacheId +
16650                    " at new path: " + newMountPath);
16651            cid = newCacheId;
16652
16653            final File beforeCodeFile = new File(packagePath);
16654            setMountPath(newMountPath);
16655            final File afterCodeFile = new File(packagePath);
16656
16657            // Reflect the rename in scanned details
16658            pkg.setCodePath(afterCodeFile.getAbsolutePath());
16659            pkg.setBaseCodePath(FileUtils.rewriteAfterRename(beforeCodeFile,
16660                    afterCodeFile, pkg.baseCodePath));
16661            pkg.setSplitCodePaths(FileUtils.rewriteAfterRename(beforeCodeFile,
16662                    afterCodeFile, pkg.splitCodePaths));
16663
16664            // Reflect the rename in app info
16665            pkg.setApplicationVolumeUuid(pkg.volumeUuid);
16666            pkg.setApplicationInfoCodePath(pkg.codePath);
16667            pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
16668            pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
16669            pkg.setApplicationInfoResourcePath(pkg.codePath);
16670            pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath);
16671            pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
16672
16673            return true;
16674        }
16675
16676        private void setMountPath(String mountPath) {
16677            final File mountFile = new File(mountPath);
16678
16679            final File monolithicFile = new File(mountFile, RES_FILE_NAME);
16680            if (monolithicFile.exists()) {
16681                packagePath = monolithicFile.getAbsolutePath();
16682                if (isFwdLocked()) {
16683                    resourcePath = new File(mountFile, PUBLIC_RES_FILE_NAME).getAbsolutePath();
16684                } else {
16685                    resourcePath = packagePath;
16686                }
16687            } else {
16688                packagePath = mountFile.getAbsolutePath();
16689                resourcePath = packagePath;
16690            }
16691        }
16692
16693        int doPostInstall(int status, int uid) {
16694            if (status != PackageManager.INSTALL_SUCCEEDED) {
16695                cleanUp();
16696            } else {
16697                final int groupOwner;
16698                final String protectedFile;
16699                if (isFwdLocked()) {
16700                    groupOwner = UserHandle.getSharedAppGid(uid);
16701                    protectedFile = RES_FILE_NAME;
16702                } else {
16703                    groupOwner = -1;
16704                    protectedFile = null;
16705                }
16706
16707                if (uid < Process.FIRST_APPLICATION_UID
16708                        || !PackageHelper.fixSdPermissions(cid, groupOwner, protectedFile)) {
16709                    Slog.e(TAG, "Failed to finalize " + cid);
16710                    PackageHelper.destroySdDir(cid);
16711                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
16712                }
16713
16714                boolean mounted = PackageHelper.isContainerMounted(cid);
16715                if (!mounted) {
16716                    PackageHelper.mountSdDir(cid, getEncryptKey(), Process.myUid());
16717                }
16718            }
16719            return status;
16720        }
16721
16722        private void cleanUp() {
16723            if (DEBUG_SD_INSTALL) Slog.i(TAG, "cleanUp");
16724
16725            // Destroy secure container
16726            PackageHelper.destroySdDir(cid);
16727        }
16728
16729        private List<String> getAllCodePaths() {
16730            final File codeFile = new File(getCodePath());
16731            if (codeFile != null && codeFile.exists()) {
16732                try {
16733                    final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0);
16734                    return pkg.getAllCodePaths();
16735                } catch (PackageParserException e) {
16736                    // Ignored; we tried our best
16737                }
16738            }
16739            return Collections.EMPTY_LIST;
16740        }
16741
16742        void cleanUpResourcesLI() {
16743            // Enumerate all code paths before deleting
16744            cleanUpResourcesLI(getAllCodePaths());
16745        }
16746
16747        private void cleanUpResourcesLI(List<String> allCodePaths) {
16748            cleanUp();
16749            removeDexFiles(allCodePaths, instructionSets);
16750        }
16751
16752        String getPackageName() {
16753            return getAsecPackageName(cid);
16754        }
16755
16756        boolean doPostDeleteLI(boolean delete) {
16757            if (DEBUG_SD_INSTALL) Slog.i(TAG, "doPostDeleteLI() del=" + delete);
16758            final List<String> allCodePaths = getAllCodePaths();
16759            boolean mounted = PackageHelper.isContainerMounted(cid);
16760            if (mounted) {
16761                // Unmount first
16762                if (PackageHelper.unMountSdDir(cid)) {
16763                    mounted = false;
16764                }
16765            }
16766            if (!mounted && delete) {
16767                cleanUpResourcesLI(allCodePaths);
16768            }
16769            return !mounted;
16770        }
16771
16772        @Override
16773        int doPreCopy() {
16774            if (isFwdLocked()) {
16775                if (!PackageHelper.fixSdPermissions(cid, getPackageUid(DEFAULT_CONTAINER_PACKAGE,
16776                        MATCH_SYSTEM_ONLY, UserHandle.USER_SYSTEM), RES_FILE_NAME)) {
16777                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
16778                }
16779            }
16780
16781            return PackageManager.INSTALL_SUCCEEDED;
16782        }
16783
16784        @Override
16785        int doPostCopy(int uid) {
16786            if (isFwdLocked()) {
16787                if (uid < Process.FIRST_APPLICATION_UID
16788                        || !PackageHelper.fixSdPermissions(cid, UserHandle.getSharedAppGid(uid),
16789                                RES_FILE_NAME)) {
16790                    Slog.e(TAG, "Failed to finalize " + cid);
16791                    PackageHelper.destroySdDir(cid);
16792                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
16793                }
16794            }
16795
16796            return PackageManager.INSTALL_SUCCEEDED;
16797        }
16798    }
16799
16800    /**
16801     * Logic to handle movement of existing installed applications.
16802     */
16803    class MoveInstallArgs extends InstallArgs {
16804        private File codeFile;
16805        private File resourceFile;
16806
16807        /** New install */
16808        MoveInstallArgs(InstallParams params) {
16809            super(params.origin, params.move, params.observer, params.installFlags,
16810                    params.installerPackageName, params.volumeUuid,
16811                    params.getUser(), null /* instruction sets */, params.packageAbiOverride,
16812                    params.grantedRuntimePermissions,
16813                    params.traceMethod, params.traceCookie, params.certificates,
16814                    params.installReason);
16815        }
16816
16817        int copyApk(IMediaContainerService imcs, boolean temp) {
16818            if (DEBUG_INSTALL) Slog.d(TAG, "Moving " + move.packageName + " from "
16819                    + move.fromUuid + " to " + move.toUuid);
16820            synchronized (mInstaller) {
16821                try {
16822                    mInstaller.moveCompleteApp(move.fromUuid, move.toUuid, move.packageName,
16823                            move.dataAppName, move.appId, move.seinfo, move.targetSdkVersion);
16824                } catch (InstallerException e) {
16825                    Slog.w(TAG, "Failed to move app", e);
16826                    return PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
16827                }
16828            }
16829
16830            codeFile = new File(Environment.getDataAppDirectory(move.toUuid), move.dataAppName);
16831            resourceFile = codeFile;
16832            if (DEBUG_INSTALL) Slog.d(TAG, "codeFile after move is " + codeFile);
16833
16834            return PackageManager.INSTALL_SUCCEEDED;
16835        }
16836
16837        int doPreInstall(int status) {
16838            if (status != PackageManager.INSTALL_SUCCEEDED) {
16839                cleanUp(move.toUuid);
16840            }
16841            return status;
16842        }
16843
16844        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
16845            if (status != PackageManager.INSTALL_SUCCEEDED) {
16846                cleanUp(move.toUuid);
16847                return false;
16848            }
16849
16850            // Reflect the move in app info
16851            pkg.setApplicationVolumeUuid(pkg.volumeUuid);
16852            pkg.setApplicationInfoCodePath(pkg.codePath);
16853            pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
16854            pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
16855            pkg.setApplicationInfoResourcePath(pkg.codePath);
16856            pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath);
16857            pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
16858
16859            return true;
16860        }
16861
16862        int doPostInstall(int status, int uid) {
16863            if (status == PackageManager.INSTALL_SUCCEEDED) {
16864                cleanUp(move.fromUuid);
16865            } else {
16866                cleanUp(move.toUuid);
16867            }
16868            return status;
16869        }
16870
16871        @Override
16872        String getCodePath() {
16873            return (codeFile != null) ? codeFile.getAbsolutePath() : null;
16874        }
16875
16876        @Override
16877        String getResourcePath() {
16878            return (resourceFile != null) ? resourceFile.getAbsolutePath() : null;
16879        }
16880
16881        private boolean cleanUp(String volumeUuid) {
16882            final File codeFile = new File(Environment.getDataAppDirectory(volumeUuid),
16883                    move.dataAppName);
16884            Slog.d(TAG, "Cleaning up " + move.packageName + " on " + volumeUuid);
16885            final int[] userIds = sUserManager.getUserIds();
16886            synchronized (mInstallLock) {
16887                // Clean up both app data and code
16888                // All package moves are frozen until finished
16889                for (int userId : userIds) {
16890                    try {
16891                        mInstaller.destroyAppData(volumeUuid, move.packageName, userId,
16892                                StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE, 0);
16893                    } catch (InstallerException e) {
16894                        Slog.w(TAG, String.valueOf(e));
16895                    }
16896                }
16897                removeCodePathLI(codeFile);
16898            }
16899            return true;
16900        }
16901
16902        void cleanUpResourcesLI() {
16903            throw new UnsupportedOperationException();
16904        }
16905
16906        boolean doPostDeleteLI(boolean delete) {
16907            throw new UnsupportedOperationException();
16908        }
16909    }
16910
16911    static String getAsecPackageName(String packageCid) {
16912        int idx = packageCid.lastIndexOf("-");
16913        if (idx == -1) {
16914            return packageCid;
16915        }
16916        return packageCid.substring(0, idx);
16917    }
16918
16919    // Utility method used to create code paths based on package name and available index.
16920    private static String getNextCodePath(String oldCodePath, String prefix, String suffix) {
16921        String idxStr = "";
16922        int idx = 1;
16923        // Fall back to default value of idx=1 if prefix is not
16924        // part of oldCodePath
16925        if (oldCodePath != null) {
16926            String subStr = oldCodePath;
16927            // Drop the suffix right away
16928            if (suffix != null && subStr.endsWith(suffix)) {
16929                subStr = subStr.substring(0, subStr.length() - suffix.length());
16930            }
16931            // If oldCodePath already contains prefix find out the
16932            // ending index to either increment or decrement.
16933            int sidx = subStr.lastIndexOf(prefix);
16934            if (sidx != -1) {
16935                subStr = subStr.substring(sidx + prefix.length());
16936                if (subStr != null) {
16937                    if (subStr.startsWith(INSTALL_PACKAGE_SUFFIX)) {
16938                        subStr = subStr.substring(INSTALL_PACKAGE_SUFFIX.length());
16939                    }
16940                    try {
16941                        idx = Integer.parseInt(subStr);
16942                        if (idx <= 1) {
16943                            idx++;
16944                        } else {
16945                            idx--;
16946                        }
16947                    } catch(NumberFormatException e) {
16948                    }
16949                }
16950            }
16951        }
16952        idxStr = INSTALL_PACKAGE_SUFFIX + Integer.toString(idx);
16953        return prefix + idxStr;
16954    }
16955
16956    private File getNextCodePath(File targetDir, String packageName) {
16957        File result;
16958        SecureRandom random = new SecureRandom();
16959        byte[] bytes = new byte[16];
16960        do {
16961            random.nextBytes(bytes);
16962            String suffix = Base64.encodeToString(bytes, Base64.URL_SAFE | Base64.NO_WRAP);
16963            result = new File(targetDir, packageName + "-" + suffix);
16964        } while (result.exists());
16965        return result;
16966    }
16967
16968    // Utility method that returns the relative package path with respect
16969    // to the installation directory. Like say for /data/data/com.test-1.apk
16970    // string com.test-1 is returned.
16971    static String deriveCodePathName(String codePath) {
16972        if (codePath == null) {
16973            return null;
16974        }
16975        final File codeFile = new File(codePath);
16976        final String name = codeFile.getName();
16977        if (codeFile.isDirectory()) {
16978            return name;
16979        } else if (name.endsWith(".apk") || name.endsWith(".tmp")) {
16980            final int lastDot = name.lastIndexOf('.');
16981            return name.substring(0, lastDot);
16982        } else {
16983            Slog.w(TAG, "Odd, " + codePath + " doesn't look like an APK");
16984            return null;
16985        }
16986    }
16987
16988    static class PackageInstalledInfo {
16989        String name;
16990        int uid;
16991        // The set of users that originally had this package installed.
16992        int[] origUsers;
16993        // The set of users that now have this package installed.
16994        int[] newUsers;
16995        PackageParser.Package pkg;
16996        int returnCode;
16997        String returnMsg;
16998        PackageRemovedInfo removedInfo;
16999        ArrayMap<String, PackageInstalledInfo> addedChildPackages;
17000
17001        public void setError(int code, String msg) {
17002            setReturnCode(code);
17003            setReturnMessage(msg);
17004            Slog.w(TAG, msg);
17005        }
17006
17007        public void setError(String msg, PackageParserException e) {
17008            setReturnCode(e.error);
17009            setReturnMessage(ExceptionUtils.getCompleteMessage(msg, e));
17010            Slog.w(TAG, msg, e);
17011        }
17012
17013        public void setError(String msg, PackageManagerException e) {
17014            returnCode = e.error;
17015            setReturnMessage(ExceptionUtils.getCompleteMessage(msg, e));
17016            Slog.w(TAG, msg, e);
17017        }
17018
17019        public void setReturnCode(int returnCode) {
17020            this.returnCode = returnCode;
17021            final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0;
17022            for (int i = 0; i < childCount; i++) {
17023                addedChildPackages.valueAt(i).returnCode = returnCode;
17024            }
17025        }
17026
17027        private void setReturnMessage(String returnMsg) {
17028            this.returnMsg = returnMsg;
17029            final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0;
17030            for (int i = 0; i < childCount; i++) {
17031                addedChildPackages.valueAt(i).returnMsg = returnMsg;
17032            }
17033        }
17034
17035        // In some error cases we want to convey more info back to the observer
17036        String origPackage;
17037        String origPermission;
17038    }
17039
17040    /*
17041     * Install a non-existing package.
17042     */
17043    private void installNewPackageLIF(PackageParser.Package pkg, final int policyFlags,
17044            int scanFlags, UserHandle user, String installerPackageName, String volumeUuid,
17045            PackageInstalledInfo res, int installReason) {
17046        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installNewPackage");
17047
17048        // Remember this for later, in case we need to rollback this install
17049        String pkgName = pkg.packageName;
17050
17051        if (DEBUG_INSTALL) Slog.d(TAG, "installNewPackageLI: " + pkg);
17052
17053        synchronized(mPackages) {
17054            final String renamedPackage = mSettings.getRenamedPackageLPr(pkgName);
17055            if (renamedPackage != null) {
17056                // A package with the same name is already installed, though
17057                // it has been renamed to an older name.  The package we
17058                // are trying to install should be installed as an update to
17059                // the existing one, but that has not been requested, so bail.
17060                res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName
17061                        + " without first uninstalling package running as "
17062                        + renamedPackage);
17063                return;
17064            }
17065            if (mPackages.containsKey(pkgName)) {
17066                // Don't allow installation over an existing package with the same name.
17067                res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName
17068                        + " without first uninstalling.");
17069                return;
17070            }
17071        }
17072
17073        try {
17074            PackageParser.Package newPackage = scanPackageTracedLI(pkg, policyFlags, scanFlags,
17075                    System.currentTimeMillis(), user);
17076
17077            updateSettingsLI(newPackage, installerPackageName, null, res, user, installReason);
17078
17079            if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
17080                prepareAppDataAfterInstallLIF(newPackage);
17081
17082            } else {
17083                // Remove package from internal structures, but keep around any
17084                // data that might have already existed
17085                deletePackageLIF(pkgName, UserHandle.ALL, false, null,
17086                        PackageManager.DELETE_KEEP_DATA, res.removedInfo, true, null);
17087            }
17088        } catch (PackageManagerException e) {
17089            res.setError("Package couldn't be installed in " + pkg.codePath, e);
17090        }
17091
17092        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
17093    }
17094
17095    private boolean shouldCheckUpgradeKeySetLP(PackageSetting oldPs, int scanFlags) {
17096        // Can't rotate keys during boot or if sharedUser.
17097        if (oldPs == null || (scanFlags&SCAN_INITIAL) != 0 || oldPs.sharedUser != null
17098                || !oldPs.keySetData.isUsingUpgradeKeySets()) {
17099            return false;
17100        }
17101        // app is using upgradeKeySets; make sure all are valid
17102        KeySetManagerService ksms = mSettings.mKeySetManagerService;
17103        long[] upgradeKeySets = oldPs.keySetData.getUpgradeKeySets();
17104        for (int i = 0; i < upgradeKeySets.length; i++) {
17105            if (!ksms.isIdValidKeySetId(upgradeKeySets[i])) {
17106                Slog.wtf(TAG, "Package "
17107                         + (oldPs.name != null ? oldPs.name : "<null>")
17108                         + " contains upgrade-key-set reference to unknown key-set: "
17109                         + upgradeKeySets[i]
17110                         + " reverting to signatures check.");
17111                return false;
17112            }
17113        }
17114        return true;
17115    }
17116
17117    private boolean checkUpgradeKeySetLP(PackageSetting oldPS, PackageParser.Package newPkg) {
17118        // Upgrade keysets are being used.  Determine if new package has a superset of the
17119        // required keys.
17120        long[] upgradeKeySets = oldPS.keySetData.getUpgradeKeySets();
17121        KeySetManagerService ksms = mSettings.mKeySetManagerService;
17122        for (int i = 0; i < upgradeKeySets.length; i++) {
17123            Set<PublicKey> upgradeSet = ksms.getPublicKeysFromKeySetLPr(upgradeKeySets[i]);
17124            if (upgradeSet != null && newPkg.mSigningKeys.containsAll(upgradeSet)) {
17125                return true;
17126            }
17127        }
17128        return false;
17129    }
17130
17131    private static void updateDigest(MessageDigest digest, File file) throws IOException {
17132        try (DigestInputStream digestStream =
17133                new DigestInputStream(new FileInputStream(file), digest)) {
17134            while (digestStream.read() != -1) {} // nothing to do; just plow through the file
17135        }
17136    }
17137
17138    private void replacePackageLIF(PackageParser.Package pkg, final int policyFlags, int scanFlags,
17139            UserHandle user, String installerPackageName, PackageInstalledInfo res,
17140            int installReason) {
17141        final boolean isInstantApp = (scanFlags & SCAN_AS_INSTANT_APP) != 0;
17142
17143        final PackageParser.Package oldPackage;
17144        final PackageSetting ps;
17145        final String pkgName = pkg.packageName;
17146        final int[] allUsers;
17147        final int[] installedUsers;
17148
17149        synchronized(mPackages) {
17150            oldPackage = mPackages.get(pkgName);
17151            if (DEBUG_INSTALL) Slog.d(TAG, "replacePackageLI: new=" + pkg + ", old=" + oldPackage);
17152
17153            // don't allow upgrade to target a release SDK from a pre-release SDK
17154            final boolean oldTargetsPreRelease = oldPackage.applicationInfo.targetSdkVersion
17155                    == android.os.Build.VERSION_CODES.CUR_DEVELOPMENT;
17156            final boolean newTargetsPreRelease = pkg.applicationInfo.targetSdkVersion
17157                    == android.os.Build.VERSION_CODES.CUR_DEVELOPMENT;
17158            if (oldTargetsPreRelease
17159                    && !newTargetsPreRelease
17160                    && ((policyFlags & PackageParser.PARSE_FORCE_SDK) == 0)) {
17161                Slog.w(TAG, "Can't install package targeting released sdk");
17162                res.setReturnCode(PackageManager.INSTALL_FAILED_UPDATE_INCOMPATIBLE);
17163                return;
17164            }
17165
17166            ps = mSettings.mPackages.get(pkgName);
17167
17168            // verify signatures are valid
17169            if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) {
17170                if (!checkUpgradeKeySetLP(ps, pkg)) {
17171                    res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
17172                            "New package not signed by keys specified by upgrade-keysets: "
17173                                    + pkgName);
17174                    return;
17175                }
17176            } else {
17177                // default to original signature matching
17178                if (compareSignatures(oldPackage.mSignatures, pkg.mSignatures)
17179                        != PackageManager.SIGNATURE_MATCH) {
17180                    res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
17181                            "New package has a different signature: " + pkgName);
17182                    return;
17183                }
17184            }
17185
17186            // don't allow a system upgrade unless the upgrade hash matches
17187            if (oldPackage.restrictUpdateHash != null && oldPackage.isSystemApp()) {
17188                byte[] digestBytes = null;
17189                try {
17190                    final MessageDigest digest = MessageDigest.getInstance("SHA-512");
17191                    updateDigest(digest, new File(pkg.baseCodePath));
17192                    if (!ArrayUtils.isEmpty(pkg.splitCodePaths)) {
17193                        for (String path : pkg.splitCodePaths) {
17194                            updateDigest(digest, new File(path));
17195                        }
17196                    }
17197                    digestBytes = digest.digest();
17198                } catch (NoSuchAlgorithmException | IOException e) {
17199                    res.setError(INSTALL_FAILED_INVALID_APK,
17200                            "Could not compute hash: " + pkgName);
17201                    return;
17202                }
17203                if (!Arrays.equals(oldPackage.restrictUpdateHash, digestBytes)) {
17204                    res.setError(INSTALL_FAILED_INVALID_APK,
17205                            "New package fails restrict-update check: " + pkgName);
17206                    return;
17207                }
17208                // retain upgrade restriction
17209                pkg.restrictUpdateHash = oldPackage.restrictUpdateHash;
17210            }
17211
17212            // Check for shared user id changes
17213            String invalidPackageName =
17214                    getParentOrChildPackageChangedSharedUser(oldPackage, pkg);
17215            if (invalidPackageName != null) {
17216                res.setError(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE,
17217                        "Package " + invalidPackageName + " tried to change user "
17218                                + oldPackage.mSharedUserId);
17219                return;
17220            }
17221
17222            // In case of rollback, remember per-user/profile install state
17223            allUsers = sUserManager.getUserIds();
17224            installedUsers = ps.queryInstalledUsers(allUsers, true);
17225
17226            // don't allow an upgrade from full to ephemeral
17227            if (isInstantApp) {
17228                if (user == null || user.getIdentifier() == UserHandle.USER_ALL) {
17229                    for (int currentUser : allUsers) {
17230                        if (!ps.getInstantApp(currentUser)) {
17231                            // can't downgrade from full to instant
17232                            Slog.w(TAG, "Can't replace full app with instant app: " + pkgName
17233                                    + " for user: " + currentUser);
17234                            res.setReturnCode(PackageManager.INSTALL_FAILED_INSTANT_APP_INVALID);
17235                            return;
17236                        }
17237                    }
17238                } else if (!ps.getInstantApp(user.getIdentifier())) {
17239                    // can't downgrade from full to instant
17240                    Slog.w(TAG, "Can't replace full app with instant app: " + pkgName
17241                            + " for user: " + user.getIdentifier());
17242                    res.setReturnCode(PackageManager.INSTALL_FAILED_INSTANT_APP_INVALID);
17243                    return;
17244                }
17245            }
17246        }
17247
17248        // Update what is removed
17249        res.removedInfo = new PackageRemovedInfo(this);
17250        res.removedInfo.uid = oldPackage.applicationInfo.uid;
17251        res.removedInfo.removedPackage = oldPackage.packageName;
17252        res.removedInfo.installerPackageName = ps.installerPackageName;
17253        res.removedInfo.isStaticSharedLib = pkg.staticSharedLibName != null;
17254        res.removedInfo.isUpdate = true;
17255        res.removedInfo.origUsers = installedUsers;
17256        res.removedInfo.installReasons = new SparseArray<>(installedUsers.length);
17257        for (int i = 0; i < installedUsers.length; i++) {
17258            final int userId = installedUsers[i];
17259            res.removedInfo.installReasons.put(userId, ps.getInstallReason(userId));
17260        }
17261
17262        final int childCount = (oldPackage.childPackages != null)
17263                ? oldPackage.childPackages.size() : 0;
17264        for (int i = 0; i < childCount; i++) {
17265            boolean childPackageUpdated = false;
17266            PackageParser.Package childPkg = oldPackage.childPackages.get(i);
17267            final PackageSetting childPs = mSettings.getPackageLPr(childPkg.packageName);
17268            if (res.addedChildPackages != null) {
17269                PackageInstalledInfo childRes = res.addedChildPackages.get(childPkg.packageName);
17270                if (childRes != null) {
17271                    childRes.removedInfo.uid = childPkg.applicationInfo.uid;
17272                    childRes.removedInfo.removedPackage = childPkg.packageName;
17273                    if (childPs != null) {
17274                        childRes.removedInfo.installerPackageName = childPs.installerPackageName;
17275                    }
17276                    childRes.removedInfo.isUpdate = true;
17277                    childRes.removedInfo.installReasons = res.removedInfo.installReasons;
17278                    childPackageUpdated = true;
17279                }
17280            }
17281            if (!childPackageUpdated) {
17282                PackageRemovedInfo childRemovedRes = new PackageRemovedInfo(this);
17283                childRemovedRes.removedPackage = childPkg.packageName;
17284                if (childPs != null) {
17285                    childRemovedRes.installerPackageName = childPs.installerPackageName;
17286                }
17287                childRemovedRes.isUpdate = false;
17288                childRemovedRes.dataRemoved = true;
17289                synchronized (mPackages) {
17290                    if (childPs != null) {
17291                        childRemovedRes.origUsers = childPs.queryInstalledUsers(allUsers, true);
17292                    }
17293                }
17294                if (res.removedInfo.removedChildPackages == null) {
17295                    res.removedInfo.removedChildPackages = new ArrayMap<>();
17296                }
17297                res.removedInfo.removedChildPackages.put(childPkg.packageName, childRemovedRes);
17298            }
17299        }
17300
17301        boolean sysPkg = (isSystemApp(oldPackage));
17302        if (sysPkg) {
17303            // Set the system/privileged flags as needed
17304            final boolean privileged =
17305                    (oldPackage.applicationInfo.privateFlags
17306                            & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0;
17307            final int systemPolicyFlags = policyFlags
17308                    | PackageParser.PARSE_IS_SYSTEM
17309                    | (privileged ? PackageParser.PARSE_IS_PRIVILEGED : 0);
17310
17311            replaceSystemPackageLIF(oldPackage, pkg, systemPolicyFlags, scanFlags,
17312                    user, allUsers, installerPackageName, res, installReason);
17313        } else {
17314            replaceNonSystemPackageLIF(oldPackage, pkg, policyFlags, scanFlags,
17315                    user, allUsers, installerPackageName, res, installReason);
17316        }
17317    }
17318
17319    @Override
17320    public List<String> getPreviousCodePaths(String packageName) {
17321        final int callingUid = Binder.getCallingUid();
17322        final List<String> result = new ArrayList<>();
17323        if (getInstantAppPackageName(callingUid) != null) {
17324            return result;
17325        }
17326        final PackageSetting ps = mSettings.mPackages.get(packageName);
17327        if (ps != null
17328                && ps.oldCodePaths != null
17329                && !filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
17330            result.addAll(ps.oldCodePaths);
17331        }
17332        return result;
17333    }
17334
17335    private void replaceNonSystemPackageLIF(PackageParser.Package deletedPackage,
17336            PackageParser.Package pkg, final int policyFlags, int scanFlags, UserHandle user,
17337            int[] allUsers, String installerPackageName, PackageInstalledInfo res,
17338            int installReason) {
17339        if (DEBUG_INSTALL) Slog.d(TAG, "replaceNonSystemPackageLI: new=" + pkg + ", old="
17340                + deletedPackage);
17341
17342        String pkgName = deletedPackage.packageName;
17343        boolean deletedPkg = true;
17344        boolean addedPkg = false;
17345        boolean updatedSettings = false;
17346        final boolean killApp = (scanFlags & SCAN_DONT_KILL_APP) == 0;
17347        final int deleteFlags = PackageManager.DELETE_KEEP_DATA
17348                | (killApp ? 0 : PackageManager.DELETE_DONT_KILL_APP);
17349
17350        final long origUpdateTime = (pkg.mExtras != null)
17351                ? ((PackageSetting)pkg.mExtras).lastUpdateTime : 0;
17352
17353        // First delete the existing package while retaining the data directory
17354        if (!deletePackageLIF(pkgName, null, true, allUsers, deleteFlags,
17355                res.removedInfo, true, pkg)) {
17356            // If the existing package wasn't successfully deleted
17357            res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, "replaceNonSystemPackageLI");
17358            deletedPkg = false;
17359        } else {
17360            // Successfully deleted the old package; proceed with replace.
17361
17362            // If deleted package lived in a container, give users a chance to
17363            // relinquish resources before killing.
17364            if (deletedPackage.isForwardLocked() || isExternal(deletedPackage)) {
17365                if (DEBUG_INSTALL) {
17366                    Slog.i(TAG, "upgrading pkg " + deletedPackage + " is ASEC-hosted -> UNAVAILABLE");
17367                }
17368                final int[] uidArray = new int[] { deletedPackage.applicationInfo.uid };
17369                final ArrayList<String> pkgList = new ArrayList<String>(1);
17370                pkgList.add(deletedPackage.applicationInfo.packageName);
17371                sendResourcesChangedBroadcast(false, true, pkgList, uidArray, null);
17372            }
17373
17374            clearAppDataLIF(pkg, UserHandle.USER_ALL, StorageManager.FLAG_STORAGE_DE
17375                    | StorageManager.FLAG_STORAGE_CE | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
17376            clearAppProfilesLIF(deletedPackage, UserHandle.USER_ALL);
17377
17378            try {
17379                final PackageParser.Package newPackage = scanPackageTracedLI(pkg, policyFlags,
17380                        scanFlags | SCAN_UPDATE_TIME, System.currentTimeMillis(), user);
17381                updateSettingsLI(newPackage, installerPackageName, allUsers, res, user,
17382                        installReason);
17383
17384                // Update the in-memory copy of the previous code paths.
17385                PackageSetting ps = mSettings.mPackages.get(pkgName);
17386                if (!killApp) {
17387                    if (ps.oldCodePaths == null) {
17388                        ps.oldCodePaths = new ArraySet<>();
17389                    }
17390                    Collections.addAll(ps.oldCodePaths, deletedPackage.baseCodePath);
17391                    if (deletedPackage.splitCodePaths != null) {
17392                        Collections.addAll(ps.oldCodePaths, deletedPackage.splitCodePaths);
17393                    }
17394                } else {
17395                    ps.oldCodePaths = null;
17396                }
17397                if (ps.childPackageNames != null) {
17398                    for (int i = ps.childPackageNames.size() - 1; i >= 0; --i) {
17399                        final String childPkgName = ps.childPackageNames.get(i);
17400                        final PackageSetting childPs = mSettings.mPackages.get(childPkgName);
17401                        childPs.oldCodePaths = ps.oldCodePaths;
17402                    }
17403                }
17404                // set instant app status, but, only if it's explicitly specified
17405                final boolean instantApp = (scanFlags & SCAN_AS_INSTANT_APP) != 0;
17406                final boolean fullApp = (scanFlags & SCAN_AS_FULL_APP) != 0;
17407                setInstantAppForUser(ps, user.getIdentifier(), instantApp, fullApp);
17408                prepareAppDataAfterInstallLIF(newPackage);
17409                addedPkg = true;
17410                mDexManager.notifyPackageUpdated(newPackage.packageName,
17411                        newPackage.baseCodePath, newPackage.splitCodePaths);
17412            } catch (PackageManagerException e) {
17413                res.setError("Package couldn't be installed in " + pkg.codePath, e);
17414            }
17415        }
17416
17417        if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
17418            if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, rolling pack: " + pkgName);
17419
17420            // Revert all internal state mutations and added folders for the failed install
17421            if (addedPkg) {
17422                deletePackageLIF(pkgName, null, true, allUsers, deleteFlags,
17423                        res.removedInfo, true, null);
17424            }
17425
17426            // Restore the old package
17427            if (deletedPkg) {
17428                if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, reinstalling: " + deletedPackage);
17429                File restoreFile = new File(deletedPackage.codePath);
17430                // Parse old package
17431                boolean oldExternal = isExternal(deletedPackage);
17432                int oldParseFlags  = mDefParseFlags | PackageParser.PARSE_CHATTY |
17433                        (deletedPackage.isForwardLocked() ? PackageParser.PARSE_FORWARD_LOCK : 0) |
17434                        (oldExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0);
17435                int oldScanFlags = SCAN_UPDATE_SIGNATURE | SCAN_UPDATE_TIME;
17436                try {
17437                    scanPackageTracedLI(restoreFile, oldParseFlags, oldScanFlags, origUpdateTime,
17438                            null);
17439                } catch (PackageManagerException e) {
17440                    Slog.e(TAG, "Failed to restore package : " + pkgName + " after failed upgrade: "
17441                            + e.getMessage());
17442                    return;
17443                }
17444
17445                synchronized (mPackages) {
17446                    // Ensure the installer package name up to date
17447                    setInstallerPackageNameLPw(deletedPackage, installerPackageName);
17448
17449                    // Update permissions for restored package
17450                    updatePermissionsLPw(deletedPackage, UPDATE_PERMISSIONS_ALL);
17451
17452                    mSettings.writeLPr();
17453                }
17454
17455                Slog.i(TAG, "Successfully restored package : " + pkgName + " after failed upgrade");
17456            }
17457        } else {
17458            synchronized (mPackages) {
17459                PackageSetting ps = mSettings.getPackageLPr(pkg.packageName);
17460                if (ps != null) {
17461                    res.removedInfo.removedForAllUsers = mPackages.get(ps.name) == null;
17462                    if (res.removedInfo.removedChildPackages != null) {
17463                        final int childCount = res.removedInfo.removedChildPackages.size();
17464                        // Iterate in reverse as we may modify the collection
17465                        for (int i = childCount - 1; i >= 0; i--) {
17466                            String childPackageName = res.removedInfo.removedChildPackages.keyAt(i);
17467                            if (res.addedChildPackages.containsKey(childPackageName)) {
17468                                res.removedInfo.removedChildPackages.removeAt(i);
17469                            } else {
17470                                PackageRemovedInfo childInfo = res.removedInfo
17471                                        .removedChildPackages.valueAt(i);
17472                                childInfo.removedForAllUsers = mPackages.get(
17473                                        childInfo.removedPackage) == null;
17474                            }
17475                        }
17476                    }
17477                }
17478            }
17479        }
17480    }
17481
17482    private void replaceSystemPackageLIF(PackageParser.Package deletedPackage,
17483            PackageParser.Package pkg, final int policyFlags, int scanFlags, UserHandle user,
17484            int[] allUsers, String installerPackageName, PackageInstalledInfo res,
17485            int installReason) {
17486        if (DEBUG_INSTALL) Slog.d(TAG, "replaceSystemPackageLI: new=" + pkg
17487                + ", old=" + deletedPackage);
17488
17489        final boolean disabledSystem;
17490
17491        // Remove existing system package
17492        removePackageLI(deletedPackage, true);
17493
17494        synchronized (mPackages) {
17495            disabledSystem = disableSystemPackageLPw(deletedPackage, pkg);
17496        }
17497        if (!disabledSystem) {
17498            // We didn't need to disable the .apk as a current system package,
17499            // which means we are replacing another update that is already
17500            // installed.  We need to make sure to delete the older one's .apk.
17501            res.removedInfo.args = createInstallArgsForExisting(0,
17502                    deletedPackage.applicationInfo.getCodePath(),
17503                    deletedPackage.applicationInfo.getResourcePath(),
17504                    getAppDexInstructionSets(deletedPackage.applicationInfo));
17505        } else {
17506            res.removedInfo.args = null;
17507        }
17508
17509        // Successfully disabled the old package. Now proceed with re-installation
17510        clearAppDataLIF(pkg, UserHandle.USER_ALL, StorageManager.FLAG_STORAGE_DE
17511                | StorageManager.FLAG_STORAGE_CE | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
17512        clearAppProfilesLIF(deletedPackage, UserHandle.USER_ALL);
17513
17514        res.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
17515        pkg.setApplicationInfoFlags(ApplicationInfo.FLAG_UPDATED_SYSTEM_APP,
17516                ApplicationInfo.FLAG_UPDATED_SYSTEM_APP);
17517
17518        PackageParser.Package newPackage = null;
17519        try {
17520            // Add the package to the internal data structures
17521            newPackage = scanPackageTracedLI(pkg, policyFlags, scanFlags, 0, user);
17522
17523            // Set the update and install times
17524            PackageSetting deletedPkgSetting = (PackageSetting) deletedPackage.mExtras;
17525            setInstallAndUpdateTime(newPackage, deletedPkgSetting.firstInstallTime,
17526                    System.currentTimeMillis());
17527
17528            // Update the package dynamic state if succeeded
17529            if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
17530                // Now that the install succeeded make sure we remove data
17531                // directories for any child package the update removed.
17532                final int deletedChildCount = (deletedPackage.childPackages != null)
17533                        ? deletedPackage.childPackages.size() : 0;
17534                final int newChildCount = (newPackage.childPackages != null)
17535                        ? newPackage.childPackages.size() : 0;
17536                for (int i = 0; i < deletedChildCount; i++) {
17537                    PackageParser.Package deletedChildPkg = deletedPackage.childPackages.get(i);
17538                    boolean childPackageDeleted = true;
17539                    for (int j = 0; j < newChildCount; j++) {
17540                        PackageParser.Package newChildPkg = newPackage.childPackages.get(j);
17541                        if (deletedChildPkg.packageName.equals(newChildPkg.packageName)) {
17542                            childPackageDeleted = false;
17543                            break;
17544                        }
17545                    }
17546                    if (childPackageDeleted) {
17547                        PackageSetting ps = mSettings.getDisabledSystemPkgLPr(
17548                                deletedChildPkg.packageName);
17549                        if (ps != null && res.removedInfo.removedChildPackages != null) {
17550                            PackageRemovedInfo removedChildRes = res.removedInfo
17551                                    .removedChildPackages.get(deletedChildPkg.packageName);
17552                            removePackageDataLIF(ps, allUsers, removedChildRes, 0, false);
17553                            removedChildRes.removedForAllUsers = mPackages.get(ps.name) == null;
17554                        }
17555                    }
17556                }
17557
17558                updateSettingsLI(newPackage, installerPackageName, allUsers, res, user,
17559                        installReason);
17560                prepareAppDataAfterInstallLIF(newPackage);
17561
17562                mDexManager.notifyPackageUpdated(newPackage.packageName,
17563                            newPackage.baseCodePath, newPackage.splitCodePaths);
17564            }
17565        } catch (PackageManagerException e) {
17566            res.setReturnCode(INSTALL_FAILED_INTERNAL_ERROR);
17567            res.setError("Package couldn't be installed in " + pkg.codePath, e);
17568        }
17569
17570        if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
17571            // Re installation failed. Restore old information
17572            // Remove new pkg information
17573            if (newPackage != null) {
17574                removeInstalledPackageLI(newPackage, true);
17575            }
17576            // Add back the old system package
17577            try {
17578                scanPackageTracedLI(deletedPackage, policyFlags, SCAN_UPDATE_SIGNATURE, 0, user);
17579            } catch (PackageManagerException e) {
17580                Slog.e(TAG, "Failed to restore original package: " + e.getMessage());
17581            }
17582
17583            synchronized (mPackages) {
17584                if (disabledSystem) {
17585                    enableSystemPackageLPw(deletedPackage);
17586                }
17587
17588                // Ensure the installer package name up to date
17589                setInstallerPackageNameLPw(deletedPackage, installerPackageName);
17590
17591                // Update permissions for restored package
17592                updatePermissionsLPw(deletedPackage, UPDATE_PERMISSIONS_ALL);
17593
17594                mSettings.writeLPr();
17595            }
17596
17597            Slog.i(TAG, "Successfully restored package : " + deletedPackage.packageName
17598                    + " after failed upgrade");
17599        }
17600    }
17601
17602    /**
17603     * Checks whether the parent or any of the child packages have a change shared
17604     * user. For a package to be a valid update the shred users of the parent and
17605     * the children should match. We may later support changing child shared users.
17606     * @param oldPkg The updated package.
17607     * @param newPkg The update package.
17608     * @return The shared user that change between the versions.
17609     */
17610    private String getParentOrChildPackageChangedSharedUser(PackageParser.Package oldPkg,
17611            PackageParser.Package newPkg) {
17612        // Check parent shared user
17613        if (!Objects.equals(oldPkg.mSharedUserId, newPkg.mSharedUserId)) {
17614            return newPkg.packageName;
17615        }
17616        // Check child shared users
17617        final int oldChildCount = (oldPkg.childPackages != null) ? oldPkg.childPackages.size() : 0;
17618        final int newChildCount = (newPkg.childPackages != null) ? newPkg.childPackages.size() : 0;
17619        for (int i = 0; i < newChildCount; i++) {
17620            PackageParser.Package newChildPkg = newPkg.childPackages.get(i);
17621            // If this child was present, did it have the same shared user?
17622            for (int j = 0; j < oldChildCount; j++) {
17623                PackageParser.Package oldChildPkg = oldPkg.childPackages.get(j);
17624                if (newChildPkg.packageName.equals(oldChildPkg.packageName)
17625                        && !Objects.equals(newChildPkg.mSharedUserId, oldChildPkg.mSharedUserId)) {
17626                    return newChildPkg.packageName;
17627                }
17628            }
17629        }
17630        return null;
17631    }
17632
17633    private void removeNativeBinariesLI(PackageSetting ps) {
17634        // Remove the lib path for the parent package
17635        if (ps != null) {
17636            NativeLibraryHelper.removeNativeBinariesLI(ps.legacyNativeLibraryPathString);
17637            // Remove the lib path for the child packages
17638            final int childCount = (ps.childPackageNames != null) ? ps.childPackageNames.size() : 0;
17639            for (int i = 0; i < childCount; i++) {
17640                PackageSetting childPs = null;
17641                synchronized (mPackages) {
17642                    childPs = mSettings.getPackageLPr(ps.childPackageNames.get(i));
17643                }
17644                if (childPs != null) {
17645                    NativeLibraryHelper.removeNativeBinariesLI(childPs
17646                            .legacyNativeLibraryPathString);
17647                }
17648            }
17649        }
17650    }
17651
17652    private void enableSystemPackageLPw(PackageParser.Package pkg) {
17653        // Enable the parent package
17654        mSettings.enableSystemPackageLPw(pkg.packageName);
17655        // Enable the child packages
17656        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
17657        for (int i = 0; i < childCount; i++) {
17658            PackageParser.Package childPkg = pkg.childPackages.get(i);
17659            mSettings.enableSystemPackageLPw(childPkg.packageName);
17660        }
17661    }
17662
17663    private boolean disableSystemPackageLPw(PackageParser.Package oldPkg,
17664            PackageParser.Package newPkg) {
17665        // Disable the parent package (parent always replaced)
17666        boolean disabled = mSettings.disableSystemPackageLPw(oldPkg.packageName, true);
17667        // Disable the child packages
17668        final int childCount = (oldPkg.childPackages != null) ? oldPkg.childPackages.size() : 0;
17669        for (int i = 0; i < childCount; i++) {
17670            PackageParser.Package childPkg = oldPkg.childPackages.get(i);
17671            final boolean replace = newPkg.hasChildPackage(childPkg.packageName);
17672            disabled |= mSettings.disableSystemPackageLPw(childPkg.packageName, replace);
17673        }
17674        return disabled;
17675    }
17676
17677    private void setInstallerPackageNameLPw(PackageParser.Package pkg,
17678            String installerPackageName) {
17679        // Enable the parent package
17680        mSettings.setInstallerPackageName(pkg.packageName, installerPackageName);
17681        // Enable the child packages
17682        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
17683        for (int i = 0; i < childCount; i++) {
17684            PackageParser.Package childPkg = pkg.childPackages.get(i);
17685            mSettings.setInstallerPackageName(childPkg.packageName, installerPackageName);
17686        }
17687    }
17688
17689    private int[] revokeUnusedSharedUserPermissionsLPw(SharedUserSetting su, int[] allUserIds) {
17690        // Collect all used permissions in the UID
17691        ArraySet<String> usedPermissions = new ArraySet<>();
17692        final int packageCount = su.packages.size();
17693        for (int i = 0; i < packageCount; i++) {
17694            PackageSetting ps = su.packages.valueAt(i);
17695            if (ps.pkg == null) {
17696                continue;
17697            }
17698            final int requestedPermCount = ps.pkg.requestedPermissions.size();
17699            for (int j = 0; j < requestedPermCount; j++) {
17700                String permission = ps.pkg.requestedPermissions.get(j);
17701                BasePermission bp = mSettings.mPermissions.get(permission);
17702                if (bp != null) {
17703                    usedPermissions.add(permission);
17704                }
17705            }
17706        }
17707
17708        PermissionsState permissionsState = su.getPermissionsState();
17709        // Prune install permissions
17710        List<PermissionState> installPermStates = permissionsState.getInstallPermissionStates();
17711        final int installPermCount = installPermStates.size();
17712        for (int i = installPermCount - 1; i >= 0;  i--) {
17713            PermissionState permissionState = installPermStates.get(i);
17714            if (!usedPermissions.contains(permissionState.getName())) {
17715                BasePermission bp = mSettings.mPermissions.get(permissionState.getName());
17716                if (bp != null) {
17717                    permissionsState.revokeInstallPermission(bp);
17718                    permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL,
17719                            PackageManager.MASK_PERMISSION_FLAGS, 0);
17720                }
17721            }
17722        }
17723
17724        int[] runtimePermissionChangedUserIds = EmptyArray.INT;
17725
17726        // Prune runtime permissions
17727        for (int userId : allUserIds) {
17728            List<PermissionState> runtimePermStates = permissionsState
17729                    .getRuntimePermissionStates(userId);
17730            final int runtimePermCount = runtimePermStates.size();
17731            for (int i = runtimePermCount - 1; i >= 0; i--) {
17732                PermissionState permissionState = runtimePermStates.get(i);
17733                if (!usedPermissions.contains(permissionState.getName())) {
17734                    BasePermission bp = mSettings.mPermissions.get(permissionState.getName());
17735                    if (bp != null) {
17736                        permissionsState.revokeRuntimePermission(bp, userId);
17737                        permissionsState.updatePermissionFlags(bp, userId,
17738                                PackageManager.MASK_PERMISSION_FLAGS, 0);
17739                        runtimePermissionChangedUserIds = ArrayUtils.appendInt(
17740                                runtimePermissionChangedUserIds, userId);
17741                    }
17742                }
17743            }
17744        }
17745
17746        return runtimePermissionChangedUserIds;
17747    }
17748
17749    private void updateSettingsLI(PackageParser.Package newPackage, String installerPackageName,
17750            int[] allUsers, PackageInstalledInfo res, UserHandle user, int installReason) {
17751        // Update the parent package setting
17752        updateSettingsInternalLI(newPackage, installerPackageName, allUsers, res.origUsers,
17753                res, user, installReason);
17754        // Update the child packages setting
17755        final int childCount = (newPackage.childPackages != null)
17756                ? newPackage.childPackages.size() : 0;
17757        for (int i = 0; i < childCount; i++) {
17758            PackageParser.Package childPackage = newPackage.childPackages.get(i);
17759            PackageInstalledInfo childRes = res.addedChildPackages.get(childPackage.packageName);
17760            updateSettingsInternalLI(childPackage, installerPackageName, allUsers,
17761                    childRes.origUsers, childRes, user, installReason);
17762        }
17763    }
17764
17765    private void updateSettingsInternalLI(PackageParser.Package newPackage,
17766            String installerPackageName, int[] allUsers, int[] installedForUsers,
17767            PackageInstalledInfo res, UserHandle user, int installReason) {
17768        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings");
17769
17770        String pkgName = newPackage.packageName;
17771        synchronized (mPackages) {
17772            //write settings. the installStatus will be incomplete at this stage.
17773            //note that the new package setting would have already been
17774            //added to mPackages. It hasn't been persisted yet.
17775            mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_INCOMPLETE);
17776            // TODO: Remove this write? It's also written at the end of this method
17777            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings");
17778            mSettings.writeLPr();
17779            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
17780        }
17781
17782        if (DEBUG_INSTALL) Slog.d(TAG, "New package installed in " + newPackage.codePath);
17783        synchronized (mPackages) {
17784            updatePermissionsLPw(newPackage.packageName, newPackage,
17785                    UPDATE_PERMISSIONS_REPLACE_PKG | (newPackage.permissions.size() > 0
17786                            ? UPDATE_PERMISSIONS_ALL : 0));
17787            // For system-bundled packages, we assume that installing an upgraded version
17788            // of the package implies that the user actually wants to run that new code,
17789            // so we enable the package.
17790            PackageSetting ps = mSettings.mPackages.get(pkgName);
17791            final int userId = user.getIdentifier();
17792            if (ps != null) {
17793                if (isSystemApp(newPackage)) {
17794                    if (DEBUG_INSTALL) {
17795                        Slog.d(TAG, "Implicitly enabling system package on upgrade: " + pkgName);
17796                    }
17797                    // Enable system package for requested users
17798                    if (res.origUsers != null) {
17799                        for (int origUserId : res.origUsers) {
17800                            if (userId == UserHandle.USER_ALL || userId == origUserId) {
17801                                ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT,
17802                                        origUserId, installerPackageName);
17803                            }
17804                        }
17805                    }
17806                    // Also convey the prior install/uninstall state
17807                    if (allUsers != null && installedForUsers != null) {
17808                        for (int currentUserId : allUsers) {
17809                            final boolean installed = ArrayUtils.contains(
17810                                    installedForUsers, currentUserId);
17811                            if (DEBUG_INSTALL) {
17812                                Slog.d(TAG, "    user " + currentUserId + " => " + installed);
17813                            }
17814                            ps.setInstalled(installed, currentUserId);
17815                        }
17816                        // these install state changes will be persisted in the
17817                        // upcoming call to mSettings.writeLPr().
17818                    }
17819                }
17820                // It's implied that when a user requests installation, they want the app to be
17821                // installed and enabled.
17822                if (userId != UserHandle.USER_ALL) {
17823                    ps.setInstalled(true, userId);
17824                    ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, userId, installerPackageName);
17825                }
17826
17827                // When replacing an existing package, preserve the original install reason for all
17828                // users that had the package installed before.
17829                final Set<Integer> previousUserIds = new ArraySet<>();
17830                if (res.removedInfo != null && res.removedInfo.installReasons != null) {
17831                    final int installReasonCount = res.removedInfo.installReasons.size();
17832                    for (int i = 0; i < installReasonCount; i++) {
17833                        final int previousUserId = res.removedInfo.installReasons.keyAt(i);
17834                        final int previousInstallReason = res.removedInfo.installReasons.valueAt(i);
17835                        ps.setInstallReason(previousInstallReason, previousUserId);
17836                        previousUserIds.add(previousUserId);
17837                    }
17838                }
17839
17840                // Set install reason for users that are having the package newly installed.
17841                if (userId == UserHandle.USER_ALL) {
17842                    for (int currentUserId : sUserManager.getUserIds()) {
17843                        if (!previousUserIds.contains(currentUserId)) {
17844                            ps.setInstallReason(installReason, currentUserId);
17845                        }
17846                    }
17847                } else if (!previousUserIds.contains(userId)) {
17848                    ps.setInstallReason(installReason, userId);
17849                }
17850                mSettings.writeKernelMappingLPr(ps);
17851            }
17852            res.name = pkgName;
17853            res.uid = newPackage.applicationInfo.uid;
17854            res.pkg = newPackage;
17855            mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_COMPLETE);
17856            mSettings.setInstallerPackageName(pkgName, installerPackageName);
17857            res.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
17858            //to update install status
17859            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings");
17860            mSettings.writeLPr();
17861            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
17862        }
17863
17864        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
17865    }
17866
17867    private void installPackageTracedLI(InstallArgs args, PackageInstalledInfo res) {
17868        try {
17869            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installPackage");
17870            installPackageLI(args, res);
17871        } finally {
17872            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
17873        }
17874    }
17875
17876    private void installPackageLI(InstallArgs args, PackageInstalledInfo res) {
17877        final int installFlags = args.installFlags;
17878        final String installerPackageName = args.installerPackageName;
17879        final String volumeUuid = args.volumeUuid;
17880        final File tmpPackageFile = new File(args.getCodePath());
17881        final boolean forwardLocked = ((installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0);
17882        final boolean onExternal = (((installFlags & PackageManager.INSTALL_EXTERNAL) != 0)
17883                || (args.volumeUuid != null));
17884        final boolean instantApp = ((installFlags & PackageManager.INSTALL_INSTANT_APP) != 0);
17885        final boolean fullApp = ((installFlags & PackageManager.INSTALL_FULL_APP) != 0);
17886        final boolean forceSdk = ((installFlags & PackageManager.INSTALL_FORCE_SDK) != 0);
17887        boolean replace = false;
17888        int scanFlags = SCAN_NEW_INSTALL | SCAN_UPDATE_SIGNATURE;
17889        if (args.move != null) {
17890            // moving a complete application; perform an initial scan on the new install location
17891            scanFlags |= SCAN_INITIAL;
17892        }
17893        if ((installFlags & PackageManager.INSTALL_DONT_KILL_APP) != 0) {
17894            scanFlags |= SCAN_DONT_KILL_APP;
17895        }
17896        if (instantApp) {
17897            scanFlags |= SCAN_AS_INSTANT_APP;
17898        }
17899        if (fullApp) {
17900            scanFlags |= SCAN_AS_FULL_APP;
17901        }
17902
17903        // Result object to be returned
17904        res.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
17905
17906        if (DEBUG_INSTALL) Slog.d(TAG, "installPackageLI: path=" + tmpPackageFile);
17907
17908        // Sanity check
17909        if (instantApp && (forwardLocked || onExternal)) {
17910            Slog.i(TAG, "Incompatible ephemeral install; fwdLocked=" + forwardLocked
17911                    + " external=" + onExternal);
17912            res.setReturnCode(PackageManager.INSTALL_FAILED_INSTANT_APP_INVALID);
17913            return;
17914        }
17915
17916        // Retrieve PackageSettings and parse package
17917        final int parseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY
17918                | PackageParser.PARSE_ENFORCE_CODE
17919                | (forwardLocked ? PackageParser.PARSE_FORWARD_LOCK : 0)
17920                | (onExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0)
17921                | (instantApp ? PackageParser.PARSE_IS_EPHEMERAL : 0)
17922                | (forceSdk ? PackageParser.PARSE_FORCE_SDK : 0);
17923        PackageParser pp = new PackageParser();
17924        pp.setSeparateProcesses(mSeparateProcesses);
17925        pp.setDisplayMetrics(mMetrics);
17926        pp.setCallback(mPackageParserCallback);
17927
17928        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "parsePackage");
17929        final PackageParser.Package pkg;
17930        try {
17931            pkg = pp.parsePackage(tmpPackageFile, parseFlags);
17932        } catch (PackageParserException e) {
17933            res.setError("Failed parse during installPackageLI", e);
17934            return;
17935        } finally {
17936            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
17937        }
17938
17939        // Instant apps must have target SDK >= O and have targetSanboxVersion >= 2
17940        if (instantApp && pkg.applicationInfo.targetSdkVersion <= Build.VERSION_CODES.N_MR1) {
17941            Slog.w(TAG, "Instant app package " + pkg.packageName + " does not target O");
17942            res.setError(INSTALL_FAILED_SANDBOX_VERSION_DOWNGRADE,
17943                    "Instant app package must target O");
17944            return;
17945        }
17946        if (instantApp && pkg.applicationInfo.targetSandboxVersion != 2) {
17947            Slog.w(TAG, "Instant app package " + pkg.packageName
17948                    + " does not target targetSandboxVersion 2");
17949            res.setError(INSTALL_FAILED_SANDBOX_VERSION_DOWNGRADE,
17950                    "Instant app package must use targetSanboxVersion 2");
17951            return;
17952        }
17953
17954        if (pkg.applicationInfo.isStaticSharedLibrary()) {
17955            // Static shared libraries have synthetic package names
17956            renameStaticSharedLibraryPackage(pkg);
17957
17958            // No static shared libs on external storage
17959            if (onExternal) {
17960                Slog.i(TAG, "Static shared libs can only be installed on internal storage.");
17961                res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION,
17962                        "Packages declaring static-shared libs cannot be updated");
17963                return;
17964            }
17965        }
17966
17967        // If we are installing a clustered package add results for the children
17968        if (pkg.childPackages != null) {
17969            synchronized (mPackages) {
17970                final int childCount = pkg.childPackages.size();
17971                for (int i = 0; i < childCount; i++) {
17972                    PackageParser.Package childPkg = pkg.childPackages.get(i);
17973                    PackageInstalledInfo childRes = new PackageInstalledInfo();
17974                    childRes.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
17975                    childRes.pkg = childPkg;
17976                    childRes.name = childPkg.packageName;
17977                    PackageSetting childPs = mSettings.getPackageLPr(childPkg.packageName);
17978                    if (childPs != null) {
17979                        childRes.origUsers = childPs.queryInstalledUsers(
17980                                sUserManager.getUserIds(), true);
17981                    }
17982                    if ((mPackages.containsKey(childPkg.packageName))) {
17983                        childRes.removedInfo = new PackageRemovedInfo(this);
17984                        childRes.removedInfo.removedPackage = childPkg.packageName;
17985                        childRes.removedInfo.installerPackageName = childPs.installerPackageName;
17986                    }
17987                    if (res.addedChildPackages == null) {
17988                        res.addedChildPackages = new ArrayMap<>();
17989                    }
17990                    res.addedChildPackages.put(childPkg.packageName, childRes);
17991                }
17992            }
17993        }
17994
17995        // If package doesn't declare API override, mark that we have an install
17996        // time CPU ABI override.
17997        if (TextUtils.isEmpty(pkg.cpuAbiOverride)) {
17998            pkg.cpuAbiOverride = args.abiOverride;
17999        }
18000
18001        String pkgName = res.name = pkg.packageName;
18002        if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_TEST_ONLY) != 0) {
18003            if ((installFlags & PackageManager.INSTALL_ALLOW_TEST) == 0) {
18004                res.setError(INSTALL_FAILED_TEST_ONLY, "installPackageLI");
18005                return;
18006            }
18007        }
18008
18009        try {
18010            // either use what we've been given or parse directly from the APK
18011            if (args.certificates != null) {
18012                try {
18013                    PackageParser.populateCertificates(pkg, args.certificates);
18014                } catch (PackageParserException e) {
18015                    // there was something wrong with the certificates we were given;
18016                    // try to pull them from the APK
18017                    PackageParser.collectCertificates(pkg, parseFlags);
18018                }
18019            } else {
18020                PackageParser.collectCertificates(pkg, parseFlags);
18021            }
18022        } catch (PackageParserException e) {
18023            res.setError("Failed collect during installPackageLI", e);
18024            return;
18025        }
18026
18027        // Get rid of all references to package scan path via parser.
18028        pp = null;
18029        String oldCodePath = null;
18030        boolean systemApp = false;
18031        synchronized (mPackages) {
18032            // Check if installing already existing package
18033            if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
18034                String oldName = mSettings.getRenamedPackageLPr(pkgName);
18035                if (pkg.mOriginalPackages != null
18036                        && pkg.mOriginalPackages.contains(oldName)
18037                        && mPackages.containsKey(oldName)) {
18038                    // This package is derived from an original package,
18039                    // and this device has been updating from that original
18040                    // name.  We must continue using the original name, so
18041                    // rename the new package here.
18042                    pkg.setPackageName(oldName);
18043                    pkgName = pkg.packageName;
18044                    replace = true;
18045                    if (DEBUG_INSTALL) Slog.d(TAG, "Replacing existing renamed package: oldName="
18046                            + oldName + " pkgName=" + pkgName);
18047                } else if (mPackages.containsKey(pkgName)) {
18048                    // This package, under its official name, already exists
18049                    // on the device; we should replace it.
18050                    replace = true;
18051                    if (DEBUG_INSTALL) Slog.d(TAG, "Replace existing pacakge: " + pkgName);
18052                }
18053
18054                // Child packages are installed through the parent package
18055                if (pkg.parentPackage != null) {
18056                    res.setError(PackageManager.INSTALL_PARSE_FAILED_BAD_PACKAGE_NAME,
18057                            "Package " + pkg.packageName + " is child of package "
18058                                    + pkg.parentPackage.parentPackage + ". Child packages "
18059                                    + "can be updated only through the parent package.");
18060                    return;
18061                }
18062
18063                if (replace) {
18064                    // Prevent apps opting out from runtime permissions
18065                    PackageParser.Package oldPackage = mPackages.get(pkgName);
18066                    final int oldTargetSdk = oldPackage.applicationInfo.targetSdkVersion;
18067                    final int newTargetSdk = pkg.applicationInfo.targetSdkVersion;
18068                    if (oldTargetSdk > Build.VERSION_CODES.LOLLIPOP_MR1
18069                            && newTargetSdk <= Build.VERSION_CODES.LOLLIPOP_MR1) {
18070                        res.setError(PackageManager.INSTALL_FAILED_PERMISSION_MODEL_DOWNGRADE,
18071                                "Package " + pkg.packageName + " new target SDK " + newTargetSdk
18072                                        + " doesn't support runtime permissions but the old"
18073                                        + " target SDK " + oldTargetSdk + " does.");
18074                        return;
18075                    }
18076                    // Prevent apps from downgrading their targetSandbox.
18077                    final int oldTargetSandbox = oldPackage.applicationInfo.targetSandboxVersion;
18078                    final int newTargetSandbox = pkg.applicationInfo.targetSandboxVersion;
18079                    if (oldTargetSandbox == 2 && newTargetSandbox != 2) {
18080                        res.setError(PackageManager.INSTALL_FAILED_SANDBOX_VERSION_DOWNGRADE,
18081                                "Package " + pkg.packageName + " new target sandbox "
18082                                + newTargetSandbox + " is incompatible with the previous value of"
18083                                + oldTargetSandbox + ".");
18084                        return;
18085                    }
18086
18087                    // Prevent installing of child packages
18088                    if (oldPackage.parentPackage != null) {
18089                        res.setError(PackageManager.INSTALL_PARSE_FAILED_BAD_PACKAGE_NAME,
18090                                "Package " + pkg.packageName + " is child of package "
18091                                        + oldPackage.parentPackage + ". Child packages "
18092                                        + "can be updated only through the parent package.");
18093                        return;
18094                    }
18095                }
18096            }
18097
18098            PackageSetting ps = mSettings.mPackages.get(pkgName);
18099            if (ps != null) {
18100                if (DEBUG_INSTALL) Slog.d(TAG, "Existing package: " + ps);
18101
18102                // Static shared libs have same package with different versions where
18103                // we internally use a synthetic package name to allow multiple versions
18104                // of the same package, therefore we need to compare signatures against
18105                // the package setting for the latest library version.
18106                PackageSetting signatureCheckPs = ps;
18107                if (pkg.applicationInfo.isStaticSharedLibrary()) {
18108                    SharedLibraryEntry libraryEntry = getLatestSharedLibraVersionLPr(pkg);
18109                    if (libraryEntry != null) {
18110                        signatureCheckPs = mSettings.getPackageLPr(libraryEntry.apk);
18111                    }
18112                }
18113
18114                // Quick sanity check that we're signed correctly if updating;
18115                // we'll check this again later when scanning, but we want to
18116                // bail early here before tripping over redefined permissions.
18117                if (shouldCheckUpgradeKeySetLP(signatureCheckPs, scanFlags)) {
18118                    if (!checkUpgradeKeySetLP(signatureCheckPs, pkg)) {
18119                        res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package "
18120                                + pkg.packageName + " upgrade keys do not match the "
18121                                + "previously installed version");
18122                        return;
18123                    }
18124                } else {
18125                    try {
18126                        verifySignaturesLP(signatureCheckPs, pkg);
18127                    } catch (PackageManagerException e) {
18128                        res.setError(e.error, e.getMessage());
18129                        return;
18130                    }
18131                }
18132
18133                oldCodePath = mSettings.mPackages.get(pkgName).codePathString;
18134                if (ps.pkg != null && ps.pkg.applicationInfo != null) {
18135                    systemApp = (ps.pkg.applicationInfo.flags &
18136                            ApplicationInfo.FLAG_SYSTEM) != 0;
18137                }
18138                res.origUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
18139            }
18140
18141            int N = pkg.permissions.size();
18142            for (int i = N-1; i >= 0; i--) {
18143                PackageParser.Permission perm = pkg.permissions.get(i);
18144                BasePermission bp = mSettings.mPermissions.get(perm.info.name);
18145
18146                // Don't allow anyone but the system to define ephemeral permissions.
18147                if ((perm.info.protectionLevel & PermissionInfo.PROTECTION_FLAG_EPHEMERAL) != 0
18148                        && !systemApp) {
18149                    Slog.w(TAG, "Non-System package " + pkg.packageName
18150                            + " attempting to delcare ephemeral permission "
18151                            + perm.info.name + "; Removing ephemeral.");
18152                    perm.info.protectionLevel &= ~PermissionInfo.PROTECTION_FLAG_EPHEMERAL;
18153                }
18154                // Check whether the newly-scanned package wants to define an already-defined perm
18155                if (bp != null) {
18156                    // If the defining package is signed with our cert, it's okay.  This
18157                    // also includes the "updating the same package" case, of course.
18158                    // "updating same package" could also involve key-rotation.
18159                    final boolean sigsOk;
18160                    if (bp.sourcePackage.equals(pkg.packageName)
18161                            && (bp.packageSetting instanceof PackageSetting)
18162                            && (shouldCheckUpgradeKeySetLP((PackageSetting) bp.packageSetting,
18163                                    scanFlags))) {
18164                        sigsOk = checkUpgradeKeySetLP((PackageSetting) bp.packageSetting, pkg);
18165                    } else {
18166                        sigsOk = compareSignatures(bp.packageSetting.signatures.mSignatures,
18167                                pkg.mSignatures) == PackageManager.SIGNATURE_MATCH;
18168                    }
18169                    if (!sigsOk) {
18170                        // If the owning package is the system itself, we log but allow
18171                        // install to proceed; we fail the install on all other permission
18172                        // redefinitions.
18173                        if (!bp.sourcePackage.equals("android")) {
18174                            res.setError(INSTALL_FAILED_DUPLICATE_PERMISSION, "Package "
18175                                    + pkg.packageName + " attempting to redeclare permission "
18176                                    + perm.info.name + " already owned by " + bp.sourcePackage);
18177                            res.origPermission = perm.info.name;
18178                            res.origPackage = bp.sourcePackage;
18179                            return;
18180                        } else {
18181                            Slog.w(TAG, "Package " + pkg.packageName
18182                                    + " attempting to redeclare system permission "
18183                                    + perm.info.name + "; ignoring new declaration");
18184                            pkg.permissions.remove(i);
18185                        }
18186                    } else if (!PLATFORM_PACKAGE_NAME.equals(pkg.packageName)) {
18187                        // Prevent apps to change protection level to dangerous from any other
18188                        // type as this would allow a privilege escalation where an app adds a
18189                        // normal/signature permission in other app's group and later redefines
18190                        // it as dangerous leading to the group auto-grant.
18191                        if ((perm.info.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE)
18192                                == PermissionInfo.PROTECTION_DANGEROUS) {
18193                            if (bp != null && !bp.isRuntime()) {
18194                                Slog.w(TAG, "Package " + pkg.packageName + " trying to change a "
18195                                        + "non-runtime permission " + perm.info.name
18196                                        + " to runtime; keeping old protection level");
18197                                perm.info.protectionLevel = bp.protectionLevel;
18198                            }
18199                        }
18200                    }
18201                }
18202            }
18203        }
18204
18205        if (systemApp) {
18206            if (onExternal) {
18207                // Abort update; system app can't be replaced with app on sdcard
18208                res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION,
18209                        "Cannot install updates to system apps on sdcard");
18210                return;
18211            } else if (instantApp) {
18212                // Abort update; system app can't be replaced with an instant app
18213                res.setError(INSTALL_FAILED_INSTANT_APP_INVALID,
18214                        "Cannot update a system app with an instant app");
18215                return;
18216            }
18217        }
18218
18219        if (args.move != null) {
18220            // We did an in-place move, so dex is ready to roll
18221            scanFlags |= SCAN_NO_DEX;
18222            scanFlags |= SCAN_MOVE;
18223
18224            synchronized (mPackages) {
18225                final PackageSetting ps = mSettings.mPackages.get(pkgName);
18226                if (ps == null) {
18227                    res.setError(INSTALL_FAILED_INTERNAL_ERROR,
18228                            "Missing settings for moved package " + pkgName);
18229                }
18230
18231                // We moved the entire application as-is, so bring over the
18232                // previously derived ABI information.
18233                pkg.applicationInfo.primaryCpuAbi = ps.primaryCpuAbiString;
18234                pkg.applicationInfo.secondaryCpuAbi = ps.secondaryCpuAbiString;
18235            }
18236
18237        } else if (!forwardLocked && !pkg.applicationInfo.isExternalAsec()) {
18238            // Enable SCAN_NO_DEX flag to skip dexopt at a later stage
18239            scanFlags |= SCAN_NO_DEX;
18240
18241            try {
18242                String abiOverride = (TextUtils.isEmpty(pkg.cpuAbiOverride) ?
18243                    args.abiOverride : pkg.cpuAbiOverride);
18244                final boolean extractNativeLibs = !pkg.isLibrary();
18245                derivePackageAbi(pkg, new File(pkg.codePath), abiOverride,
18246                        extractNativeLibs, mAppLib32InstallDir);
18247            } catch (PackageManagerException pme) {
18248                Slog.e(TAG, "Error deriving application ABI", pme);
18249                res.setError(INSTALL_FAILED_INTERNAL_ERROR, "Error deriving application ABI");
18250                return;
18251            }
18252
18253            // Shared libraries for the package need to be updated.
18254            synchronized (mPackages) {
18255                try {
18256                    updateSharedLibrariesLPr(pkg, null);
18257                } catch (PackageManagerException e) {
18258                    Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
18259                }
18260            }
18261
18262            // dexopt can take some time to complete, so, for instant apps, we skip this
18263            // step during installation. Instead, we'll take extra time the first time the
18264            // instant app starts. It's preferred to do it this way to provide continuous
18265            // progress to the user instead of mysteriously blocking somewhere in the
18266            // middle of running an instant app. The default behaviour can be overridden
18267            // via gservices.
18268            if (!instantApp || Global.getInt(
18269                        mContext.getContentResolver(), Global.INSTANT_APP_DEXOPT_ENABLED, 0) != 0) {
18270                Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt");
18271                // Do not run PackageDexOptimizer through the local performDexOpt
18272                // method because `pkg` may not be in `mPackages` yet.
18273                //
18274                // Also, don't fail application installs if the dexopt step fails.
18275                DexoptOptions dexoptOptions = new DexoptOptions(pkg.packageName,
18276                        REASON_INSTALL,
18277                        DexoptOptions.DEXOPT_BOOT_COMPLETE);
18278                mPackageDexOptimizer.performDexOpt(pkg, pkg.usesLibraryFiles,
18279                        null /* instructionSets */,
18280                        getOrCreateCompilerPackageStats(pkg),
18281                        mDexManager.isUsedByOtherApps(pkg.packageName),
18282                        dexoptOptions);
18283                Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
18284            }
18285
18286            // Notify BackgroundDexOptService that the package has been changed.
18287            // If this is an update of a package which used to fail to compile,
18288            // BDOS will remove it from its blacklist.
18289            // TODO: Layering violation
18290            BackgroundDexOptService.notifyPackageChanged(pkg.packageName);
18291        }
18292
18293        if (!args.doRename(res.returnCode, pkg, oldCodePath)) {
18294            res.setError(INSTALL_FAILED_INSUFFICIENT_STORAGE, "Failed rename");
18295            return;
18296        }
18297
18298        startIntentFilterVerifications(args.user.getIdentifier(), replace, pkg);
18299
18300        try (PackageFreezer freezer = freezePackageForInstall(pkgName, installFlags,
18301                "installPackageLI")) {
18302            if (replace) {
18303                if (pkg.applicationInfo.isStaticSharedLibrary()) {
18304                    // Static libs have a synthetic package name containing the version
18305                    // and cannot be updated as an update would get a new package name,
18306                    // unless this is the exact same version code which is useful for
18307                    // development.
18308                    PackageParser.Package existingPkg = mPackages.get(pkg.packageName);
18309                    if (existingPkg != null && existingPkg.mVersionCode != pkg.mVersionCode) {
18310                        res.setError(INSTALL_FAILED_DUPLICATE_PACKAGE, "Packages declaring "
18311                                + "static-shared libs cannot be updated");
18312                        return;
18313                    }
18314                }
18315                replacePackageLIF(pkg, parseFlags, scanFlags | SCAN_REPLACING, args.user,
18316                        installerPackageName, res, args.installReason);
18317            } else {
18318                installNewPackageLIF(pkg, parseFlags, scanFlags | SCAN_DELETE_DATA_ON_FAILURES,
18319                        args.user, installerPackageName, volumeUuid, res, args.installReason);
18320            }
18321        }
18322
18323        synchronized (mPackages) {
18324            final PackageSetting ps = mSettings.mPackages.get(pkgName);
18325            if (ps != null) {
18326                res.newUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
18327                ps.setUpdateAvailable(false /*updateAvailable*/);
18328            }
18329
18330            final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
18331            for (int i = 0; i < childCount; i++) {
18332                PackageParser.Package childPkg = pkg.childPackages.get(i);
18333                PackageInstalledInfo childRes = res.addedChildPackages.get(childPkg.packageName);
18334                PackageSetting childPs = mSettings.getPackageLPr(childPkg.packageName);
18335                if (childPs != null) {
18336                    childRes.newUsers = childPs.queryInstalledUsers(
18337                            sUserManager.getUserIds(), true);
18338                }
18339            }
18340
18341            if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
18342                updateSequenceNumberLP(ps, res.newUsers);
18343                updateInstantAppInstallerLocked(pkgName);
18344            }
18345        }
18346    }
18347
18348    private void startIntentFilterVerifications(int userId, boolean replacing,
18349            PackageParser.Package pkg) {
18350        if (mIntentFilterVerifierComponent == null) {
18351            Slog.w(TAG, "No IntentFilter verification will not be done as "
18352                    + "there is no IntentFilterVerifier available!");
18353            return;
18354        }
18355
18356        final int verifierUid = getPackageUid(
18357                mIntentFilterVerifierComponent.getPackageName(),
18358                MATCH_DEBUG_TRIAGED_MISSING,
18359                (userId == UserHandle.USER_ALL) ? UserHandle.USER_SYSTEM : userId);
18360
18361        Message msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS);
18362        msg.obj = new IFVerificationParams(pkg, replacing, userId, verifierUid);
18363        mHandler.sendMessage(msg);
18364
18365        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
18366        for (int i = 0; i < childCount; i++) {
18367            PackageParser.Package childPkg = pkg.childPackages.get(i);
18368            msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS);
18369            msg.obj = new IFVerificationParams(childPkg, replacing, userId, verifierUid);
18370            mHandler.sendMessage(msg);
18371        }
18372    }
18373
18374    private void verifyIntentFiltersIfNeeded(int userId, int verifierUid, boolean replacing,
18375            PackageParser.Package pkg) {
18376        int size = pkg.activities.size();
18377        if (size == 0) {
18378            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
18379                    "No activity, so no need to verify any IntentFilter!");
18380            return;
18381        }
18382
18383        final boolean hasDomainURLs = hasDomainURLs(pkg);
18384        if (!hasDomainURLs) {
18385            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
18386                    "No domain URLs, so no need to verify any IntentFilter!");
18387            return;
18388        }
18389
18390        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Checking for userId:" + userId
18391                + " if any IntentFilter from the " + size
18392                + " Activities needs verification ...");
18393
18394        int count = 0;
18395        final String packageName = pkg.packageName;
18396
18397        synchronized (mPackages) {
18398            // If this is a new install and we see that we've already run verification for this
18399            // package, we have nothing to do: it means the state was restored from backup.
18400            if (!replacing) {
18401                IntentFilterVerificationInfo ivi =
18402                        mSettings.getIntentFilterVerificationLPr(packageName);
18403                if (ivi != null) {
18404                    if (DEBUG_DOMAIN_VERIFICATION) {
18405                        Slog.i(TAG, "Package " + packageName+ " already verified: status="
18406                                + ivi.getStatusString());
18407                    }
18408                    return;
18409                }
18410            }
18411
18412            // If any filters need to be verified, then all need to be.
18413            boolean needToVerify = false;
18414            for (PackageParser.Activity a : pkg.activities) {
18415                for (ActivityIntentInfo filter : a.intents) {
18416                    if (filter.needsVerification() && needsNetworkVerificationLPr(filter)) {
18417                        if (DEBUG_DOMAIN_VERIFICATION) {
18418                            Slog.d(TAG, "Intent filter needs verification, so processing all filters");
18419                        }
18420                        needToVerify = true;
18421                        break;
18422                    }
18423                }
18424            }
18425
18426            if (needToVerify) {
18427                final int verificationId = mIntentFilterVerificationToken++;
18428                for (PackageParser.Activity a : pkg.activities) {
18429                    for (ActivityIntentInfo filter : a.intents) {
18430                        if (filter.handlesWebUris(true) && needsNetworkVerificationLPr(filter)) {
18431                            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
18432                                    "Verification needed for IntentFilter:" + filter.toString());
18433                            mIntentFilterVerifier.addOneIntentFilterVerification(
18434                                    verifierUid, userId, verificationId, filter, packageName);
18435                            count++;
18436                        }
18437                    }
18438                }
18439            }
18440        }
18441
18442        if (count > 0) {
18443            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Starting " + count
18444                    + " IntentFilter verification" + (count > 1 ? "s" : "")
18445                    +  " for userId:" + userId);
18446            mIntentFilterVerifier.startVerifications(userId);
18447        } else {
18448            if (DEBUG_DOMAIN_VERIFICATION) {
18449                Slog.d(TAG, "No filters or not all autoVerify for " + packageName);
18450            }
18451        }
18452    }
18453
18454    private boolean needsNetworkVerificationLPr(ActivityIntentInfo filter) {
18455        final ComponentName cn  = filter.activity.getComponentName();
18456        final String packageName = cn.getPackageName();
18457
18458        IntentFilterVerificationInfo ivi = mSettings.getIntentFilterVerificationLPr(
18459                packageName);
18460        if (ivi == null) {
18461            return true;
18462        }
18463        int status = ivi.getStatus();
18464        switch (status) {
18465            case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED:
18466            case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK:
18467                return true;
18468
18469            default:
18470                // Nothing to do
18471                return false;
18472        }
18473    }
18474
18475    private static boolean isMultiArch(ApplicationInfo info) {
18476        return (info.flags & ApplicationInfo.FLAG_MULTIARCH) != 0;
18477    }
18478
18479    private static boolean isExternal(PackageParser.Package pkg) {
18480        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
18481    }
18482
18483    private static boolean isExternal(PackageSetting ps) {
18484        return (ps.pkgFlags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
18485    }
18486
18487    private static boolean isSystemApp(PackageParser.Package pkg) {
18488        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0;
18489    }
18490
18491    private static boolean isPrivilegedApp(PackageParser.Package pkg) {
18492        return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0;
18493    }
18494
18495    private static boolean hasDomainURLs(PackageParser.Package pkg) {
18496        return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_HAS_DOMAIN_URLS) != 0;
18497    }
18498
18499    private static boolean isSystemApp(PackageSetting ps) {
18500        return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0;
18501    }
18502
18503    private static boolean isUpdatedSystemApp(PackageSetting ps) {
18504        return (ps.pkgFlags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0;
18505    }
18506
18507    private int packageFlagsToInstallFlags(PackageSetting ps) {
18508        int installFlags = 0;
18509        if (isExternal(ps) && TextUtils.isEmpty(ps.volumeUuid)) {
18510            // This existing package was an external ASEC install when we have
18511            // the external flag without a UUID
18512            installFlags |= PackageManager.INSTALL_EXTERNAL;
18513        }
18514        if (ps.isForwardLocked()) {
18515            installFlags |= PackageManager.INSTALL_FORWARD_LOCK;
18516        }
18517        return installFlags;
18518    }
18519
18520    private String getVolumeUuidForPackage(PackageParser.Package pkg) {
18521        if (isExternal(pkg)) {
18522            if (TextUtils.isEmpty(pkg.volumeUuid)) {
18523                return StorageManager.UUID_PRIMARY_PHYSICAL;
18524            } else {
18525                return pkg.volumeUuid;
18526            }
18527        } else {
18528            return StorageManager.UUID_PRIVATE_INTERNAL;
18529        }
18530    }
18531
18532    private VersionInfo getSettingsVersionForPackage(PackageParser.Package pkg) {
18533        if (isExternal(pkg)) {
18534            if (TextUtils.isEmpty(pkg.volumeUuid)) {
18535                return mSettings.getExternalVersion();
18536            } else {
18537                return mSettings.findOrCreateVersion(pkg.volumeUuid);
18538            }
18539        } else {
18540            return mSettings.getInternalVersion();
18541        }
18542    }
18543
18544    private void deleteTempPackageFiles() {
18545        final FilenameFilter filter = new FilenameFilter() {
18546            public boolean accept(File dir, String name) {
18547                return name.startsWith("vmdl") && name.endsWith(".tmp");
18548            }
18549        };
18550        for (File file : mDrmAppPrivateInstallDir.listFiles(filter)) {
18551            file.delete();
18552        }
18553    }
18554
18555    @Override
18556    public void deletePackageAsUser(String packageName, int versionCode,
18557            IPackageDeleteObserver observer, int userId, int flags) {
18558        deletePackageVersioned(new VersionedPackage(packageName, versionCode),
18559                new LegacyPackageDeleteObserver(observer).getBinder(), userId, flags);
18560    }
18561
18562    @Override
18563    public void deletePackageVersioned(VersionedPackage versionedPackage,
18564            final IPackageDeleteObserver2 observer, final int userId, final int deleteFlags) {
18565        final int callingUid = Binder.getCallingUid();
18566        mContext.enforceCallingOrSelfPermission(
18567                android.Manifest.permission.DELETE_PACKAGES, null);
18568        final boolean canViewInstantApps = canViewInstantApps(callingUid, userId);
18569        Preconditions.checkNotNull(versionedPackage);
18570        Preconditions.checkNotNull(observer);
18571        Preconditions.checkArgumentInRange(versionedPackage.getVersionCode(),
18572                PackageManager.VERSION_CODE_HIGHEST,
18573                Integer.MAX_VALUE, "versionCode must be >= -1");
18574
18575        final String packageName = versionedPackage.getPackageName();
18576        final int versionCode = versionedPackage.getVersionCode();
18577        final String internalPackageName;
18578        synchronized (mPackages) {
18579            // Normalize package name to handle renamed packages and static libs
18580            internalPackageName = resolveInternalPackageNameLPr(versionedPackage.getPackageName(),
18581                    versionedPackage.getVersionCode());
18582        }
18583
18584        final int uid = Binder.getCallingUid();
18585        if (!isOrphaned(internalPackageName)
18586                && !isCallerAllowedToSilentlyUninstall(uid, internalPackageName)) {
18587            try {
18588                final Intent intent = new Intent(Intent.ACTION_UNINSTALL_PACKAGE);
18589                intent.setData(Uri.fromParts(PACKAGE_SCHEME, packageName, null));
18590                intent.putExtra(PackageInstaller.EXTRA_CALLBACK, observer.asBinder());
18591                observer.onUserActionRequired(intent);
18592            } catch (RemoteException re) {
18593            }
18594            return;
18595        }
18596        final boolean deleteAllUsers = (deleteFlags & PackageManager.DELETE_ALL_USERS) != 0;
18597        final int[] users = deleteAllUsers ? sUserManager.getUserIds() : new int[]{ userId };
18598        if (UserHandle.getUserId(uid) != userId || (deleteAllUsers && users.length > 1)) {
18599            mContext.enforceCallingOrSelfPermission(
18600                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
18601                    "deletePackage for user " + userId);
18602        }
18603
18604        if (isUserRestricted(userId, UserManager.DISALLOW_UNINSTALL_APPS)) {
18605            try {
18606                observer.onPackageDeleted(packageName,
18607                        PackageManager.DELETE_FAILED_USER_RESTRICTED, null);
18608            } catch (RemoteException re) {
18609            }
18610            return;
18611        }
18612
18613        if (!deleteAllUsers && getBlockUninstallForUser(internalPackageName, userId)) {
18614            try {
18615                observer.onPackageDeleted(packageName,
18616                        PackageManager.DELETE_FAILED_OWNER_BLOCKED, null);
18617            } catch (RemoteException re) {
18618            }
18619            return;
18620        }
18621
18622        if (DEBUG_REMOVE) {
18623            Slog.d(TAG, "deletePackageAsUser: pkg=" + internalPackageName + " user=" + userId
18624                    + " deleteAllUsers: " + deleteAllUsers + " version="
18625                    + (versionCode == PackageManager.VERSION_CODE_HIGHEST
18626                    ? "VERSION_CODE_HIGHEST" : versionCode));
18627        }
18628        // Queue up an async operation since the package deletion may take a little while.
18629        mHandler.post(new Runnable() {
18630            public void run() {
18631                mHandler.removeCallbacks(this);
18632                int returnCode;
18633                final PackageSetting ps = mSettings.mPackages.get(internalPackageName);
18634                boolean doDeletePackage = true;
18635                if (ps != null) {
18636                    final boolean targetIsInstantApp =
18637                            ps.getInstantApp(UserHandle.getUserId(callingUid));
18638                    doDeletePackage = !targetIsInstantApp
18639                            || canViewInstantApps;
18640                }
18641                if (doDeletePackage) {
18642                    if (!deleteAllUsers) {
18643                        returnCode = deletePackageX(internalPackageName, versionCode,
18644                                userId, deleteFlags);
18645                    } else {
18646                        int[] blockUninstallUserIds = getBlockUninstallForUsers(
18647                                internalPackageName, users);
18648                        // If nobody is blocking uninstall, proceed with delete for all users
18649                        if (ArrayUtils.isEmpty(blockUninstallUserIds)) {
18650                            returnCode = deletePackageX(internalPackageName, versionCode,
18651                                    userId, deleteFlags);
18652                        } else {
18653                            // Otherwise uninstall individually for users with blockUninstalls=false
18654                            final int userFlags = deleteFlags & ~PackageManager.DELETE_ALL_USERS;
18655                            for (int userId : users) {
18656                                if (!ArrayUtils.contains(blockUninstallUserIds, userId)) {
18657                                    returnCode = deletePackageX(internalPackageName, versionCode,
18658                                            userId, userFlags);
18659                                    if (returnCode != PackageManager.DELETE_SUCCEEDED) {
18660                                        Slog.w(TAG, "Package delete failed for user " + userId
18661                                                + ", returnCode " + returnCode);
18662                                    }
18663                                }
18664                            }
18665                            // The app has only been marked uninstalled for certain users.
18666                            // We still need to report that delete was blocked
18667                            returnCode = PackageManager.DELETE_FAILED_OWNER_BLOCKED;
18668                        }
18669                    }
18670                } else {
18671                    returnCode = PackageManager.DELETE_FAILED_INTERNAL_ERROR;
18672                }
18673                try {
18674                    observer.onPackageDeleted(packageName, returnCode, null);
18675                } catch (RemoteException e) {
18676                    Log.i(TAG, "Observer no longer exists.");
18677                } //end catch
18678            } //end run
18679        });
18680    }
18681
18682    private String resolveExternalPackageNameLPr(PackageParser.Package pkg) {
18683        if (pkg.staticSharedLibName != null) {
18684            return pkg.manifestPackageName;
18685        }
18686        return pkg.packageName;
18687    }
18688
18689    private String resolveInternalPackageNameLPr(String packageName, int versionCode) {
18690        // Handle renamed packages
18691        String normalizedPackageName = mSettings.getRenamedPackageLPr(packageName);
18692        packageName = normalizedPackageName != null ? normalizedPackageName : packageName;
18693
18694        // Is this a static library?
18695        SparseArray<SharedLibraryEntry> versionedLib =
18696                mStaticLibsByDeclaringPackage.get(packageName);
18697        if (versionedLib == null || versionedLib.size() <= 0) {
18698            return packageName;
18699        }
18700
18701        // Figure out which lib versions the caller can see
18702        SparseIntArray versionsCallerCanSee = null;
18703        final int callingAppId = UserHandle.getAppId(Binder.getCallingUid());
18704        if (callingAppId != Process.SYSTEM_UID && callingAppId != Process.SHELL_UID
18705                && callingAppId != Process.ROOT_UID) {
18706            versionsCallerCanSee = new SparseIntArray();
18707            String libName = versionedLib.valueAt(0).info.getName();
18708            String[] uidPackages = getPackagesForUid(Binder.getCallingUid());
18709            if (uidPackages != null) {
18710                for (String uidPackage : uidPackages) {
18711                    PackageSetting ps = mSettings.getPackageLPr(uidPackage);
18712                    final int libIdx = ArrayUtils.indexOf(ps.usesStaticLibraries, libName);
18713                    if (libIdx >= 0) {
18714                        final int libVersion = ps.usesStaticLibrariesVersions[libIdx];
18715                        versionsCallerCanSee.append(libVersion, libVersion);
18716                    }
18717                }
18718            }
18719        }
18720
18721        // Caller can see nothing - done
18722        if (versionsCallerCanSee != null && versionsCallerCanSee.size() <= 0) {
18723            return packageName;
18724        }
18725
18726        // Find the version the caller can see and the app version code
18727        SharedLibraryEntry highestVersion = null;
18728        final int versionCount = versionedLib.size();
18729        for (int i = 0; i < versionCount; i++) {
18730            SharedLibraryEntry libEntry = versionedLib.valueAt(i);
18731            if (versionsCallerCanSee != null && versionsCallerCanSee.indexOfKey(
18732                    libEntry.info.getVersion()) < 0) {
18733                continue;
18734            }
18735            final int libVersionCode = libEntry.info.getDeclaringPackage().getVersionCode();
18736            if (versionCode != PackageManager.VERSION_CODE_HIGHEST) {
18737                if (libVersionCode == versionCode) {
18738                    return libEntry.apk;
18739                }
18740            } else if (highestVersion == null) {
18741                highestVersion = libEntry;
18742            } else if (libVersionCode  > highestVersion.info
18743                    .getDeclaringPackage().getVersionCode()) {
18744                highestVersion = libEntry;
18745            }
18746        }
18747
18748        if (highestVersion != null) {
18749            return highestVersion.apk;
18750        }
18751
18752        return packageName;
18753    }
18754
18755    private boolean isCallerAllowedToSilentlyUninstall(int callingUid, String pkgName) {
18756        if (callingUid == Process.SHELL_UID || callingUid == Process.ROOT_UID
18757              || UserHandle.getAppId(callingUid) == Process.SYSTEM_UID) {
18758            return true;
18759        }
18760        final int callingUserId = UserHandle.getUserId(callingUid);
18761        // If the caller installed the pkgName, then allow it to silently uninstall.
18762        if (callingUid == getPackageUid(getInstallerPackageName(pkgName), 0, callingUserId)) {
18763            return true;
18764        }
18765
18766        // Allow package verifier to silently uninstall.
18767        if (mRequiredVerifierPackage != null &&
18768                callingUid == getPackageUid(mRequiredVerifierPackage, 0, callingUserId)) {
18769            return true;
18770        }
18771
18772        // Allow package uninstaller to silently uninstall.
18773        if (mRequiredUninstallerPackage != null &&
18774                callingUid == getPackageUid(mRequiredUninstallerPackage, 0, callingUserId)) {
18775            return true;
18776        }
18777
18778        // Allow storage manager to silently uninstall.
18779        if (mStorageManagerPackage != null &&
18780                callingUid == getPackageUid(mStorageManagerPackage, 0, callingUserId)) {
18781            return true;
18782        }
18783
18784        // Allow caller having MANAGE_PROFILE_AND_DEVICE_OWNERS permission to silently
18785        // uninstall for device owner provisioning.
18786        if (checkUidPermission(MANAGE_PROFILE_AND_DEVICE_OWNERS, callingUid)
18787                == PERMISSION_GRANTED) {
18788            return true;
18789        }
18790
18791        return false;
18792    }
18793
18794    private int[] getBlockUninstallForUsers(String packageName, int[] userIds) {
18795        int[] result = EMPTY_INT_ARRAY;
18796        for (int userId : userIds) {
18797            if (getBlockUninstallForUser(packageName, userId)) {
18798                result = ArrayUtils.appendInt(result, userId);
18799            }
18800        }
18801        return result;
18802    }
18803
18804    @Override
18805    public boolean isPackageDeviceAdminOnAnyUser(String packageName) {
18806        final int callingUid = Binder.getCallingUid();
18807        if (getInstantAppPackageName(callingUid) != null
18808                && !isCallerSameApp(packageName, callingUid)) {
18809            return false;
18810        }
18811        return isPackageDeviceAdmin(packageName, UserHandle.USER_ALL);
18812    }
18813
18814    private boolean isPackageDeviceAdmin(String packageName, int userId) {
18815        IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface(
18816                ServiceManager.getService(Context.DEVICE_POLICY_SERVICE));
18817        try {
18818            if (dpm != null) {
18819                final ComponentName deviceOwnerComponentName = dpm.getDeviceOwnerComponent(
18820                        /* callingUserOnly =*/ false);
18821                final String deviceOwnerPackageName = deviceOwnerComponentName == null ? null
18822                        : deviceOwnerComponentName.getPackageName();
18823                // Does the package contains the device owner?
18824                // TODO Do we have to do it even if userId != UserHandle.USER_ALL?  Otherwise,
18825                // this check is probably not needed, since DO should be registered as a device
18826                // admin on some user too. (Original bug for this: b/17657954)
18827                if (packageName.equals(deviceOwnerPackageName)) {
18828                    return true;
18829                }
18830                // Does it contain a device admin for any user?
18831                int[] users;
18832                if (userId == UserHandle.USER_ALL) {
18833                    users = sUserManager.getUserIds();
18834                } else {
18835                    users = new int[]{userId};
18836                }
18837                for (int i = 0; i < users.length; ++i) {
18838                    if (dpm.packageHasActiveAdmins(packageName, users[i])) {
18839                        return true;
18840                    }
18841                }
18842            }
18843        } catch (RemoteException e) {
18844        }
18845        return false;
18846    }
18847
18848    private boolean shouldKeepUninstalledPackageLPr(String packageName) {
18849        return mKeepUninstalledPackages != null && mKeepUninstalledPackages.contains(packageName);
18850    }
18851
18852    /**
18853     *  This method is an internal method that could be get invoked either
18854     *  to delete an installed package or to clean up a failed installation.
18855     *  After deleting an installed package, a broadcast is sent to notify any
18856     *  listeners that the package has been removed. For cleaning up a failed
18857     *  installation, the broadcast is not necessary since the package's
18858     *  installation wouldn't have sent the initial broadcast either
18859     *  The key steps in deleting a package are
18860     *  deleting the package information in internal structures like mPackages,
18861     *  deleting the packages base directories through installd
18862     *  updating mSettings to reflect current status
18863     *  persisting settings for later use
18864     *  sending a broadcast if necessary
18865     */
18866    int deletePackageX(String packageName, int versionCode, int userId, int deleteFlags) {
18867        final PackageRemovedInfo info = new PackageRemovedInfo(this);
18868        final boolean res;
18869
18870        final int removeUser = (deleteFlags & PackageManager.DELETE_ALL_USERS) != 0
18871                ? UserHandle.USER_ALL : userId;
18872
18873        if (isPackageDeviceAdmin(packageName, removeUser)) {
18874            Slog.w(TAG, "Not removing package " + packageName + ": has active device admin");
18875            return PackageManager.DELETE_FAILED_DEVICE_POLICY_MANAGER;
18876        }
18877
18878        PackageSetting uninstalledPs = null;
18879        PackageParser.Package pkg = null;
18880
18881        // for the uninstall-updates case and restricted profiles, remember the per-
18882        // user handle installed state
18883        int[] allUsers;
18884        synchronized (mPackages) {
18885            uninstalledPs = mSettings.mPackages.get(packageName);
18886            if (uninstalledPs == null) {
18887                Slog.w(TAG, "Not removing non-existent package " + packageName);
18888                return PackageManager.DELETE_FAILED_INTERNAL_ERROR;
18889            }
18890
18891            if (versionCode != PackageManager.VERSION_CODE_HIGHEST
18892                    && uninstalledPs.versionCode != versionCode) {
18893                Slog.w(TAG, "Not removing package " + packageName + " with versionCode "
18894                        + uninstalledPs.versionCode + " != " + versionCode);
18895                return PackageManager.DELETE_FAILED_INTERNAL_ERROR;
18896            }
18897
18898            // Static shared libs can be declared by any package, so let us not
18899            // allow removing a package if it provides a lib others depend on.
18900            pkg = mPackages.get(packageName);
18901
18902            allUsers = sUserManager.getUserIds();
18903
18904            if (pkg != null && pkg.staticSharedLibName != null) {
18905                SharedLibraryEntry libEntry = getSharedLibraryEntryLPr(pkg.staticSharedLibName,
18906                        pkg.staticSharedLibVersion);
18907                if (libEntry != null) {
18908                    for (int currUserId : allUsers) {
18909                        if (removeUser != UserHandle.USER_ALL && removeUser != currUserId) {
18910                            continue;
18911                        }
18912                        List<VersionedPackage> libClientPackages = getPackagesUsingSharedLibraryLPr(
18913                                libEntry.info, 0, currUserId);
18914                        if (!ArrayUtils.isEmpty(libClientPackages)) {
18915                            Slog.w(TAG, "Not removing package " + pkg.manifestPackageName
18916                                    + " hosting lib " + libEntry.info.getName() + " version "
18917                                    + libEntry.info.getVersion() + " used by " + libClientPackages
18918                                    + " for user " + currUserId);
18919                            return PackageManager.DELETE_FAILED_USED_SHARED_LIBRARY;
18920                        }
18921                    }
18922                }
18923            }
18924
18925            info.origUsers = uninstalledPs.queryInstalledUsers(allUsers, true);
18926        }
18927
18928        final int freezeUser;
18929        if (isUpdatedSystemApp(uninstalledPs)
18930                && ((deleteFlags & PackageManager.DELETE_SYSTEM_APP) == 0)) {
18931            // We're downgrading a system app, which will apply to all users, so
18932            // freeze them all during the downgrade
18933            freezeUser = UserHandle.USER_ALL;
18934        } else {
18935            freezeUser = removeUser;
18936        }
18937
18938        synchronized (mInstallLock) {
18939            if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageX: pkg=" + packageName + " user=" + userId);
18940            try (PackageFreezer freezer = freezePackageForDelete(packageName, freezeUser,
18941                    deleteFlags, "deletePackageX")) {
18942                res = deletePackageLIF(packageName, UserHandle.of(removeUser), true, allUsers,
18943                        deleteFlags | FLAGS_REMOVE_CHATTY, info, true, null);
18944            }
18945            synchronized (mPackages) {
18946                if (res) {
18947                    if (pkg != null) {
18948                        mInstantAppRegistry.onPackageUninstalledLPw(pkg, info.removedUsers);
18949                    }
18950                    updateSequenceNumberLP(uninstalledPs, info.removedUsers);
18951                    updateInstantAppInstallerLocked(packageName);
18952                }
18953            }
18954        }
18955
18956        if (res) {
18957            final boolean killApp = (deleteFlags & PackageManager.DELETE_DONT_KILL_APP) == 0;
18958            info.sendPackageRemovedBroadcasts(killApp);
18959            info.sendSystemPackageUpdatedBroadcasts();
18960            info.sendSystemPackageAppearedBroadcasts();
18961        }
18962        // Force a gc here.
18963        Runtime.getRuntime().gc();
18964        // Delete the resources here after sending the broadcast to let
18965        // other processes clean up before deleting resources.
18966        if (info.args != null) {
18967            synchronized (mInstallLock) {
18968                info.args.doPostDeleteLI(true);
18969            }
18970        }
18971
18972        return res ? PackageManager.DELETE_SUCCEEDED : PackageManager.DELETE_FAILED_INTERNAL_ERROR;
18973    }
18974
18975    static class PackageRemovedInfo {
18976        final PackageSender packageSender;
18977        String removedPackage;
18978        String installerPackageName;
18979        int uid = -1;
18980        int removedAppId = -1;
18981        int[] origUsers;
18982        int[] removedUsers = null;
18983        int[] broadcastUsers = null;
18984        SparseArray<Integer> installReasons;
18985        boolean isRemovedPackageSystemUpdate = false;
18986        boolean isUpdate;
18987        boolean dataRemoved;
18988        boolean removedForAllUsers;
18989        boolean isStaticSharedLib;
18990        // Clean up resources deleted packages.
18991        InstallArgs args = null;
18992        ArrayMap<String, PackageRemovedInfo> removedChildPackages;
18993        ArrayMap<String, PackageInstalledInfo> appearedChildPackages;
18994
18995        PackageRemovedInfo(PackageSender packageSender) {
18996            this.packageSender = packageSender;
18997        }
18998
18999        void sendPackageRemovedBroadcasts(boolean killApp) {
19000            sendPackageRemovedBroadcastInternal(killApp);
19001            final int childCount = removedChildPackages != null ? removedChildPackages.size() : 0;
19002            for (int i = 0; i < childCount; i++) {
19003                PackageRemovedInfo childInfo = removedChildPackages.valueAt(i);
19004                childInfo.sendPackageRemovedBroadcastInternal(killApp);
19005            }
19006        }
19007
19008        void sendSystemPackageUpdatedBroadcasts() {
19009            if (isRemovedPackageSystemUpdate) {
19010                sendSystemPackageUpdatedBroadcastsInternal();
19011                final int childCount = (removedChildPackages != null)
19012                        ? removedChildPackages.size() : 0;
19013                for (int i = 0; i < childCount; i++) {
19014                    PackageRemovedInfo childInfo = removedChildPackages.valueAt(i);
19015                    if (childInfo.isRemovedPackageSystemUpdate) {
19016                        childInfo.sendSystemPackageUpdatedBroadcastsInternal();
19017                    }
19018                }
19019            }
19020        }
19021
19022        void sendSystemPackageAppearedBroadcasts() {
19023            final int packageCount = (appearedChildPackages != null)
19024                    ? appearedChildPackages.size() : 0;
19025            for (int i = 0; i < packageCount; i++) {
19026                PackageInstalledInfo installedInfo = appearedChildPackages.valueAt(i);
19027                packageSender.sendPackageAddedForNewUsers(installedInfo.name,
19028                    true, UserHandle.getAppId(installedInfo.uid),
19029                    installedInfo.newUsers);
19030            }
19031        }
19032
19033        private void sendSystemPackageUpdatedBroadcastsInternal() {
19034            Bundle extras = new Bundle(2);
19035            extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid);
19036            extras.putBoolean(Intent.EXTRA_REPLACING, true);
19037            packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
19038                removedPackage, extras, 0, null /*targetPackage*/, null, null);
19039            packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED,
19040                removedPackage, extras, 0, null /*targetPackage*/, null, null);
19041            packageSender.sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED,
19042                null, null, 0, removedPackage, null, null);
19043            if (installerPackageName != null) {
19044                packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
19045                        removedPackage, extras, 0 /*flags*/,
19046                        installerPackageName, null, null);
19047                packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED,
19048                        removedPackage, extras, 0 /*flags*/,
19049                        installerPackageName, null, null);
19050            }
19051        }
19052
19053        private void sendPackageRemovedBroadcastInternal(boolean killApp) {
19054            // Don't send static shared library removal broadcasts as these
19055            // libs are visible only the the apps that depend on them an one
19056            // cannot remove the library if it has a dependency.
19057            if (isStaticSharedLib) {
19058                return;
19059            }
19060            Bundle extras = new Bundle(2);
19061            extras.putInt(Intent.EXTRA_UID, removedAppId >= 0  ? removedAppId : uid);
19062            extras.putBoolean(Intent.EXTRA_DATA_REMOVED, dataRemoved);
19063            extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, !killApp);
19064            if (isUpdate || isRemovedPackageSystemUpdate) {
19065                extras.putBoolean(Intent.EXTRA_REPLACING, true);
19066            }
19067            extras.putBoolean(Intent.EXTRA_REMOVED_FOR_ALL_USERS, removedForAllUsers);
19068            if (removedPackage != null) {
19069                packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED,
19070                    removedPackage, extras, 0, null /*targetPackage*/, null, broadcastUsers);
19071                if (installerPackageName != null) {
19072                    packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED,
19073                            removedPackage, extras, 0 /*flags*/,
19074                            installerPackageName, null, broadcastUsers);
19075                }
19076                if (dataRemoved && !isRemovedPackageSystemUpdate) {
19077                    packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_FULLY_REMOVED,
19078                        removedPackage, extras,
19079                        Intent.FLAG_RECEIVER_INCLUDE_BACKGROUND,
19080                        null, null, broadcastUsers);
19081                }
19082            }
19083            if (removedAppId >= 0) {
19084                packageSender.sendPackageBroadcast(Intent.ACTION_UID_REMOVED,
19085                    null, extras, Intent.FLAG_RECEIVER_INCLUDE_BACKGROUND,
19086                    null, null, broadcastUsers);
19087            }
19088        }
19089
19090        void populateUsers(int[] userIds, PackageSetting deletedPackageSetting) {
19091            removedUsers = userIds;
19092            if (removedUsers == null) {
19093                broadcastUsers = null;
19094                return;
19095            }
19096
19097            broadcastUsers = EMPTY_INT_ARRAY;
19098            for (int i = userIds.length - 1; i >= 0; --i) {
19099                final int userId = userIds[i];
19100                if (deletedPackageSetting.getInstantApp(userId)) {
19101                    continue;
19102                }
19103                broadcastUsers = ArrayUtils.appendInt(broadcastUsers, userId);
19104            }
19105        }
19106    }
19107
19108    /*
19109     * This method deletes the package from internal data structures. If the DONT_DELETE_DATA
19110     * flag is not set, the data directory is removed as well.
19111     * make sure this flag is set for partially installed apps. If not its meaningless to
19112     * delete a partially installed application.
19113     */
19114    private void removePackageDataLIF(PackageSetting ps, int[] allUserHandles,
19115            PackageRemovedInfo outInfo, int flags, boolean writeSettings) {
19116        String packageName = ps.name;
19117        if (DEBUG_REMOVE) Slog.d(TAG, "removePackageDataLI: " + ps);
19118        // Retrieve object to delete permissions for shared user later on
19119        final PackageParser.Package deletedPkg;
19120        final PackageSetting deletedPs;
19121        // reader
19122        synchronized (mPackages) {
19123            deletedPkg = mPackages.get(packageName);
19124            deletedPs = mSettings.mPackages.get(packageName);
19125            if (outInfo != null) {
19126                outInfo.removedPackage = packageName;
19127                outInfo.installerPackageName = ps.installerPackageName;
19128                outInfo.isStaticSharedLib = deletedPkg != null
19129                        && deletedPkg.staticSharedLibName != null;
19130                outInfo.populateUsers(deletedPs == null ? null
19131                        : deletedPs.queryInstalledUsers(sUserManager.getUserIds(), true), deletedPs);
19132            }
19133        }
19134
19135        removePackageLI(ps, (flags & FLAGS_REMOVE_CHATTY) != 0);
19136
19137        if ((flags & PackageManager.DELETE_KEEP_DATA) == 0) {
19138            final PackageParser.Package resolvedPkg;
19139            if (deletedPkg != null) {
19140                resolvedPkg = deletedPkg;
19141            } else {
19142                // We don't have a parsed package when it lives on an ejected
19143                // adopted storage device, so fake something together
19144                resolvedPkg = new PackageParser.Package(ps.name);
19145                resolvedPkg.setVolumeUuid(ps.volumeUuid);
19146            }
19147            destroyAppDataLIF(resolvedPkg, UserHandle.USER_ALL,
19148                    StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
19149            destroyAppProfilesLIF(resolvedPkg, UserHandle.USER_ALL);
19150            if (outInfo != null) {
19151                outInfo.dataRemoved = true;
19152            }
19153            schedulePackageCleaning(packageName, UserHandle.USER_ALL, true);
19154        }
19155
19156        int removedAppId = -1;
19157
19158        // writer
19159        synchronized (mPackages) {
19160            boolean installedStateChanged = false;
19161            if (deletedPs != null) {
19162                if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) {
19163                    clearIntentFilterVerificationsLPw(deletedPs.name, UserHandle.USER_ALL);
19164                    clearDefaultBrowserIfNeeded(packageName);
19165                    mSettings.mKeySetManagerService.removeAppKeySetDataLPw(packageName);
19166                    removedAppId = mSettings.removePackageLPw(packageName);
19167                    if (outInfo != null) {
19168                        outInfo.removedAppId = removedAppId;
19169                    }
19170                    updatePermissionsLPw(deletedPs.name, null, 0);
19171                    if (deletedPs.sharedUser != null) {
19172                        // Remove permissions associated with package. Since runtime
19173                        // permissions are per user we have to kill the removed package
19174                        // or packages running under the shared user of the removed
19175                        // package if revoking the permissions requested only by the removed
19176                        // package is successful and this causes a change in gids.
19177                        for (int userId : UserManagerService.getInstance().getUserIds()) {
19178                            final int userIdToKill = mSettings.updateSharedUserPermsLPw(deletedPs,
19179                                    userId);
19180                            if (userIdToKill == UserHandle.USER_ALL
19181                                    || userIdToKill >= UserHandle.USER_SYSTEM) {
19182                                // If gids changed for this user, kill all affected packages.
19183                                mHandler.post(new Runnable() {
19184                                    @Override
19185                                    public void run() {
19186                                        // This has to happen with no lock held.
19187                                        killApplication(deletedPs.name, deletedPs.appId,
19188                                                KILL_APP_REASON_GIDS_CHANGED);
19189                                    }
19190                                });
19191                                break;
19192                            }
19193                        }
19194                    }
19195                    clearPackagePreferredActivitiesLPw(deletedPs.name, UserHandle.USER_ALL);
19196                }
19197                // make sure to preserve per-user disabled state if this removal was just
19198                // a downgrade of a system app to the factory package
19199                if (allUserHandles != null && outInfo != null && outInfo.origUsers != null) {
19200                    if (DEBUG_REMOVE) {
19201                        Slog.d(TAG, "Propagating install state across downgrade");
19202                    }
19203                    for (int userId : allUserHandles) {
19204                        final boolean installed = ArrayUtils.contains(outInfo.origUsers, userId);
19205                        if (DEBUG_REMOVE) {
19206                            Slog.d(TAG, "    user " + userId + " => " + installed);
19207                        }
19208                        if (installed != ps.getInstalled(userId)) {
19209                            installedStateChanged = true;
19210                        }
19211                        ps.setInstalled(installed, userId);
19212                    }
19213                }
19214            }
19215            // can downgrade to reader
19216            if (writeSettings) {
19217                // Save settings now
19218                mSettings.writeLPr();
19219            }
19220            if (installedStateChanged) {
19221                mSettings.writeKernelMappingLPr(ps);
19222            }
19223        }
19224        if (removedAppId != -1) {
19225            // A user ID was deleted here. Go through all users and remove it
19226            // from KeyStore.
19227            removeKeystoreDataIfNeeded(UserHandle.USER_ALL, removedAppId);
19228        }
19229    }
19230
19231    static boolean locationIsPrivileged(File path) {
19232        try {
19233            final String privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app")
19234                    .getCanonicalPath();
19235            return path.getCanonicalPath().startsWith(privilegedAppDir);
19236        } catch (IOException e) {
19237            Slog.e(TAG, "Unable to access code path " + path);
19238        }
19239        return false;
19240    }
19241
19242    /*
19243     * Tries to delete system package.
19244     */
19245    private boolean deleteSystemPackageLIF(PackageParser.Package deletedPkg,
19246            PackageSetting deletedPs, int[] allUserHandles, int flags, PackageRemovedInfo outInfo,
19247            boolean writeSettings) {
19248        if (deletedPs.parentPackageName != null) {
19249            Slog.w(TAG, "Attempt to delete child system package " + deletedPkg.packageName);
19250            return false;
19251        }
19252
19253        final boolean applyUserRestrictions
19254                = (allUserHandles != null) && (outInfo.origUsers != null);
19255        final PackageSetting disabledPs;
19256        // Confirm if the system package has been updated
19257        // An updated system app can be deleted. This will also have to restore
19258        // the system pkg from system partition
19259        // reader
19260        synchronized (mPackages) {
19261            disabledPs = mSettings.getDisabledSystemPkgLPr(deletedPs.name);
19262        }
19263
19264        if (DEBUG_REMOVE) Slog.d(TAG, "deleteSystemPackageLI: newPs=" + deletedPkg.packageName
19265                + " disabledPs=" + disabledPs);
19266
19267        if (disabledPs == null) {
19268            Slog.w(TAG, "Attempt to delete unknown system package "+ deletedPkg.packageName);
19269            return false;
19270        } else if (DEBUG_REMOVE) {
19271            Slog.d(TAG, "Deleting system pkg from data partition");
19272        }
19273
19274        if (DEBUG_REMOVE) {
19275            if (applyUserRestrictions) {
19276                Slog.d(TAG, "Remembering install states:");
19277                for (int userId : allUserHandles) {
19278                    final boolean finstalled = ArrayUtils.contains(outInfo.origUsers, userId);
19279                    Slog.d(TAG, "   u=" + userId + " inst=" + finstalled);
19280                }
19281            }
19282        }
19283
19284        // Delete the updated package
19285        outInfo.isRemovedPackageSystemUpdate = true;
19286        if (outInfo.removedChildPackages != null) {
19287            final int childCount = (deletedPs.childPackageNames != null)
19288                    ? deletedPs.childPackageNames.size() : 0;
19289            for (int i = 0; i < childCount; i++) {
19290                String childPackageName = deletedPs.childPackageNames.get(i);
19291                if (disabledPs.childPackageNames != null && disabledPs.childPackageNames
19292                        .contains(childPackageName)) {
19293                    PackageRemovedInfo childInfo = outInfo.removedChildPackages.get(
19294                            childPackageName);
19295                    if (childInfo != null) {
19296                        childInfo.isRemovedPackageSystemUpdate = true;
19297                    }
19298                }
19299            }
19300        }
19301
19302        if (disabledPs.versionCode < deletedPs.versionCode) {
19303            // Delete data for downgrades
19304            flags &= ~PackageManager.DELETE_KEEP_DATA;
19305        } else {
19306            // Preserve data by setting flag
19307            flags |= PackageManager.DELETE_KEEP_DATA;
19308        }
19309
19310        boolean ret = deleteInstalledPackageLIF(deletedPs, true, flags, allUserHandles,
19311                outInfo, writeSettings, disabledPs.pkg);
19312        if (!ret) {
19313            return false;
19314        }
19315
19316        // writer
19317        synchronized (mPackages) {
19318            // Reinstate the old system package
19319            enableSystemPackageLPw(disabledPs.pkg);
19320            // Remove any native libraries from the upgraded package.
19321            removeNativeBinariesLI(deletedPs);
19322        }
19323
19324        // Install the system package
19325        if (DEBUG_REMOVE) Slog.d(TAG, "Re-installing system package: " + disabledPs);
19326        int parseFlags = mDefParseFlags
19327                | PackageParser.PARSE_MUST_BE_APK
19328                | PackageParser.PARSE_IS_SYSTEM
19329                | PackageParser.PARSE_IS_SYSTEM_DIR;
19330        if (locationIsPrivileged(disabledPs.codePath)) {
19331            parseFlags |= PackageParser.PARSE_IS_PRIVILEGED;
19332        }
19333
19334        final PackageParser.Package newPkg;
19335        try {
19336            newPkg = scanPackageTracedLI(disabledPs.codePath, parseFlags, 0 /* scanFlags */,
19337                0 /* currentTime */, null);
19338        } catch (PackageManagerException e) {
19339            Slog.w(TAG, "Failed to restore system package:" + deletedPkg.packageName + ": "
19340                    + e.getMessage());
19341            return false;
19342        }
19343
19344        try {
19345            // update shared libraries for the newly re-installed system package
19346            updateSharedLibrariesLPr(newPkg, null);
19347        } catch (PackageManagerException e) {
19348            Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
19349        }
19350
19351        prepareAppDataAfterInstallLIF(newPkg);
19352
19353        // writer
19354        synchronized (mPackages) {
19355            PackageSetting ps = mSettings.mPackages.get(newPkg.packageName);
19356
19357            // Propagate the permissions state as we do not want to drop on the floor
19358            // runtime permissions. The update permissions method below will take
19359            // care of removing obsolete permissions and grant install permissions.
19360            ps.getPermissionsState().copyFrom(deletedPs.getPermissionsState());
19361            updatePermissionsLPw(newPkg.packageName, newPkg,
19362                    UPDATE_PERMISSIONS_ALL | UPDATE_PERMISSIONS_REPLACE_PKG);
19363
19364            if (applyUserRestrictions) {
19365                boolean installedStateChanged = false;
19366                if (DEBUG_REMOVE) {
19367                    Slog.d(TAG, "Propagating install state across reinstall");
19368                }
19369                for (int userId : allUserHandles) {
19370                    final boolean installed = ArrayUtils.contains(outInfo.origUsers, userId);
19371                    if (DEBUG_REMOVE) {
19372                        Slog.d(TAG, "    user " + userId + " => " + installed);
19373                    }
19374                    if (installed != ps.getInstalled(userId)) {
19375                        installedStateChanged = true;
19376                    }
19377                    ps.setInstalled(installed, userId);
19378
19379                    mSettings.writeRuntimePermissionsForUserLPr(userId, false);
19380                }
19381                // Regardless of writeSettings we need to ensure that this restriction
19382                // state propagation is persisted
19383                mSettings.writeAllUsersPackageRestrictionsLPr();
19384                if (installedStateChanged) {
19385                    mSettings.writeKernelMappingLPr(ps);
19386                }
19387            }
19388            // can downgrade to reader here
19389            if (writeSettings) {
19390                mSettings.writeLPr();
19391            }
19392        }
19393        return true;
19394    }
19395
19396    private boolean deleteInstalledPackageLIF(PackageSetting ps,
19397            boolean deleteCodeAndResources, int flags, int[] allUserHandles,
19398            PackageRemovedInfo outInfo, boolean writeSettings,
19399            PackageParser.Package replacingPackage) {
19400        synchronized (mPackages) {
19401            if (outInfo != null) {
19402                outInfo.uid = ps.appId;
19403            }
19404
19405            if (outInfo != null && outInfo.removedChildPackages != null) {
19406                final int childCount = (ps.childPackageNames != null)
19407                        ? ps.childPackageNames.size() : 0;
19408                for (int i = 0; i < childCount; i++) {
19409                    String childPackageName = ps.childPackageNames.get(i);
19410                    PackageSetting childPs = mSettings.mPackages.get(childPackageName);
19411                    if (childPs == null) {
19412                        return false;
19413                    }
19414                    PackageRemovedInfo childInfo = outInfo.removedChildPackages.get(
19415                            childPackageName);
19416                    if (childInfo != null) {
19417                        childInfo.uid = childPs.appId;
19418                    }
19419                }
19420            }
19421        }
19422
19423        // Delete package data from internal structures and also remove data if flag is set
19424        removePackageDataLIF(ps, allUserHandles, outInfo, flags, writeSettings);
19425
19426        // Delete the child packages data
19427        final int childCount = (ps.childPackageNames != null) ? ps.childPackageNames.size() : 0;
19428        for (int i = 0; i < childCount; i++) {
19429            PackageSetting childPs;
19430            synchronized (mPackages) {
19431                childPs = mSettings.getPackageLPr(ps.childPackageNames.get(i));
19432            }
19433            if (childPs != null) {
19434                PackageRemovedInfo childOutInfo = (outInfo != null
19435                        && outInfo.removedChildPackages != null)
19436                        ? outInfo.removedChildPackages.get(childPs.name) : null;
19437                final int deleteFlags = (flags & DELETE_KEEP_DATA) != 0
19438                        && (replacingPackage != null
19439                        && !replacingPackage.hasChildPackage(childPs.name))
19440                        ? flags & ~DELETE_KEEP_DATA : flags;
19441                removePackageDataLIF(childPs, allUserHandles, childOutInfo,
19442                        deleteFlags, writeSettings);
19443            }
19444        }
19445
19446        // Delete application code and resources only for parent packages
19447        if (ps.parentPackageName == null) {
19448            if (deleteCodeAndResources && (outInfo != null)) {
19449                outInfo.args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
19450                        ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
19451                if (DEBUG_SD_INSTALL) Slog.i(TAG, "args=" + outInfo.args);
19452            }
19453        }
19454
19455        return true;
19456    }
19457
19458    @Override
19459    public boolean setBlockUninstallForUser(String packageName, boolean blockUninstall,
19460            int userId) {
19461        mContext.enforceCallingOrSelfPermission(
19462                android.Manifest.permission.DELETE_PACKAGES, null);
19463        synchronized (mPackages) {
19464            // Cannot block uninstall of static shared libs as they are
19465            // considered a part of the using app (emulating static linking).
19466            // Also static libs are installed always on internal storage.
19467            PackageParser.Package pkg = mPackages.get(packageName);
19468            if (pkg != null && pkg.staticSharedLibName != null) {
19469                Slog.w(TAG, "Cannot block uninstall of package: " + packageName
19470                        + " providing static shared library: " + pkg.staticSharedLibName);
19471                return false;
19472            }
19473            mSettings.setBlockUninstallLPw(userId, packageName, blockUninstall);
19474            mSettings.writePackageRestrictionsLPr(userId);
19475        }
19476        return true;
19477    }
19478
19479    @Override
19480    public boolean getBlockUninstallForUser(String packageName, int userId) {
19481        synchronized (mPackages) {
19482            final PackageSetting ps = mSettings.mPackages.get(packageName);
19483            if (ps == null || filterAppAccessLPr(ps, Binder.getCallingUid(), userId)) {
19484                return false;
19485            }
19486            return mSettings.getBlockUninstallLPr(userId, packageName);
19487        }
19488    }
19489
19490    @Override
19491    public boolean setRequiredForSystemUser(String packageName, boolean systemUserApp) {
19492        enforceSystemOrRoot("setRequiredForSystemUser can only be run by the system or root");
19493        synchronized (mPackages) {
19494            PackageSetting ps = mSettings.mPackages.get(packageName);
19495            if (ps == null) {
19496                Log.w(TAG, "Package doesn't exist: " + packageName);
19497                return false;
19498            }
19499            if (systemUserApp) {
19500                ps.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_REQUIRED_FOR_SYSTEM_USER;
19501            } else {
19502                ps.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_REQUIRED_FOR_SYSTEM_USER;
19503            }
19504            mSettings.writeLPr();
19505        }
19506        return true;
19507    }
19508
19509    /*
19510     * This method handles package deletion in general
19511     */
19512    private boolean deletePackageLIF(String packageName, UserHandle user,
19513            boolean deleteCodeAndResources, int[] allUserHandles, int flags,
19514            PackageRemovedInfo outInfo, boolean writeSettings,
19515            PackageParser.Package replacingPackage) {
19516        if (packageName == null) {
19517            Slog.w(TAG, "Attempt to delete null packageName.");
19518            return false;
19519        }
19520
19521        if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageLI: " + packageName + " user " + user);
19522
19523        PackageSetting ps;
19524        synchronized (mPackages) {
19525            ps = mSettings.mPackages.get(packageName);
19526            if (ps == null) {
19527                Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
19528                return false;
19529            }
19530
19531            if (ps.parentPackageName != null && (!isSystemApp(ps)
19532                    || (flags & PackageManager.DELETE_SYSTEM_APP) != 0)) {
19533                if (DEBUG_REMOVE) {
19534                    Slog.d(TAG, "Uninstalled child package:" + packageName + " for user:"
19535                            + ((user == null) ? UserHandle.USER_ALL : user));
19536                }
19537                final int removedUserId = (user != null) ? user.getIdentifier()
19538                        : UserHandle.USER_ALL;
19539                if (!clearPackageStateForUserLIF(ps, removedUserId, outInfo)) {
19540                    return false;
19541                }
19542                markPackageUninstalledForUserLPw(ps, user);
19543                scheduleWritePackageRestrictionsLocked(user);
19544                return true;
19545            }
19546        }
19547
19548        if (((!isSystemApp(ps) || (flags&PackageManager.DELETE_SYSTEM_APP) != 0) && user != null
19549                && user.getIdentifier() != UserHandle.USER_ALL)) {
19550            // The caller is asking that the package only be deleted for a single
19551            // user.  To do this, we just mark its uninstalled state and delete
19552            // its data. If this is a system app, we only allow this to happen if
19553            // they have set the special DELETE_SYSTEM_APP which requests different
19554            // semantics than normal for uninstalling system apps.
19555            markPackageUninstalledForUserLPw(ps, user);
19556
19557            if (!isSystemApp(ps)) {
19558                // Do not uninstall the APK if an app should be cached
19559                boolean keepUninstalledPackage = shouldKeepUninstalledPackageLPr(packageName);
19560                if (ps.isAnyInstalled(sUserManager.getUserIds()) || keepUninstalledPackage) {
19561                    // Other user still have this package installed, so all
19562                    // we need to do is clear this user's data and save that
19563                    // it is uninstalled.
19564                    if (DEBUG_REMOVE) Slog.d(TAG, "Still installed by other users");
19565                    if (!clearPackageStateForUserLIF(ps, user.getIdentifier(), outInfo)) {
19566                        return false;
19567                    }
19568                    scheduleWritePackageRestrictionsLocked(user);
19569                    return true;
19570                } else {
19571                    // We need to set it back to 'installed' so the uninstall
19572                    // broadcasts will be sent correctly.
19573                    if (DEBUG_REMOVE) Slog.d(TAG, "Not installed by other users, full delete");
19574                    ps.setInstalled(true, user.getIdentifier());
19575                    mSettings.writeKernelMappingLPr(ps);
19576                }
19577            } else {
19578                // This is a system app, so we assume that the
19579                // other users still have this package installed, so all
19580                // we need to do is clear this user's data and save that
19581                // it is uninstalled.
19582                if (DEBUG_REMOVE) Slog.d(TAG, "Deleting system app");
19583                if (!clearPackageStateForUserLIF(ps, user.getIdentifier(), outInfo)) {
19584                    return false;
19585                }
19586                scheduleWritePackageRestrictionsLocked(user);
19587                return true;
19588            }
19589        }
19590
19591        // If we are deleting a composite package for all users, keep track
19592        // of result for each child.
19593        if (ps.childPackageNames != null && outInfo != null) {
19594            synchronized (mPackages) {
19595                final int childCount = ps.childPackageNames.size();
19596                outInfo.removedChildPackages = new ArrayMap<>(childCount);
19597                for (int i = 0; i < childCount; i++) {
19598                    String childPackageName = ps.childPackageNames.get(i);
19599                    PackageRemovedInfo childInfo = new PackageRemovedInfo(this);
19600                    childInfo.removedPackage = childPackageName;
19601                    childInfo.installerPackageName = ps.installerPackageName;
19602                    outInfo.removedChildPackages.put(childPackageName, childInfo);
19603                    PackageSetting childPs = mSettings.getPackageLPr(childPackageName);
19604                    if (childPs != null) {
19605                        childInfo.origUsers = childPs.queryInstalledUsers(allUserHandles, true);
19606                    }
19607                }
19608            }
19609        }
19610
19611        boolean ret = false;
19612        if (isSystemApp(ps)) {
19613            if (DEBUG_REMOVE) Slog.d(TAG, "Removing system package: " + ps.name);
19614            // When an updated system application is deleted we delete the existing resources
19615            // as well and fall back to existing code in system partition
19616            ret = deleteSystemPackageLIF(ps.pkg, ps, allUserHandles, flags, outInfo, writeSettings);
19617        } else {
19618            if (DEBUG_REMOVE) Slog.d(TAG, "Removing non-system package: " + ps.name);
19619            ret = deleteInstalledPackageLIF(ps, deleteCodeAndResources, flags, allUserHandles,
19620                    outInfo, writeSettings, replacingPackage);
19621        }
19622
19623        // Take a note whether we deleted the package for all users
19624        if (outInfo != null) {
19625            outInfo.removedForAllUsers = mPackages.get(ps.name) == null;
19626            if (outInfo.removedChildPackages != null) {
19627                synchronized (mPackages) {
19628                    final int childCount = outInfo.removedChildPackages.size();
19629                    for (int i = 0; i < childCount; i++) {
19630                        PackageRemovedInfo childInfo = outInfo.removedChildPackages.valueAt(i);
19631                        if (childInfo != null) {
19632                            childInfo.removedForAllUsers = mPackages.get(
19633                                    childInfo.removedPackage) == null;
19634                        }
19635                    }
19636                }
19637            }
19638            // If we uninstalled an update to a system app there may be some
19639            // child packages that appeared as they are declared in the system
19640            // app but were not declared in the update.
19641            if (isSystemApp(ps)) {
19642                synchronized (mPackages) {
19643                    PackageSetting updatedPs = mSettings.getPackageLPr(ps.name);
19644                    final int childCount = (updatedPs.childPackageNames != null)
19645                            ? updatedPs.childPackageNames.size() : 0;
19646                    for (int i = 0; i < childCount; i++) {
19647                        String childPackageName = updatedPs.childPackageNames.get(i);
19648                        if (outInfo.removedChildPackages == null
19649                                || outInfo.removedChildPackages.indexOfKey(childPackageName) < 0) {
19650                            PackageSetting childPs = mSettings.getPackageLPr(childPackageName);
19651                            if (childPs == null) {
19652                                continue;
19653                            }
19654                            PackageInstalledInfo installRes = new PackageInstalledInfo();
19655                            installRes.name = childPackageName;
19656                            installRes.newUsers = childPs.queryInstalledUsers(allUserHandles, true);
19657                            installRes.pkg = mPackages.get(childPackageName);
19658                            installRes.uid = childPs.pkg.applicationInfo.uid;
19659                            if (outInfo.appearedChildPackages == null) {
19660                                outInfo.appearedChildPackages = new ArrayMap<>();
19661                            }
19662                            outInfo.appearedChildPackages.put(childPackageName, installRes);
19663                        }
19664                    }
19665                }
19666            }
19667        }
19668
19669        return ret;
19670    }
19671
19672    private void markPackageUninstalledForUserLPw(PackageSetting ps, UserHandle user) {
19673        final int[] userIds = (user == null || user.getIdentifier() == UserHandle.USER_ALL)
19674                ? sUserManager.getUserIds() : new int[] {user.getIdentifier()};
19675        for (int nextUserId : userIds) {
19676            if (DEBUG_REMOVE) {
19677                Slog.d(TAG, "Marking package:" + ps.name + " uninstalled for user:" + nextUserId);
19678            }
19679            ps.setUserState(nextUserId, 0, COMPONENT_ENABLED_STATE_DEFAULT,
19680                    false /*installed*/,
19681                    true /*stopped*/,
19682                    true /*notLaunched*/,
19683                    false /*hidden*/,
19684                    false /*suspended*/,
19685                    false /*instantApp*/,
19686                    null /*lastDisableAppCaller*/,
19687                    null /*enabledComponents*/,
19688                    null /*disabledComponents*/,
19689                    ps.readUserState(nextUserId).domainVerificationStatus,
19690                    0, PackageManager.INSTALL_REASON_UNKNOWN);
19691        }
19692        mSettings.writeKernelMappingLPr(ps);
19693    }
19694
19695    private boolean clearPackageStateForUserLIF(PackageSetting ps, int userId,
19696            PackageRemovedInfo outInfo) {
19697        final PackageParser.Package pkg;
19698        synchronized (mPackages) {
19699            pkg = mPackages.get(ps.name);
19700        }
19701
19702        final int[] userIds = (userId == UserHandle.USER_ALL) ? sUserManager.getUserIds()
19703                : new int[] {userId};
19704        for (int nextUserId : userIds) {
19705            if (DEBUG_REMOVE) {
19706                Slog.d(TAG, "Updating package:" + ps.name + " install state for user:"
19707                        + nextUserId);
19708            }
19709
19710            destroyAppDataLIF(pkg, userId,
19711                    StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
19712            destroyAppProfilesLIF(pkg, userId);
19713            clearDefaultBrowserIfNeededForUser(ps.name, userId);
19714            removeKeystoreDataIfNeeded(nextUserId, ps.appId);
19715            schedulePackageCleaning(ps.name, nextUserId, false);
19716            synchronized (mPackages) {
19717                if (clearPackagePreferredActivitiesLPw(ps.name, nextUserId)) {
19718                    scheduleWritePackageRestrictionsLocked(nextUserId);
19719                }
19720                resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, nextUserId);
19721            }
19722        }
19723
19724        if (outInfo != null) {
19725            outInfo.removedPackage = ps.name;
19726            outInfo.installerPackageName = ps.installerPackageName;
19727            outInfo.isStaticSharedLib = pkg != null && pkg.staticSharedLibName != null;
19728            outInfo.removedAppId = ps.appId;
19729            outInfo.removedUsers = userIds;
19730            outInfo.broadcastUsers = userIds;
19731        }
19732
19733        return true;
19734    }
19735
19736    private final class ClearStorageConnection implements ServiceConnection {
19737        IMediaContainerService mContainerService;
19738
19739        @Override
19740        public void onServiceConnected(ComponentName name, IBinder service) {
19741            synchronized (this) {
19742                mContainerService = IMediaContainerService.Stub
19743                        .asInterface(Binder.allowBlocking(service));
19744                notifyAll();
19745            }
19746        }
19747
19748        @Override
19749        public void onServiceDisconnected(ComponentName name) {
19750        }
19751    }
19752
19753    private void clearExternalStorageDataSync(String packageName, int userId, boolean allData) {
19754        if (DEFAULT_CONTAINER_PACKAGE.equals(packageName)) return;
19755
19756        final boolean mounted;
19757        if (Environment.isExternalStorageEmulated()) {
19758            mounted = true;
19759        } else {
19760            final String status = Environment.getExternalStorageState();
19761
19762            mounted = status.equals(Environment.MEDIA_MOUNTED)
19763                    || status.equals(Environment.MEDIA_MOUNTED_READ_ONLY);
19764        }
19765
19766        if (!mounted) {
19767            return;
19768        }
19769
19770        final Intent containerIntent = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
19771        int[] users;
19772        if (userId == UserHandle.USER_ALL) {
19773            users = sUserManager.getUserIds();
19774        } else {
19775            users = new int[] { userId };
19776        }
19777        final ClearStorageConnection conn = new ClearStorageConnection();
19778        if (mContext.bindServiceAsUser(
19779                containerIntent, conn, Context.BIND_AUTO_CREATE, UserHandle.SYSTEM)) {
19780            try {
19781                for (int curUser : users) {
19782                    long timeout = SystemClock.uptimeMillis() + 5000;
19783                    synchronized (conn) {
19784                        long now;
19785                        while (conn.mContainerService == null &&
19786                                (now = SystemClock.uptimeMillis()) < timeout) {
19787                            try {
19788                                conn.wait(timeout - now);
19789                            } catch (InterruptedException e) {
19790                            }
19791                        }
19792                    }
19793                    if (conn.mContainerService == null) {
19794                        return;
19795                    }
19796
19797                    final UserEnvironment userEnv = new UserEnvironment(curUser);
19798                    clearDirectory(conn.mContainerService,
19799                            userEnv.buildExternalStorageAppCacheDirs(packageName));
19800                    if (allData) {
19801                        clearDirectory(conn.mContainerService,
19802                                userEnv.buildExternalStorageAppDataDirs(packageName));
19803                        clearDirectory(conn.mContainerService,
19804                                userEnv.buildExternalStorageAppMediaDirs(packageName));
19805                    }
19806                }
19807            } finally {
19808                mContext.unbindService(conn);
19809            }
19810        }
19811    }
19812
19813    @Override
19814    public void clearApplicationProfileData(String packageName) {
19815        enforceSystemOrRoot("Only the system can clear all profile data");
19816
19817        final PackageParser.Package pkg;
19818        synchronized (mPackages) {
19819            pkg = mPackages.get(packageName);
19820        }
19821
19822        try (PackageFreezer freezer = freezePackage(packageName, "clearApplicationProfileData")) {
19823            synchronized (mInstallLock) {
19824                clearAppProfilesLIF(pkg, UserHandle.USER_ALL);
19825            }
19826        }
19827    }
19828
19829    @Override
19830    public void clearApplicationUserData(final String packageName,
19831            final IPackageDataObserver observer, final int userId) {
19832        mContext.enforceCallingOrSelfPermission(
19833                android.Manifest.permission.CLEAR_APP_USER_DATA, null);
19834
19835        final int callingUid = Binder.getCallingUid();
19836        enforceCrossUserPermission(callingUid, userId,
19837                true /* requireFullPermission */, false /* checkShell */, "clear application data");
19838
19839        final PackageSetting ps = mSettings.getPackageLPr(packageName);
19840        if (ps != null && filterAppAccessLPr(ps, callingUid, userId)) {
19841            return;
19842        }
19843        if (mProtectedPackages.isPackageDataProtected(userId, packageName)) {
19844            throw new SecurityException("Cannot clear data for a protected package: "
19845                    + packageName);
19846        }
19847        // Queue up an async operation since the package deletion may take a little while.
19848        mHandler.post(new Runnable() {
19849            public void run() {
19850                mHandler.removeCallbacks(this);
19851                final boolean succeeded;
19852                try (PackageFreezer freezer = freezePackage(packageName,
19853                        "clearApplicationUserData")) {
19854                    synchronized (mInstallLock) {
19855                        succeeded = clearApplicationUserDataLIF(packageName, userId);
19856                    }
19857                    clearExternalStorageDataSync(packageName, userId, true);
19858                    synchronized (mPackages) {
19859                        mInstantAppRegistry.deleteInstantApplicationMetadataLPw(
19860                                packageName, userId);
19861                    }
19862                }
19863                if (succeeded) {
19864                    // invoke DeviceStorageMonitor's update method to clear any notifications
19865                    DeviceStorageMonitorInternal dsm = LocalServices
19866                            .getService(DeviceStorageMonitorInternal.class);
19867                    if (dsm != null) {
19868                        dsm.checkMemory();
19869                    }
19870                }
19871                if(observer != null) {
19872                    try {
19873                        observer.onRemoveCompleted(packageName, succeeded);
19874                    } catch (RemoteException e) {
19875                        Log.i(TAG, "Observer no longer exists.");
19876                    }
19877                } //end if observer
19878            } //end run
19879        });
19880    }
19881
19882    private boolean clearApplicationUserDataLIF(String packageName, int userId) {
19883        if (packageName == null) {
19884            Slog.w(TAG, "Attempt to delete null packageName.");
19885            return false;
19886        }
19887
19888        // Try finding details about the requested package
19889        PackageParser.Package pkg;
19890        synchronized (mPackages) {
19891            pkg = mPackages.get(packageName);
19892            if (pkg == null) {
19893                final PackageSetting ps = mSettings.mPackages.get(packageName);
19894                if (ps != null) {
19895                    pkg = ps.pkg;
19896                }
19897            }
19898
19899            if (pkg == null) {
19900                Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
19901                return false;
19902            }
19903
19904            PackageSetting ps = (PackageSetting) pkg.mExtras;
19905            resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
19906        }
19907
19908        clearAppDataLIF(pkg, userId,
19909                StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
19910
19911        final int appId = UserHandle.getAppId(pkg.applicationInfo.uid);
19912        removeKeystoreDataIfNeeded(userId, appId);
19913
19914        UserManagerInternal umInternal = getUserManagerInternal();
19915        final int flags;
19916        if (umInternal.isUserUnlockingOrUnlocked(userId)) {
19917            flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
19918        } else if (umInternal.isUserRunning(userId)) {
19919            flags = StorageManager.FLAG_STORAGE_DE;
19920        } else {
19921            flags = 0;
19922        }
19923        prepareAppDataContentsLIF(pkg, userId, flags);
19924
19925        return true;
19926    }
19927
19928    /**
19929     * Reverts user permission state changes (permissions and flags) in
19930     * all packages for a given user.
19931     *
19932     * @param userId The device user for which to do a reset.
19933     */
19934    private void resetUserChangesToRuntimePermissionsAndFlagsLPw(int userId) {
19935        final int packageCount = mPackages.size();
19936        for (int i = 0; i < packageCount; i++) {
19937            PackageParser.Package pkg = mPackages.valueAt(i);
19938            PackageSetting ps = (PackageSetting) pkg.mExtras;
19939            resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
19940        }
19941    }
19942
19943    private void resetNetworkPolicies(int userId) {
19944        LocalServices.getService(NetworkPolicyManagerInternal.class).resetUserState(userId);
19945    }
19946
19947    /**
19948     * Reverts user permission state changes (permissions and flags).
19949     *
19950     * @param ps The package for which to reset.
19951     * @param userId The device user for which to do a reset.
19952     */
19953    private void resetUserChangesToRuntimePermissionsAndFlagsLPw(
19954            final PackageSetting ps, final int userId) {
19955        if (ps.pkg == null) {
19956            return;
19957        }
19958
19959        // These are flags that can change base on user actions.
19960        final int userSettableMask = FLAG_PERMISSION_USER_SET
19961                | FLAG_PERMISSION_USER_FIXED
19962                | FLAG_PERMISSION_REVOKE_ON_UPGRADE
19963                | FLAG_PERMISSION_REVIEW_REQUIRED;
19964
19965        final int policyOrSystemFlags = FLAG_PERMISSION_SYSTEM_FIXED
19966                | FLAG_PERMISSION_POLICY_FIXED;
19967
19968        boolean writeInstallPermissions = false;
19969        boolean writeRuntimePermissions = false;
19970
19971        final int permissionCount = ps.pkg.requestedPermissions.size();
19972        for (int i = 0; i < permissionCount; i++) {
19973            String permission = ps.pkg.requestedPermissions.get(i);
19974
19975            BasePermission bp = mSettings.mPermissions.get(permission);
19976            if (bp == null) {
19977                continue;
19978            }
19979
19980            // If shared user we just reset the state to which only this app contributed.
19981            if (ps.sharedUser != null) {
19982                boolean used = false;
19983                final int packageCount = ps.sharedUser.packages.size();
19984                for (int j = 0; j < packageCount; j++) {
19985                    PackageSetting pkg = ps.sharedUser.packages.valueAt(j);
19986                    if (pkg.pkg != null && !pkg.pkg.packageName.equals(ps.pkg.packageName)
19987                            && pkg.pkg.requestedPermissions.contains(permission)) {
19988                        used = true;
19989                        break;
19990                    }
19991                }
19992                if (used) {
19993                    continue;
19994                }
19995            }
19996
19997            PermissionsState permissionsState = ps.getPermissionsState();
19998
19999            final int oldFlags = permissionsState.getPermissionFlags(bp.name, userId);
20000
20001            // Always clear the user settable flags.
20002            final boolean hasInstallState = permissionsState.getInstallPermissionState(
20003                    bp.name) != null;
20004            // If permission review is enabled and this is a legacy app, mark the
20005            // permission as requiring a review as this is the initial state.
20006            int flags = 0;
20007            if (mPermissionReviewRequired
20008                    && ps.pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) {
20009                flags |= FLAG_PERMISSION_REVIEW_REQUIRED;
20010            }
20011            if (permissionsState.updatePermissionFlags(bp, userId, userSettableMask, flags)) {
20012                if (hasInstallState) {
20013                    writeInstallPermissions = true;
20014                } else {
20015                    writeRuntimePermissions = true;
20016                }
20017            }
20018
20019            // Below is only runtime permission handling.
20020            if (!bp.isRuntime()) {
20021                continue;
20022            }
20023
20024            // Never clobber system or policy.
20025            if ((oldFlags & policyOrSystemFlags) != 0) {
20026                continue;
20027            }
20028
20029            // If this permission was granted by default, make sure it is.
20030            if ((oldFlags & FLAG_PERMISSION_GRANTED_BY_DEFAULT) != 0) {
20031                if (permissionsState.grantRuntimePermission(bp, userId)
20032                        != PERMISSION_OPERATION_FAILURE) {
20033                    writeRuntimePermissions = true;
20034                }
20035            // If permission review is enabled the permissions for a legacy apps
20036            // are represented as constantly granted runtime ones, so don't revoke.
20037            } else if ((flags & FLAG_PERMISSION_REVIEW_REQUIRED) == 0) {
20038                // Otherwise, reset the permission.
20039                final int revokeResult = permissionsState.revokeRuntimePermission(bp, userId);
20040                switch (revokeResult) {
20041                    case PERMISSION_OPERATION_SUCCESS:
20042                    case PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: {
20043                        writeRuntimePermissions = true;
20044                        final int appId = ps.appId;
20045                        mHandler.post(new Runnable() {
20046                            @Override
20047                            public void run() {
20048                                killUid(appId, userId, KILL_APP_REASON_PERMISSIONS_REVOKED);
20049                            }
20050                        });
20051                    } break;
20052                }
20053            }
20054        }
20055
20056        // Synchronously write as we are taking permissions away.
20057        if (writeRuntimePermissions) {
20058            mSettings.writeRuntimePermissionsForUserLPr(userId, true);
20059        }
20060
20061        // Synchronously write as we are taking permissions away.
20062        if (writeInstallPermissions) {
20063            mSettings.writeLPr();
20064        }
20065    }
20066
20067    /**
20068     * Remove entries from the keystore daemon. Will only remove it if the
20069     * {@code appId} is valid.
20070     */
20071    private static void removeKeystoreDataIfNeeded(int userId, int appId) {
20072        if (appId < 0) {
20073            return;
20074        }
20075
20076        final KeyStore keyStore = KeyStore.getInstance();
20077        if (keyStore != null) {
20078            if (userId == UserHandle.USER_ALL) {
20079                for (final int individual : sUserManager.getUserIds()) {
20080                    keyStore.clearUid(UserHandle.getUid(individual, appId));
20081                }
20082            } else {
20083                keyStore.clearUid(UserHandle.getUid(userId, appId));
20084            }
20085        } else {
20086            Slog.w(TAG, "Could not contact keystore to clear entries for app id " + appId);
20087        }
20088    }
20089
20090    @Override
20091    public void deleteApplicationCacheFiles(final String packageName,
20092            final IPackageDataObserver observer) {
20093        final int userId = UserHandle.getCallingUserId();
20094        deleteApplicationCacheFilesAsUser(packageName, userId, observer);
20095    }
20096
20097    @Override
20098    public void deleteApplicationCacheFilesAsUser(final String packageName, final int userId,
20099            final IPackageDataObserver observer) {
20100        final int callingUid = Binder.getCallingUid();
20101        mContext.enforceCallingOrSelfPermission(
20102                android.Manifest.permission.DELETE_CACHE_FILES, null);
20103        enforceCrossUserPermission(callingUid, userId,
20104                /* requireFullPermission= */ true, /* checkShell= */ false,
20105                "delete application cache files");
20106        final int hasAccessInstantApps = mContext.checkCallingOrSelfPermission(
20107                android.Manifest.permission.ACCESS_INSTANT_APPS);
20108
20109        final PackageParser.Package pkg;
20110        synchronized (mPackages) {
20111            pkg = mPackages.get(packageName);
20112        }
20113
20114        // Queue up an async operation since the package deletion may take a little while.
20115        mHandler.post(new Runnable() {
20116            public void run() {
20117                final PackageSetting ps = pkg == null ? null : (PackageSetting) pkg.mExtras;
20118                boolean doClearData = true;
20119                if (ps != null) {
20120                    final boolean targetIsInstantApp =
20121                            ps.getInstantApp(UserHandle.getUserId(callingUid));
20122                    doClearData = !targetIsInstantApp
20123                            || hasAccessInstantApps == PackageManager.PERMISSION_GRANTED;
20124                }
20125                if (doClearData) {
20126                    synchronized (mInstallLock) {
20127                        final int flags = StorageManager.FLAG_STORAGE_DE
20128                                | StorageManager.FLAG_STORAGE_CE;
20129                        // We're only clearing cache files, so we don't care if the
20130                        // app is unfrozen and still able to run
20131                        clearAppDataLIF(pkg, userId, flags | Installer.FLAG_CLEAR_CACHE_ONLY);
20132                        clearAppDataLIF(pkg, userId, flags | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
20133                    }
20134                    clearExternalStorageDataSync(packageName, userId, false);
20135                }
20136                if (observer != null) {
20137                    try {
20138                        observer.onRemoveCompleted(packageName, true);
20139                    } catch (RemoteException e) {
20140                        Log.i(TAG, "Observer no longer exists.");
20141                    }
20142                }
20143            }
20144        });
20145    }
20146
20147    @Override
20148    public void getPackageSizeInfo(final String packageName, int userHandle,
20149            final IPackageStatsObserver observer) {
20150        throw new UnsupportedOperationException(
20151                "Shame on you for calling the hidden API getPackageSizeInfo(). Shame!");
20152    }
20153
20154    private boolean getPackageSizeInfoLI(String packageName, int userId, PackageStats stats) {
20155        final PackageSetting ps;
20156        synchronized (mPackages) {
20157            ps = mSettings.mPackages.get(packageName);
20158            if (ps == null) {
20159                Slog.w(TAG, "Failed to find settings for " + packageName);
20160                return false;
20161            }
20162        }
20163
20164        final String[] packageNames = { packageName };
20165        final long[] ceDataInodes = { ps.getCeDataInode(userId) };
20166        final String[] codePaths = { ps.codePathString };
20167
20168        try {
20169            mInstaller.getAppSize(ps.volumeUuid, packageNames, userId, 0,
20170                    ps.appId, ceDataInodes, codePaths, stats);
20171
20172            // For now, ignore code size of packages on system partition
20173            if (isSystemApp(ps) && !isUpdatedSystemApp(ps)) {
20174                stats.codeSize = 0;
20175            }
20176
20177            // External clients expect these to be tracked separately
20178            stats.dataSize -= stats.cacheSize;
20179
20180        } catch (InstallerException e) {
20181            Slog.w(TAG, String.valueOf(e));
20182            return false;
20183        }
20184
20185        return true;
20186    }
20187
20188    private int getUidTargetSdkVersionLockedLPr(int uid) {
20189        Object obj = mSettings.getUserIdLPr(uid);
20190        if (obj instanceof SharedUserSetting) {
20191            final SharedUserSetting sus = (SharedUserSetting) obj;
20192            int vers = Build.VERSION_CODES.CUR_DEVELOPMENT;
20193            final Iterator<PackageSetting> it = sus.packages.iterator();
20194            while (it.hasNext()) {
20195                final PackageSetting ps = it.next();
20196                if (ps.pkg != null) {
20197                    int v = ps.pkg.applicationInfo.targetSdkVersion;
20198                    if (v < vers) vers = v;
20199                }
20200            }
20201            return vers;
20202        } else if (obj instanceof PackageSetting) {
20203            final PackageSetting ps = (PackageSetting) obj;
20204            if (ps.pkg != null) {
20205                return ps.pkg.applicationInfo.targetSdkVersion;
20206            }
20207        }
20208        return Build.VERSION_CODES.CUR_DEVELOPMENT;
20209    }
20210
20211    @Override
20212    public void addPreferredActivity(IntentFilter filter, int match,
20213            ComponentName[] set, ComponentName activity, int userId) {
20214        addPreferredActivityInternal(filter, match, set, activity, true, userId,
20215                "Adding preferred");
20216    }
20217
20218    private void addPreferredActivityInternal(IntentFilter filter, int match,
20219            ComponentName[] set, ComponentName activity, boolean always, int userId,
20220            String opname) {
20221        // writer
20222        int callingUid = Binder.getCallingUid();
20223        enforceCrossUserPermission(callingUid, userId,
20224                true /* requireFullPermission */, false /* checkShell */, "add preferred activity");
20225        if (filter.countActions() == 0) {
20226            Slog.w(TAG, "Cannot set a preferred activity with no filter actions");
20227            return;
20228        }
20229        synchronized (mPackages) {
20230            if (mContext.checkCallingOrSelfPermission(
20231                    android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
20232                    != PackageManager.PERMISSION_GRANTED) {
20233                if (getUidTargetSdkVersionLockedLPr(callingUid)
20234                        < Build.VERSION_CODES.FROYO) {
20235                    Slog.w(TAG, "Ignoring addPreferredActivity() from uid "
20236                            + callingUid);
20237                    return;
20238                }
20239                mContext.enforceCallingOrSelfPermission(
20240                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
20241            }
20242
20243            PreferredIntentResolver pir = mSettings.editPreferredActivitiesLPw(userId);
20244            Slog.i(TAG, opname + " activity " + activity.flattenToShortString() + " for user "
20245                    + userId + ":");
20246            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
20247            pir.addFilter(new PreferredActivity(filter, match, set, activity, always));
20248            scheduleWritePackageRestrictionsLocked(userId);
20249            postPreferredActivityChangedBroadcast(userId);
20250        }
20251    }
20252
20253    private void postPreferredActivityChangedBroadcast(int userId) {
20254        mHandler.post(() -> {
20255            final IActivityManager am = ActivityManager.getService();
20256            if (am == null) {
20257                return;
20258            }
20259
20260            final Intent intent = new Intent(Intent.ACTION_PREFERRED_ACTIVITY_CHANGED);
20261            intent.putExtra(Intent.EXTRA_USER_HANDLE, userId);
20262            try {
20263                am.broadcastIntent(null, intent, null, null,
20264                        0, null, null, null, android.app.AppOpsManager.OP_NONE,
20265                        null, false, false, userId);
20266            } catch (RemoteException e) {
20267            }
20268        });
20269    }
20270
20271    @Override
20272    public void replacePreferredActivity(IntentFilter filter, int match,
20273            ComponentName[] set, ComponentName activity, int userId) {
20274        if (filter.countActions() != 1) {
20275            throw new IllegalArgumentException(
20276                    "replacePreferredActivity expects filter to have only 1 action.");
20277        }
20278        if (filter.countDataAuthorities() != 0
20279                || filter.countDataPaths() != 0
20280                || filter.countDataSchemes() > 1
20281                || filter.countDataTypes() != 0) {
20282            throw new IllegalArgumentException(
20283                    "replacePreferredActivity expects filter to have no data authorities, " +
20284                    "paths, or types; and at most one scheme.");
20285        }
20286
20287        final int callingUid = Binder.getCallingUid();
20288        enforceCrossUserPermission(callingUid, userId,
20289                true /* requireFullPermission */, false /* checkShell */,
20290                "replace preferred activity");
20291        synchronized (mPackages) {
20292            if (mContext.checkCallingOrSelfPermission(
20293                    android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
20294                    != PackageManager.PERMISSION_GRANTED) {
20295                if (getUidTargetSdkVersionLockedLPr(callingUid)
20296                        < Build.VERSION_CODES.FROYO) {
20297                    Slog.w(TAG, "Ignoring replacePreferredActivity() from uid "
20298                            + Binder.getCallingUid());
20299                    return;
20300                }
20301                mContext.enforceCallingOrSelfPermission(
20302                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
20303            }
20304
20305            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
20306            if (pir != null) {
20307                // Get all of the existing entries that exactly match this filter.
20308                ArrayList<PreferredActivity> existing = pir.findFilters(filter);
20309                if (existing != null && existing.size() == 1) {
20310                    PreferredActivity cur = existing.get(0);
20311                    if (DEBUG_PREFERRED) {
20312                        Slog.i(TAG, "Checking replace of preferred:");
20313                        filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
20314                        if (!cur.mPref.mAlways) {
20315                            Slog.i(TAG, "  -- CUR; not mAlways!");
20316                        } else {
20317                            Slog.i(TAG, "  -- CUR: mMatch=" + cur.mPref.mMatch);
20318                            Slog.i(TAG, "  -- CUR: mSet="
20319                                    + Arrays.toString(cur.mPref.mSetComponents));
20320                            Slog.i(TAG, "  -- CUR: mComponent=" + cur.mPref.mShortComponent);
20321                            Slog.i(TAG, "  -- NEW: mMatch="
20322                                    + (match&IntentFilter.MATCH_CATEGORY_MASK));
20323                            Slog.i(TAG, "  -- CUR: mSet=" + Arrays.toString(set));
20324                            Slog.i(TAG, "  -- CUR: mComponent=" + activity.flattenToShortString());
20325                        }
20326                    }
20327                    if (cur.mPref.mAlways && cur.mPref.mComponent.equals(activity)
20328                            && cur.mPref.mMatch == (match&IntentFilter.MATCH_CATEGORY_MASK)
20329                            && cur.mPref.sameSet(set)) {
20330                        // Setting the preferred activity to what it happens to be already
20331                        if (DEBUG_PREFERRED) {
20332                            Slog.i(TAG, "Replacing with same preferred activity "
20333                                    + cur.mPref.mShortComponent + " for user "
20334                                    + userId + ":");
20335                            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
20336                        }
20337                        return;
20338                    }
20339                }
20340
20341                if (existing != null) {
20342                    if (DEBUG_PREFERRED) {
20343                        Slog.i(TAG, existing.size() + " existing preferred matches for:");
20344                        filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
20345                    }
20346                    for (int i = 0; i < existing.size(); i++) {
20347                        PreferredActivity pa = existing.get(i);
20348                        if (DEBUG_PREFERRED) {
20349                            Slog.i(TAG, "Removing existing preferred activity "
20350                                    + pa.mPref.mComponent + ":");
20351                            pa.dump(new LogPrinter(Log.INFO, TAG), "  ");
20352                        }
20353                        pir.removeFilter(pa);
20354                    }
20355                }
20356            }
20357            addPreferredActivityInternal(filter, match, set, activity, true, userId,
20358                    "Replacing preferred");
20359        }
20360    }
20361
20362    @Override
20363    public void clearPackagePreferredActivities(String packageName) {
20364        final int callingUid = Binder.getCallingUid();
20365        if (getInstantAppPackageName(callingUid) != null) {
20366            return;
20367        }
20368        // writer
20369        synchronized (mPackages) {
20370            PackageParser.Package pkg = mPackages.get(packageName);
20371            if (pkg == null || pkg.applicationInfo.uid != callingUid) {
20372                if (mContext.checkCallingOrSelfPermission(
20373                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
20374                        != PackageManager.PERMISSION_GRANTED) {
20375                    if (getUidTargetSdkVersionLockedLPr(callingUid)
20376                            < Build.VERSION_CODES.FROYO) {
20377                        Slog.w(TAG, "Ignoring clearPackagePreferredActivities() from uid "
20378                                + callingUid);
20379                        return;
20380                    }
20381                    mContext.enforceCallingOrSelfPermission(
20382                            android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
20383                }
20384            }
20385            final PackageSetting ps = mSettings.getPackageLPr(packageName);
20386            if (ps != null
20387                    && filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
20388                return;
20389            }
20390            int user = UserHandle.getCallingUserId();
20391            if (clearPackagePreferredActivitiesLPw(packageName, user)) {
20392                scheduleWritePackageRestrictionsLocked(user);
20393            }
20394        }
20395    }
20396
20397    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
20398    boolean clearPackagePreferredActivitiesLPw(String packageName, int userId) {
20399        ArrayList<PreferredActivity> removed = null;
20400        boolean changed = false;
20401        for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
20402            final int thisUserId = mSettings.mPreferredActivities.keyAt(i);
20403            PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
20404            if (userId != UserHandle.USER_ALL && userId != thisUserId) {
20405                continue;
20406            }
20407            Iterator<PreferredActivity> it = pir.filterIterator();
20408            while (it.hasNext()) {
20409                PreferredActivity pa = it.next();
20410                // Mark entry for removal only if it matches the package name
20411                // and the entry is of type "always".
20412                if (packageName == null ||
20413                        (pa.mPref.mComponent.getPackageName().equals(packageName)
20414                                && pa.mPref.mAlways)) {
20415                    if (removed == null) {
20416                        removed = new ArrayList<PreferredActivity>();
20417                    }
20418                    removed.add(pa);
20419                }
20420            }
20421            if (removed != null) {
20422                for (int j=0; j<removed.size(); j++) {
20423                    PreferredActivity pa = removed.get(j);
20424                    pir.removeFilter(pa);
20425                }
20426                changed = true;
20427            }
20428        }
20429        if (changed) {
20430            postPreferredActivityChangedBroadcast(userId);
20431        }
20432        return changed;
20433    }
20434
20435    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
20436    private void clearIntentFilterVerificationsLPw(int userId) {
20437        final int packageCount = mPackages.size();
20438        for (int i = 0; i < packageCount; i++) {
20439            PackageParser.Package pkg = mPackages.valueAt(i);
20440            clearIntentFilterVerificationsLPw(pkg.packageName, userId);
20441        }
20442    }
20443
20444    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
20445    void clearIntentFilterVerificationsLPw(String packageName, int userId) {
20446        if (userId == UserHandle.USER_ALL) {
20447            if (mSettings.removeIntentFilterVerificationLPw(packageName,
20448                    sUserManager.getUserIds())) {
20449                for (int oneUserId : sUserManager.getUserIds()) {
20450                    scheduleWritePackageRestrictionsLocked(oneUserId);
20451                }
20452            }
20453        } else {
20454            if (mSettings.removeIntentFilterVerificationLPw(packageName, userId)) {
20455                scheduleWritePackageRestrictionsLocked(userId);
20456            }
20457        }
20458    }
20459
20460    /** Clears state for all users, and touches intent filter verification policy */
20461    void clearDefaultBrowserIfNeeded(String packageName) {
20462        for (int oneUserId : sUserManager.getUserIds()) {
20463            clearDefaultBrowserIfNeededForUser(packageName, oneUserId);
20464        }
20465    }
20466
20467    private void clearDefaultBrowserIfNeededForUser(String packageName, int userId) {
20468        final String defaultBrowserPackageName = getDefaultBrowserPackageName(userId);
20469        if (!TextUtils.isEmpty(defaultBrowserPackageName)) {
20470            if (packageName.equals(defaultBrowserPackageName)) {
20471                setDefaultBrowserPackageName(null, userId);
20472            }
20473        }
20474    }
20475
20476    @Override
20477    public void resetApplicationPreferences(int userId) {
20478        mContext.enforceCallingOrSelfPermission(
20479                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
20480        final long identity = Binder.clearCallingIdentity();
20481        // writer
20482        try {
20483            synchronized (mPackages) {
20484                clearPackagePreferredActivitiesLPw(null, userId);
20485                mSettings.applyDefaultPreferredAppsLPw(this, userId);
20486                // TODO: We have to reset the default SMS and Phone. This requires
20487                // significant refactoring to keep all default apps in the package
20488                // manager (cleaner but more work) or have the services provide
20489                // callbacks to the package manager to request a default app reset.
20490                applyFactoryDefaultBrowserLPw(userId);
20491                clearIntentFilterVerificationsLPw(userId);
20492                primeDomainVerificationsLPw(userId);
20493                resetUserChangesToRuntimePermissionsAndFlagsLPw(userId);
20494                scheduleWritePackageRestrictionsLocked(userId);
20495            }
20496            resetNetworkPolicies(userId);
20497        } finally {
20498            Binder.restoreCallingIdentity(identity);
20499        }
20500    }
20501
20502    @Override
20503    public int getPreferredActivities(List<IntentFilter> outFilters,
20504            List<ComponentName> outActivities, String packageName) {
20505        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
20506            return 0;
20507        }
20508        int num = 0;
20509        final int userId = UserHandle.getCallingUserId();
20510        // reader
20511        synchronized (mPackages) {
20512            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
20513            if (pir != null) {
20514                final Iterator<PreferredActivity> it = pir.filterIterator();
20515                while (it.hasNext()) {
20516                    final PreferredActivity pa = it.next();
20517                    if (packageName == null
20518                            || (pa.mPref.mComponent.getPackageName().equals(packageName)
20519                                    && pa.mPref.mAlways)) {
20520                        if (outFilters != null) {
20521                            outFilters.add(new IntentFilter(pa));
20522                        }
20523                        if (outActivities != null) {
20524                            outActivities.add(pa.mPref.mComponent);
20525                        }
20526                    }
20527                }
20528            }
20529        }
20530
20531        return num;
20532    }
20533
20534    @Override
20535    public void addPersistentPreferredActivity(IntentFilter filter, ComponentName activity,
20536            int userId) {
20537        int callingUid = Binder.getCallingUid();
20538        if (callingUid != Process.SYSTEM_UID) {
20539            throw new SecurityException(
20540                    "addPersistentPreferredActivity can only be run by the system");
20541        }
20542        if (filter.countActions() == 0) {
20543            Slog.w(TAG, "Cannot set a preferred activity with no filter actions");
20544            return;
20545        }
20546        synchronized (mPackages) {
20547            Slog.i(TAG, "Adding persistent preferred activity " + activity + " for user " + userId +
20548                    ":");
20549            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
20550            mSettings.editPersistentPreferredActivitiesLPw(userId).addFilter(
20551                    new PersistentPreferredActivity(filter, activity));
20552            scheduleWritePackageRestrictionsLocked(userId);
20553            postPreferredActivityChangedBroadcast(userId);
20554        }
20555    }
20556
20557    @Override
20558    public void clearPackagePersistentPreferredActivities(String packageName, int userId) {
20559        int callingUid = Binder.getCallingUid();
20560        if (callingUid != Process.SYSTEM_UID) {
20561            throw new SecurityException(
20562                    "clearPackagePersistentPreferredActivities can only be run by the system");
20563        }
20564        ArrayList<PersistentPreferredActivity> removed = null;
20565        boolean changed = false;
20566        synchronized (mPackages) {
20567            for (int i=0; i<mSettings.mPersistentPreferredActivities.size(); i++) {
20568                final int thisUserId = mSettings.mPersistentPreferredActivities.keyAt(i);
20569                PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities
20570                        .valueAt(i);
20571                if (userId != thisUserId) {
20572                    continue;
20573                }
20574                Iterator<PersistentPreferredActivity> it = ppir.filterIterator();
20575                while (it.hasNext()) {
20576                    PersistentPreferredActivity ppa = it.next();
20577                    // Mark entry for removal only if it matches the package name.
20578                    if (ppa.mComponent.getPackageName().equals(packageName)) {
20579                        if (removed == null) {
20580                            removed = new ArrayList<PersistentPreferredActivity>();
20581                        }
20582                        removed.add(ppa);
20583                    }
20584                }
20585                if (removed != null) {
20586                    for (int j=0; j<removed.size(); j++) {
20587                        PersistentPreferredActivity ppa = removed.get(j);
20588                        ppir.removeFilter(ppa);
20589                    }
20590                    changed = true;
20591                }
20592            }
20593
20594            if (changed) {
20595                scheduleWritePackageRestrictionsLocked(userId);
20596                postPreferredActivityChangedBroadcast(userId);
20597            }
20598        }
20599    }
20600
20601    /**
20602     * Common machinery for picking apart a restored XML blob and passing
20603     * it to a caller-supplied functor to be applied to the running system.
20604     */
20605    private void restoreFromXml(XmlPullParser parser, int userId,
20606            String expectedStartTag, BlobXmlRestorer functor)
20607            throws IOException, XmlPullParserException {
20608        int type;
20609        while ((type = parser.next()) != XmlPullParser.START_TAG
20610                && type != XmlPullParser.END_DOCUMENT) {
20611        }
20612        if (type != XmlPullParser.START_TAG) {
20613            // oops didn't find a start tag?!
20614            if (DEBUG_BACKUP) {
20615                Slog.e(TAG, "Didn't find start tag during restore");
20616            }
20617            return;
20618        }
20619Slog.v(TAG, ":: restoreFromXml() : got to tag " + parser.getName());
20620        // this is supposed to be TAG_PREFERRED_BACKUP
20621        if (!expectedStartTag.equals(parser.getName())) {
20622            if (DEBUG_BACKUP) {
20623                Slog.e(TAG, "Found unexpected tag " + parser.getName());
20624            }
20625            return;
20626        }
20627
20628        // skip interfering stuff, then we're aligned with the backing implementation
20629        while ((type = parser.next()) == XmlPullParser.TEXT) { }
20630Slog.v(TAG, ":: stepped forward, applying functor at tag " + parser.getName());
20631        functor.apply(parser, userId);
20632    }
20633
20634    private interface BlobXmlRestorer {
20635        public void apply(XmlPullParser parser, int userId) throws IOException, XmlPullParserException;
20636    }
20637
20638    /**
20639     * Non-Binder method, support for the backup/restore mechanism: write the
20640     * full set of preferred activities in its canonical XML format.  Returns the
20641     * XML output as a byte array, or null if there is none.
20642     */
20643    @Override
20644    public byte[] getPreferredActivityBackup(int userId) {
20645        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
20646            throw new SecurityException("Only the system may call getPreferredActivityBackup()");
20647        }
20648
20649        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
20650        try {
20651            final XmlSerializer serializer = new FastXmlSerializer();
20652            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
20653            serializer.startDocument(null, true);
20654            serializer.startTag(null, TAG_PREFERRED_BACKUP);
20655
20656            synchronized (mPackages) {
20657                mSettings.writePreferredActivitiesLPr(serializer, userId, true);
20658            }
20659
20660            serializer.endTag(null, TAG_PREFERRED_BACKUP);
20661            serializer.endDocument();
20662            serializer.flush();
20663        } catch (Exception e) {
20664            if (DEBUG_BACKUP) {
20665                Slog.e(TAG, "Unable to write preferred activities for backup", e);
20666            }
20667            return null;
20668        }
20669
20670        return dataStream.toByteArray();
20671    }
20672
20673    @Override
20674    public void restorePreferredActivities(byte[] backup, int userId) {
20675        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
20676            throw new SecurityException("Only the system may call restorePreferredActivities()");
20677        }
20678
20679        try {
20680            final XmlPullParser parser = Xml.newPullParser();
20681            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
20682            restoreFromXml(parser, userId, TAG_PREFERRED_BACKUP,
20683                    new BlobXmlRestorer() {
20684                        @Override
20685                        public void apply(XmlPullParser parser, int userId)
20686                                throws XmlPullParserException, IOException {
20687                            synchronized (mPackages) {
20688                                mSettings.readPreferredActivitiesLPw(parser, userId);
20689                            }
20690                        }
20691                    } );
20692        } catch (Exception e) {
20693            if (DEBUG_BACKUP) {
20694                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
20695            }
20696        }
20697    }
20698
20699    /**
20700     * Non-Binder method, support for the backup/restore mechanism: write the
20701     * default browser (etc) settings in its canonical XML format.  Returns the default
20702     * browser XML representation as a byte array, or null if there is none.
20703     */
20704    @Override
20705    public byte[] getDefaultAppsBackup(int userId) {
20706        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
20707            throw new SecurityException("Only the system may call getDefaultAppsBackup()");
20708        }
20709
20710        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
20711        try {
20712            final XmlSerializer serializer = new FastXmlSerializer();
20713            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
20714            serializer.startDocument(null, true);
20715            serializer.startTag(null, TAG_DEFAULT_APPS);
20716
20717            synchronized (mPackages) {
20718                mSettings.writeDefaultAppsLPr(serializer, userId);
20719            }
20720
20721            serializer.endTag(null, TAG_DEFAULT_APPS);
20722            serializer.endDocument();
20723            serializer.flush();
20724        } catch (Exception e) {
20725            if (DEBUG_BACKUP) {
20726                Slog.e(TAG, "Unable to write default apps for backup", e);
20727            }
20728            return null;
20729        }
20730
20731        return dataStream.toByteArray();
20732    }
20733
20734    @Override
20735    public void restoreDefaultApps(byte[] backup, int userId) {
20736        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
20737            throw new SecurityException("Only the system may call restoreDefaultApps()");
20738        }
20739
20740        try {
20741            final XmlPullParser parser = Xml.newPullParser();
20742            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
20743            restoreFromXml(parser, userId, TAG_DEFAULT_APPS,
20744                    new BlobXmlRestorer() {
20745                        @Override
20746                        public void apply(XmlPullParser parser, int userId)
20747                                throws XmlPullParserException, IOException {
20748                            synchronized (mPackages) {
20749                                mSettings.readDefaultAppsLPw(parser, userId);
20750                            }
20751                        }
20752                    } );
20753        } catch (Exception e) {
20754            if (DEBUG_BACKUP) {
20755                Slog.e(TAG, "Exception restoring default apps: " + e.getMessage());
20756            }
20757        }
20758    }
20759
20760    @Override
20761    public byte[] getIntentFilterVerificationBackup(int userId) {
20762        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
20763            throw new SecurityException("Only the system may call getIntentFilterVerificationBackup()");
20764        }
20765
20766        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
20767        try {
20768            final XmlSerializer serializer = new FastXmlSerializer();
20769            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
20770            serializer.startDocument(null, true);
20771            serializer.startTag(null, TAG_INTENT_FILTER_VERIFICATION);
20772
20773            synchronized (mPackages) {
20774                mSettings.writeAllDomainVerificationsLPr(serializer, userId);
20775            }
20776
20777            serializer.endTag(null, TAG_INTENT_FILTER_VERIFICATION);
20778            serializer.endDocument();
20779            serializer.flush();
20780        } catch (Exception e) {
20781            if (DEBUG_BACKUP) {
20782                Slog.e(TAG, "Unable to write default apps for backup", e);
20783            }
20784            return null;
20785        }
20786
20787        return dataStream.toByteArray();
20788    }
20789
20790    @Override
20791    public void restoreIntentFilterVerification(byte[] backup, int userId) {
20792        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
20793            throw new SecurityException("Only the system may call restorePreferredActivities()");
20794        }
20795
20796        try {
20797            final XmlPullParser parser = Xml.newPullParser();
20798            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
20799            restoreFromXml(parser, userId, TAG_INTENT_FILTER_VERIFICATION,
20800                    new BlobXmlRestorer() {
20801                        @Override
20802                        public void apply(XmlPullParser parser, int userId)
20803                                throws XmlPullParserException, IOException {
20804                            synchronized (mPackages) {
20805                                mSettings.readAllDomainVerificationsLPr(parser, userId);
20806                                mSettings.writeLPr();
20807                            }
20808                        }
20809                    } );
20810        } catch (Exception e) {
20811            if (DEBUG_BACKUP) {
20812                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
20813            }
20814        }
20815    }
20816
20817    @Override
20818    public byte[] getPermissionGrantBackup(int userId) {
20819        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
20820            throw new SecurityException("Only the system may call getPermissionGrantBackup()");
20821        }
20822
20823        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
20824        try {
20825            final XmlSerializer serializer = new FastXmlSerializer();
20826            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
20827            serializer.startDocument(null, true);
20828            serializer.startTag(null, TAG_PERMISSION_BACKUP);
20829
20830            synchronized (mPackages) {
20831                serializeRuntimePermissionGrantsLPr(serializer, userId);
20832            }
20833
20834            serializer.endTag(null, TAG_PERMISSION_BACKUP);
20835            serializer.endDocument();
20836            serializer.flush();
20837        } catch (Exception e) {
20838            if (DEBUG_BACKUP) {
20839                Slog.e(TAG, "Unable to write default apps for backup", e);
20840            }
20841            return null;
20842        }
20843
20844        return dataStream.toByteArray();
20845    }
20846
20847    @Override
20848    public void restorePermissionGrants(byte[] backup, int userId) {
20849        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
20850            throw new SecurityException("Only the system may call restorePermissionGrants()");
20851        }
20852
20853        try {
20854            final XmlPullParser parser = Xml.newPullParser();
20855            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
20856            restoreFromXml(parser, userId, TAG_PERMISSION_BACKUP,
20857                    new BlobXmlRestorer() {
20858                        @Override
20859                        public void apply(XmlPullParser parser, int userId)
20860                                throws XmlPullParserException, IOException {
20861                            synchronized (mPackages) {
20862                                processRestoredPermissionGrantsLPr(parser, userId);
20863                            }
20864                        }
20865                    } );
20866        } catch (Exception e) {
20867            if (DEBUG_BACKUP) {
20868                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
20869            }
20870        }
20871    }
20872
20873    private void serializeRuntimePermissionGrantsLPr(XmlSerializer serializer, final int userId)
20874            throws IOException {
20875        serializer.startTag(null, TAG_ALL_GRANTS);
20876
20877        final int N = mSettings.mPackages.size();
20878        for (int i = 0; i < N; i++) {
20879            final PackageSetting ps = mSettings.mPackages.valueAt(i);
20880            boolean pkgGrantsKnown = false;
20881
20882            PermissionsState packagePerms = ps.getPermissionsState();
20883
20884            for (PermissionState state : packagePerms.getRuntimePermissionStates(userId)) {
20885                final int grantFlags = state.getFlags();
20886                // only look at grants that are not system/policy fixed
20887                if ((grantFlags & SYSTEM_RUNTIME_GRANT_MASK) == 0) {
20888                    final boolean isGranted = state.isGranted();
20889                    // And only back up the user-twiddled state bits
20890                    if (isGranted || (grantFlags & USER_RUNTIME_GRANT_MASK) != 0) {
20891                        final String packageName = mSettings.mPackages.keyAt(i);
20892                        if (!pkgGrantsKnown) {
20893                            serializer.startTag(null, TAG_GRANT);
20894                            serializer.attribute(null, ATTR_PACKAGE_NAME, packageName);
20895                            pkgGrantsKnown = true;
20896                        }
20897
20898                        final boolean userSet =
20899                                (grantFlags & FLAG_PERMISSION_USER_SET) != 0;
20900                        final boolean userFixed =
20901                                (grantFlags & FLAG_PERMISSION_USER_FIXED) != 0;
20902                        final boolean revoke =
20903                                (grantFlags & FLAG_PERMISSION_REVOKE_ON_UPGRADE) != 0;
20904
20905                        serializer.startTag(null, TAG_PERMISSION);
20906                        serializer.attribute(null, ATTR_PERMISSION_NAME, state.getName());
20907                        if (isGranted) {
20908                            serializer.attribute(null, ATTR_IS_GRANTED, "true");
20909                        }
20910                        if (userSet) {
20911                            serializer.attribute(null, ATTR_USER_SET, "true");
20912                        }
20913                        if (userFixed) {
20914                            serializer.attribute(null, ATTR_USER_FIXED, "true");
20915                        }
20916                        if (revoke) {
20917                            serializer.attribute(null, ATTR_REVOKE_ON_UPGRADE, "true");
20918                        }
20919                        serializer.endTag(null, TAG_PERMISSION);
20920                    }
20921                }
20922            }
20923
20924            if (pkgGrantsKnown) {
20925                serializer.endTag(null, TAG_GRANT);
20926            }
20927        }
20928
20929        serializer.endTag(null, TAG_ALL_GRANTS);
20930    }
20931
20932    private void processRestoredPermissionGrantsLPr(XmlPullParser parser, int userId)
20933            throws XmlPullParserException, IOException {
20934        String pkgName = null;
20935        int outerDepth = parser.getDepth();
20936        int type;
20937        while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
20938                && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) {
20939            if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) {
20940                continue;
20941            }
20942
20943            final String tagName = parser.getName();
20944            if (tagName.equals(TAG_GRANT)) {
20945                pkgName = parser.getAttributeValue(null, ATTR_PACKAGE_NAME);
20946                if (DEBUG_BACKUP) {
20947                    Slog.v(TAG, "+++ Restoring grants for package " + pkgName);
20948                }
20949            } else if (tagName.equals(TAG_PERMISSION)) {
20950
20951                final boolean isGranted = "true".equals(parser.getAttributeValue(null, ATTR_IS_GRANTED));
20952                final String permName = parser.getAttributeValue(null, ATTR_PERMISSION_NAME);
20953
20954                int newFlagSet = 0;
20955                if ("true".equals(parser.getAttributeValue(null, ATTR_USER_SET))) {
20956                    newFlagSet |= FLAG_PERMISSION_USER_SET;
20957                }
20958                if ("true".equals(parser.getAttributeValue(null, ATTR_USER_FIXED))) {
20959                    newFlagSet |= FLAG_PERMISSION_USER_FIXED;
20960                }
20961                if ("true".equals(parser.getAttributeValue(null, ATTR_REVOKE_ON_UPGRADE))) {
20962                    newFlagSet |= FLAG_PERMISSION_REVOKE_ON_UPGRADE;
20963                }
20964                if (DEBUG_BACKUP) {
20965                    Slog.v(TAG, "  + Restoring grant: pkg=" + pkgName + " perm=" + permName
20966                            + " granted=" + isGranted + " bits=0x" + Integer.toHexString(newFlagSet));
20967                }
20968                final PackageSetting ps = mSettings.mPackages.get(pkgName);
20969                if (ps != null) {
20970                    // Already installed so we apply the grant immediately
20971                    if (DEBUG_BACKUP) {
20972                        Slog.v(TAG, "        + already installed; applying");
20973                    }
20974                    PermissionsState perms = ps.getPermissionsState();
20975                    BasePermission bp = mSettings.mPermissions.get(permName);
20976                    if (bp != null) {
20977                        if (isGranted) {
20978                            perms.grantRuntimePermission(bp, userId);
20979                        }
20980                        if (newFlagSet != 0) {
20981                            perms.updatePermissionFlags(bp, userId, USER_RUNTIME_GRANT_MASK, newFlagSet);
20982                        }
20983                    }
20984                } else {
20985                    // Need to wait for post-restore install to apply the grant
20986                    if (DEBUG_BACKUP) {
20987                        Slog.v(TAG, "        - not yet installed; saving for later");
20988                    }
20989                    mSettings.processRestoredPermissionGrantLPr(pkgName, permName,
20990                            isGranted, newFlagSet, userId);
20991                }
20992            } else {
20993                PackageManagerService.reportSettingsProblem(Log.WARN,
20994                        "Unknown element under <" + TAG_PERMISSION_BACKUP + ">: " + tagName);
20995                XmlUtils.skipCurrentTag(parser);
20996            }
20997        }
20998
20999        scheduleWriteSettingsLocked();
21000        mSettings.writeRuntimePermissionsForUserLPr(userId, false);
21001    }
21002
21003    @Override
21004    public void addCrossProfileIntentFilter(IntentFilter intentFilter, String ownerPackage,
21005            int sourceUserId, int targetUserId, int flags) {
21006        mContext.enforceCallingOrSelfPermission(
21007                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
21008        int callingUid = Binder.getCallingUid();
21009        enforceOwnerRights(ownerPackage, callingUid);
21010        enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId);
21011        if (intentFilter.countActions() == 0) {
21012            Slog.w(TAG, "Cannot set a crossProfile intent filter with no filter actions");
21013            return;
21014        }
21015        synchronized (mPackages) {
21016            CrossProfileIntentFilter newFilter = new CrossProfileIntentFilter(intentFilter,
21017                    ownerPackage, targetUserId, flags);
21018            CrossProfileIntentResolver resolver =
21019                    mSettings.editCrossProfileIntentResolverLPw(sourceUserId);
21020            ArrayList<CrossProfileIntentFilter> existing = resolver.findFilters(intentFilter);
21021            // We have all those whose filter is equal. Now checking if the rest is equal as well.
21022            if (existing != null) {
21023                int size = existing.size();
21024                for (int i = 0; i < size; i++) {
21025                    if (newFilter.equalsIgnoreFilter(existing.get(i))) {
21026                        return;
21027                    }
21028                }
21029            }
21030            resolver.addFilter(newFilter);
21031            scheduleWritePackageRestrictionsLocked(sourceUserId);
21032        }
21033    }
21034
21035    @Override
21036    public void clearCrossProfileIntentFilters(int sourceUserId, String ownerPackage) {
21037        mContext.enforceCallingOrSelfPermission(
21038                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
21039        final int callingUid = Binder.getCallingUid();
21040        enforceOwnerRights(ownerPackage, callingUid);
21041        enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId);
21042        synchronized (mPackages) {
21043            CrossProfileIntentResolver resolver =
21044                    mSettings.editCrossProfileIntentResolverLPw(sourceUserId);
21045            ArraySet<CrossProfileIntentFilter> set =
21046                    new ArraySet<CrossProfileIntentFilter>(resolver.filterSet());
21047            for (CrossProfileIntentFilter filter : set) {
21048                if (filter.getOwnerPackage().equals(ownerPackage)) {
21049                    resolver.removeFilter(filter);
21050                }
21051            }
21052            scheduleWritePackageRestrictionsLocked(sourceUserId);
21053        }
21054    }
21055
21056    // Enforcing that callingUid is owning pkg on userId
21057    private void enforceOwnerRights(String pkg, int callingUid) {
21058        // The system owns everything.
21059        if (UserHandle.getAppId(callingUid) == Process.SYSTEM_UID) {
21060            return;
21061        }
21062        final int callingUserId = UserHandle.getUserId(callingUid);
21063        PackageInfo pi = getPackageInfo(pkg, 0, callingUserId);
21064        if (pi == null) {
21065            throw new IllegalArgumentException("Unknown package " + pkg + " on user "
21066                    + callingUserId);
21067        }
21068        if (!UserHandle.isSameApp(pi.applicationInfo.uid, callingUid)) {
21069            throw new SecurityException("Calling uid " + callingUid
21070                    + " does not own package " + pkg);
21071        }
21072    }
21073
21074    @Override
21075    public ComponentName getHomeActivities(List<ResolveInfo> allHomeCandidates) {
21076        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
21077            return null;
21078        }
21079        return getHomeActivitiesAsUser(allHomeCandidates, UserHandle.getCallingUserId());
21080    }
21081
21082    public void sendSessionCommitBroadcast(PackageInstaller.SessionInfo sessionInfo, int userId) {
21083        UserManagerService ums = UserManagerService.getInstance();
21084        if (ums != null) {
21085            final UserInfo parent = ums.getProfileParent(userId);
21086            final int launcherUid = (parent != null) ? parent.id : userId;
21087            final ComponentName launcherComponent = getDefaultHomeActivity(launcherUid);
21088            if (launcherComponent != null) {
21089                Intent launcherIntent = new Intent(PackageInstaller.ACTION_SESSION_COMMITTED)
21090                        .putExtra(PackageInstaller.EXTRA_SESSION, sessionInfo)
21091                        .putExtra(Intent.EXTRA_USER, UserHandle.of(userId))
21092                        .setPackage(launcherComponent.getPackageName());
21093                mContext.sendBroadcastAsUser(launcherIntent, UserHandle.of(launcherUid));
21094            }
21095        }
21096    }
21097
21098    /**
21099     * Report the 'Home' activity which is currently set as "always use this one". If non is set
21100     * then reports the most likely home activity or null if there are more than one.
21101     */
21102    private ComponentName getDefaultHomeActivity(int userId) {
21103        List<ResolveInfo> allHomeCandidates = new ArrayList<>();
21104        ComponentName cn = getHomeActivitiesAsUser(allHomeCandidates, userId);
21105        if (cn != null) {
21106            return cn;
21107        }
21108
21109        // Find the launcher with the highest priority and return that component if there are no
21110        // other home activity with the same priority.
21111        int lastPriority = Integer.MIN_VALUE;
21112        ComponentName lastComponent = null;
21113        final int size = allHomeCandidates.size();
21114        for (int i = 0; i < size; i++) {
21115            final ResolveInfo ri = allHomeCandidates.get(i);
21116            if (ri.priority > lastPriority) {
21117                lastComponent = ri.activityInfo.getComponentName();
21118                lastPriority = ri.priority;
21119            } else if (ri.priority == lastPriority) {
21120                // Two components found with same priority.
21121                lastComponent = null;
21122            }
21123        }
21124        return lastComponent;
21125    }
21126
21127    private Intent getHomeIntent() {
21128        Intent intent = new Intent(Intent.ACTION_MAIN);
21129        intent.addCategory(Intent.CATEGORY_HOME);
21130        intent.addCategory(Intent.CATEGORY_DEFAULT);
21131        return intent;
21132    }
21133
21134    private IntentFilter getHomeFilter() {
21135        IntentFilter filter = new IntentFilter(Intent.ACTION_MAIN);
21136        filter.addCategory(Intent.CATEGORY_HOME);
21137        filter.addCategory(Intent.CATEGORY_DEFAULT);
21138        return filter;
21139    }
21140
21141    ComponentName getHomeActivitiesAsUser(List<ResolveInfo> allHomeCandidates,
21142            int userId) {
21143        Intent intent  = getHomeIntent();
21144        List<ResolveInfo> list = queryIntentActivitiesInternal(intent, null,
21145                PackageManager.GET_META_DATA, userId);
21146        ResolveInfo preferred = findPreferredActivity(intent, null, 0, list, 0,
21147                true, false, false, userId);
21148
21149        allHomeCandidates.clear();
21150        if (list != null) {
21151            for (ResolveInfo ri : list) {
21152                allHomeCandidates.add(ri);
21153            }
21154        }
21155        return (preferred == null || preferred.activityInfo == null)
21156                ? null
21157                : new ComponentName(preferred.activityInfo.packageName,
21158                        preferred.activityInfo.name);
21159    }
21160
21161    @Override
21162    public void setHomeActivity(ComponentName comp, int userId) {
21163        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
21164            return;
21165        }
21166        ArrayList<ResolveInfo> homeActivities = new ArrayList<>();
21167        getHomeActivitiesAsUser(homeActivities, userId);
21168
21169        boolean found = false;
21170
21171        final int size = homeActivities.size();
21172        final ComponentName[] set = new ComponentName[size];
21173        for (int i = 0; i < size; i++) {
21174            final ResolveInfo candidate = homeActivities.get(i);
21175            final ActivityInfo info = candidate.activityInfo;
21176            final ComponentName activityName = new ComponentName(info.packageName, info.name);
21177            set[i] = activityName;
21178            if (!found && activityName.equals(comp)) {
21179                found = true;
21180            }
21181        }
21182        if (!found) {
21183            throw new IllegalArgumentException("Component " + comp + " cannot be home on user "
21184                    + userId);
21185        }
21186        replacePreferredActivity(getHomeFilter(), IntentFilter.MATCH_CATEGORY_EMPTY,
21187                set, comp, userId);
21188    }
21189
21190    private @Nullable String getSetupWizardPackageName() {
21191        final Intent intent = new Intent(Intent.ACTION_MAIN);
21192        intent.addCategory(Intent.CATEGORY_SETUP_WIZARD);
21193
21194        final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, null,
21195                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE
21196                        | MATCH_DISABLED_COMPONENTS,
21197                UserHandle.myUserId());
21198        if (matches.size() == 1) {
21199            return matches.get(0).getComponentInfo().packageName;
21200        } else {
21201            Slog.e(TAG, "There should probably be exactly one setup wizard; found " + matches.size()
21202                    + ": matches=" + matches);
21203            return null;
21204        }
21205    }
21206
21207    private @Nullable String getStorageManagerPackageName() {
21208        final Intent intent = new Intent(StorageManager.ACTION_MANAGE_STORAGE);
21209
21210        final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, null,
21211                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE
21212                        | MATCH_DISABLED_COMPONENTS,
21213                UserHandle.myUserId());
21214        if (matches.size() == 1) {
21215            return matches.get(0).getComponentInfo().packageName;
21216        } else {
21217            Slog.e(TAG, "There should probably be exactly one storage manager; found "
21218                    + matches.size() + ": matches=" + matches);
21219            return null;
21220        }
21221    }
21222
21223    @Override
21224    public void setApplicationEnabledSetting(String appPackageName,
21225            int newState, int flags, int userId, String callingPackage) {
21226        if (!sUserManager.exists(userId)) return;
21227        if (callingPackage == null) {
21228            callingPackage = Integer.toString(Binder.getCallingUid());
21229        }
21230        setEnabledSetting(appPackageName, null, newState, flags, userId, callingPackage);
21231    }
21232
21233    @Override
21234    public void setUpdateAvailable(String packageName, boolean updateAvailable) {
21235        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, null);
21236        synchronized (mPackages) {
21237            final PackageSetting pkgSetting = mSettings.mPackages.get(packageName);
21238            if (pkgSetting != null) {
21239                pkgSetting.setUpdateAvailable(updateAvailable);
21240            }
21241        }
21242    }
21243
21244    @Override
21245    public void setComponentEnabledSetting(ComponentName componentName,
21246            int newState, int flags, int userId) {
21247        if (!sUserManager.exists(userId)) return;
21248        setEnabledSetting(componentName.getPackageName(),
21249                componentName.getClassName(), newState, flags, userId, null);
21250    }
21251
21252    private void setEnabledSetting(final String packageName, String className, int newState,
21253            final int flags, int userId, String callingPackage) {
21254        if (!(newState == COMPONENT_ENABLED_STATE_DEFAULT
21255              || newState == COMPONENT_ENABLED_STATE_ENABLED
21256              || newState == COMPONENT_ENABLED_STATE_DISABLED
21257              || newState == COMPONENT_ENABLED_STATE_DISABLED_USER
21258              || newState == COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED)) {
21259            throw new IllegalArgumentException("Invalid new component state: "
21260                    + newState);
21261        }
21262        PackageSetting pkgSetting;
21263        final int callingUid = Binder.getCallingUid();
21264        final int permission;
21265        if (callingUid == Process.SYSTEM_UID) {
21266            permission = PackageManager.PERMISSION_GRANTED;
21267        } else {
21268            permission = mContext.checkCallingOrSelfPermission(
21269                    android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
21270        }
21271        enforceCrossUserPermission(callingUid, userId,
21272                false /* requireFullPermission */, true /* checkShell */, "set enabled");
21273        final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
21274        boolean sendNow = false;
21275        boolean isApp = (className == null);
21276        final boolean isCallerInstantApp = (getInstantAppPackageName(callingUid) != null);
21277        String componentName = isApp ? packageName : className;
21278        int packageUid = -1;
21279        ArrayList<String> components;
21280
21281        // reader
21282        synchronized (mPackages) {
21283            pkgSetting = mSettings.mPackages.get(packageName);
21284            if (pkgSetting == null) {
21285                if (!isCallerInstantApp) {
21286                    if (className == null) {
21287                        throw new IllegalArgumentException("Unknown package: " + packageName);
21288                    }
21289                    throw new IllegalArgumentException(
21290                            "Unknown component: " + packageName + "/" + className);
21291                } else {
21292                    // throw SecurityException to prevent leaking package information
21293                    throw new SecurityException(
21294                            "Attempt to change component state; "
21295                            + "pid=" + Binder.getCallingPid()
21296                            + ", uid=" + callingUid
21297                            + (className == null
21298                                    ? ", package=" + packageName
21299                                    : ", component=" + packageName + "/" + className));
21300                }
21301            }
21302        }
21303
21304        // Limit who can change which apps
21305        if (!UserHandle.isSameApp(callingUid, pkgSetting.appId)) {
21306            // Don't allow apps that don't have permission to modify other apps
21307            if (!allowedByPermission
21308                    || filterAppAccessLPr(pkgSetting, callingUid, userId)) {
21309                throw new SecurityException(
21310                        "Attempt to change component state; "
21311                        + "pid=" + Binder.getCallingPid()
21312                        + ", uid=" + callingUid
21313                        + (className == null
21314                                ? ", package=" + packageName
21315                                : ", component=" + packageName + "/" + className));
21316            }
21317            // Don't allow changing protected packages.
21318            if (mProtectedPackages.isPackageStateProtected(userId, packageName)) {
21319                throw new SecurityException("Cannot disable a protected package: " + packageName);
21320            }
21321        }
21322
21323        synchronized (mPackages) {
21324            if (callingUid == Process.SHELL_UID
21325                    && (pkgSetting.pkgFlags & ApplicationInfo.FLAG_TEST_ONLY) == 0) {
21326                // Shell can only change whole packages between ENABLED and DISABLED_USER states
21327                // unless it is a test package.
21328                int oldState = pkgSetting.getEnabled(userId);
21329                if (className == null
21330                    &&
21331                    (oldState == COMPONENT_ENABLED_STATE_DISABLED_USER
21332                     || oldState == COMPONENT_ENABLED_STATE_DEFAULT
21333                     || oldState == COMPONENT_ENABLED_STATE_ENABLED)
21334                    &&
21335                    (newState == COMPONENT_ENABLED_STATE_DISABLED_USER
21336                     || newState == COMPONENT_ENABLED_STATE_DEFAULT
21337                     || newState == COMPONENT_ENABLED_STATE_ENABLED)) {
21338                    // ok
21339                } else {
21340                    throw new SecurityException(
21341                            "Shell cannot change component state for " + packageName + "/"
21342                            + className + " to " + newState);
21343                }
21344            }
21345            if (className == null) {
21346                // We're dealing with an application/package level state change
21347                if (pkgSetting.getEnabled(userId) == newState) {
21348                    // Nothing to do
21349                    return;
21350                }
21351                if (newState == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT
21352                    || newState == PackageManager.COMPONENT_ENABLED_STATE_ENABLED) {
21353                    // Don't care about who enables an app.
21354                    callingPackage = null;
21355                }
21356                pkgSetting.setEnabled(newState, userId, callingPackage);
21357                // pkgSetting.pkg.mSetEnabled = newState;
21358            } else {
21359                // We're dealing with a component level state change
21360                // First, verify that this is a valid class name.
21361                PackageParser.Package pkg = pkgSetting.pkg;
21362                if (pkg == null || !pkg.hasComponentClassName(className)) {
21363                    if (pkg != null &&
21364                            pkg.applicationInfo.targetSdkVersion >=
21365                                    Build.VERSION_CODES.JELLY_BEAN) {
21366                        throw new IllegalArgumentException("Component class " + className
21367                                + " does not exist in " + packageName);
21368                    } else {
21369                        Slog.w(TAG, "Failed setComponentEnabledSetting: component class "
21370                                + className + " does not exist in " + packageName);
21371                    }
21372                }
21373                switch (newState) {
21374                case COMPONENT_ENABLED_STATE_ENABLED:
21375                    if (!pkgSetting.enableComponentLPw(className, userId)) {
21376                        return;
21377                    }
21378                    break;
21379                case COMPONENT_ENABLED_STATE_DISABLED:
21380                    if (!pkgSetting.disableComponentLPw(className, userId)) {
21381                        return;
21382                    }
21383                    break;
21384                case COMPONENT_ENABLED_STATE_DEFAULT:
21385                    if (!pkgSetting.restoreComponentLPw(className, userId)) {
21386                        return;
21387                    }
21388                    break;
21389                default:
21390                    Slog.e(TAG, "Invalid new component state: " + newState);
21391                    return;
21392                }
21393            }
21394            scheduleWritePackageRestrictionsLocked(userId);
21395            updateSequenceNumberLP(pkgSetting, new int[] { userId });
21396            final long callingId = Binder.clearCallingIdentity();
21397            try {
21398                updateInstantAppInstallerLocked(packageName);
21399            } finally {
21400                Binder.restoreCallingIdentity(callingId);
21401            }
21402            components = mPendingBroadcasts.get(userId, packageName);
21403            final boolean newPackage = components == null;
21404            if (newPackage) {
21405                components = new ArrayList<String>();
21406            }
21407            if (!components.contains(componentName)) {
21408                components.add(componentName);
21409            }
21410            if ((flags&PackageManager.DONT_KILL_APP) == 0) {
21411                sendNow = true;
21412                // Purge entry from pending broadcast list if another one exists already
21413                // since we are sending one right away.
21414                mPendingBroadcasts.remove(userId, packageName);
21415            } else {
21416                if (newPackage) {
21417                    mPendingBroadcasts.put(userId, packageName, components);
21418                }
21419                if (!mHandler.hasMessages(SEND_PENDING_BROADCAST)) {
21420                    // Schedule a message
21421                    mHandler.sendEmptyMessageDelayed(SEND_PENDING_BROADCAST, BROADCAST_DELAY);
21422                }
21423            }
21424        }
21425
21426        long callingId = Binder.clearCallingIdentity();
21427        try {
21428            if (sendNow) {
21429                packageUid = UserHandle.getUid(userId, pkgSetting.appId);
21430                sendPackageChangedBroadcast(packageName,
21431                        (flags&PackageManager.DONT_KILL_APP) != 0, components, packageUid);
21432            }
21433        } finally {
21434            Binder.restoreCallingIdentity(callingId);
21435        }
21436    }
21437
21438    @Override
21439    public void flushPackageRestrictionsAsUser(int userId) {
21440        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
21441            return;
21442        }
21443        if (!sUserManager.exists(userId)) {
21444            return;
21445        }
21446        enforceCrossUserPermission(Binder.getCallingUid(), userId, false /* requireFullPermission*/,
21447                false /* checkShell */, "flushPackageRestrictions");
21448        synchronized (mPackages) {
21449            mSettings.writePackageRestrictionsLPr(userId);
21450            mDirtyUsers.remove(userId);
21451            if (mDirtyUsers.isEmpty()) {
21452                mHandler.removeMessages(WRITE_PACKAGE_RESTRICTIONS);
21453            }
21454        }
21455    }
21456
21457    private void sendPackageChangedBroadcast(String packageName,
21458            boolean killFlag, ArrayList<String> componentNames, int packageUid) {
21459        if (DEBUG_INSTALL)
21460            Log.v(TAG, "Sending package changed: package=" + packageName + " components="
21461                    + componentNames);
21462        Bundle extras = new Bundle(4);
21463        extras.putString(Intent.EXTRA_CHANGED_COMPONENT_NAME, componentNames.get(0));
21464        String nameList[] = new String[componentNames.size()];
21465        componentNames.toArray(nameList);
21466        extras.putStringArray(Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST, nameList);
21467        extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, killFlag);
21468        extras.putInt(Intent.EXTRA_UID, packageUid);
21469        // If this is not reporting a change of the overall package, then only send it
21470        // to registered receivers.  We don't want to launch a swath of apps for every
21471        // little component state change.
21472        final int flags = !componentNames.contains(packageName)
21473                ? Intent.FLAG_RECEIVER_REGISTERED_ONLY : 0;
21474        sendPackageBroadcast(Intent.ACTION_PACKAGE_CHANGED,  packageName, extras, flags, null, null,
21475                new int[] {UserHandle.getUserId(packageUid)});
21476    }
21477
21478    @Override
21479    public void setPackageStoppedState(String packageName, boolean stopped, int userId) {
21480        if (!sUserManager.exists(userId)) return;
21481        final int callingUid = Binder.getCallingUid();
21482        if (getInstantAppPackageName(callingUid) != null) {
21483            return;
21484        }
21485        final int permission = mContext.checkCallingOrSelfPermission(
21486                android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
21487        final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
21488        enforceCrossUserPermission(callingUid, userId,
21489                true /* requireFullPermission */, true /* checkShell */, "stop package");
21490        // writer
21491        synchronized (mPackages) {
21492            final PackageSetting ps = mSettings.mPackages.get(packageName);
21493            if (!filterAppAccessLPr(ps, callingUid, userId)
21494                    && mSettings.setPackageStoppedStateLPw(this, packageName, stopped,
21495                            allowedByPermission, callingUid, userId)) {
21496                scheduleWritePackageRestrictionsLocked(userId);
21497            }
21498        }
21499    }
21500
21501    @Override
21502    public String getInstallerPackageName(String packageName) {
21503        final int callingUid = Binder.getCallingUid();
21504        if (getInstantAppPackageName(callingUid) != null) {
21505            return null;
21506        }
21507        // reader
21508        synchronized (mPackages) {
21509            final PackageSetting ps = mSettings.mPackages.get(packageName);
21510            if (filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
21511                return null;
21512            }
21513            return mSettings.getInstallerPackageNameLPr(packageName);
21514        }
21515    }
21516
21517    public boolean isOrphaned(String packageName) {
21518        // reader
21519        synchronized (mPackages) {
21520            return mSettings.isOrphaned(packageName);
21521        }
21522    }
21523
21524    @Override
21525    public int getApplicationEnabledSetting(String packageName, int userId) {
21526        if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
21527        int callingUid = Binder.getCallingUid();
21528        enforceCrossUserPermission(callingUid, userId,
21529                false /* requireFullPermission */, false /* checkShell */, "get enabled");
21530        // reader
21531        synchronized (mPackages) {
21532            if (filterAppAccessLPr(mSettings.getPackageLPr(packageName), callingUid, userId)) {
21533                return COMPONENT_ENABLED_STATE_DISABLED;
21534            }
21535            return mSettings.getApplicationEnabledSettingLPr(packageName, userId);
21536        }
21537    }
21538
21539    @Override
21540    public int getComponentEnabledSetting(ComponentName component, int userId) {
21541        if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
21542        int callingUid = Binder.getCallingUid();
21543        enforceCrossUserPermission(callingUid, userId,
21544                false /*requireFullPermission*/, false /*checkShell*/, "getComponentEnabled");
21545        synchronized (mPackages) {
21546            if (filterAppAccessLPr(mSettings.getPackageLPr(component.getPackageName()), callingUid,
21547                    component, TYPE_UNKNOWN, userId)) {
21548                return COMPONENT_ENABLED_STATE_DISABLED;
21549            }
21550            return mSettings.getComponentEnabledSettingLPr(component, userId);
21551        }
21552    }
21553
21554    @Override
21555    public void enterSafeMode() {
21556        enforceSystemOrRoot("Only the system can request entering safe mode");
21557
21558        if (!mSystemReady) {
21559            mSafeMode = true;
21560        }
21561    }
21562
21563    @Override
21564    public void systemReady() {
21565        enforceSystemOrRoot("Only the system can claim the system is ready");
21566
21567        mSystemReady = true;
21568        final ContentResolver resolver = mContext.getContentResolver();
21569        ContentObserver co = new ContentObserver(mHandler) {
21570            @Override
21571            public void onChange(boolean selfChange) {
21572                mEphemeralAppsDisabled =
21573                        (Global.getInt(resolver, Global.ENABLE_EPHEMERAL_FEATURE, 1) == 0) ||
21574                                (Secure.getInt(resolver, Secure.INSTANT_APPS_ENABLED, 1) == 0);
21575            }
21576        };
21577        mContext.getContentResolver().registerContentObserver(android.provider.Settings.Global
21578                        .getUriFor(Global.ENABLE_EPHEMERAL_FEATURE),
21579                false, co, UserHandle.USER_SYSTEM);
21580        mContext.getContentResolver().registerContentObserver(android.provider.Settings.Global
21581                        .getUriFor(Secure.INSTANT_APPS_ENABLED), false, co, UserHandle.USER_SYSTEM);
21582        co.onChange(true);
21583
21584        // Disable any carrier apps. We do this very early in boot to prevent the apps from being
21585        // disabled after already being started.
21586        CarrierAppUtils.disableCarrierAppsUntilPrivileged(mContext.getOpPackageName(), this,
21587                mContext.getContentResolver(), UserHandle.USER_SYSTEM);
21588
21589        // Read the compatibilty setting when the system is ready.
21590        boolean compatibilityModeEnabled = android.provider.Settings.Global.getInt(
21591                mContext.getContentResolver(),
21592                android.provider.Settings.Global.COMPATIBILITY_MODE, 1) == 1;
21593        PackageParser.setCompatibilityModeEnabled(compatibilityModeEnabled);
21594        if (DEBUG_SETTINGS) {
21595            Log.d(TAG, "compatibility mode:" + compatibilityModeEnabled);
21596        }
21597
21598        int[] grantPermissionsUserIds = EMPTY_INT_ARRAY;
21599
21600        synchronized (mPackages) {
21601            // Verify that all of the preferred activity components actually
21602            // exist.  It is possible for applications to be updated and at
21603            // that point remove a previously declared activity component that
21604            // had been set as a preferred activity.  We try to clean this up
21605            // the next time we encounter that preferred activity, but it is
21606            // possible for the user flow to never be able to return to that
21607            // situation so here we do a sanity check to make sure we haven't
21608            // left any junk around.
21609            ArrayList<PreferredActivity> removed = new ArrayList<PreferredActivity>();
21610            for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
21611                PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
21612                removed.clear();
21613                for (PreferredActivity pa : pir.filterSet()) {
21614                    if (mActivities.mActivities.get(pa.mPref.mComponent) == null) {
21615                        removed.add(pa);
21616                    }
21617                }
21618                if (removed.size() > 0) {
21619                    for (int r=0; r<removed.size(); r++) {
21620                        PreferredActivity pa = removed.get(r);
21621                        Slog.w(TAG, "Removing dangling preferred activity: "
21622                                + pa.mPref.mComponent);
21623                        pir.removeFilter(pa);
21624                    }
21625                    mSettings.writePackageRestrictionsLPr(
21626                            mSettings.mPreferredActivities.keyAt(i));
21627                }
21628            }
21629
21630            for (int userId : UserManagerService.getInstance().getUserIds()) {
21631                if (!mSettings.areDefaultRuntimePermissionsGrantedLPr(userId)) {
21632                    grantPermissionsUserIds = ArrayUtils.appendInt(
21633                            grantPermissionsUserIds, userId);
21634                }
21635            }
21636        }
21637        sUserManager.systemReady();
21638
21639        // If we upgraded grant all default permissions before kicking off.
21640        for (int userId : grantPermissionsUserIds) {
21641            mDefaultPermissionPolicy.grantDefaultPermissions(userId);
21642        }
21643
21644        // If we did not grant default permissions, we preload from this the
21645        // default permission exceptions lazily to ensure we don't hit the
21646        // disk on a new user creation.
21647        if (grantPermissionsUserIds == EMPTY_INT_ARRAY) {
21648            mDefaultPermissionPolicy.scheduleReadDefaultPermissionExceptions();
21649        }
21650
21651        // Kick off any messages waiting for system ready
21652        if (mPostSystemReadyMessages != null) {
21653            for (Message msg : mPostSystemReadyMessages) {
21654                msg.sendToTarget();
21655            }
21656            mPostSystemReadyMessages = null;
21657        }
21658
21659        // Watch for external volumes that come and go over time
21660        final StorageManager storage = mContext.getSystemService(StorageManager.class);
21661        storage.registerListener(mStorageListener);
21662
21663        mInstallerService.systemReady();
21664        mPackageDexOptimizer.systemReady();
21665
21666        StorageManagerInternal StorageManagerInternal = LocalServices.getService(
21667                StorageManagerInternal.class);
21668        StorageManagerInternal.addExternalStoragePolicy(
21669                new StorageManagerInternal.ExternalStorageMountPolicy() {
21670            @Override
21671            public int getMountMode(int uid, String packageName) {
21672                if (Process.isIsolated(uid)) {
21673                    return Zygote.MOUNT_EXTERNAL_NONE;
21674                }
21675                if (checkUidPermission(WRITE_MEDIA_STORAGE, uid) == PERMISSION_GRANTED) {
21676                    return Zygote.MOUNT_EXTERNAL_DEFAULT;
21677                }
21678                if (checkUidPermission(READ_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) {
21679                    return Zygote.MOUNT_EXTERNAL_DEFAULT;
21680                }
21681                if (checkUidPermission(WRITE_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) {
21682                    return Zygote.MOUNT_EXTERNAL_READ;
21683                }
21684                return Zygote.MOUNT_EXTERNAL_WRITE;
21685            }
21686
21687            @Override
21688            public boolean hasExternalStorage(int uid, String packageName) {
21689                return true;
21690            }
21691        });
21692
21693        // Now that we're mostly running, clean up stale users and apps
21694        sUserManager.reconcileUsers(StorageManager.UUID_PRIVATE_INTERNAL);
21695        reconcileApps(StorageManager.UUID_PRIVATE_INTERNAL);
21696
21697        if (mPrivappPermissionsViolations != null) {
21698            Slog.wtf(TAG,"Signature|privileged permissions not in "
21699                    + "privapp-permissions whitelist: " + mPrivappPermissionsViolations);
21700            mPrivappPermissionsViolations = null;
21701        }
21702    }
21703
21704    public void waitForAppDataPrepared() {
21705        if (mPrepareAppDataFuture == null) {
21706            return;
21707        }
21708        ConcurrentUtils.waitForFutureNoInterrupt(mPrepareAppDataFuture, "wait for prepareAppData");
21709        mPrepareAppDataFuture = null;
21710    }
21711
21712    @Override
21713    public boolean isSafeMode() {
21714        // allow instant applications
21715        return mSafeMode;
21716    }
21717
21718    @Override
21719    public boolean hasSystemUidErrors() {
21720        // allow instant applications
21721        return mHasSystemUidErrors;
21722    }
21723
21724    static String arrayToString(int[] array) {
21725        StringBuffer buf = new StringBuffer(128);
21726        buf.append('[');
21727        if (array != null) {
21728            for (int i=0; i<array.length; i++) {
21729                if (i > 0) buf.append(", ");
21730                buf.append(array[i]);
21731            }
21732        }
21733        buf.append(']');
21734        return buf.toString();
21735    }
21736
21737    static class DumpState {
21738        public static final int DUMP_LIBS = 1 << 0;
21739        public static final int DUMP_FEATURES = 1 << 1;
21740        public static final int DUMP_ACTIVITY_RESOLVERS = 1 << 2;
21741        public static final int DUMP_SERVICE_RESOLVERS = 1 << 3;
21742        public static final int DUMP_RECEIVER_RESOLVERS = 1 << 4;
21743        public static final int DUMP_CONTENT_RESOLVERS = 1 << 5;
21744        public static final int DUMP_PERMISSIONS = 1 << 6;
21745        public static final int DUMP_PACKAGES = 1 << 7;
21746        public static final int DUMP_SHARED_USERS = 1 << 8;
21747        public static final int DUMP_MESSAGES = 1 << 9;
21748        public static final int DUMP_PROVIDERS = 1 << 10;
21749        public static final int DUMP_VERIFIERS = 1 << 11;
21750        public static final int DUMP_PREFERRED = 1 << 12;
21751        public static final int DUMP_PREFERRED_XML = 1 << 13;
21752        public static final int DUMP_KEYSETS = 1 << 14;
21753        public static final int DUMP_VERSION = 1 << 15;
21754        public static final int DUMP_INSTALLS = 1 << 16;
21755        public static final int DUMP_INTENT_FILTER_VERIFIERS = 1 << 17;
21756        public static final int DUMP_DOMAIN_PREFERRED = 1 << 18;
21757        public static final int DUMP_FROZEN = 1 << 19;
21758        public static final int DUMP_DEXOPT = 1 << 20;
21759        public static final int DUMP_COMPILER_STATS = 1 << 21;
21760        public static final int DUMP_CHANGES = 1 << 22;
21761
21762        public static final int OPTION_SHOW_FILTERS = 1 << 0;
21763
21764        private int mTypes;
21765
21766        private int mOptions;
21767
21768        private boolean mTitlePrinted;
21769
21770        private SharedUserSetting mSharedUser;
21771
21772        public boolean isDumping(int type) {
21773            if (mTypes == 0 && type != DUMP_PREFERRED_XML) {
21774                return true;
21775            }
21776
21777            return (mTypes & type) != 0;
21778        }
21779
21780        public void setDump(int type) {
21781            mTypes |= type;
21782        }
21783
21784        public boolean isOptionEnabled(int option) {
21785            return (mOptions & option) != 0;
21786        }
21787
21788        public void setOptionEnabled(int option) {
21789            mOptions |= option;
21790        }
21791
21792        public boolean onTitlePrinted() {
21793            final boolean printed = mTitlePrinted;
21794            mTitlePrinted = true;
21795            return printed;
21796        }
21797
21798        public boolean getTitlePrinted() {
21799            return mTitlePrinted;
21800        }
21801
21802        public void setTitlePrinted(boolean enabled) {
21803            mTitlePrinted = enabled;
21804        }
21805
21806        public SharedUserSetting getSharedUser() {
21807            return mSharedUser;
21808        }
21809
21810        public void setSharedUser(SharedUserSetting user) {
21811            mSharedUser = user;
21812        }
21813    }
21814
21815    @Override
21816    public void onShellCommand(FileDescriptor in, FileDescriptor out,
21817            FileDescriptor err, String[] args, ShellCallback callback,
21818            ResultReceiver resultReceiver) {
21819        (new PackageManagerShellCommand(this)).exec(
21820                this, in, out, err, args, callback, resultReceiver);
21821    }
21822
21823    @Override
21824    protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
21825        if (!DumpUtils.checkDumpAndUsageStatsPermission(mContext, TAG, pw)) return;
21826
21827        DumpState dumpState = new DumpState();
21828        boolean fullPreferred = false;
21829        boolean checkin = false;
21830
21831        String packageName = null;
21832        ArraySet<String> permissionNames = null;
21833
21834        int opti = 0;
21835        while (opti < args.length) {
21836            String opt = args[opti];
21837            if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') {
21838                break;
21839            }
21840            opti++;
21841
21842            if ("-a".equals(opt)) {
21843                // Right now we only know how to print all.
21844            } else if ("-h".equals(opt)) {
21845                pw.println("Package manager dump options:");
21846                pw.println("  [-h] [-f] [--checkin] [cmd] ...");
21847                pw.println("    --checkin: dump for a checkin");
21848                pw.println("    -f: print details of intent filters");
21849                pw.println("    -h: print this help");
21850                pw.println("  cmd may be one of:");
21851                pw.println("    l[ibraries]: list known shared libraries");
21852                pw.println("    f[eatures]: list device features");
21853                pw.println("    k[eysets]: print known keysets");
21854                pw.println("    r[esolvers] [activity|service|receiver|content]: dump intent resolvers");
21855                pw.println("    perm[issions]: dump permissions");
21856                pw.println("    permission [name ...]: dump declaration and use of given permission");
21857                pw.println("    pref[erred]: print preferred package settings");
21858                pw.println("    preferred-xml [--full]: print preferred package settings as xml");
21859                pw.println("    prov[iders]: dump content providers");
21860                pw.println("    p[ackages]: dump installed packages");
21861                pw.println("    s[hared-users]: dump shared user IDs");
21862                pw.println("    m[essages]: print collected runtime messages");
21863                pw.println("    v[erifiers]: print package verifier info");
21864                pw.println("    d[omain-preferred-apps]: print domains preferred apps");
21865                pw.println("    i[ntent-filter-verifiers]|ifv: print intent filter verifier info");
21866                pw.println("    version: print database version info");
21867                pw.println("    write: write current settings now");
21868                pw.println("    installs: details about install sessions");
21869                pw.println("    check-permission <permission> <package> [<user>]: does pkg hold perm?");
21870                pw.println("    dexopt: dump dexopt state");
21871                pw.println("    compiler-stats: dump compiler statistics");
21872                pw.println("    enabled-overlays: dump list of enabled overlay packages");
21873                pw.println("    <package.name>: info about given package");
21874                return;
21875            } else if ("--checkin".equals(opt)) {
21876                checkin = true;
21877            } else if ("-f".equals(opt)) {
21878                dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS);
21879            } else if ("--proto".equals(opt)) {
21880                dumpProto(fd);
21881                return;
21882            } else {
21883                pw.println("Unknown argument: " + opt + "; use -h for help");
21884            }
21885        }
21886
21887        // Is the caller requesting to dump a particular piece of data?
21888        if (opti < args.length) {
21889            String cmd = args[opti];
21890            opti++;
21891            // Is this a package name?
21892            if ("android".equals(cmd) || cmd.contains(".")) {
21893                packageName = cmd;
21894                // When dumping a single package, we always dump all of its
21895                // filter information since the amount of data will be reasonable.
21896                dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS);
21897            } else if ("check-permission".equals(cmd)) {
21898                if (opti >= args.length) {
21899                    pw.println("Error: check-permission missing permission argument");
21900                    return;
21901                }
21902                String perm = args[opti];
21903                opti++;
21904                if (opti >= args.length) {
21905                    pw.println("Error: check-permission missing package argument");
21906                    return;
21907                }
21908
21909                String pkg = args[opti];
21910                opti++;
21911                int user = UserHandle.getUserId(Binder.getCallingUid());
21912                if (opti < args.length) {
21913                    try {
21914                        user = Integer.parseInt(args[opti]);
21915                    } catch (NumberFormatException e) {
21916                        pw.println("Error: check-permission user argument is not a number: "
21917                                + args[opti]);
21918                        return;
21919                    }
21920                }
21921
21922                // Normalize package name to handle renamed packages and static libs
21923                pkg = resolveInternalPackageNameLPr(pkg, PackageManager.VERSION_CODE_HIGHEST);
21924
21925                pw.println(checkPermission(perm, pkg, user));
21926                return;
21927            } else if ("l".equals(cmd) || "libraries".equals(cmd)) {
21928                dumpState.setDump(DumpState.DUMP_LIBS);
21929            } else if ("f".equals(cmd) || "features".equals(cmd)) {
21930                dumpState.setDump(DumpState.DUMP_FEATURES);
21931            } else if ("r".equals(cmd) || "resolvers".equals(cmd)) {
21932                if (opti >= args.length) {
21933                    dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS
21934                            | DumpState.DUMP_SERVICE_RESOLVERS
21935                            | DumpState.DUMP_RECEIVER_RESOLVERS
21936                            | DumpState.DUMP_CONTENT_RESOLVERS);
21937                } else {
21938                    while (opti < args.length) {
21939                        String name = args[opti];
21940                        if ("a".equals(name) || "activity".equals(name)) {
21941                            dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS);
21942                        } else if ("s".equals(name) || "service".equals(name)) {
21943                            dumpState.setDump(DumpState.DUMP_SERVICE_RESOLVERS);
21944                        } else if ("r".equals(name) || "receiver".equals(name)) {
21945                            dumpState.setDump(DumpState.DUMP_RECEIVER_RESOLVERS);
21946                        } else if ("c".equals(name) || "content".equals(name)) {
21947                            dumpState.setDump(DumpState.DUMP_CONTENT_RESOLVERS);
21948                        } else {
21949                            pw.println("Error: unknown resolver table type: " + name);
21950                            return;
21951                        }
21952                        opti++;
21953                    }
21954                }
21955            } else if ("perm".equals(cmd) || "permissions".equals(cmd)) {
21956                dumpState.setDump(DumpState.DUMP_PERMISSIONS);
21957            } else if ("permission".equals(cmd)) {
21958                if (opti >= args.length) {
21959                    pw.println("Error: permission requires permission name");
21960                    return;
21961                }
21962                permissionNames = new ArraySet<>();
21963                while (opti < args.length) {
21964                    permissionNames.add(args[opti]);
21965                    opti++;
21966                }
21967                dumpState.setDump(DumpState.DUMP_PERMISSIONS
21968                        | DumpState.DUMP_PACKAGES | DumpState.DUMP_SHARED_USERS);
21969            } else if ("pref".equals(cmd) || "preferred".equals(cmd)) {
21970                dumpState.setDump(DumpState.DUMP_PREFERRED);
21971            } else if ("preferred-xml".equals(cmd)) {
21972                dumpState.setDump(DumpState.DUMP_PREFERRED_XML);
21973                if (opti < args.length && "--full".equals(args[opti])) {
21974                    fullPreferred = true;
21975                    opti++;
21976                }
21977            } else if ("d".equals(cmd) || "domain-preferred-apps".equals(cmd)) {
21978                dumpState.setDump(DumpState.DUMP_DOMAIN_PREFERRED);
21979            } else if ("p".equals(cmd) || "packages".equals(cmd)) {
21980                dumpState.setDump(DumpState.DUMP_PACKAGES);
21981            } else if ("s".equals(cmd) || "shared-users".equals(cmd)) {
21982                dumpState.setDump(DumpState.DUMP_SHARED_USERS);
21983            } else if ("prov".equals(cmd) || "providers".equals(cmd)) {
21984                dumpState.setDump(DumpState.DUMP_PROVIDERS);
21985            } else if ("m".equals(cmd) || "messages".equals(cmd)) {
21986                dumpState.setDump(DumpState.DUMP_MESSAGES);
21987            } else if ("v".equals(cmd) || "verifiers".equals(cmd)) {
21988                dumpState.setDump(DumpState.DUMP_VERIFIERS);
21989            } else if ("i".equals(cmd) || "ifv".equals(cmd)
21990                    || "intent-filter-verifiers".equals(cmd)) {
21991                dumpState.setDump(DumpState.DUMP_INTENT_FILTER_VERIFIERS);
21992            } else if ("version".equals(cmd)) {
21993                dumpState.setDump(DumpState.DUMP_VERSION);
21994            } else if ("k".equals(cmd) || "keysets".equals(cmd)) {
21995                dumpState.setDump(DumpState.DUMP_KEYSETS);
21996            } else if ("installs".equals(cmd)) {
21997                dumpState.setDump(DumpState.DUMP_INSTALLS);
21998            } else if ("frozen".equals(cmd)) {
21999                dumpState.setDump(DumpState.DUMP_FROZEN);
22000            } else if ("dexopt".equals(cmd)) {
22001                dumpState.setDump(DumpState.DUMP_DEXOPT);
22002            } else if ("compiler-stats".equals(cmd)) {
22003                dumpState.setDump(DumpState.DUMP_COMPILER_STATS);
22004            } else if ("changes".equals(cmd)) {
22005                dumpState.setDump(DumpState.DUMP_CHANGES);
22006            } else if ("write".equals(cmd)) {
22007                synchronized (mPackages) {
22008                    mSettings.writeLPr();
22009                    pw.println("Settings written.");
22010                    return;
22011                }
22012            }
22013        }
22014
22015        if (checkin) {
22016            pw.println("vers,1");
22017        }
22018
22019        // reader
22020        synchronized (mPackages) {
22021            if (dumpState.isDumping(DumpState.DUMP_VERSION) && packageName == null) {
22022                if (!checkin) {
22023                    if (dumpState.onTitlePrinted())
22024                        pw.println();
22025                    pw.println("Database versions:");
22026                    mSettings.dumpVersionLPr(new IndentingPrintWriter(pw, "  "));
22027                }
22028            }
22029
22030            if (dumpState.isDumping(DumpState.DUMP_VERIFIERS) && packageName == null) {
22031                if (!checkin) {
22032                    if (dumpState.onTitlePrinted())
22033                        pw.println();
22034                    pw.println("Verifiers:");
22035                    pw.print("  Required: ");
22036                    pw.print(mRequiredVerifierPackage);
22037                    pw.print(" (uid=");
22038                    pw.print(getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING,
22039                            UserHandle.USER_SYSTEM));
22040                    pw.println(")");
22041                } else if (mRequiredVerifierPackage != null) {
22042                    pw.print("vrfy,"); pw.print(mRequiredVerifierPackage);
22043                    pw.print(",");
22044                    pw.println(getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING,
22045                            UserHandle.USER_SYSTEM));
22046                }
22047            }
22048
22049            if (dumpState.isDumping(DumpState.DUMP_INTENT_FILTER_VERIFIERS) &&
22050                    packageName == null) {
22051                if (mIntentFilterVerifierComponent != null) {
22052                    String verifierPackageName = mIntentFilterVerifierComponent.getPackageName();
22053                    if (!checkin) {
22054                        if (dumpState.onTitlePrinted())
22055                            pw.println();
22056                        pw.println("Intent Filter Verifier:");
22057                        pw.print("  Using: ");
22058                        pw.print(verifierPackageName);
22059                        pw.print(" (uid=");
22060                        pw.print(getPackageUid(verifierPackageName, MATCH_DEBUG_TRIAGED_MISSING,
22061                                UserHandle.USER_SYSTEM));
22062                        pw.println(")");
22063                    } else if (verifierPackageName != null) {
22064                        pw.print("ifv,"); pw.print(verifierPackageName);
22065                        pw.print(",");
22066                        pw.println(getPackageUid(verifierPackageName, MATCH_DEBUG_TRIAGED_MISSING,
22067                                UserHandle.USER_SYSTEM));
22068                    }
22069                } else {
22070                    pw.println();
22071                    pw.println("No Intent Filter Verifier available!");
22072                }
22073            }
22074
22075            if (dumpState.isDumping(DumpState.DUMP_LIBS) && packageName == null) {
22076                boolean printedHeader = false;
22077                final Iterator<String> it = mSharedLibraries.keySet().iterator();
22078                while (it.hasNext()) {
22079                    String libName = it.next();
22080                    SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(libName);
22081                    if (versionedLib == null) {
22082                        continue;
22083                    }
22084                    final int versionCount = versionedLib.size();
22085                    for (int i = 0; i < versionCount; i++) {
22086                        SharedLibraryEntry libEntry = versionedLib.valueAt(i);
22087                        if (!checkin) {
22088                            if (!printedHeader) {
22089                                if (dumpState.onTitlePrinted())
22090                                    pw.println();
22091                                pw.println("Libraries:");
22092                                printedHeader = true;
22093                            }
22094                            pw.print("  ");
22095                        } else {
22096                            pw.print("lib,");
22097                        }
22098                        pw.print(libEntry.info.getName());
22099                        if (libEntry.info.isStatic()) {
22100                            pw.print(" version=" + libEntry.info.getVersion());
22101                        }
22102                        if (!checkin) {
22103                            pw.print(" -> ");
22104                        }
22105                        if (libEntry.path != null) {
22106                            pw.print(" (jar) ");
22107                            pw.print(libEntry.path);
22108                        } else {
22109                            pw.print(" (apk) ");
22110                            pw.print(libEntry.apk);
22111                        }
22112                        pw.println();
22113                    }
22114                }
22115            }
22116
22117            if (dumpState.isDumping(DumpState.DUMP_FEATURES) && packageName == null) {
22118                if (dumpState.onTitlePrinted())
22119                    pw.println();
22120                if (!checkin) {
22121                    pw.println("Features:");
22122                }
22123
22124                synchronized (mAvailableFeatures) {
22125                    for (FeatureInfo feat : mAvailableFeatures.values()) {
22126                        if (checkin) {
22127                            pw.print("feat,");
22128                            pw.print(feat.name);
22129                            pw.print(",");
22130                            pw.println(feat.version);
22131                        } else {
22132                            pw.print("  ");
22133                            pw.print(feat.name);
22134                            if (feat.version > 0) {
22135                                pw.print(" version=");
22136                                pw.print(feat.version);
22137                            }
22138                            pw.println();
22139                        }
22140                    }
22141                }
22142            }
22143
22144            if (!checkin && dumpState.isDumping(DumpState.DUMP_ACTIVITY_RESOLVERS)) {
22145                if (mActivities.dump(pw, dumpState.getTitlePrinted() ? "\nActivity Resolver Table:"
22146                        : "Activity Resolver Table:", "  ", packageName,
22147                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
22148                    dumpState.setTitlePrinted(true);
22149                }
22150            }
22151            if (!checkin && dumpState.isDumping(DumpState.DUMP_RECEIVER_RESOLVERS)) {
22152                if (mReceivers.dump(pw, dumpState.getTitlePrinted() ? "\nReceiver Resolver Table:"
22153                        : "Receiver Resolver Table:", "  ", packageName,
22154                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
22155                    dumpState.setTitlePrinted(true);
22156                }
22157            }
22158            if (!checkin && dumpState.isDumping(DumpState.DUMP_SERVICE_RESOLVERS)) {
22159                if (mServices.dump(pw, dumpState.getTitlePrinted() ? "\nService Resolver Table:"
22160                        : "Service Resolver Table:", "  ", packageName,
22161                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
22162                    dumpState.setTitlePrinted(true);
22163                }
22164            }
22165            if (!checkin && dumpState.isDumping(DumpState.DUMP_CONTENT_RESOLVERS)) {
22166                if (mProviders.dump(pw, dumpState.getTitlePrinted() ? "\nProvider Resolver Table:"
22167                        : "Provider Resolver Table:", "  ", packageName,
22168                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
22169                    dumpState.setTitlePrinted(true);
22170                }
22171            }
22172
22173            if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED)) {
22174                for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
22175                    PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
22176                    int user = mSettings.mPreferredActivities.keyAt(i);
22177                    if (pir.dump(pw,
22178                            dumpState.getTitlePrinted()
22179                                ? "\nPreferred Activities User " + user + ":"
22180                                : "Preferred Activities User " + user + ":", "  ",
22181                            packageName, true, false)) {
22182                        dumpState.setTitlePrinted(true);
22183                    }
22184                }
22185            }
22186
22187            if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED_XML)) {
22188                pw.flush();
22189                FileOutputStream fout = new FileOutputStream(fd);
22190                BufferedOutputStream str = new BufferedOutputStream(fout);
22191                XmlSerializer serializer = new FastXmlSerializer();
22192                try {
22193                    serializer.setOutput(str, StandardCharsets.UTF_8.name());
22194                    serializer.startDocument(null, true);
22195                    serializer.setFeature(
22196                            "http://xmlpull.org/v1/doc/features.html#indent-output", true);
22197                    mSettings.writePreferredActivitiesLPr(serializer, 0, fullPreferred);
22198                    serializer.endDocument();
22199                    serializer.flush();
22200                } catch (IllegalArgumentException e) {
22201                    pw.println("Failed writing: " + e);
22202                } catch (IllegalStateException e) {
22203                    pw.println("Failed writing: " + e);
22204                } catch (IOException e) {
22205                    pw.println("Failed writing: " + e);
22206                }
22207            }
22208
22209            if (!checkin
22210                    && dumpState.isDumping(DumpState.DUMP_DOMAIN_PREFERRED)
22211                    && packageName == null) {
22212                pw.println();
22213                int count = mSettings.mPackages.size();
22214                if (count == 0) {
22215                    pw.println("No applications!");
22216                    pw.println();
22217                } else {
22218                    final String prefix = "  ";
22219                    Collection<PackageSetting> allPackageSettings = mSettings.mPackages.values();
22220                    if (allPackageSettings.size() == 0) {
22221                        pw.println("No domain preferred apps!");
22222                        pw.println();
22223                    } else {
22224                        pw.println("App verification status:");
22225                        pw.println();
22226                        count = 0;
22227                        for (PackageSetting ps : allPackageSettings) {
22228                            IntentFilterVerificationInfo ivi = ps.getIntentFilterVerificationInfo();
22229                            if (ivi == null || ivi.getPackageName() == null) continue;
22230                            pw.println(prefix + "Package: " + ivi.getPackageName());
22231                            pw.println(prefix + "Domains: " + ivi.getDomainsString());
22232                            pw.println(prefix + "Status:  " + ivi.getStatusString());
22233                            pw.println();
22234                            count++;
22235                        }
22236                        if (count == 0) {
22237                            pw.println(prefix + "No app verification established.");
22238                            pw.println();
22239                        }
22240                        for (int userId : sUserManager.getUserIds()) {
22241                            pw.println("App linkages for user " + userId + ":");
22242                            pw.println();
22243                            count = 0;
22244                            for (PackageSetting ps : allPackageSettings) {
22245                                final long status = ps.getDomainVerificationStatusForUser(userId);
22246                                if (status >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED
22247                                        && !DEBUG_DOMAIN_VERIFICATION) {
22248                                    continue;
22249                                }
22250                                pw.println(prefix + "Package: " + ps.name);
22251                                pw.println(prefix + "Domains: " + dumpDomainString(ps.name));
22252                                String statusStr = IntentFilterVerificationInfo.
22253                                        getStatusStringFromValue(status);
22254                                pw.println(prefix + "Status:  " + statusStr);
22255                                pw.println();
22256                                count++;
22257                            }
22258                            if (count == 0) {
22259                                pw.println(prefix + "No configured app linkages.");
22260                                pw.println();
22261                            }
22262                        }
22263                    }
22264                }
22265            }
22266
22267            if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS)) {
22268                mSettings.dumpPermissionsLPr(pw, packageName, permissionNames, dumpState);
22269                if (packageName == null && permissionNames == null) {
22270                    for (int iperm=0; iperm<mAppOpPermissionPackages.size(); iperm++) {
22271                        if (iperm == 0) {
22272                            if (dumpState.onTitlePrinted())
22273                                pw.println();
22274                            pw.println("AppOp Permissions:");
22275                        }
22276                        pw.print("  AppOp Permission ");
22277                        pw.print(mAppOpPermissionPackages.keyAt(iperm));
22278                        pw.println(":");
22279                        ArraySet<String> pkgs = mAppOpPermissionPackages.valueAt(iperm);
22280                        for (int ipkg=0; ipkg<pkgs.size(); ipkg++) {
22281                            pw.print("    "); pw.println(pkgs.valueAt(ipkg));
22282                        }
22283                    }
22284                }
22285            }
22286
22287            if (!checkin && dumpState.isDumping(DumpState.DUMP_PROVIDERS)) {
22288                boolean printedSomething = false;
22289                for (PackageParser.Provider p : mProviders.mProviders.values()) {
22290                    if (packageName != null && !packageName.equals(p.info.packageName)) {
22291                        continue;
22292                    }
22293                    if (!printedSomething) {
22294                        if (dumpState.onTitlePrinted())
22295                            pw.println();
22296                        pw.println("Registered ContentProviders:");
22297                        printedSomething = true;
22298                    }
22299                    pw.print("  "); p.printComponentShortName(pw); pw.println(":");
22300                    pw.print("    "); pw.println(p.toString());
22301                }
22302                printedSomething = false;
22303                for (Map.Entry<String, PackageParser.Provider> entry :
22304                        mProvidersByAuthority.entrySet()) {
22305                    PackageParser.Provider p = entry.getValue();
22306                    if (packageName != null && !packageName.equals(p.info.packageName)) {
22307                        continue;
22308                    }
22309                    if (!printedSomething) {
22310                        if (dumpState.onTitlePrinted())
22311                            pw.println();
22312                        pw.println("ContentProvider Authorities:");
22313                        printedSomething = true;
22314                    }
22315                    pw.print("  ["); pw.print(entry.getKey()); pw.println("]:");
22316                    pw.print("    "); pw.println(p.toString());
22317                    if (p.info != null && p.info.applicationInfo != null) {
22318                        final String appInfo = p.info.applicationInfo.toString();
22319                        pw.print("      applicationInfo="); pw.println(appInfo);
22320                    }
22321                }
22322            }
22323
22324            if (!checkin && dumpState.isDumping(DumpState.DUMP_KEYSETS)) {
22325                mSettings.mKeySetManagerService.dumpLPr(pw, packageName, dumpState);
22326            }
22327
22328            if (dumpState.isDumping(DumpState.DUMP_PACKAGES)) {
22329                mSettings.dumpPackagesLPr(pw, packageName, permissionNames, dumpState, checkin);
22330            }
22331
22332            if (dumpState.isDumping(DumpState.DUMP_SHARED_USERS)) {
22333                mSettings.dumpSharedUsersLPr(pw, packageName, permissionNames, dumpState, checkin);
22334            }
22335
22336            if (dumpState.isDumping(DumpState.DUMP_CHANGES)) {
22337                if (dumpState.onTitlePrinted()) pw.println();
22338                pw.println("Package Changes:");
22339                pw.print("  Sequence number="); pw.println(mChangedPackagesSequenceNumber);
22340                final int K = mChangedPackages.size();
22341                for (int i = 0; i < K; i++) {
22342                    final SparseArray<String> changes = mChangedPackages.valueAt(i);
22343                    pw.print("  User "); pw.print(mChangedPackages.keyAt(i)); pw.println(":");
22344                    final int N = changes.size();
22345                    if (N == 0) {
22346                        pw.print("    "); pw.println("No packages changed");
22347                    } else {
22348                        for (int j = 0; j < N; j++) {
22349                            final String pkgName = changes.valueAt(j);
22350                            final int sequenceNumber = changes.keyAt(j);
22351                            pw.print("    ");
22352                            pw.print("seq=");
22353                            pw.print(sequenceNumber);
22354                            pw.print(", package=");
22355                            pw.println(pkgName);
22356                        }
22357                    }
22358                }
22359            }
22360
22361            if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS) && packageName == null) {
22362                mSettings.dumpRestoredPermissionGrantsLPr(pw, dumpState);
22363            }
22364
22365            if (!checkin && dumpState.isDumping(DumpState.DUMP_FROZEN) && packageName == null) {
22366                // XXX should handle packageName != null by dumping only install data that
22367                // the given package is involved with.
22368                if (dumpState.onTitlePrinted()) pw.println();
22369
22370                final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, "  ", 120);
22371                ipw.println();
22372                ipw.println("Frozen packages:");
22373                ipw.increaseIndent();
22374                if (mFrozenPackages.size() == 0) {
22375                    ipw.println("(none)");
22376                } else {
22377                    for (int i = 0; i < mFrozenPackages.size(); i++) {
22378                        ipw.println(mFrozenPackages.valueAt(i));
22379                    }
22380                }
22381                ipw.decreaseIndent();
22382            }
22383
22384            if (!checkin && dumpState.isDumping(DumpState.DUMP_DEXOPT)) {
22385                if (dumpState.onTitlePrinted()) pw.println();
22386                dumpDexoptStateLPr(pw, packageName);
22387            }
22388
22389            if (!checkin && dumpState.isDumping(DumpState.DUMP_COMPILER_STATS)) {
22390                if (dumpState.onTitlePrinted()) pw.println();
22391                dumpCompilerStatsLPr(pw, packageName);
22392            }
22393
22394            if (!checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES) && packageName == null) {
22395                if (dumpState.onTitlePrinted()) pw.println();
22396                mSettings.dumpReadMessagesLPr(pw, dumpState);
22397
22398                pw.println();
22399                pw.println("Package warning messages:");
22400                BufferedReader in = null;
22401                String line = null;
22402                try {
22403                    in = new BufferedReader(new FileReader(getSettingsProblemFile()));
22404                    while ((line = in.readLine()) != null) {
22405                        if (line.contains("ignored: updated version")) continue;
22406                        pw.println(line);
22407                    }
22408                } catch (IOException ignored) {
22409                } finally {
22410                    IoUtils.closeQuietly(in);
22411                }
22412            }
22413
22414            if (checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES)) {
22415                BufferedReader in = null;
22416                String line = null;
22417                try {
22418                    in = new BufferedReader(new FileReader(getSettingsProblemFile()));
22419                    while ((line = in.readLine()) != null) {
22420                        if (line.contains("ignored: updated version")) continue;
22421                        pw.print("msg,");
22422                        pw.println(line);
22423                    }
22424                } catch (IOException ignored) {
22425                } finally {
22426                    IoUtils.closeQuietly(in);
22427                }
22428            }
22429        }
22430
22431        // PackageInstaller should be called outside of mPackages lock
22432        if (!checkin && dumpState.isDumping(DumpState.DUMP_INSTALLS) && packageName == null) {
22433            // XXX should handle packageName != null by dumping only install data that
22434            // the given package is involved with.
22435            if (dumpState.onTitlePrinted()) pw.println();
22436            mInstallerService.dump(new IndentingPrintWriter(pw, "  ", 120));
22437        }
22438    }
22439
22440    private void dumpProto(FileDescriptor fd) {
22441        final ProtoOutputStream proto = new ProtoOutputStream(fd);
22442
22443        synchronized (mPackages) {
22444            final long requiredVerifierPackageToken =
22445                    proto.start(PackageServiceDumpProto.REQUIRED_VERIFIER_PACKAGE);
22446            proto.write(PackageServiceDumpProto.PackageShortProto.NAME, mRequiredVerifierPackage);
22447            proto.write(
22448                    PackageServiceDumpProto.PackageShortProto.UID,
22449                    getPackageUid(
22450                            mRequiredVerifierPackage,
22451                            MATCH_DEBUG_TRIAGED_MISSING,
22452                            UserHandle.USER_SYSTEM));
22453            proto.end(requiredVerifierPackageToken);
22454
22455            if (mIntentFilterVerifierComponent != null) {
22456                String verifierPackageName = mIntentFilterVerifierComponent.getPackageName();
22457                final long verifierPackageToken =
22458                        proto.start(PackageServiceDumpProto.VERIFIER_PACKAGE);
22459                proto.write(PackageServiceDumpProto.PackageShortProto.NAME, verifierPackageName);
22460                proto.write(
22461                        PackageServiceDumpProto.PackageShortProto.UID,
22462                        getPackageUid(
22463                                verifierPackageName,
22464                                MATCH_DEBUG_TRIAGED_MISSING,
22465                                UserHandle.USER_SYSTEM));
22466                proto.end(verifierPackageToken);
22467            }
22468
22469            dumpSharedLibrariesProto(proto);
22470            dumpFeaturesProto(proto);
22471            mSettings.dumpPackagesProto(proto);
22472            mSettings.dumpSharedUsersProto(proto);
22473            dumpMessagesProto(proto);
22474        }
22475        proto.flush();
22476    }
22477
22478    private void dumpMessagesProto(ProtoOutputStream proto) {
22479        BufferedReader in = null;
22480        String line = null;
22481        try {
22482            in = new BufferedReader(new FileReader(getSettingsProblemFile()));
22483            while ((line = in.readLine()) != null) {
22484                if (line.contains("ignored: updated version")) continue;
22485                proto.write(PackageServiceDumpProto.MESSAGES, line);
22486            }
22487        } catch (IOException ignored) {
22488        } finally {
22489            IoUtils.closeQuietly(in);
22490        }
22491    }
22492
22493    private void dumpFeaturesProto(ProtoOutputStream proto) {
22494        synchronized (mAvailableFeatures) {
22495            final int count = mAvailableFeatures.size();
22496            for (int i = 0; i < count; i++) {
22497                final FeatureInfo feat = mAvailableFeatures.valueAt(i);
22498                final long featureToken = proto.start(PackageServiceDumpProto.FEATURES);
22499                proto.write(PackageServiceDumpProto.FeatureProto.NAME, feat.name);
22500                proto.write(PackageServiceDumpProto.FeatureProto.VERSION, feat.version);
22501                proto.end(featureToken);
22502            }
22503        }
22504    }
22505
22506    private void dumpSharedLibrariesProto(ProtoOutputStream proto) {
22507        final int count = mSharedLibraries.size();
22508        for (int i = 0; i < count; i++) {
22509            final String libName = mSharedLibraries.keyAt(i);
22510            SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(libName);
22511            if (versionedLib == null) {
22512                continue;
22513            }
22514            final int versionCount = versionedLib.size();
22515            for (int j = 0; j < versionCount; j++) {
22516                final SharedLibraryEntry libEntry = versionedLib.valueAt(j);
22517                final long sharedLibraryToken =
22518                        proto.start(PackageServiceDumpProto.SHARED_LIBRARIES);
22519                proto.write(PackageServiceDumpProto.SharedLibraryProto.NAME, libEntry.info.getName());
22520                final boolean isJar = (libEntry.path != null);
22521                proto.write(PackageServiceDumpProto.SharedLibraryProto.IS_JAR, isJar);
22522                if (isJar) {
22523                    proto.write(PackageServiceDumpProto.SharedLibraryProto.PATH, libEntry.path);
22524                } else {
22525                    proto.write(PackageServiceDumpProto.SharedLibraryProto.APK, libEntry.apk);
22526                }
22527                proto.end(sharedLibraryToken);
22528            }
22529        }
22530    }
22531
22532    private void dumpDexoptStateLPr(PrintWriter pw, String packageName) {
22533        final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, "  ", 120);
22534        ipw.println();
22535        ipw.println("Dexopt state:");
22536        ipw.increaseIndent();
22537        Collection<PackageParser.Package> packages = null;
22538        if (packageName != null) {
22539            PackageParser.Package targetPackage = mPackages.get(packageName);
22540            if (targetPackage != null) {
22541                packages = Collections.singletonList(targetPackage);
22542            } else {
22543                ipw.println("Unable to find package: " + packageName);
22544                return;
22545            }
22546        } else {
22547            packages = mPackages.values();
22548        }
22549
22550        for (PackageParser.Package pkg : packages) {
22551            ipw.println("[" + pkg.packageName + "]");
22552            ipw.increaseIndent();
22553            mPackageDexOptimizer.dumpDexoptState(ipw, pkg);
22554            ipw.decreaseIndent();
22555        }
22556    }
22557
22558    private void dumpCompilerStatsLPr(PrintWriter pw, String packageName) {
22559        final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, "  ", 120);
22560        ipw.println();
22561        ipw.println("Compiler stats:");
22562        ipw.increaseIndent();
22563        Collection<PackageParser.Package> packages = null;
22564        if (packageName != null) {
22565            PackageParser.Package targetPackage = mPackages.get(packageName);
22566            if (targetPackage != null) {
22567                packages = Collections.singletonList(targetPackage);
22568            } else {
22569                ipw.println("Unable to find package: " + packageName);
22570                return;
22571            }
22572        } else {
22573            packages = mPackages.values();
22574        }
22575
22576        for (PackageParser.Package pkg : packages) {
22577            ipw.println("[" + pkg.packageName + "]");
22578            ipw.increaseIndent();
22579
22580            CompilerStats.PackageStats stats = getCompilerPackageStats(pkg.packageName);
22581            if (stats == null) {
22582                ipw.println("(No recorded stats)");
22583            } else {
22584                stats.dump(ipw);
22585            }
22586            ipw.decreaseIndent();
22587        }
22588    }
22589
22590    private String dumpDomainString(String packageName) {
22591        List<IntentFilterVerificationInfo> iviList = getIntentFilterVerifications(packageName)
22592                .getList();
22593        List<IntentFilter> filters = getAllIntentFilters(packageName).getList();
22594
22595        ArraySet<String> result = new ArraySet<>();
22596        if (iviList.size() > 0) {
22597            for (IntentFilterVerificationInfo ivi : iviList) {
22598                for (String host : ivi.getDomains()) {
22599                    result.add(host);
22600                }
22601            }
22602        }
22603        if (filters != null && filters.size() > 0) {
22604            for (IntentFilter filter : filters) {
22605                if (filter.hasCategory(Intent.CATEGORY_BROWSABLE)
22606                        && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) ||
22607                                filter.hasDataScheme(IntentFilter.SCHEME_HTTPS))) {
22608                    result.addAll(filter.getHostsList());
22609                }
22610            }
22611        }
22612
22613        StringBuilder sb = new StringBuilder(result.size() * 16);
22614        for (String domain : result) {
22615            if (sb.length() > 0) sb.append(" ");
22616            sb.append(domain);
22617        }
22618        return sb.toString();
22619    }
22620
22621    // ------- apps on sdcard specific code -------
22622    static final boolean DEBUG_SD_INSTALL = false;
22623
22624    private static final String SD_ENCRYPTION_KEYSTORE_NAME = "AppsOnSD";
22625
22626    private static final String SD_ENCRYPTION_ALGORITHM = "AES";
22627
22628    private boolean mMediaMounted = false;
22629
22630    static String getEncryptKey() {
22631        try {
22632            String sdEncKey = SystemKeyStore.getInstance().retrieveKeyHexString(
22633                    SD_ENCRYPTION_KEYSTORE_NAME);
22634            if (sdEncKey == null) {
22635                sdEncKey = SystemKeyStore.getInstance().generateNewKeyHexString(128,
22636                        SD_ENCRYPTION_ALGORITHM, SD_ENCRYPTION_KEYSTORE_NAME);
22637                if (sdEncKey == null) {
22638                    Slog.e(TAG, "Failed to create encryption keys");
22639                    return null;
22640                }
22641            }
22642            return sdEncKey;
22643        } catch (NoSuchAlgorithmException nsae) {
22644            Slog.e(TAG, "Failed to create encryption keys with exception: " + nsae);
22645            return null;
22646        } catch (IOException ioe) {
22647            Slog.e(TAG, "Failed to retrieve encryption keys with exception: " + ioe);
22648            return null;
22649        }
22650    }
22651
22652    /*
22653     * Update media status on PackageManager.
22654     */
22655    @Override
22656    public void updateExternalMediaStatus(final boolean mediaStatus, final boolean reportStatus) {
22657        enforceSystemOrRoot("Media status can only be updated by the system");
22658        // reader; this apparently protects mMediaMounted, but should probably
22659        // be a different lock in that case.
22660        synchronized (mPackages) {
22661            Log.i(TAG, "Updating external media status from "
22662                    + (mMediaMounted ? "mounted" : "unmounted") + " to "
22663                    + (mediaStatus ? "mounted" : "unmounted"));
22664            if (DEBUG_SD_INSTALL)
22665                Log.i(TAG, "updateExternalMediaStatus:: mediaStatus=" + mediaStatus
22666                        + ", mMediaMounted=" + mMediaMounted);
22667            if (mediaStatus == mMediaMounted) {
22668                final Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1
22669                        : 0, -1);
22670                mHandler.sendMessage(msg);
22671                return;
22672            }
22673            mMediaMounted = mediaStatus;
22674        }
22675        // Queue up an async operation since the package installation may take a
22676        // little while.
22677        mHandler.post(new Runnable() {
22678            public void run() {
22679                updateExternalMediaStatusInner(mediaStatus, reportStatus, true);
22680            }
22681        });
22682    }
22683
22684    /**
22685     * Called by StorageManagerService when the initial ASECs to scan are available.
22686     * Should block until all the ASEC containers are finished being scanned.
22687     */
22688    public void scanAvailableAsecs() {
22689        updateExternalMediaStatusInner(true, false, false);
22690    }
22691
22692    /*
22693     * Collect information of applications on external media, map them against
22694     * existing containers and update information based on current mount status.
22695     * Please note that we always have to report status if reportStatus has been
22696     * set to true especially when unloading packages.
22697     */
22698    private void updateExternalMediaStatusInner(boolean isMounted, boolean reportStatus,
22699            boolean externalStorage) {
22700        ArrayMap<AsecInstallArgs, String> processCids = new ArrayMap<>();
22701        int[] uidArr = EmptyArray.INT;
22702
22703        final String[] list = PackageHelper.getSecureContainerList();
22704        if (ArrayUtils.isEmpty(list)) {
22705            Log.i(TAG, "No secure containers found");
22706        } else {
22707            // Process list of secure containers and categorize them
22708            // as active or stale based on their package internal state.
22709
22710            // reader
22711            synchronized (mPackages) {
22712                for (String cid : list) {
22713                    // Leave stages untouched for now; installer service owns them
22714                    if (PackageInstallerService.isStageName(cid)) continue;
22715
22716                    if (DEBUG_SD_INSTALL)
22717                        Log.i(TAG, "Processing container " + cid);
22718                    String pkgName = getAsecPackageName(cid);
22719                    if (pkgName == null) {
22720                        Slog.i(TAG, "Found stale container " + cid + " with no package name");
22721                        continue;
22722                    }
22723                    if (DEBUG_SD_INSTALL)
22724                        Log.i(TAG, "Looking for pkg : " + pkgName);
22725
22726                    final PackageSetting ps = mSettings.mPackages.get(pkgName);
22727                    if (ps == null) {
22728                        Slog.i(TAG, "Found stale container " + cid + " with no matching settings");
22729                        continue;
22730                    }
22731
22732                    /*
22733                     * Skip packages that are not external if we're unmounting
22734                     * external storage.
22735                     */
22736                    if (externalStorage && !isMounted && !isExternal(ps)) {
22737                        continue;
22738                    }
22739
22740                    final AsecInstallArgs args = new AsecInstallArgs(cid,
22741                            getAppDexInstructionSets(ps), ps.isForwardLocked());
22742                    // The package status is changed only if the code path
22743                    // matches between settings and the container id.
22744                    if (ps.codePathString != null
22745                            && ps.codePathString.startsWith(args.getCodePath())) {
22746                        if (DEBUG_SD_INSTALL) {
22747                            Log.i(TAG, "Container : " + cid + " corresponds to pkg : " + pkgName
22748                                    + " at code path: " + ps.codePathString);
22749                        }
22750
22751                        // We do have a valid package installed on sdcard
22752                        processCids.put(args, ps.codePathString);
22753                        final int uid = ps.appId;
22754                        if (uid != -1) {
22755                            uidArr = ArrayUtils.appendInt(uidArr, uid);
22756                        }
22757                    } else {
22758                        Slog.i(TAG, "Found stale container " + cid + ": expected codePath="
22759                                + ps.codePathString);
22760                    }
22761                }
22762            }
22763
22764            Arrays.sort(uidArr);
22765        }
22766
22767        // Process packages with valid entries.
22768        if (isMounted) {
22769            if (DEBUG_SD_INSTALL)
22770                Log.i(TAG, "Loading packages");
22771            loadMediaPackages(processCids, uidArr, externalStorage);
22772            startCleaningPackages();
22773            mInstallerService.onSecureContainersAvailable();
22774        } else {
22775            if (DEBUG_SD_INSTALL)
22776                Log.i(TAG, "Unloading packages");
22777            unloadMediaPackages(processCids, uidArr, reportStatus);
22778        }
22779    }
22780
22781    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
22782            ArrayList<ApplicationInfo> infos, IIntentReceiver finishedReceiver) {
22783        final int size = infos.size();
22784        final String[] packageNames = new String[size];
22785        final int[] packageUids = new int[size];
22786        for (int i = 0; i < size; i++) {
22787            final ApplicationInfo info = infos.get(i);
22788            packageNames[i] = info.packageName;
22789            packageUids[i] = info.uid;
22790        }
22791        sendResourcesChangedBroadcast(mediaStatus, replacing, packageNames, packageUids,
22792                finishedReceiver);
22793    }
22794
22795    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
22796            ArrayList<String> pkgList, int uidArr[], IIntentReceiver finishedReceiver) {
22797        sendResourcesChangedBroadcast(mediaStatus, replacing,
22798                pkgList.toArray(new String[pkgList.size()]), uidArr, finishedReceiver);
22799    }
22800
22801    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
22802            String[] pkgList, int uidArr[], IIntentReceiver finishedReceiver) {
22803        int size = pkgList.length;
22804        if (size > 0) {
22805            // Send broadcasts here
22806            Bundle extras = new Bundle();
22807            extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList);
22808            if (uidArr != null) {
22809                extras.putIntArray(Intent.EXTRA_CHANGED_UID_LIST, uidArr);
22810            }
22811            if (replacing) {
22812                extras.putBoolean(Intent.EXTRA_REPLACING, replacing);
22813            }
22814            String action = mediaStatus ? Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE
22815                    : Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE;
22816            sendPackageBroadcast(action, null, extras, 0, null, finishedReceiver, null);
22817        }
22818    }
22819
22820   /*
22821     * Look at potentially valid container ids from processCids If package
22822     * information doesn't match the one on record or package scanning fails,
22823     * the cid is added to list of removeCids. We currently don't delete stale
22824     * containers.
22825     */
22826    private void loadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int[] uidArr,
22827            boolean externalStorage) {
22828        ArrayList<String> pkgList = new ArrayList<String>();
22829        Set<AsecInstallArgs> keys = processCids.keySet();
22830
22831        for (AsecInstallArgs args : keys) {
22832            String codePath = processCids.get(args);
22833            if (DEBUG_SD_INSTALL)
22834                Log.i(TAG, "Loading container : " + args.cid);
22835            int retCode = PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
22836            try {
22837                // Make sure there are no container errors first.
22838                if (args.doPreInstall(PackageManager.INSTALL_SUCCEEDED) != PackageManager.INSTALL_SUCCEEDED) {
22839                    Slog.e(TAG, "Failed to mount cid : " + args.cid
22840                            + " when installing from sdcard");
22841                    continue;
22842                }
22843                // Check code path here.
22844                if (codePath == null || !codePath.startsWith(args.getCodePath())) {
22845                    Slog.e(TAG, "Container " + args.cid + " cachepath " + args.getCodePath()
22846                            + " does not match one in settings " + codePath);
22847                    continue;
22848                }
22849                // Parse package
22850                int parseFlags = mDefParseFlags;
22851                if (args.isExternalAsec()) {
22852                    parseFlags |= PackageParser.PARSE_EXTERNAL_STORAGE;
22853                }
22854                if (args.isFwdLocked()) {
22855                    parseFlags |= PackageParser.PARSE_FORWARD_LOCK;
22856                }
22857
22858                synchronized (mInstallLock) {
22859                    PackageParser.Package pkg = null;
22860                    try {
22861                        // Sadly we don't know the package name yet to freeze it
22862                        pkg = scanPackageTracedLI(new File(codePath), parseFlags,
22863                                SCAN_IGNORE_FROZEN, 0, null);
22864                    } catch (PackageManagerException e) {
22865                        Slog.w(TAG, "Failed to scan " + codePath + ": " + e.getMessage());
22866                    }
22867                    // Scan the package
22868                    if (pkg != null) {
22869                        /*
22870                         * TODO why is the lock being held? doPostInstall is
22871                         * called in other places without the lock. This needs
22872                         * to be straightened out.
22873                         */
22874                        // writer
22875                        synchronized (mPackages) {
22876                            retCode = PackageManager.INSTALL_SUCCEEDED;
22877                            pkgList.add(pkg.packageName);
22878                            // Post process args
22879                            args.doPostInstall(PackageManager.INSTALL_SUCCEEDED,
22880                                    pkg.applicationInfo.uid);
22881                        }
22882                    } else {
22883                        Slog.i(TAG, "Failed to install pkg from  " + codePath + " from sdcard");
22884                    }
22885                }
22886
22887            } finally {
22888                if (retCode != PackageManager.INSTALL_SUCCEEDED) {
22889                    Log.w(TAG, "Container " + args.cid + " is stale, retCode=" + retCode);
22890                }
22891            }
22892        }
22893        // writer
22894        synchronized (mPackages) {
22895            // If the platform SDK has changed since the last time we booted,
22896            // we need to re-grant app permission to catch any new ones that
22897            // appear. This is really a hack, and means that apps can in some
22898            // cases get permissions that the user didn't initially explicitly
22899            // allow... it would be nice to have some better way to handle
22900            // this situation.
22901            final VersionInfo ver = externalStorage ? mSettings.getExternalVersion()
22902                    : mSettings.getInternalVersion();
22903            final String volumeUuid = externalStorage ? StorageManager.UUID_PRIMARY_PHYSICAL
22904                    : StorageManager.UUID_PRIVATE_INTERNAL;
22905
22906            int updateFlags = UPDATE_PERMISSIONS_ALL;
22907            if (ver.sdkVersion != mSdkVersion) {
22908                logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to "
22909                        + mSdkVersion + "; regranting permissions for external");
22910                updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL;
22911            }
22912            updatePermissionsLPw(null, null, volumeUuid, updateFlags);
22913
22914            // Yay, everything is now upgraded
22915            ver.forceCurrent();
22916
22917            // can downgrade to reader
22918            // Persist settings
22919            mSettings.writeLPr();
22920        }
22921        // Send a broadcast to let everyone know we are done processing
22922        if (pkgList.size() > 0) {
22923            sendResourcesChangedBroadcast(true, false, pkgList, uidArr, null);
22924        }
22925    }
22926
22927   /*
22928     * Utility method to unload a list of specified containers
22929     */
22930    private void unloadAllContainers(Set<AsecInstallArgs> cidArgs) {
22931        // Just unmount all valid containers.
22932        for (AsecInstallArgs arg : cidArgs) {
22933            synchronized (mInstallLock) {
22934                arg.doPostDeleteLI(false);
22935           }
22936       }
22937   }
22938
22939    /*
22940     * Unload packages mounted on external media. This involves deleting package
22941     * data from internal structures, sending broadcasts about disabled packages,
22942     * gc'ing to free up references, unmounting all secure containers
22943     * corresponding to packages on external media, and posting a
22944     * UPDATED_MEDIA_STATUS message if status has been requested. Please note
22945     * that we always have to post this message if status has been requested no
22946     * matter what.
22947     */
22948    private void unloadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int uidArr[],
22949            final boolean reportStatus) {
22950        if (DEBUG_SD_INSTALL)
22951            Log.i(TAG, "unloading media packages");
22952        ArrayList<String> pkgList = new ArrayList<String>();
22953        ArrayList<AsecInstallArgs> failedList = new ArrayList<AsecInstallArgs>();
22954        final Set<AsecInstallArgs> keys = processCids.keySet();
22955        for (AsecInstallArgs args : keys) {
22956            String pkgName = args.getPackageName();
22957            if (DEBUG_SD_INSTALL)
22958                Log.i(TAG, "Trying to unload pkg : " + pkgName);
22959            // Delete package internally
22960            PackageRemovedInfo outInfo = new PackageRemovedInfo(this);
22961            synchronized (mInstallLock) {
22962                final int deleteFlags = PackageManager.DELETE_KEEP_DATA;
22963                final boolean res;
22964                try (PackageFreezer freezer = freezePackageForDelete(pkgName, deleteFlags,
22965                        "unloadMediaPackages")) {
22966                    res = deletePackageLIF(pkgName, null, false, null, deleteFlags, outInfo, false,
22967                            null);
22968                }
22969                if (res) {
22970                    pkgList.add(pkgName);
22971                } else {
22972                    Slog.e(TAG, "Failed to delete pkg from sdcard : " + pkgName);
22973                    failedList.add(args);
22974                }
22975            }
22976        }
22977
22978        // reader
22979        synchronized (mPackages) {
22980            // We didn't update the settings after removing each package;
22981            // write them now for all packages.
22982            mSettings.writeLPr();
22983        }
22984
22985        // We have to absolutely send UPDATED_MEDIA_STATUS only
22986        // after confirming that all the receivers processed the ordered
22987        // broadcast when packages get disabled, force a gc to clean things up.
22988        // and unload all the containers.
22989        if (pkgList.size() > 0) {
22990            sendResourcesChangedBroadcast(false, false, pkgList, uidArr,
22991                    new IIntentReceiver.Stub() {
22992                public void performReceive(Intent intent, int resultCode, String data,
22993                        Bundle extras, boolean ordered, boolean sticky,
22994                        int sendingUser) throws RemoteException {
22995                    Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS,
22996                            reportStatus ? 1 : 0, 1, keys);
22997                    mHandler.sendMessage(msg);
22998                }
22999            });
23000        } else {
23001            Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 : 0, -1,
23002                    keys);
23003            mHandler.sendMessage(msg);
23004        }
23005    }
23006
23007    private void loadPrivatePackages(final VolumeInfo vol) {
23008        mHandler.post(new Runnable() {
23009            @Override
23010            public void run() {
23011                loadPrivatePackagesInner(vol);
23012            }
23013        });
23014    }
23015
23016    private void loadPrivatePackagesInner(VolumeInfo vol) {
23017        final String volumeUuid = vol.fsUuid;
23018        if (TextUtils.isEmpty(volumeUuid)) {
23019            Slog.e(TAG, "Loading internal storage is probably a mistake; ignoring");
23020            return;
23021        }
23022
23023        final ArrayList<PackageFreezer> freezers = new ArrayList<>();
23024        final ArrayList<ApplicationInfo> loaded = new ArrayList<>();
23025        final int parseFlags = mDefParseFlags | PackageParser.PARSE_EXTERNAL_STORAGE;
23026
23027        final VersionInfo ver;
23028        final List<PackageSetting> packages;
23029        synchronized (mPackages) {
23030            ver = mSettings.findOrCreateVersion(volumeUuid);
23031            packages = mSettings.getVolumePackagesLPr(volumeUuid);
23032        }
23033
23034        for (PackageSetting ps : packages) {
23035            freezers.add(freezePackage(ps.name, "loadPrivatePackagesInner"));
23036            synchronized (mInstallLock) {
23037                final PackageParser.Package pkg;
23038                try {
23039                    pkg = scanPackageTracedLI(ps.codePath, parseFlags, SCAN_INITIAL, 0, null);
23040                    loaded.add(pkg.applicationInfo);
23041
23042                } catch (PackageManagerException e) {
23043                    Slog.w(TAG, "Failed to scan " + ps.codePath + ": " + e.getMessage());
23044                }
23045
23046                if (!Build.FINGERPRINT.equals(ver.fingerprint)) {
23047                    clearAppDataLIF(ps.pkg, UserHandle.USER_ALL,
23048                            StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE
23049                                    | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
23050                }
23051            }
23052        }
23053
23054        // Reconcile app data for all started/unlocked users
23055        final StorageManager sm = mContext.getSystemService(StorageManager.class);
23056        final UserManager um = mContext.getSystemService(UserManager.class);
23057        UserManagerInternal umInternal = getUserManagerInternal();
23058        for (UserInfo user : um.getUsers()) {
23059            final int flags;
23060            if (umInternal.isUserUnlockingOrUnlocked(user.id)) {
23061                flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
23062            } else if (umInternal.isUserRunning(user.id)) {
23063                flags = StorageManager.FLAG_STORAGE_DE;
23064            } else {
23065                continue;
23066            }
23067
23068            try {
23069                sm.prepareUserStorage(volumeUuid, user.id, user.serialNumber, flags);
23070                synchronized (mInstallLock) {
23071                    reconcileAppsDataLI(volumeUuid, user.id, flags, true /* migrateAppData */);
23072                }
23073            } catch (IllegalStateException e) {
23074                // Device was probably ejected, and we'll process that event momentarily
23075                Slog.w(TAG, "Failed to prepare storage: " + e);
23076            }
23077        }
23078
23079        synchronized (mPackages) {
23080            int updateFlags = UPDATE_PERMISSIONS_ALL;
23081            if (ver.sdkVersion != mSdkVersion) {
23082                logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to "
23083                        + mSdkVersion + "; regranting permissions for " + volumeUuid);
23084                updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL;
23085            }
23086            updatePermissionsLPw(null, null, volumeUuid, updateFlags);
23087
23088            // Yay, everything is now upgraded
23089            ver.forceCurrent();
23090
23091            mSettings.writeLPr();
23092        }
23093
23094        for (PackageFreezer freezer : freezers) {
23095            freezer.close();
23096        }
23097
23098        if (DEBUG_INSTALL) Slog.d(TAG, "Loaded packages " + loaded);
23099        sendResourcesChangedBroadcast(true, false, loaded, null);
23100    }
23101
23102    private void unloadPrivatePackages(final VolumeInfo vol) {
23103        mHandler.post(new Runnable() {
23104            @Override
23105            public void run() {
23106                unloadPrivatePackagesInner(vol);
23107            }
23108        });
23109    }
23110
23111    private void unloadPrivatePackagesInner(VolumeInfo vol) {
23112        final String volumeUuid = vol.fsUuid;
23113        if (TextUtils.isEmpty(volumeUuid)) {
23114            Slog.e(TAG, "Unloading internal storage is probably a mistake; ignoring");
23115            return;
23116        }
23117
23118        final ArrayList<ApplicationInfo> unloaded = new ArrayList<>();
23119        synchronized (mInstallLock) {
23120        synchronized (mPackages) {
23121            final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(volumeUuid);
23122            for (PackageSetting ps : packages) {
23123                if (ps.pkg == null) continue;
23124
23125                final ApplicationInfo info = ps.pkg.applicationInfo;
23126                final int deleteFlags = PackageManager.DELETE_KEEP_DATA;
23127                final PackageRemovedInfo outInfo = new PackageRemovedInfo(this);
23128
23129                try (PackageFreezer freezer = freezePackageForDelete(ps.name, deleteFlags,
23130                        "unloadPrivatePackagesInner")) {
23131                    if (deletePackageLIF(ps.name, null, false, null, deleteFlags, outInfo,
23132                            false, null)) {
23133                        unloaded.add(info);
23134                    } else {
23135                        Slog.w(TAG, "Failed to unload " + ps.codePath);
23136                    }
23137                }
23138
23139                // Try very hard to release any references to this package
23140                // so we don't risk the system server being killed due to
23141                // open FDs
23142                AttributeCache.instance().removePackage(ps.name);
23143            }
23144
23145            mSettings.writeLPr();
23146        }
23147        }
23148
23149        if (DEBUG_INSTALL) Slog.d(TAG, "Unloaded packages " + unloaded);
23150        sendResourcesChangedBroadcast(false, false, unloaded, null);
23151
23152        // Try very hard to release any references to this path so we don't risk
23153        // the system server being killed due to open FDs
23154        ResourcesManager.getInstance().invalidatePath(vol.getPath().getAbsolutePath());
23155
23156        for (int i = 0; i < 3; i++) {
23157            System.gc();
23158            System.runFinalization();
23159        }
23160    }
23161
23162    private void assertPackageKnown(String volumeUuid, String packageName)
23163            throws PackageManagerException {
23164        synchronized (mPackages) {
23165            // Normalize package name to handle renamed packages
23166            packageName = normalizePackageNameLPr(packageName);
23167
23168            final PackageSetting ps = mSettings.mPackages.get(packageName);
23169            if (ps == null) {
23170                throw new PackageManagerException("Package " + packageName + " is unknown");
23171            } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) {
23172                throw new PackageManagerException(
23173                        "Package " + packageName + " found on unknown volume " + volumeUuid
23174                                + "; expected volume " + ps.volumeUuid);
23175            }
23176        }
23177    }
23178
23179    private void assertPackageKnownAndInstalled(String volumeUuid, String packageName, int userId)
23180            throws PackageManagerException {
23181        synchronized (mPackages) {
23182            // Normalize package name to handle renamed packages
23183            packageName = normalizePackageNameLPr(packageName);
23184
23185            final PackageSetting ps = mSettings.mPackages.get(packageName);
23186            if (ps == null) {
23187                throw new PackageManagerException("Package " + packageName + " is unknown");
23188            } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) {
23189                throw new PackageManagerException(
23190                        "Package " + packageName + " found on unknown volume " + volumeUuid
23191                                + "; expected volume " + ps.volumeUuid);
23192            } else if (!ps.getInstalled(userId)) {
23193                throw new PackageManagerException(
23194                        "Package " + packageName + " not installed for user " + userId);
23195            }
23196        }
23197    }
23198
23199    private List<String> collectAbsoluteCodePaths() {
23200        synchronized (mPackages) {
23201            List<String> codePaths = new ArrayList<>();
23202            final int packageCount = mSettings.mPackages.size();
23203            for (int i = 0; i < packageCount; i++) {
23204                final PackageSetting ps = mSettings.mPackages.valueAt(i);
23205                codePaths.add(ps.codePath.getAbsolutePath());
23206            }
23207            return codePaths;
23208        }
23209    }
23210
23211    /**
23212     * Examine all apps present on given mounted volume, and destroy apps that
23213     * aren't expected, either due to uninstallation or reinstallation on
23214     * another volume.
23215     */
23216    private void reconcileApps(String volumeUuid) {
23217        List<String> absoluteCodePaths = collectAbsoluteCodePaths();
23218        List<File> filesToDelete = null;
23219
23220        final File[] files = FileUtils.listFilesOrEmpty(
23221                Environment.getDataAppDirectory(volumeUuid));
23222        for (File file : files) {
23223            final boolean isPackage = (isApkFile(file) || file.isDirectory())
23224                    && !PackageInstallerService.isStageName(file.getName());
23225            if (!isPackage) {
23226                // Ignore entries which are not packages
23227                continue;
23228            }
23229
23230            String absolutePath = file.getAbsolutePath();
23231
23232            boolean pathValid = false;
23233            final int absoluteCodePathCount = absoluteCodePaths.size();
23234            for (int i = 0; i < absoluteCodePathCount; i++) {
23235                String absoluteCodePath = absoluteCodePaths.get(i);
23236                if (absolutePath.startsWith(absoluteCodePath)) {
23237                    pathValid = true;
23238                    break;
23239                }
23240            }
23241
23242            if (!pathValid) {
23243                if (filesToDelete == null) {
23244                    filesToDelete = new ArrayList<>();
23245                }
23246                filesToDelete.add(file);
23247            }
23248        }
23249
23250        if (filesToDelete != null) {
23251            final int fileToDeleteCount = filesToDelete.size();
23252            for (int i = 0; i < fileToDeleteCount; i++) {
23253                File fileToDelete = filesToDelete.get(i);
23254                logCriticalInfo(Log.WARN, "Destroying orphaned" + fileToDelete);
23255                synchronized (mInstallLock) {
23256                    removeCodePathLI(fileToDelete);
23257                }
23258            }
23259        }
23260    }
23261
23262    /**
23263     * Reconcile all app data for the given user.
23264     * <p>
23265     * Verifies that directories exist and that ownership and labeling is
23266     * correct for all installed apps on all mounted volumes.
23267     */
23268    void reconcileAppsData(int userId, int flags, boolean migrateAppsData) {
23269        final StorageManager storage = mContext.getSystemService(StorageManager.class);
23270        for (VolumeInfo vol : storage.getWritablePrivateVolumes()) {
23271            final String volumeUuid = vol.getFsUuid();
23272            synchronized (mInstallLock) {
23273                reconcileAppsDataLI(volumeUuid, userId, flags, migrateAppsData);
23274            }
23275        }
23276    }
23277
23278    private void reconcileAppsDataLI(String volumeUuid, int userId, int flags,
23279            boolean migrateAppData) {
23280        reconcileAppsDataLI(volumeUuid, userId, flags, migrateAppData, false /* onlyCoreApps */);
23281    }
23282
23283    /**
23284     * Reconcile all app data on given mounted volume.
23285     * <p>
23286     * Destroys app data that isn't expected, either due to uninstallation or
23287     * reinstallation on another volume.
23288     * <p>
23289     * Verifies that directories exist and that ownership and labeling is
23290     * correct for all installed apps.
23291     * @returns list of skipped non-core packages (if {@code onlyCoreApps} is true)
23292     */
23293    private List<String> reconcileAppsDataLI(String volumeUuid, int userId, int flags,
23294            boolean migrateAppData, boolean onlyCoreApps) {
23295        Slog.v(TAG, "reconcileAppsData for " + volumeUuid + " u" + userId + " 0x"
23296                + Integer.toHexString(flags) + " migrateAppData=" + migrateAppData);
23297        List<String> result = onlyCoreApps ? new ArrayList<>() : null;
23298
23299        final File ceDir = Environment.getDataUserCeDirectory(volumeUuid, userId);
23300        final File deDir = Environment.getDataUserDeDirectory(volumeUuid, userId);
23301
23302        // First look for stale data that doesn't belong, and check if things
23303        // have changed since we did our last restorecon
23304        if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) {
23305            if (StorageManager.isFileEncryptedNativeOrEmulated()
23306                    && !StorageManager.isUserKeyUnlocked(userId)) {
23307                throw new RuntimeException(
23308                        "Yikes, someone asked us to reconcile CE storage while " + userId
23309                                + " was still locked; this would have caused massive data loss!");
23310            }
23311
23312            final File[] files = FileUtils.listFilesOrEmpty(ceDir);
23313            for (File file : files) {
23314                final String packageName = file.getName();
23315                try {
23316                    assertPackageKnownAndInstalled(volumeUuid, packageName, userId);
23317                } catch (PackageManagerException e) {
23318                    logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e);
23319                    try {
23320                        mInstaller.destroyAppData(volumeUuid, packageName, userId,
23321                                StorageManager.FLAG_STORAGE_CE, 0);
23322                    } catch (InstallerException e2) {
23323                        logCriticalInfo(Log.WARN, "Failed to destroy: " + e2);
23324                    }
23325                }
23326            }
23327        }
23328        if ((flags & StorageManager.FLAG_STORAGE_DE) != 0) {
23329            final File[] files = FileUtils.listFilesOrEmpty(deDir);
23330            for (File file : files) {
23331                final String packageName = file.getName();
23332                try {
23333                    assertPackageKnownAndInstalled(volumeUuid, packageName, userId);
23334                } catch (PackageManagerException e) {
23335                    logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e);
23336                    try {
23337                        mInstaller.destroyAppData(volumeUuid, packageName, userId,
23338                                StorageManager.FLAG_STORAGE_DE, 0);
23339                    } catch (InstallerException e2) {
23340                        logCriticalInfo(Log.WARN, "Failed to destroy: " + e2);
23341                    }
23342                }
23343            }
23344        }
23345
23346        // Ensure that data directories are ready to roll for all packages
23347        // installed for this volume and user
23348        final List<PackageSetting> packages;
23349        synchronized (mPackages) {
23350            packages = mSettings.getVolumePackagesLPr(volumeUuid);
23351        }
23352        int preparedCount = 0;
23353        for (PackageSetting ps : packages) {
23354            final String packageName = ps.name;
23355            if (ps.pkg == null) {
23356                Slog.w(TAG, "Odd, missing scanned package " + packageName);
23357                // TODO: might be due to legacy ASEC apps; we should circle back
23358                // and reconcile again once they're scanned
23359                continue;
23360            }
23361            // Skip non-core apps if requested
23362            if (onlyCoreApps && !ps.pkg.coreApp) {
23363                result.add(packageName);
23364                continue;
23365            }
23366
23367            if (ps.getInstalled(userId)) {
23368                prepareAppDataAndMigrateLIF(ps.pkg, userId, flags, migrateAppData);
23369                preparedCount++;
23370            }
23371        }
23372
23373        Slog.v(TAG, "reconcileAppsData finished " + preparedCount + " packages");
23374        return result;
23375    }
23376
23377    /**
23378     * Prepare app data for the given app just after it was installed or
23379     * upgraded. This method carefully only touches users that it's installed
23380     * for, and it forces a restorecon to handle any seinfo changes.
23381     * <p>
23382     * Verifies that directories exist and that ownership and labeling is
23383     * correct for all installed apps. If there is an ownership mismatch, it
23384     * will try recovering system apps by wiping data; third-party app data is
23385     * left intact.
23386     * <p>
23387     * <em>Note: To avoid a deadlock, do not call this method with {@code mPackages} lock held</em>
23388     */
23389    private void prepareAppDataAfterInstallLIF(PackageParser.Package pkg) {
23390        final PackageSetting ps;
23391        synchronized (mPackages) {
23392            ps = mSettings.mPackages.get(pkg.packageName);
23393            mSettings.writeKernelMappingLPr(ps);
23394        }
23395
23396        final UserManager um = mContext.getSystemService(UserManager.class);
23397        UserManagerInternal umInternal = getUserManagerInternal();
23398        for (UserInfo user : um.getUsers()) {
23399            final int flags;
23400            if (umInternal.isUserUnlockingOrUnlocked(user.id)) {
23401                flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
23402            } else if (umInternal.isUserRunning(user.id)) {
23403                flags = StorageManager.FLAG_STORAGE_DE;
23404            } else {
23405                continue;
23406            }
23407
23408            if (ps.getInstalled(user.id)) {
23409                // TODO: when user data is locked, mark that we're still dirty
23410                prepareAppDataLIF(pkg, user.id, flags);
23411            }
23412        }
23413    }
23414
23415    /**
23416     * Prepare app data for the given app.
23417     * <p>
23418     * Verifies that directories exist and that ownership and labeling is
23419     * correct for all installed apps. If there is an ownership mismatch, this
23420     * will try recovering system apps by wiping data; third-party app data is
23421     * left intact.
23422     */
23423    private void prepareAppDataLIF(PackageParser.Package pkg, int userId, int flags) {
23424        if (pkg == null) {
23425            Slog.wtf(TAG, "Package was null!", new Throwable());
23426            return;
23427        }
23428        prepareAppDataLeafLIF(pkg, userId, flags);
23429        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
23430        for (int i = 0; i < childCount; i++) {
23431            prepareAppDataLeafLIF(pkg.childPackages.get(i), userId, flags);
23432        }
23433    }
23434
23435    private void prepareAppDataAndMigrateLIF(PackageParser.Package pkg, int userId, int flags,
23436            boolean maybeMigrateAppData) {
23437        prepareAppDataLIF(pkg, userId, flags);
23438
23439        if (maybeMigrateAppData && maybeMigrateAppDataLIF(pkg, userId)) {
23440            // We may have just shuffled around app data directories, so
23441            // prepare them one more time
23442            prepareAppDataLIF(pkg, userId, flags);
23443        }
23444    }
23445
23446    private void prepareAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) {
23447        if (DEBUG_APP_DATA) {
23448            Slog.v(TAG, "prepareAppData for " + pkg.packageName + " u" + userId + " 0x"
23449                    + Integer.toHexString(flags));
23450        }
23451
23452        final String volumeUuid = pkg.volumeUuid;
23453        final String packageName = pkg.packageName;
23454        final ApplicationInfo app = pkg.applicationInfo;
23455        final int appId = UserHandle.getAppId(app.uid);
23456
23457        Preconditions.checkNotNull(app.seInfo);
23458
23459        long ceDataInode = -1;
23460        try {
23461            ceDataInode = mInstaller.createAppData(volumeUuid, packageName, userId, flags,
23462                    appId, app.seInfo, app.targetSdkVersion);
23463        } catch (InstallerException e) {
23464            if (app.isSystemApp()) {
23465                logCriticalInfo(Log.ERROR, "Failed to create app data for " + packageName
23466                        + ", but trying to recover: " + e);
23467                destroyAppDataLeafLIF(pkg, userId, flags);
23468                try {
23469                    ceDataInode = mInstaller.createAppData(volumeUuid, packageName, userId, flags,
23470                            appId, app.seInfo, app.targetSdkVersion);
23471                    logCriticalInfo(Log.DEBUG, "Recovery succeeded!");
23472                } catch (InstallerException e2) {
23473                    logCriticalInfo(Log.DEBUG, "Recovery failed!");
23474                }
23475            } else {
23476                Slog.e(TAG, "Failed to create app data for " + packageName + ": " + e);
23477            }
23478        }
23479
23480        if ((flags & StorageManager.FLAG_STORAGE_CE) != 0 && ceDataInode != -1) {
23481            // TODO: mark this structure as dirty so we persist it!
23482            synchronized (mPackages) {
23483                final PackageSetting ps = mSettings.mPackages.get(packageName);
23484                if (ps != null) {
23485                    ps.setCeDataInode(ceDataInode, userId);
23486                }
23487            }
23488        }
23489
23490        prepareAppDataContentsLeafLIF(pkg, userId, flags);
23491    }
23492
23493    private void prepareAppDataContentsLIF(PackageParser.Package pkg, int userId, int flags) {
23494        if (pkg == null) {
23495            Slog.wtf(TAG, "Package was null!", new Throwable());
23496            return;
23497        }
23498        prepareAppDataContentsLeafLIF(pkg, userId, flags);
23499        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
23500        for (int i = 0; i < childCount; i++) {
23501            prepareAppDataContentsLeafLIF(pkg.childPackages.get(i), userId, flags);
23502        }
23503    }
23504
23505    private void prepareAppDataContentsLeafLIF(PackageParser.Package pkg, int userId, int flags) {
23506        final String volumeUuid = pkg.volumeUuid;
23507        final String packageName = pkg.packageName;
23508        final ApplicationInfo app = pkg.applicationInfo;
23509
23510        if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) {
23511            // Create a native library symlink only if we have native libraries
23512            // and if the native libraries are 32 bit libraries. We do not provide
23513            // this symlink for 64 bit libraries.
23514            if (app.primaryCpuAbi != null && !VMRuntime.is64BitAbi(app.primaryCpuAbi)) {
23515                final String nativeLibPath = app.nativeLibraryDir;
23516                try {
23517                    mInstaller.linkNativeLibraryDirectory(volumeUuid, packageName,
23518                            nativeLibPath, userId);
23519                } catch (InstallerException e) {
23520                    Slog.e(TAG, "Failed to link native for " + packageName + ": " + e);
23521                }
23522            }
23523        }
23524    }
23525
23526    /**
23527     * For system apps on non-FBE devices, this method migrates any existing
23528     * CE/DE data to match the {@code defaultToDeviceProtectedStorage} flag
23529     * requested by the app.
23530     */
23531    private boolean maybeMigrateAppDataLIF(PackageParser.Package pkg, int userId) {
23532        if (pkg.isSystemApp() && !StorageManager.isFileEncryptedNativeOrEmulated()
23533                && PackageManager.APPLY_DEFAULT_TO_DEVICE_PROTECTED_STORAGE) {
23534            final int storageTarget = pkg.applicationInfo.isDefaultToDeviceProtectedStorage()
23535                    ? StorageManager.FLAG_STORAGE_DE : StorageManager.FLAG_STORAGE_CE;
23536            try {
23537                mInstaller.migrateAppData(pkg.volumeUuid, pkg.packageName, userId,
23538                        storageTarget);
23539            } catch (InstallerException e) {
23540                logCriticalInfo(Log.WARN,
23541                        "Failed to migrate " + pkg.packageName + ": " + e.getMessage());
23542            }
23543            return true;
23544        } else {
23545            return false;
23546        }
23547    }
23548
23549    public PackageFreezer freezePackage(String packageName, String killReason) {
23550        return freezePackage(packageName, UserHandle.USER_ALL, killReason);
23551    }
23552
23553    public PackageFreezer freezePackage(String packageName, int userId, String killReason) {
23554        return new PackageFreezer(packageName, userId, killReason);
23555    }
23556
23557    public PackageFreezer freezePackageForInstall(String packageName, int installFlags,
23558            String killReason) {
23559        return freezePackageForInstall(packageName, UserHandle.USER_ALL, installFlags, killReason);
23560    }
23561
23562    public PackageFreezer freezePackageForInstall(String packageName, int userId, int installFlags,
23563            String killReason) {
23564        if ((installFlags & PackageManager.INSTALL_DONT_KILL_APP) != 0) {
23565            return new PackageFreezer();
23566        } else {
23567            return freezePackage(packageName, userId, killReason);
23568        }
23569    }
23570
23571    public PackageFreezer freezePackageForDelete(String packageName, int deleteFlags,
23572            String killReason) {
23573        return freezePackageForDelete(packageName, UserHandle.USER_ALL, deleteFlags, killReason);
23574    }
23575
23576    public PackageFreezer freezePackageForDelete(String packageName, int userId, int deleteFlags,
23577            String killReason) {
23578        if ((deleteFlags & PackageManager.DELETE_DONT_KILL_APP) != 0) {
23579            return new PackageFreezer();
23580        } else {
23581            return freezePackage(packageName, userId, killReason);
23582        }
23583    }
23584
23585    /**
23586     * Class that freezes and kills the given package upon creation, and
23587     * unfreezes it upon closing. This is typically used when doing surgery on
23588     * app code/data to prevent the app from running while you're working.
23589     */
23590    private class PackageFreezer implements AutoCloseable {
23591        private final String mPackageName;
23592        private final PackageFreezer[] mChildren;
23593
23594        private final boolean mWeFroze;
23595
23596        private final AtomicBoolean mClosed = new AtomicBoolean();
23597        private final CloseGuard mCloseGuard = CloseGuard.get();
23598
23599        /**
23600         * Create and return a stub freezer that doesn't actually do anything,
23601         * typically used when someone requested
23602         * {@link PackageManager#INSTALL_DONT_KILL_APP} or
23603         * {@link PackageManager#DELETE_DONT_KILL_APP}.
23604         */
23605        public PackageFreezer() {
23606            mPackageName = null;
23607            mChildren = null;
23608            mWeFroze = false;
23609            mCloseGuard.open("close");
23610        }
23611
23612        public PackageFreezer(String packageName, int userId, String killReason) {
23613            synchronized (mPackages) {
23614                mPackageName = packageName;
23615                mWeFroze = mFrozenPackages.add(mPackageName);
23616
23617                final PackageSetting ps = mSettings.mPackages.get(mPackageName);
23618                if (ps != null) {
23619                    killApplication(ps.name, ps.appId, userId, killReason);
23620                }
23621
23622                final PackageParser.Package p = mPackages.get(packageName);
23623                if (p != null && p.childPackages != null) {
23624                    final int N = p.childPackages.size();
23625                    mChildren = new PackageFreezer[N];
23626                    for (int i = 0; i < N; i++) {
23627                        mChildren[i] = new PackageFreezer(p.childPackages.get(i).packageName,
23628                                userId, killReason);
23629                    }
23630                } else {
23631                    mChildren = null;
23632                }
23633            }
23634            mCloseGuard.open("close");
23635        }
23636
23637        @Override
23638        protected void finalize() throws Throwable {
23639            try {
23640                if (mCloseGuard != null) {
23641                    mCloseGuard.warnIfOpen();
23642                }
23643
23644                close();
23645            } finally {
23646                super.finalize();
23647            }
23648        }
23649
23650        @Override
23651        public void close() {
23652            mCloseGuard.close();
23653            if (mClosed.compareAndSet(false, true)) {
23654                synchronized (mPackages) {
23655                    if (mWeFroze) {
23656                        mFrozenPackages.remove(mPackageName);
23657                    }
23658
23659                    if (mChildren != null) {
23660                        for (PackageFreezer freezer : mChildren) {
23661                            freezer.close();
23662                        }
23663                    }
23664                }
23665            }
23666        }
23667    }
23668
23669    /**
23670     * Verify that given package is currently frozen.
23671     */
23672    private void checkPackageFrozen(String packageName) {
23673        synchronized (mPackages) {
23674            if (!mFrozenPackages.contains(packageName)) {
23675                Slog.wtf(TAG, "Expected " + packageName + " to be frozen!", new Throwable());
23676            }
23677        }
23678    }
23679
23680    @Override
23681    public int movePackage(final String packageName, final String volumeUuid) {
23682        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null);
23683
23684        final int callingUid = Binder.getCallingUid();
23685        final UserHandle user = new UserHandle(UserHandle.getUserId(callingUid));
23686        final int moveId = mNextMoveId.getAndIncrement();
23687        mHandler.post(new Runnable() {
23688            @Override
23689            public void run() {
23690                try {
23691                    movePackageInternal(packageName, volumeUuid, moveId, callingUid, user);
23692                } catch (PackageManagerException e) {
23693                    Slog.w(TAG, "Failed to move " + packageName, e);
23694                    mMoveCallbacks.notifyStatusChanged(moveId,
23695                            PackageManager.MOVE_FAILED_INTERNAL_ERROR);
23696                }
23697            }
23698        });
23699        return moveId;
23700    }
23701
23702    private void movePackageInternal(final String packageName, final String volumeUuid,
23703            final int moveId, final int callingUid, UserHandle user)
23704                    throws PackageManagerException {
23705        final StorageManager storage = mContext.getSystemService(StorageManager.class);
23706        final PackageManager pm = mContext.getPackageManager();
23707
23708        final boolean currentAsec;
23709        final String currentVolumeUuid;
23710        final File codeFile;
23711        final String installerPackageName;
23712        final String packageAbiOverride;
23713        final int appId;
23714        final String seinfo;
23715        final String label;
23716        final int targetSdkVersion;
23717        final PackageFreezer freezer;
23718        final int[] installedUserIds;
23719
23720        // reader
23721        synchronized (mPackages) {
23722            final PackageParser.Package pkg = mPackages.get(packageName);
23723            final PackageSetting ps = mSettings.mPackages.get(packageName);
23724            if (pkg == null
23725                    || ps == null
23726                    || filterAppAccessLPr(ps, callingUid, user.getIdentifier())) {
23727                throw new PackageManagerException(MOVE_FAILED_DOESNT_EXIST, "Missing package");
23728            }
23729            if (pkg.applicationInfo.isSystemApp()) {
23730                throw new PackageManagerException(MOVE_FAILED_SYSTEM_PACKAGE,
23731                        "Cannot move system application");
23732            }
23733
23734            final boolean isInternalStorage = VolumeInfo.ID_PRIVATE_INTERNAL.equals(volumeUuid);
23735            final boolean allow3rdPartyOnInternal = mContext.getResources().getBoolean(
23736                    com.android.internal.R.bool.config_allow3rdPartyAppOnInternal);
23737            if (isInternalStorage && !allow3rdPartyOnInternal) {
23738                throw new PackageManagerException(MOVE_FAILED_3RD_PARTY_NOT_ALLOWED_ON_INTERNAL,
23739                        "3rd party apps are not allowed on internal storage");
23740            }
23741
23742            if (pkg.applicationInfo.isExternalAsec()) {
23743                currentAsec = true;
23744                currentVolumeUuid = StorageManager.UUID_PRIMARY_PHYSICAL;
23745            } else if (pkg.applicationInfo.isForwardLocked()) {
23746                currentAsec = true;
23747                currentVolumeUuid = "forward_locked";
23748            } else {
23749                currentAsec = false;
23750                currentVolumeUuid = ps.volumeUuid;
23751
23752                final File probe = new File(pkg.codePath);
23753                final File probeOat = new File(probe, "oat");
23754                if (!probe.isDirectory() || !probeOat.isDirectory()) {
23755                    throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
23756                            "Move only supported for modern cluster style installs");
23757                }
23758            }
23759
23760            if (Objects.equals(currentVolumeUuid, volumeUuid)) {
23761                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
23762                        "Package already moved to " + volumeUuid);
23763            }
23764            if (pkg.applicationInfo.isInternal() && isPackageDeviceAdminOnAnyUser(packageName)) {
23765                throw new PackageManagerException(MOVE_FAILED_DEVICE_ADMIN,
23766                        "Device admin cannot be moved");
23767            }
23768
23769            if (mFrozenPackages.contains(packageName)) {
23770                throw new PackageManagerException(MOVE_FAILED_OPERATION_PENDING,
23771                        "Failed to move already frozen package");
23772            }
23773
23774            codeFile = new File(pkg.codePath);
23775            installerPackageName = ps.installerPackageName;
23776            packageAbiOverride = ps.cpuAbiOverrideString;
23777            appId = UserHandle.getAppId(pkg.applicationInfo.uid);
23778            seinfo = pkg.applicationInfo.seInfo;
23779            label = String.valueOf(pm.getApplicationLabel(pkg.applicationInfo));
23780            targetSdkVersion = pkg.applicationInfo.targetSdkVersion;
23781            freezer = freezePackage(packageName, "movePackageInternal");
23782            installedUserIds = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
23783        }
23784
23785        final Bundle extras = new Bundle();
23786        extras.putString(Intent.EXTRA_PACKAGE_NAME, packageName);
23787        extras.putString(Intent.EXTRA_TITLE, label);
23788        mMoveCallbacks.notifyCreated(moveId, extras);
23789
23790        int installFlags;
23791        final boolean moveCompleteApp;
23792        final File measurePath;
23793
23794        if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, volumeUuid)) {
23795            installFlags = INSTALL_INTERNAL;
23796            moveCompleteApp = !currentAsec;
23797            measurePath = Environment.getDataAppDirectory(volumeUuid);
23798        } else if (Objects.equals(StorageManager.UUID_PRIMARY_PHYSICAL, volumeUuid)) {
23799            installFlags = INSTALL_EXTERNAL;
23800            moveCompleteApp = false;
23801            measurePath = storage.getPrimaryPhysicalVolume().getPath();
23802        } else {
23803            final VolumeInfo volume = storage.findVolumeByUuid(volumeUuid);
23804            if (volume == null || volume.getType() != VolumeInfo.TYPE_PRIVATE
23805                    || !volume.isMountedWritable()) {
23806                freezer.close();
23807                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
23808                        "Move location not mounted private volume");
23809            }
23810
23811            Preconditions.checkState(!currentAsec);
23812
23813            installFlags = INSTALL_INTERNAL;
23814            moveCompleteApp = true;
23815            measurePath = Environment.getDataAppDirectory(volumeUuid);
23816        }
23817
23818        final PackageStats stats = new PackageStats(null, -1);
23819        synchronized (mInstaller) {
23820            for (int userId : installedUserIds) {
23821                if (!getPackageSizeInfoLI(packageName, userId, stats)) {
23822                    freezer.close();
23823                    throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
23824                            "Failed to measure package size");
23825                }
23826            }
23827        }
23828
23829        if (DEBUG_INSTALL) Slog.d(TAG, "Measured code size " + stats.codeSize + ", data size "
23830                + stats.dataSize);
23831
23832        final long startFreeBytes = measurePath.getUsableSpace();
23833        final long sizeBytes;
23834        if (moveCompleteApp) {
23835            sizeBytes = stats.codeSize + stats.dataSize;
23836        } else {
23837            sizeBytes = stats.codeSize;
23838        }
23839
23840        if (sizeBytes > storage.getStorageBytesUntilLow(measurePath)) {
23841            freezer.close();
23842            throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
23843                    "Not enough free space to move");
23844        }
23845
23846        mMoveCallbacks.notifyStatusChanged(moveId, 10);
23847
23848        final CountDownLatch installedLatch = new CountDownLatch(1);
23849        final IPackageInstallObserver2 installObserver = new IPackageInstallObserver2.Stub() {
23850            @Override
23851            public void onUserActionRequired(Intent intent) throws RemoteException {
23852                throw new IllegalStateException();
23853            }
23854
23855            @Override
23856            public void onPackageInstalled(String basePackageName, int returnCode, String msg,
23857                    Bundle extras) throws RemoteException {
23858                if (DEBUG_INSTALL) Slog.d(TAG, "Install result for move: "
23859                        + PackageManager.installStatusToString(returnCode, msg));
23860
23861                installedLatch.countDown();
23862                freezer.close();
23863
23864                final int status = PackageManager.installStatusToPublicStatus(returnCode);
23865                switch (status) {
23866                    case PackageInstaller.STATUS_SUCCESS:
23867                        mMoveCallbacks.notifyStatusChanged(moveId,
23868                                PackageManager.MOVE_SUCCEEDED);
23869                        break;
23870                    case PackageInstaller.STATUS_FAILURE_STORAGE:
23871                        mMoveCallbacks.notifyStatusChanged(moveId,
23872                                PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE);
23873                        break;
23874                    default:
23875                        mMoveCallbacks.notifyStatusChanged(moveId,
23876                                PackageManager.MOVE_FAILED_INTERNAL_ERROR);
23877                        break;
23878                }
23879            }
23880        };
23881
23882        final MoveInfo move;
23883        if (moveCompleteApp) {
23884            // Kick off a thread to report progress estimates
23885            new Thread() {
23886                @Override
23887                public void run() {
23888                    while (true) {
23889                        try {
23890                            if (installedLatch.await(1, TimeUnit.SECONDS)) {
23891                                break;
23892                            }
23893                        } catch (InterruptedException ignored) {
23894                        }
23895
23896                        final long deltaFreeBytes = startFreeBytes - measurePath.getUsableSpace();
23897                        final int progress = 10 + (int) MathUtils.constrain(
23898                                ((deltaFreeBytes * 80) / sizeBytes), 0, 80);
23899                        mMoveCallbacks.notifyStatusChanged(moveId, progress);
23900                    }
23901                }
23902            }.start();
23903
23904            final String dataAppName = codeFile.getName();
23905            move = new MoveInfo(moveId, currentVolumeUuid, volumeUuid, packageName,
23906                    dataAppName, appId, seinfo, targetSdkVersion);
23907        } else {
23908            move = null;
23909        }
23910
23911        installFlags |= PackageManager.INSTALL_REPLACE_EXISTING;
23912
23913        final Message msg = mHandler.obtainMessage(INIT_COPY);
23914        final OriginInfo origin = OriginInfo.fromExistingFile(codeFile);
23915        final InstallParams params = new InstallParams(origin, move, installObserver, installFlags,
23916                installerPackageName, volumeUuid, null /*verificationInfo*/, user,
23917                packageAbiOverride, null /*grantedPermissions*/, null /*certificates*/,
23918                PackageManager.INSTALL_REASON_UNKNOWN);
23919        params.setTraceMethod("movePackage").setTraceCookie(System.identityHashCode(params));
23920        msg.obj = params;
23921
23922        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "movePackage",
23923                System.identityHashCode(msg.obj));
23924        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
23925                System.identityHashCode(msg.obj));
23926
23927        mHandler.sendMessage(msg);
23928    }
23929
23930    @Override
23931    public int movePrimaryStorage(String volumeUuid) throws RemoteException {
23932        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null);
23933
23934        final int realMoveId = mNextMoveId.getAndIncrement();
23935        final Bundle extras = new Bundle();
23936        extras.putString(VolumeRecord.EXTRA_FS_UUID, volumeUuid);
23937        mMoveCallbacks.notifyCreated(realMoveId, extras);
23938
23939        final IPackageMoveObserver callback = new IPackageMoveObserver.Stub() {
23940            @Override
23941            public void onCreated(int moveId, Bundle extras) {
23942                // Ignored
23943            }
23944
23945            @Override
23946            public void onStatusChanged(int moveId, int status, long estMillis) {
23947                mMoveCallbacks.notifyStatusChanged(realMoveId, status, estMillis);
23948            }
23949        };
23950
23951        final StorageManager storage = mContext.getSystemService(StorageManager.class);
23952        storage.setPrimaryStorageUuid(volumeUuid, callback);
23953        return realMoveId;
23954    }
23955
23956    @Override
23957    public int getMoveStatus(int moveId) {
23958        mContext.enforceCallingOrSelfPermission(
23959                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
23960        return mMoveCallbacks.mLastStatus.get(moveId);
23961    }
23962
23963    @Override
23964    public void registerMoveCallback(IPackageMoveObserver callback) {
23965        mContext.enforceCallingOrSelfPermission(
23966                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
23967        mMoveCallbacks.register(callback);
23968    }
23969
23970    @Override
23971    public void unregisterMoveCallback(IPackageMoveObserver callback) {
23972        mContext.enforceCallingOrSelfPermission(
23973                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
23974        mMoveCallbacks.unregister(callback);
23975    }
23976
23977    @Override
23978    public boolean setInstallLocation(int loc) {
23979        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WRITE_SECURE_SETTINGS,
23980                null);
23981        if (getInstallLocation() == loc) {
23982            return true;
23983        }
23984        if (loc == PackageHelper.APP_INSTALL_AUTO || loc == PackageHelper.APP_INSTALL_INTERNAL
23985                || loc == PackageHelper.APP_INSTALL_EXTERNAL) {
23986            android.provider.Settings.Global.putInt(mContext.getContentResolver(),
23987                    android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, loc);
23988            return true;
23989        }
23990        return false;
23991   }
23992
23993    @Override
23994    public int getInstallLocation() {
23995        // allow instant app access
23996        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
23997                android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION,
23998                PackageHelper.APP_INSTALL_AUTO);
23999    }
24000
24001    /** Called by UserManagerService */
24002    void cleanUpUser(UserManagerService userManager, int userHandle) {
24003        synchronized (mPackages) {
24004            mDirtyUsers.remove(userHandle);
24005            mUserNeedsBadging.delete(userHandle);
24006            mSettings.removeUserLPw(userHandle);
24007            mPendingBroadcasts.remove(userHandle);
24008            mInstantAppRegistry.onUserRemovedLPw(userHandle);
24009            removeUnusedPackagesLPw(userManager, userHandle);
24010        }
24011    }
24012
24013    /**
24014     * We're removing userHandle and would like to remove any downloaded packages
24015     * that are no longer in use by any other user.
24016     * @param userHandle the user being removed
24017     */
24018    private void removeUnusedPackagesLPw(UserManagerService userManager, final int userHandle) {
24019        final boolean DEBUG_CLEAN_APKS = false;
24020        int [] users = userManager.getUserIds();
24021        Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator();
24022        while (psit.hasNext()) {
24023            PackageSetting ps = psit.next();
24024            if (ps.pkg == null) {
24025                continue;
24026            }
24027            final String packageName = ps.pkg.packageName;
24028            // Skip over if system app
24029            if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0) {
24030                continue;
24031            }
24032            if (DEBUG_CLEAN_APKS) {
24033                Slog.i(TAG, "Checking package " + packageName);
24034            }
24035            boolean keep = shouldKeepUninstalledPackageLPr(packageName);
24036            if (keep) {
24037                if (DEBUG_CLEAN_APKS) {
24038                    Slog.i(TAG, "  Keeping package " + packageName + " - requested by DO");
24039                }
24040            } else {
24041                for (int i = 0; i < users.length; i++) {
24042                    if (users[i] != userHandle && ps.getInstalled(users[i])) {
24043                        keep = true;
24044                        if (DEBUG_CLEAN_APKS) {
24045                            Slog.i(TAG, "  Keeping package " + packageName + " for user "
24046                                    + users[i]);
24047                        }
24048                        break;
24049                    }
24050                }
24051            }
24052            if (!keep) {
24053                if (DEBUG_CLEAN_APKS) {
24054                    Slog.i(TAG, "  Removing package " + packageName);
24055                }
24056                mHandler.post(new Runnable() {
24057                    public void run() {
24058                        deletePackageX(packageName, PackageManager.VERSION_CODE_HIGHEST,
24059                                userHandle, 0);
24060                    } //end run
24061                });
24062            }
24063        }
24064    }
24065
24066    /** Called by UserManagerService */
24067    void createNewUser(int userId, String[] disallowedPackages) {
24068        synchronized (mInstallLock) {
24069            mSettings.createNewUserLI(this, mInstaller, userId, disallowedPackages);
24070        }
24071        synchronized (mPackages) {
24072            scheduleWritePackageRestrictionsLocked(userId);
24073            scheduleWritePackageListLocked(userId);
24074            applyFactoryDefaultBrowserLPw(userId);
24075            primeDomainVerificationsLPw(userId);
24076        }
24077    }
24078
24079    void onNewUserCreated(final int userId) {
24080        mDefaultPermissionPolicy.grantDefaultPermissions(userId);
24081        // If permission review for legacy apps is required, we represent
24082        // dagerous permissions for such apps as always granted runtime
24083        // permissions to keep per user flag state whether review is needed.
24084        // Hence, if a new user is added we have to propagate dangerous
24085        // permission grants for these legacy apps.
24086        if (mPermissionReviewRequired) {
24087            updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL
24088                    | UPDATE_PERMISSIONS_REPLACE_ALL);
24089        }
24090    }
24091
24092    @Override
24093    public VerifierDeviceIdentity getVerifierDeviceIdentity() throws RemoteException {
24094        mContext.enforceCallingOrSelfPermission(
24095                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
24096                "Only package verification agents can read the verifier device identity");
24097
24098        synchronized (mPackages) {
24099            return mSettings.getVerifierDeviceIdentityLPw();
24100        }
24101    }
24102
24103    @Override
24104    public void setPermissionEnforced(String permission, boolean enforced) {
24105        // TODO: Now that we no longer change GID for storage, this should to away.
24106        mContext.enforceCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS,
24107                "setPermissionEnforced");
24108        if (READ_EXTERNAL_STORAGE.equals(permission)) {
24109            synchronized (mPackages) {
24110                if (mSettings.mReadExternalStorageEnforced == null
24111                        || mSettings.mReadExternalStorageEnforced != enforced) {
24112                    mSettings.mReadExternalStorageEnforced = enforced;
24113                    mSettings.writeLPr();
24114                }
24115            }
24116            // kill any non-foreground processes so we restart them and
24117            // grant/revoke the GID.
24118            final IActivityManager am = ActivityManager.getService();
24119            if (am != null) {
24120                final long token = Binder.clearCallingIdentity();
24121                try {
24122                    am.killProcessesBelowForeground("setPermissionEnforcement");
24123                } catch (RemoteException e) {
24124                } finally {
24125                    Binder.restoreCallingIdentity(token);
24126                }
24127            }
24128        } else {
24129            throw new IllegalArgumentException("No selective enforcement for " + permission);
24130        }
24131    }
24132
24133    @Override
24134    @Deprecated
24135    public boolean isPermissionEnforced(String permission) {
24136        // allow instant applications
24137        return true;
24138    }
24139
24140    @Override
24141    public boolean isStorageLow() {
24142        // allow instant applications
24143        final long token = Binder.clearCallingIdentity();
24144        try {
24145            final DeviceStorageMonitorInternal
24146                    dsm = LocalServices.getService(DeviceStorageMonitorInternal.class);
24147            if (dsm != null) {
24148                return dsm.isMemoryLow();
24149            } else {
24150                return false;
24151            }
24152        } finally {
24153            Binder.restoreCallingIdentity(token);
24154        }
24155    }
24156
24157    @Override
24158    public IPackageInstaller getPackageInstaller() {
24159        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
24160            return null;
24161        }
24162        return mInstallerService;
24163    }
24164
24165    private boolean userNeedsBadging(int userId) {
24166        int index = mUserNeedsBadging.indexOfKey(userId);
24167        if (index < 0) {
24168            final UserInfo userInfo;
24169            final long token = Binder.clearCallingIdentity();
24170            try {
24171                userInfo = sUserManager.getUserInfo(userId);
24172            } finally {
24173                Binder.restoreCallingIdentity(token);
24174            }
24175            final boolean b;
24176            if (userInfo != null && userInfo.isManagedProfile()) {
24177                b = true;
24178            } else {
24179                b = false;
24180            }
24181            mUserNeedsBadging.put(userId, b);
24182            return b;
24183        }
24184        return mUserNeedsBadging.valueAt(index);
24185    }
24186
24187    @Override
24188    public KeySet getKeySetByAlias(String packageName, String alias) {
24189        if (packageName == null || alias == null) {
24190            return null;
24191        }
24192        synchronized(mPackages) {
24193            final PackageParser.Package pkg = mPackages.get(packageName);
24194            if (pkg == null) {
24195                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
24196                throw new IllegalArgumentException("Unknown package: " + packageName);
24197            }
24198            final PackageSetting ps = (PackageSetting) pkg.mExtras;
24199            if (filterAppAccessLPr(ps, Binder.getCallingUid(), UserHandle.getCallingUserId())) {
24200                Slog.w(TAG, "KeySet requested for filtered package: " + packageName);
24201                throw new IllegalArgumentException("Unknown package: " + packageName);
24202            }
24203            KeySetManagerService ksms = mSettings.mKeySetManagerService;
24204            return new KeySet(ksms.getKeySetByAliasAndPackageNameLPr(packageName, alias));
24205        }
24206    }
24207
24208    @Override
24209    public KeySet getSigningKeySet(String packageName) {
24210        if (packageName == null) {
24211            return null;
24212        }
24213        synchronized(mPackages) {
24214            final int callingUid = Binder.getCallingUid();
24215            final int callingUserId = UserHandle.getUserId(callingUid);
24216            final PackageParser.Package pkg = mPackages.get(packageName);
24217            if (pkg == null) {
24218                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
24219                throw new IllegalArgumentException("Unknown package: " + packageName);
24220            }
24221            final PackageSetting ps = (PackageSetting) pkg.mExtras;
24222            if (filterAppAccessLPr(ps, callingUid, callingUserId)) {
24223                // filter and pretend the package doesn't exist
24224                Slog.w(TAG, "KeySet requested for filtered package: " + packageName
24225                        + ", uid:" + callingUid);
24226                throw new IllegalArgumentException("Unknown package: " + packageName);
24227            }
24228            if (pkg.applicationInfo.uid != callingUid
24229                    && Process.SYSTEM_UID != callingUid) {
24230                throw new SecurityException("May not access signing KeySet of other apps.");
24231            }
24232            KeySetManagerService ksms = mSettings.mKeySetManagerService;
24233            return new KeySet(ksms.getSigningKeySetByPackageNameLPr(packageName));
24234        }
24235    }
24236
24237    @Override
24238    public boolean isPackageSignedByKeySet(String packageName, KeySet ks) {
24239        final int callingUid = Binder.getCallingUid();
24240        if (getInstantAppPackageName(callingUid) != null) {
24241            return false;
24242        }
24243        if (packageName == null || ks == null) {
24244            return false;
24245        }
24246        synchronized(mPackages) {
24247            final PackageParser.Package pkg = mPackages.get(packageName);
24248            if (pkg == null
24249                    || filterAppAccessLPr((PackageSetting) pkg.mExtras, callingUid,
24250                            UserHandle.getUserId(callingUid))) {
24251                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
24252                throw new IllegalArgumentException("Unknown package: " + packageName);
24253            }
24254            IBinder ksh = ks.getToken();
24255            if (ksh instanceof KeySetHandle) {
24256                KeySetManagerService ksms = mSettings.mKeySetManagerService;
24257                return ksms.packageIsSignedByLPr(packageName, (KeySetHandle) ksh);
24258            }
24259            return false;
24260        }
24261    }
24262
24263    @Override
24264    public boolean isPackageSignedByKeySetExactly(String packageName, KeySet ks) {
24265        final int callingUid = Binder.getCallingUid();
24266        if (getInstantAppPackageName(callingUid) != null) {
24267            return false;
24268        }
24269        if (packageName == null || ks == null) {
24270            return false;
24271        }
24272        synchronized(mPackages) {
24273            final PackageParser.Package pkg = mPackages.get(packageName);
24274            if (pkg == null
24275                    || filterAppAccessLPr((PackageSetting) pkg.mExtras, callingUid,
24276                            UserHandle.getUserId(callingUid))) {
24277                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
24278                throw new IllegalArgumentException("Unknown package: " + packageName);
24279            }
24280            IBinder ksh = ks.getToken();
24281            if (ksh instanceof KeySetHandle) {
24282                KeySetManagerService ksms = mSettings.mKeySetManagerService;
24283                return ksms.packageIsSignedByExactlyLPr(packageName, (KeySetHandle) ksh);
24284            }
24285            return false;
24286        }
24287    }
24288
24289    private void deletePackageIfUnusedLPr(final String packageName) {
24290        PackageSetting ps = mSettings.mPackages.get(packageName);
24291        if (ps == null) {
24292            return;
24293        }
24294        if (!ps.isAnyInstalled(sUserManager.getUserIds())) {
24295            // TODO Implement atomic delete if package is unused
24296            // It is currently possible that the package will be deleted even if it is installed
24297            // after this method returns.
24298            mHandler.post(new Runnable() {
24299                public void run() {
24300                    deletePackageX(packageName, PackageManager.VERSION_CODE_HIGHEST,
24301                            0, PackageManager.DELETE_ALL_USERS);
24302                }
24303            });
24304        }
24305    }
24306
24307    /**
24308     * Check and throw if the given before/after packages would be considered a
24309     * downgrade.
24310     */
24311    private static void checkDowngrade(PackageParser.Package before, PackageInfoLite after)
24312            throws PackageManagerException {
24313        if (after.versionCode < before.mVersionCode) {
24314            throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
24315                    "Update version code " + after.versionCode + " is older than current "
24316                    + before.mVersionCode);
24317        } else if (after.versionCode == before.mVersionCode) {
24318            if (after.baseRevisionCode < before.baseRevisionCode) {
24319                throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
24320                        "Update base revision code " + after.baseRevisionCode
24321                        + " is older than current " + before.baseRevisionCode);
24322            }
24323
24324            if (!ArrayUtils.isEmpty(after.splitNames)) {
24325                for (int i = 0; i < after.splitNames.length; i++) {
24326                    final String splitName = after.splitNames[i];
24327                    final int j = ArrayUtils.indexOf(before.splitNames, splitName);
24328                    if (j != -1) {
24329                        if (after.splitRevisionCodes[i] < before.splitRevisionCodes[j]) {
24330                            throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
24331                                    "Update split " + splitName + " revision code "
24332                                    + after.splitRevisionCodes[i] + " is older than current "
24333                                    + before.splitRevisionCodes[j]);
24334                        }
24335                    }
24336                }
24337            }
24338        }
24339    }
24340
24341    private static class MoveCallbacks extends Handler {
24342        private static final int MSG_CREATED = 1;
24343        private static final int MSG_STATUS_CHANGED = 2;
24344
24345        private final RemoteCallbackList<IPackageMoveObserver>
24346                mCallbacks = new RemoteCallbackList<>();
24347
24348        private final SparseIntArray mLastStatus = new SparseIntArray();
24349
24350        public MoveCallbacks(Looper looper) {
24351            super(looper);
24352        }
24353
24354        public void register(IPackageMoveObserver callback) {
24355            mCallbacks.register(callback);
24356        }
24357
24358        public void unregister(IPackageMoveObserver callback) {
24359            mCallbacks.unregister(callback);
24360        }
24361
24362        @Override
24363        public void handleMessage(Message msg) {
24364            final SomeArgs args = (SomeArgs) msg.obj;
24365            final int n = mCallbacks.beginBroadcast();
24366            for (int i = 0; i < n; i++) {
24367                final IPackageMoveObserver callback = mCallbacks.getBroadcastItem(i);
24368                try {
24369                    invokeCallback(callback, msg.what, args);
24370                } catch (RemoteException ignored) {
24371                }
24372            }
24373            mCallbacks.finishBroadcast();
24374            args.recycle();
24375        }
24376
24377        private void invokeCallback(IPackageMoveObserver callback, int what, SomeArgs args)
24378                throws RemoteException {
24379            switch (what) {
24380                case MSG_CREATED: {
24381                    callback.onCreated(args.argi1, (Bundle) args.arg2);
24382                    break;
24383                }
24384                case MSG_STATUS_CHANGED: {
24385                    callback.onStatusChanged(args.argi1, args.argi2, (long) args.arg3);
24386                    break;
24387                }
24388            }
24389        }
24390
24391        private void notifyCreated(int moveId, Bundle extras) {
24392            Slog.v(TAG, "Move " + moveId + " created " + extras.toString());
24393
24394            final SomeArgs args = SomeArgs.obtain();
24395            args.argi1 = moveId;
24396            args.arg2 = extras;
24397            obtainMessage(MSG_CREATED, args).sendToTarget();
24398        }
24399
24400        private void notifyStatusChanged(int moveId, int status) {
24401            notifyStatusChanged(moveId, status, -1);
24402        }
24403
24404        private void notifyStatusChanged(int moveId, int status, long estMillis) {
24405            Slog.v(TAG, "Move " + moveId + " status " + status);
24406
24407            final SomeArgs args = SomeArgs.obtain();
24408            args.argi1 = moveId;
24409            args.argi2 = status;
24410            args.arg3 = estMillis;
24411            obtainMessage(MSG_STATUS_CHANGED, args).sendToTarget();
24412
24413            synchronized (mLastStatus) {
24414                mLastStatus.put(moveId, status);
24415            }
24416        }
24417    }
24418
24419    private final static class OnPermissionChangeListeners extends Handler {
24420        private static final int MSG_ON_PERMISSIONS_CHANGED = 1;
24421
24422        private final RemoteCallbackList<IOnPermissionsChangeListener> mPermissionListeners =
24423                new RemoteCallbackList<>();
24424
24425        public OnPermissionChangeListeners(Looper looper) {
24426            super(looper);
24427        }
24428
24429        @Override
24430        public void handleMessage(Message msg) {
24431            switch (msg.what) {
24432                case MSG_ON_PERMISSIONS_CHANGED: {
24433                    final int uid = msg.arg1;
24434                    handleOnPermissionsChanged(uid);
24435                } break;
24436            }
24437        }
24438
24439        public void addListenerLocked(IOnPermissionsChangeListener listener) {
24440            mPermissionListeners.register(listener);
24441
24442        }
24443
24444        public void removeListenerLocked(IOnPermissionsChangeListener listener) {
24445            mPermissionListeners.unregister(listener);
24446        }
24447
24448        public void onPermissionsChanged(int uid) {
24449            if (mPermissionListeners.getRegisteredCallbackCount() > 0) {
24450                obtainMessage(MSG_ON_PERMISSIONS_CHANGED, uid, 0).sendToTarget();
24451            }
24452        }
24453
24454        private void handleOnPermissionsChanged(int uid) {
24455            final int count = mPermissionListeners.beginBroadcast();
24456            try {
24457                for (int i = 0; i < count; i++) {
24458                    IOnPermissionsChangeListener callback = mPermissionListeners
24459                            .getBroadcastItem(i);
24460                    try {
24461                        callback.onPermissionsChanged(uid);
24462                    } catch (RemoteException e) {
24463                        Log.e(TAG, "Permission listener is dead", e);
24464                    }
24465                }
24466            } finally {
24467                mPermissionListeners.finishBroadcast();
24468            }
24469        }
24470    }
24471
24472    private class PackageManagerInternalImpl extends PackageManagerInternal {
24473        @Override
24474        public void setLocationPackagesProvider(PackagesProvider provider) {
24475            synchronized (mPackages) {
24476                mDefaultPermissionPolicy.setLocationPackagesProviderLPw(provider);
24477            }
24478        }
24479
24480        @Override
24481        public void setVoiceInteractionPackagesProvider(PackagesProvider provider) {
24482            synchronized (mPackages) {
24483                mDefaultPermissionPolicy.setVoiceInteractionPackagesProviderLPw(provider);
24484            }
24485        }
24486
24487        @Override
24488        public void setSmsAppPackagesProvider(PackagesProvider provider) {
24489            synchronized (mPackages) {
24490                mDefaultPermissionPolicy.setSmsAppPackagesProviderLPw(provider);
24491            }
24492        }
24493
24494        @Override
24495        public void setDialerAppPackagesProvider(PackagesProvider provider) {
24496            synchronized (mPackages) {
24497                mDefaultPermissionPolicy.setDialerAppPackagesProviderLPw(provider);
24498            }
24499        }
24500
24501        @Override
24502        public void setSimCallManagerPackagesProvider(PackagesProvider provider) {
24503            synchronized (mPackages) {
24504                mDefaultPermissionPolicy.setSimCallManagerPackagesProviderLPw(provider);
24505            }
24506        }
24507
24508        @Override
24509        public void setSyncAdapterPackagesprovider(SyncAdapterPackagesProvider provider) {
24510            synchronized (mPackages) {
24511                mDefaultPermissionPolicy.setSyncAdapterPackagesProviderLPw(provider);
24512            }
24513        }
24514
24515        @Override
24516        public void grantDefaultPermissionsToDefaultSmsApp(String packageName, int userId) {
24517            synchronized (mPackages) {
24518                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSmsAppLPr(
24519                        packageName, userId);
24520            }
24521        }
24522
24523        @Override
24524        public void grantDefaultPermissionsToDefaultDialerApp(String packageName, int userId) {
24525            synchronized (mPackages) {
24526                mSettings.setDefaultDialerPackageNameLPw(packageName, userId);
24527                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultDialerAppLPr(
24528                        packageName, userId);
24529            }
24530        }
24531
24532        @Override
24533        public void grantDefaultPermissionsToDefaultSimCallManager(String packageName, int userId) {
24534            synchronized (mPackages) {
24535                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSimCallManagerLPr(
24536                        packageName, userId);
24537            }
24538        }
24539
24540        @Override
24541        public void setKeepUninstalledPackages(final List<String> packageList) {
24542            Preconditions.checkNotNull(packageList);
24543            List<String> removedFromList = null;
24544            synchronized (mPackages) {
24545                if (mKeepUninstalledPackages != null) {
24546                    final int packagesCount = mKeepUninstalledPackages.size();
24547                    for (int i = 0; i < packagesCount; i++) {
24548                        String oldPackage = mKeepUninstalledPackages.get(i);
24549                        if (packageList != null && packageList.contains(oldPackage)) {
24550                            continue;
24551                        }
24552                        if (removedFromList == null) {
24553                            removedFromList = new ArrayList<>();
24554                        }
24555                        removedFromList.add(oldPackage);
24556                    }
24557                }
24558                mKeepUninstalledPackages = new ArrayList<>(packageList);
24559                if (removedFromList != null) {
24560                    final int removedCount = removedFromList.size();
24561                    for (int i = 0; i < removedCount; i++) {
24562                        deletePackageIfUnusedLPr(removedFromList.get(i));
24563                    }
24564                }
24565            }
24566        }
24567
24568        @Override
24569        public boolean isPermissionsReviewRequired(String packageName, int userId) {
24570            synchronized (mPackages) {
24571                // If we do not support permission review, done.
24572                if (!mPermissionReviewRequired) {
24573                    return false;
24574                }
24575
24576                PackageSetting packageSetting = mSettings.mPackages.get(packageName);
24577                if (packageSetting == null) {
24578                    return false;
24579                }
24580
24581                // Permission review applies only to apps not supporting the new permission model.
24582                if (packageSetting.pkg.applicationInfo.targetSdkVersion >= Build.VERSION_CODES.M) {
24583                    return false;
24584                }
24585
24586                // Legacy apps have the permission and get user consent on launch.
24587                PermissionsState permissionsState = packageSetting.getPermissionsState();
24588                return permissionsState.isPermissionReviewRequired(userId);
24589            }
24590        }
24591
24592        @Override
24593        public PackageInfo getPackageInfo(
24594                String packageName, int flags, int filterCallingUid, int userId) {
24595            return PackageManagerService.this
24596                    .getPackageInfoInternal(packageName, PackageManager.VERSION_CODE_HIGHEST,
24597                            flags, filterCallingUid, userId);
24598        }
24599
24600        @Override
24601        public ApplicationInfo getApplicationInfo(
24602                String packageName, int flags, int filterCallingUid, int userId) {
24603            return PackageManagerService.this
24604                    .getApplicationInfoInternal(packageName, flags, filterCallingUid, userId);
24605        }
24606
24607        @Override
24608        public ActivityInfo getActivityInfo(
24609                ComponentName component, int flags, int filterCallingUid, int userId) {
24610            return PackageManagerService.this
24611                    .getActivityInfoInternal(component, flags, filterCallingUid, userId);
24612        }
24613
24614        @Override
24615        public List<ResolveInfo> queryIntentActivities(
24616                Intent intent, int flags, int filterCallingUid, int userId) {
24617            final String resolvedType = intent.resolveTypeIfNeeded(mContext.getContentResolver());
24618            return PackageManagerService.this
24619                    .queryIntentActivitiesInternal(intent, resolvedType, flags, filterCallingUid,
24620                            userId, false /*resolveForStart*/);
24621        }
24622
24623        @Override
24624        public ComponentName getHomeActivitiesAsUser(List<ResolveInfo> allHomeCandidates,
24625                int userId) {
24626            return PackageManagerService.this.getHomeActivitiesAsUser(allHomeCandidates, userId);
24627        }
24628
24629        @Override
24630        public void setDeviceAndProfileOwnerPackages(
24631                int deviceOwnerUserId, String deviceOwnerPackage,
24632                SparseArray<String> profileOwnerPackages) {
24633            mProtectedPackages.setDeviceAndProfileOwnerPackages(
24634                    deviceOwnerUserId, deviceOwnerPackage, profileOwnerPackages);
24635        }
24636
24637        @Override
24638        public boolean isPackageDataProtected(int userId, String packageName) {
24639            return mProtectedPackages.isPackageDataProtected(userId, packageName);
24640        }
24641
24642        @Override
24643        public boolean isPackageEphemeral(int userId, String packageName) {
24644            synchronized (mPackages) {
24645                final PackageSetting ps = mSettings.mPackages.get(packageName);
24646                return ps != null ? ps.getInstantApp(userId) : false;
24647            }
24648        }
24649
24650        @Override
24651        public boolean wasPackageEverLaunched(String packageName, int userId) {
24652            synchronized (mPackages) {
24653                return mSettings.wasPackageEverLaunchedLPr(packageName, userId);
24654            }
24655        }
24656
24657        @Override
24658        public void grantRuntimePermission(String packageName, String name, int userId,
24659                boolean overridePolicy) {
24660            PackageManagerService.this.grantRuntimePermission(packageName, name, userId,
24661                    overridePolicy);
24662        }
24663
24664        @Override
24665        public void revokeRuntimePermission(String packageName, String name, int userId,
24666                boolean overridePolicy) {
24667            PackageManagerService.this.revokeRuntimePermission(packageName, name, userId,
24668                    overridePolicy);
24669        }
24670
24671        @Override
24672        public String getNameForUid(int uid) {
24673            return PackageManagerService.this.getNameForUid(uid);
24674        }
24675
24676        @Override
24677        public void requestInstantAppResolutionPhaseTwo(AuxiliaryResolveInfo responseObj,
24678                Intent origIntent, String resolvedType, String callingPackage,
24679                Bundle verificationBundle, int userId) {
24680            PackageManagerService.this.requestInstantAppResolutionPhaseTwo(
24681                    responseObj, origIntent, resolvedType, callingPackage, verificationBundle,
24682                    userId);
24683        }
24684
24685        @Override
24686        public void grantEphemeralAccess(int userId, Intent intent,
24687                int targetAppId, int ephemeralAppId) {
24688            synchronized (mPackages) {
24689                mInstantAppRegistry.grantInstantAccessLPw(userId, intent,
24690                        targetAppId, ephemeralAppId);
24691            }
24692        }
24693
24694        @Override
24695        public boolean isInstantAppInstallerComponent(ComponentName component) {
24696            synchronized (mPackages) {
24697                return mInstantAppInstallerActivity != null
24698                        && mInstantAppInstallerActivity.getComponentName().equals(component);
24699            }
24700        }
24701
24702        @Override
24703        public void pruneInstantApps() {
24704            mInstantAppRegistry.pruneInstantApps();
24705        }
24706
24707        @Override
24708        public String getSetupWizardPackageName() {
24709            return mSetupWizardPackage;
24710        }
24711
24712        public void setExternalSourcesPolicy(ExternalSourcesPolicy policy) {
24713            if (policy != null) {
24714                mExternalSourcesPolicy = policy;
24715            }
24716        }
24717
24718        @Override
24719        public boolean isPackagePersistent(String packageName) {
24720            synchronized (mPackages) {
24721                PackageParser.Package pkg = mPackages.get(packageName);
24722                return pkg != null
24723                        ? ((pkg.applicationInfo.flags&(ApplicationInfo.FLAG_SYSTEM
24724                                        | ApplicationInfo.FLAG_PERSISTENT)) ==
24725                                (ApplicationInfo.FLAG_SYSTEM | ApplicationInfo.FLAG_PERSISTENT))
24726                        : false;
24727            }
24728        }
24729
24730        @Override
24731        public List<PackageInfo> getOverlayPackages(int userId) {
24732            final ArrayList<PackageInfo> overlayPackages = new ArrayList<PackageInfo>();
24733            synchronized (mPackages) {
24734                for (PackageParser.Package p : mPackages.values()) {
24735                    if (p.mOverlayTarget != null) {
24736                        PackageInfo pkg = generatePackageInfo((PackageSetting)p.mExtras, 0, userId);
24737                        if (pkg != null) {
24738                            overlayPackages.add(pkg);
24739                        }
24740                    }
24741                }
24742            }
24743            return overlayPackages;
24744        }
24745
24746        @Override
24747        public List<String> getTargetPackageNames(int userId) {
24748            List<String> targetPackages = new ArrayList<>();
24749            synchronized (mPackages) {
24750                for (PackageParser.Package p : mPackages.values()) {
24751                    if (p.mOverlayTarget == null) {
24752                        targetPackages.add(p.packageName);
24753                    }
24754                }
24755            }
24756            return targetPackages;
24757        }
24758
24759        @Override
24760        public boolean setEnabledOverlayPackages(int userId, @NonNull String targetPackageName,
24761                @Nullable List<String> overlayPackageNames) {
24762            synchronized (mPackages) {
24763                if (targetPackageName == null || mPackages.get(targetPackageName) == null) {
24764                    Slog.e(TAG, "failed to find package " + targetPackageName);
24765                    return false;
24766                }
24767                ArrayList<String> overlayPaths = null;
24768                if (overlayPackageNames != null && overlayPackageNames.size() > 0) {
24769                    final int N = overlayPackageNames.size();
24770                    overlayPaths = new ArrayList<>(N);
24771                    for (int i = 0; i < N; i++) {
24772                        final String packageName = overlayPackageNames.get(i);
24773                        final PackageParser.Package pkg = mPackages.get(packageName);
24774                        if (pkg == null) {
24775                            Slog.e(TAG, "failed to find package " + packageName);
24776                            return false;
24777                        }
24778                        overlayPaths.add(pkg.baseCodePath);
24779                    }
24780                }
24781
24782                final PackageSetting ps = mSettings.mPackages.get(targetPackageName);
24783                ps.setOverlayPaths(overlayPaths, userId);
24784                return true;
24785            }
24786        }
24787
24788        @Override
24789        public ResolveInfo resolveIntent(Intent intent, String resolvedType,
24790                int flags, int userId) {
24791            return resolveIntentInternal(
24792                    intent, resolvedType, flags, userId, true /*resolveForStart*/);
24793        }
24794
24795        @Override
24796        public ResolveInfo resolveService(Intent intent, String resolvedType,
24797                int flags, int userId, int callingUid) {
24798            return resolveServiceInternal(intent, resolvedType, flags, userId, callingUid);
24799        }
24800
24801        @Override
24802        public void addIsolatedUid(int isolatedUid, int ownerUid) {
24803            synchronized (mPackages) {
24804                mIsolatedOwners.put(isolatedUid, ownerUid);
24805            }
24806        }
24807
24808        @Override
24809        public void removeIsolatedUid(int isolatedUid) {
24810            synchronized (mPackages) {
24811                mIsolatedOwners.delete(isolatedUid);
24812            }
24813        }
24814
24815        @Override
24816        public int getUidTargetSdkVersion(int uid) {
24817            synchronized (mPackages) {
24818                return getUidTargetSdkVersionLockedLPr(uid);
24819            }
24820        }
24821
24822        @Override
24823        public boolean canAccessInstantApps(int callingUid, int userId) {
24824            return PackageManagerService.this.canViewInstantApps(callingUid, userId);
24825        }
24826    }
24827
24828    @Override
24829    public void grantDefaultPermissionsToEnabledCarrierApps(String[] packageNames, int userId) {
24830        enforceSystemOrPhoneCaller("grantPermissionsToEnabledCarrierApps");
24831        synchronized (mPackages) {
24832            final long identity = Binder.clearCallingIdentity();
24833            try {
24834                mDefaultPermissionPolicy.grantDefaultPermissionsToEnabledCarrierAppsLPr(
24835                        packageNames, userId);
24836            } finally {
24837                Binder.restoreCallingIdentity(identity);
24838            }
24839        }
24840    }
24841
24842    @Override
24843    public void grantDefaultPermissionsToEnabledImsServices(String[] packageNames, int userId) {
24844        enforceSystemOrPhoneCaller("grantDefaultPermissionsToEnabledImsServices");
24845        synchronized (mPackages) {
24846            final long identity = Binder.clearCallingIdentity();
24847            try {
24848                mDefaultPermissionPolicy.grantDefaultPermissionsToEnabledImsServicesLPr(
24849                        packageNames, userId);
24850            } finally {
24851                Binder.restoreCallingIdentity(identity);
24852            }
24853        }
24854    }
24855
24856    private static void enforceSystemOrPhoneCaller(String tag) {
24857        int callingUid = Binder.getCallingUid();
24858        if (callingUid != Process.PHONE_UID && callingUid != Process.SYSTEM_UID) {
24859            throw new SecurityException(
24860                    "Cannot call " + tag + " from UID " + callingUid);
24861        }
24862    }
24863
24864    boolean isHistoricalPackageUsageAvailable() {
24865        return mPackageUsage.isHistoricalPackageUsageAvailable();
24866    }
24867
24868    /**
24869     * Return a <b>copy</b> of the collection of packages known to the package manager.
24870     * @return A copy of the values of mPackages.
24871     */
24872    Collection<PackageParser.Package> getPackages() {
24873        synchronized (mPackages) {
24874            return new ArrayList<>(mPackages.values());
24875        }
24876    }
24877
24878    /**
24879     * Logs process start information (including base APK hash) to the security log.
24880     * @hide
24881     */
24882    @Override
24883    public void logAppProcessStartIfNeeded(String processName, int uid, String seinfo,
24884            String apkFile, int pid) {
24885        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
24886            return;
24887        }
24888        if (!SecurityLog.isLoggingEnabled()) {
24889            return;
24890        }
24891        Bundle data = new Bundle();
24892        data.putLong("startTimestamp", System.currentTimeMillis());
24893        data.putString("processName", processName);
24894        data.putInt("uid", uid);
24895        data.putString("seinfo", seinfo);
24896        data.putString("apkFile", apkFile);
24897        data.putInt("pid", pid);
24898        Message msg = mProcessLoggingHandler.obtainMessage(
24899                ProcessLoggingHandler.LOG_APP_PROCESS_START_MSG);
24900        msg.setData(data);
24901        mProcessLoggingHandler.sendMessage(msg);
24902    }
24903
24904    public CompilerStats.PackageStats getCompilerPackageStats(String pkgName) {
24905        return mCompilerStats.getPackageStats(pkgName);
24906    }
24907
24908    public CompilerStats.PackageStats getOrCreateCompilerPackageStats(PackageParser.Package pkg) {
24909        return getOrCreateCompilerPackageStats(pkg.packageName);
24910    }
24911
24912    public CompilerStats.PackageStats getOrCreateCompilerPackageStats(String pkgName) {
24913        return mCompilerStats.getOrCreatePackageStats(pkgName);
24914    }
24915
24916    public void deleteCompilerPackageStats(String pkgName) {
24917        mCompilerStats.deletePackageStats(pkgName);
24918    }
24919
24920    @Override
24921    public int getInstallReason(String packageName, int userId) {
24922        final int callingUid = Binder.getCallingUid();
24923        enforceCrossUserPermission(callingUid, userId,
24924                true /* requireFullPermission */, false /* checkShell */,
24925                "get install reason");
24926        synchronized (mPackages) {
24927            final PackageSetting ps = mSettings.mPackages.get(packageName);
24928            if (filterAppAccessLPr(ps, callingUid, userId)) {
24929                return PackageManager.INSTALL_REASON_UNKNOWN;
24930            }
24931            if (ps != null) {
24932                return ps.getInstallReason(userId);
24933            }
24934        }
24935        return PackageManager.INSTALL_REASON_UNKNOWN;
24936    }
24937
24938    @Override
24939    public boolean canRequestPackageInstalls(String packageName, int userId) {
24940        return canRequestPackageInstallsInternal(packageName, 0, userId,
24941                true /* throwIfPermNotDeclared*/);
24942    }
24943
24944    private boolean canRequestPackageInstallsInternal(String packageName, int flags, int userId,
24945            boolean throwIfPermNotDeclared) {
24946        int callingUid = Binder.getCallingUid();
24947        int uid = getPackageUid(packageName, 0, userId);
24948        if (callingUid != uid && callingUid != Process.ROOT_UID
24949                && callingUid != Process.SYSTEM_UID) {
24950            throw new SecurityException(
24951                    "Caller uid " + callingUid + " does not own package " + packageName);
24952        }
24953        ApplicationInfo info = getApplicationInfo(packageName, flags, userId);
24954        if (info == null) {
24955            return false;
24956        }
24957        if (info.targetSdkVersion < Build.VERSION_CODES.O) {
24958            return false;
24959        }
24960        String appOpPermission = Manifest.permission.REQUEST_INSTALL_PACKAGES;
24961        String[] packagesDeclaringPermission = getAppOpPermissionPackages(appOpPermission);
24962        if (!ArrayUtils.contains(packagesDeclaringPermission, packageName)) {
24963            if (throwIfPermNotDeclared) {
24964                throw new SecurityException("Need to declare " + appOpPermission
24965                        + " to call this api");
24966            } else {
24967                Slog.e(TAG, "Need to declare " + appOpPermission + " to call this api");
24968                return false;
24969            }
24970        }
24971        if (sUserManager.hasUserRestriction(UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES, userId)) {
24972            return false;
24973        }
24974        if (mExternalSourcesPolicy != null) {
24975            int isTrusted = mExternalSourcesPolicy.getPackageTrustedToInstallApps(packageName, uid);
24976            if (isTrusted != PackageManagerInternal.ExternalSourcesPolicy.USER_DEFAULT) {
24977                return isTrusted == PackageManagerInternal.ExternalSourcesPolicy.USER_TRUSTED;
24978            }
24979        }
24980        return checkUidPermission(appOpPermission, uid) == PERMISSION_GRANTED;
24981    }
24982
24983    @Override
24984    public ComponentName getInstantAppResolverSettingsComponent() {
24985        return mInstantAppResolverSettingsComponent;
24986    }
24987
24988    @Override
24989    public ComponentName getInstantAppInstallerComponent() {
24990        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
24991            return null;
24992        }
24993        return mInstantAppInstallerActivity == null
24994                ? null : mInstantAppInstallerActivity.getComponentName();
24995    }
24996
24997    @Override
24998    public String getInstantAppAndroidId(String packageName, int userId) {
24999        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.ACCESS_INSTANT_APPS,
25000                "getInstantAppAndroidId");
25001        enforceCrossUserPermission(Binder.getCallingUid(), userId,
25002                true /* requireFullPermission */, false /* checkShell */,
25003                "getInstantAppAndroidId");
25004        // Make sure the target is an Instant App.
25005        if (!isInstantApp(packageName, userId)) {
25006            return null;
25007        }
25008        synchronized (mPackages) {
25009            return mInstantAppRegistry.getInstantAppAndroidIdLPw(packageName, userId);
25010        }
25011    }
25012
25013    boolean canHaveOatDir(String packageName) {
25014        synchronized (mPackages) {
25015            PackageParser.Package p = mPackages.get(packageName);
25016            if (p == null) {
25017                return false;
25018            }
25019            return p.canHaveOatDir();
25020        }
25021    }
25022
25023    private String getOatDir(PackageParser.Package pkg) {
25024        if (!pkg.canHaveOatDir()) {
25025            return null;
25026        }
25027        File codePath = new File(pkg.codePath);
25028        if (codePath.isDirectory()) {
25029            return PackageDexOptimizer.getOatDir(codePath).getAbsolutePath();
25030        }
25031        return null;
25032    }
25033
25034    void deleteOatArtifactsOfPackage(String packageName) {
25035        final String[] instructionSets;
25036        final List<String> codePaths;
25037        final String oatDir;
25038        final PackageParser.Package pkg;
25039        synchronized (mPackages) {
25040            pkg = mPackages.get(packageName);
25041        }
25042        instructionSets = getAppDexInstructionSets(pkg.applicationInfo);
25043        codePaths = pkg.getAllCodePaths();
25044        oatDir = getOatDir(pkg);
25045
25046        for (String codePath : codePaths) {
25047            for (String isa : instructionSets) {
25048                try {
25049                    mInstaller.deleteOdex(codePath, isa, oatDir);
25050                } catch (InstallerException e) {
25051                    Log.e(TAG, "Failed deleting oat files for " + codePath, e);
25052                }
25053            }
25054        }
25055    }
25056
25057    Set<String> getUnusedPackages(long downgradeTimeThresholdMillis) {
25058        Set<String> unusedPackages = new HashSet<>();
25059        long currentTimeInMillis = System.currentTimeMillis();
25060        synchronized (mPackages) {
25061            for (PackageParser.Package pkg : mPackages.values()) {
25062                PackageSetting ps =  mSettings.mPackages.get(pkg.packageName);
25063                if (ps == null) {
25064                    continue;
25065                }
25066                PackageDexUsage.PackageUseInfo packageUseInfo = getDexManager().getPackageUseInfo(
25067                        pkg.packageName);
25068                if (PackageManagerServiceUtils
25069                        .isUnusedSinceTimeInMillis(ps.firstInstallTime, currentTimeInMillis,
25070                                downgradeTimeThresholdMillis, packageUseInfo,
25071                                pkg.getLatestPackageUseTimeInMills(),
25072                                pkg.getLatestForegroundPackageUseTimeInMills())) {
25073                    unusedPackages.add(pkg.packageName);
25074                }
25075            }
25076        }
25077        return unusedPackages;
25078    }
25079}
25080
25081interface PackageSender {
25082    void sendPackageBroadcast(final String action, final String pkg,
25083        final Bundle extras, final int flags, final String targetPkg,
25084        final IIntentReceiver finishedReceiver, final int[] userIds);
25085    void sendPackageAddedForNewUsers(String packageName, boolean isSystem,
25086        int appId, int... userIds);
25087}
25088