PackageManagerService.java revision 2dd3ad06d6413928448f0735c937a414018520ba
1/*
2 * Copyright (C) 2006 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 *      http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17package com.android.server.pm;
18
19import static android.Manifest.permission.DELETE_PACKAGES;
20import static android.Manifest.permission.INSTALL_PACKAGES;
21import static android.Manifest.permission.MANAGE_PROFILE_AND_DEVICE_OWNERS;
22import static android.Manifest.permission.READ_EXTERNAL_STORAGE;
23import static android.Manifest.permission.REQUEST_DELETE_PACKAGES;
24import static android.Manifest.permission.WRITE_EXTERNAL_STORAGE;
25import static android.Manifest.permission.WRITE_MEDIA_STORAGE;
26import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DEFAULT;
27import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED;
28import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED;
29import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED_USER;
30import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_ENABLED;
31import static android.content.pm.PackageManager.DELETE_KEEP_DATA;
32import static android.content.pm.PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT;
33import static android.content.pm.PackageManager.FLAG_PERMISSION_POLICY_FIXED;
34import static android.content.pm.PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED;
35import static android.content.pm.PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE;
36import static android.content.pm.PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
37import static android.content.pm.PackageManager.FLAG_PERMISSION_USER_FIXED;
38import static android.content.pm.PackageManager.FLAG_PERMISSION_USER_SET;
39import static android.content.pm.PackageManager.INSTALL_EXTERNAL;
40import static android.content.pm.PackageManager.INSTALL_FAILED_ALREADY_EXISTS;
41import static android.content.pm.PackageManager.INSTALL_FAILED_CONFLICTING_PROVIDER;
42import static android.content.pm.PackageManager.INSTALL_FAILED_DUPLICATE_PACKAGE;
43import static android.content.pm.PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION;
44import static android.content.pm.PackageManager.INSTALL_FAILED_INSTANT_APP_INVALID;
45import static android.content.pm.PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
46import static android.content.pm.PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
47import static android.content.pm.PackageManager.INSTALL_FAILED_INVALID_APK;
48import static android.content.pm.PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
49import static android.content.pm.PackageManager.INSTALL_FAILED_MISSING_SHARED_LIBRARY;
50import static android.content.pm.PackageManager.INSTALL_FAILED_PACKAGE_CHANGED;
51import static android.content.pm.PackageManager.INSTALL_FAILED_REPLACE_COULDNT_DELETE;
52import static android.content.pm.PackageManager.INSTALL_FAILED_SANDBOX_VERSION_DOWNGRADE;
53import static android.content.pm.PackageManager.INSTALL_FAILED_SHARED_USER_INCOMPATIBLE;
54import static android.content.pm.PackageManager.INSTALL_FAILED_TEST_ONLY;
55import static android.content.pm.PackageManager.INSTALL_FAILED_UPDATE_INCOMPATIBLE;
56import static android.content.pm.PackageManager.INSTALL_FAILED_USER_RESTRICTED;
57import static android.content.pm.PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE;
58import static android.content.pm.PackageManager.INSTALL_FORWARD_LOCK;
59import static android.content.pm.PackageManager.INSTALL_INTERNAL;
60import static android.content.pm.PackageManager.INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES;
61import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS;
62import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK;
63import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK;
64import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER;
65import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED;
66import static android.content.pm.PackageManager.MATCH_ALL;
67import static android.content.pm.PackageManager.MATCH_ANY_USER;
68import static android.content.pm.PackageManager.MATCH_DEBUG_TRIAGED_MISSING;
69import static android.content.pm.PackageManager.MATCH_DIRECT_BOOT_AWARE;
70import static android.content.pm.PackageManager.MATCH_DIRECT_BOOT_UNAWARE;
71import static android.content.pm.PackageManager.MATCH_DISABLED_COMPONENTS;
72import static android.content.pm.PackageManager.MATCH_FACTORY_ONLY;
73import static android.content.pm.PackageManager.MATCH_KNOWN_PACKAGES;
74import static android.content.pm.PackageManager.MATCH_SYSTEM_ONLY;
75import static android.content.pm.PackageManager.MATCH_UNINSTALLED_PACKAGES;
76import static android.content.pm.PackageManager.MOVE_FAILED_3RD_PARTY_NOT_ALLOWED_ON_INTERNAL;
77import static android.content.pm.PackageManager.MOVE_FAILED_DEVICE_ADMIN;
78import static android.content.pm.PackageManager.MOVE_FAILED_DOESNT_EXIST;
79import static android.content.pm.PackageManager.MOVE_FAILED_INTERNAL_ERROR;
80import static android.content.pm.PackageManager.MOVE_FAILED_LOCKED_USER;
81import static android.content.pm.PackageManager.MOVE_FAILED_OPERATION_PENDING;
82import static android.content.pm.PackageManager.MOVE_FAILED_SYSTEM_PACKAGE;
83import static android.content.pm.PackageManager.PERMISSION_DENIED;
84import static android.content.pm.PackageManager.PERMISSION_GRANTED;
85import static android.content.pm.PackageParser.PARSE_IS_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;
90
91import static com.android.internal.app.IntentForwarderActivity.FORWARD_INTENT_TO_MANAGED_PROFILE;
92import static com.android.internal.app.IntentForwarderActivity.FORWARD_INTENT_TO_PARENT;
93import static com.android.internal.content.NativeLibraryHelper.LIB64_DIR_NAME;
94import static com.android.internal.content.NativeLibraryHelper.LIB_DIR_NAME;
95import static com.android.internal.util.ArrayUtils.appendInt;
96import static com.android.server.pm.InstructionSets.getAppDexInstructionSets;
97import static com.android.server.pm.InstructionSets.getDexCodeInstructionSet;
98import static com.android.server.pm.InstructionSets.getDexCodeInstructionSets;
99import static com.android.server.pm.InstructionSets.getPreferredInstructionSet;
100import static com.android.server.pm.InstructionSets.getPrimaryInstructionSet;
101import static com.android.server.pm.PackageManagerServiceCompilerMapping.getCompilerFilterForReason;
102import static com.android.server.pm.PackageManagerServiceCompilerMapping.getDefaultCompilerFilter;
103import static com.android.server.pm.PermissionsState.PERMISSION_OPERATION_FAILURE;
104import static com.android.server.pm.PermissionsState.PERMISSION_OPERATION_SUCCESS;
105import static com.android.server.pm.PermissionsState.PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED;
106
107import static dalvik.system.DexFile.getNonProfileGuidedCompilerFilter;
108
109import android.Manifest;
110import android.annotation.IntDef;
111import android.annotation.NonNull;
112import android.annotation.Nullable;
113import android.app.ActivityManager;
114import android.app.AppOpsManager;
115import android.app.IActivityManager;
116import android.app.ResourcesManager;
117import android.app.admin.IDevicePolicyManager;
118import android.app.admin.SecurityLog;
119import android.app.backup.IBackupManager;
120import android.content.BroadcastReceiver;
121import android.content.ComponentName;
122import android.content.ContentResolver;
123import android.content.Context;
124import android.content.IIntentReceiver;
125import android.content.Intent;
126import android.content.IntentFilter;
127import android.content.IntentSender;
128import android.content.IntentSender.SendIntentException;
129import android.content.ServiceConnection;
130import android.content.pm.ActivityInfo;
131import android.content.pm.ApplicationInfo;
132import android.content.pm.AppsQueryHelper;
133import android.content.pm.AuxiliaryResolveInfo;
134import android.content.pm.ChangedPackages;
135import android.content.pm.ComponentInfo;
136import android.content.pm.FallbackCategoryProvider;
137import android.content.pm.FeatureInfo;
138import android.content.pm.IDexModuleRegisterCallback;
139import android.content.pm.IOnPermissionsChangeListener;
140import android.content.pm.IPackageDataObserver;
141import android.content.pm.IPackageDeleteObserver;
142import android.content.pm.IPackageDeleteObserver2;
143import android.content.pm.IPackageInstallObserver2;
144import android.content.pm.IPackageInstaller;
145import android.content.pm.IPackageManager;
146import android.content.pm.IPackageMoveObserver;
147import android.content.pm.IPackageStatsObserver;
148import android.content.pm.InstantAppInfo;
149import android.content.pm.InstantAppRequest;
150import android.content.pm.InstantAppResolveInfo;
151import android.content.pm.InstrumentationInfo;
152import android.content.pm.IntentFilterVerificationInfo;
153import android.content.pm.KeySet;
154import android.content.pm.PackageCleanItem;
155import android.content.pm.PackageInfo;
156import android.content.pm.PackageInfoLite;
157import android.content.pm.PackageInstaller;
158import android.content.pm.PackageManager;
159import android.content.pm.PackageManager.LegacyPackageDeleteObserver;
160import android.content.pm.PackageManagerInternal;
161import android.content.pm.PackageParser;
162import android.content.pm.PackageParser.ActivityIntentInfo;
163import android.content.pm.PackageParser.PackageLite;
164import android.content.pm.PackageParser.PackageParserException;
165import android.content.pm.PackageStats;
166import android.content.pm.PackageUserState;
167import android.content.pm.ParceledListSlice;
168import android.content.pm.PermissionGroupInfo;
169import android.content.pm.PermissionInfo;
170import android.content.pm.ProviderInfo;
171import android.content.pm.ResolveInfo;
172import android.content.pm.ServiceInfo;
173import android.content.pm.SharedLibraryInfo;
174import android.content.pm.Signature;
175import android.content.pm.UserInfo;
176import android.content.pm.VerifierDeviceIdentity;
177import android.content.pm.VerifierInfo;
178import android.content.pm.VersionedPackage;
179import android.content.res.Resources;
180import android.database.ContentObserver;
181import android.graphics.Bitmap;
182import android.hardware.display.DisplayManager;
183import android.net.Uri;
184import android.os.Binder;
185import android.os.Build;
186import android.os.Bundle;
187import android.os.Debug;
188import android.os.Environment;
189import android.os.Environment.UserEnvironment;
190import android.os.FileUtils;
191import android.os.Handler;
192import android.os.IBinder;
193import android.os.Looper;
194import android.os.Message;
195import android.os.Parcel;
196import android.os.ParcelFileDescriptor;
197import android.os.PatternMatcher;
198import android.os.Process;
199import android.os.RemoteCallbackList;
200import android.os.RemoteException;
201import android.os.ResultReceiver;
202import android.os.SELinux;
203import android.os.ServiceManager;
204import android.os.ShellCallback;
205import android.os.SystemClock;
206import android.os.SystemProperties;
207import android.os.Trace;
208import android.os.UserHandle;
209import android.os.UserManager;
210import android.os.UserManagerInternal;
211import android.os.storage.IStorageManager;
212import android.os.storage.StorageEventListener;
213import android.os.storage.StorageManager;
214import android.os.storage.StorageManagerInternal;
215import android.os.storage.VolumeInfo;
216import android.os.storage.VolumeRecord;
217import android.provider.Settings.Global;
218import android.provider.Settings.Secure;
219import android.security.KeyStore;
220import android.security.SystemKeyStore;
221import android.service.pm.PackageServiceDumpProto;
222import android.system.ErrnoException;
223import android.system.Os;
224import android.text.TextUtils;
225import android.text.format.DateUtils;
226import android.util.ArrayMap;
227import android.util.ArraySet;
228import android.util.Base64;
229import android.util.BootTimingsTraceLog;
230import android.util.DisplayMetrics;
231import android.util.EventLog;
232import android.util.ExceptionUtils;
233import android.util.Log;
234import android.util.LogPrinter;
235import android.util.MathUtils;
236import android.util.PackageUtils;
237import android.util.Pair;
238import android.util.PrintStreamPrinter;
239import android.util.Slog;
240import android.util.SparseArray;
241import android.util.SparseBooleanArray;
242import android.util.SparseIntArray;
243import android.util.Xml;
244import android.util.jar.StrictJarFile;
245import android.util.proto.ProtoOutputStream;
246import android.view.Display;
247
248import com.android.internal.R;
249import com.android.internal.annotations.GuardedBy;
250import com.android.internal.app.IMediaContainerService;
251import com.android.internal.app.ResolverActivity;
252import com.android.internal.content.NativeLibraryHelper;
253import com.android.internal.content.PackageHelper;
254import com.android.internal.logging.MetricsLogger;
255import com.android.internal.logging.nano.MetricsProto.MetricsEvent;
256import com.android.internal.os.IParcelFileDescriptorFactory;
257import com.android.internal.os.RoSystemProperties;
258import com.android.internal.os.SomeArgs;
259import com.android.internal.os.Zygote;
260import com.android.internal.telephony.CarrierAppUtils;
261import com.android.internal.util.ArrayUtils;
262import com.android.internal.util.ConcurrentUtils;
263import com.android.internal.util.DumpUtils;
264import com.android.internal.util.FastPrintWriter;
265import com.android.internal.util.FastXmlSerializer;
266import com.android.internal.util.IndentingPrintWriter;
267import com.android.internal.util.Preconditions;
268import com.android.internal.util.XmlUtils;
269import com.android.server.AttributeCache;
270import com.android.server.DeviceIdleController;
271import com.android.server.EventLogTags;
272import com.android.server.FgThread;
273import com.android.server.IntentResolver;
274import com.android.server.LocalServices;
275import com.android.server.LockGuard;
276import com.android.server.ServiceThread;
277import com.android.server.SystemConfig;
278import com.android.server.SystemServerInitThreadPool;
279import com.android.server.Watchdog;
280import com.android.server.net.NetworkPolicyManagerInternal;
281import com.android.server.pm.Installer.InstallerException;
282import com.android.server.pm.PermissionsState.PermissionState;
283import com.android.server.pm.Settings.DatabaseVersion;
284import com.android.server.pm.Settings.VersionInfo;
285import com.android.server.pm.dex.DexManager;
286import com.android.server.pm.dex.DexoptOptions;
287import com.android.server.pm.dex.PackageDexUsage;
288import com.android.server.storage.DeviceStorageMonitorInternal;
289
290import dalvik.system.CloseGuard;
291import dalvik.system.DexFile;
292import dalvik.system.VMRuntime;
293
294import libcore.io.IoUtils;
295import libcore.util.EmptyArray;
296
297import org.xmlpull.v1.XmlPullParser;
298import org.xmlpull.v1.XmlPullParserException;
299import org.xmlpull.v1.XmlSerializer;
300
301import java.io.BufferedOutputStream;
302import java.io.BufferedReader;
303import java.io.ByteArrayInputStream;
304import java.io.ByteArrayOutputStream;
305import java.io.File;
306import java.io.FileDescriptor;
307import java.io.FileInputStream;
308import java.io.FileOutputStream;
309import java.io.FileReader;
310import java.io.FilenameFilter;
311import java.io.IOException;
312import java.io.PrintWriter;
313import java.lang.annotation.Retention;
314import java.lang.annotation.RetentionPolicy;
315import java.nio.charset.StandardCharsets;
316import java.security.DigestInputStream;
317import java.security.MessageDigest;
318import java.security.NoSuchAlgorithmException;
319import java.security.PublicKey;
320import java.security.SecureRandom;
321import java.security.cert.Certificate;
322import java.security.cert.CertificateEncodingException;
323import java.security.cert.CertificateException;
324import java.text.SimpleDateFormat;
325import java.util.ArrayList;
326import java.util.Arrays;
327import java.util.Collection;
328import java.util.Collections;
329import java.util.Comparator;
330import java.util.Date;
331import java.util.HashMap;
332import java.util.HashSet;
333import java.util.Iterator;
334import java.util.List;
335import java.util.Map;
336import java.util.Objects;
337import java.util.Set;
338import java.util.concurrent.CountDownLatch;
339import java.util.concurrent.Future;
340import java.util.concurrent.TimeUnit;
341import java.util.concurrent.atomic.AtomicBoolean;
342import java.util.concurrent.atomic.AtomicInteger;
343
344/**
345 * Keep track of all those APKs everywhere.
346 * <p>
347 * Internally there are two important locks:
348 * <ul>
349 * <li>{@link #mPackages} is used to guard all in-memory parsed package details
350 * and other related state. It is a fine-grained lock that should only be held
351 * momentarily, as it's one of the most contended locks in the system.
352 * <li>{@link #mInstallLock} is used to guard all {@code installd} access, whose
353 * operations typically involve heavy lifting of application data on disk. Since
354 * {@code installd} is single-threaded, and it's operations can often be slow,
355 * this lock should never be acquired while already holding {@link #mPackages}.
356 * Conversely, it's safe to acquire {@link #mPackages} momentarily while already
357 * holding {@link #mInstallLock}.
358 * </ul>
359 * Many internal methods rely on the caller to hold the appropriate locks, and
360 * this contract is expressed through method name suffixes:
361 * <ul>
362 * <li>fooLI(): the caller must hold {@link #mInstallLock}
363 * <li>fooLIF(): the caller must hold {@link #mInstallLock} and the package
364 * being modified must be frozen
365 * <li>fooLPr(): the caller must hold {@link #mPackages} for reading
366 * <li>fooLPw(): the caller must hold {@link #mPackages} for writing
367 * </ul>
368 * <p>
369 * Because this class is very central to the platform's security; please run all
370 * CTS and unit tests whenever making modifications:
371 *
372 * <pre>
373 * $ runtest -c android.content.pm.PackageManagerTests frameworks-core
374 * $ cts-tradefed run commandAndExit cts -m CtsAppSecurityHostTestCases
375 * </pre>
376 */
377public class PackageManagerService extends IPackageManager.Stub
378        implements PackageSender {
379    static final String TAG = "PackageManager";
380    static final boolean DEBUG_SETTINGS = false;
381    static final boolean DEBUG_PREFERRED = false;
382    static final boolean DEBUG_UPGRADE = false;
383    static final boolean DEBUG_DOMAIN_VERIFICATION = false;
384    private static final boolean DEBUG_BACKUP = false;
385    private static final boolean DEBUG_INSTALL = false;
386    private static final boolean DEBUG_REMOVE = false;
387    private static final boolean DEBUG_BROADCASTS = false;
388    private static final boolean DEBUG_SHOW_INFO = false;
389    private static final boolean DEBUG_PACKAGE_INFO = false;
390    private static final boolean DEBUG_INTENT_MATCHING = false;
391    private static final boolean DEBUG_PACKAGE_SCANNING = false;
392    private static final boolean DEBUG_VERIFY = false;
393    private static final boolean DEBUG_FILTERS = false;
394    private static final boolean DEBUG_PERMISSIONS = false;
395    private static final boolean DEBUG_SHARED_LIBRARIES = false;
396
397    // Debug output for dexopting. This is shared between PackageManagerService, OtaDexoptService
398    // and PackageDexOptimizer. All these classes have their own flag to allow switching a single
399    // user, but by default initialize to this.
400    public static final boolean DEBUG_DEXOPT = false;
401
402    private static final boolean DEBUG_ABI_SELECTION = false;
403    private static final boolean DEBUG_EPHEMERAL = Build.IS_DEBUGGABLE;
404    private static final boolean DEBUG_TRIAGED_MISSING = false;
405    private static final boolean DEBUG_APP_DATA = false;
406
407    /** REMOVE. According to Svet, this was only used to reset permissions during development. */
408    static final boolean CLEAR_RUNTIME_PERMISSIONS_ON_UPGRADE = false;
409
410    private static final boolean HIDE_EPHEMERAL_APIS = false;
411
412    private static final boolean ENABLE_FREE_CACHE_V2 =
413            SystemProperties.getBoolean("fw.free_cache_v2", true);
414
415    private static final int RADIO_UID = Process.PHONE_UID;
416    private static final int LOG_UID = Process.LOG_UID;
417    private static final int NFC_UID = Process.NFC_UID;
418    private static final int BLUETOOTH_UID = Process.BLUETOOTH_UID;
419    private static final int SHELL_UID = Process.SHELL_UID;
420
421    // Cap the size of permission trees that 3rd party apps can define
422    private static final int MAX_PERMISSION_TREE_FOOTPRINT = 32768;     // characters of text
423
424    // Suffix used during package installation when copying/moving
425    // package apks to install directory.
426    private static final String INSTALL_PACKAGE_SUFFIX = "-";
427
428    static final int SCAN_NO_DEX = 1<<1;
429    static final int SCAN_FORCE_DEX = 1<<2;
430    static final int SCAN_UPDATE_SIGNATURE = 1<<3;
431    static final int SCAN_NEW_INSTALL = 1<<4;
432    static final int SCAN_UPDATE_TIME = 1<<5;
433    static final int SCAN_BOOTING = 1<<6;
434    static final int SCAN_TRUSTED_OVERLAY = 1<<7;
435    static final int SCAN_DELETE_DATA_ON_FAILURES = 1<<8;
436    static final int SCAN_REPLACING = 1<<9;
437    static final int SCAN_REQUIRE_KNOWN = 1<<10;
438    static final int SCAN_MOVE = 1<<11;
439    static final int SCAN_INITIAL = 1<<12;
440    static final int SCAN_CHECK_ONLY = 1<<13;
441    static final int SCAN_DONT_KILL_APP = 1<<14;
442    static final int SCAN_IGNORE_FROZEN = 1<<15;
443    static final int SCAN_FIRST_BOOT_OR_UPGRADE = 1<<16;
444    static final int SCAN_AS_INSTANT_APP = 1<<17;
445    static final int SCAN_AS_FULL_APP = 1<<18;
446    /** Should not be with the scan flags */
447    static final int FLAGS_REMOVE_CHATTY = 1<<31;
448
449    private static final String STATIC_SHARED_LIB_DELIMITER = "_";
450
451    private static final int[] EMPTY_INT_ARRAY = new int[0];
452
453    private static final int TYPE_UNKNOWN = 0;
454    private static final int TYPE_ACTIVITY = 1;
455    private static final int TYPE_RECEIVER = 2;
456    private static final int TYPE_SERVICE = 3;
457    private static final int TYPE_PROVIDER = 4;
458    @IntDef(prefix = { "TYPE_" }, value = {
459            TYPE_UNKNOWN,
460            TYPE_ACTIVITY,
461            TYPE_RECEIVER,
462            TYPE_SERVICE,
463            TYPE_PROVIDER,
464    })
465    @Retention(RetentionPolicy.SOURCE)
466    public @interface ComponentType {}
467
468    /**
469     * Timeout (in milliseconds) after which the watchdog should declare that
470     * our handler thread is wedged.  The usual default for such things is one
471     * minute but we sometimes do very lengthy I/O operations on this thread,
472     * such as installing multi-gigabyte applications, so ours needs to be longer.
473     */
474    static final long WATCHDOG_TIMEOUT = 1000*60*10;     // ten minutes
475
476    /**
477     * Wall-clock timeout (in milliseconds) after which we *require* that an fstrim
478     * be run on this device.  We use the value in the Settings.Global.MANDATORY_FSTRIM_INTERVAL
479     * settings entry if available, otherwise we use the hardcoded default.  If it's been
480     * more than this long since the last fstrim, we force one during the boot sequence.
481     *
482     * This backstops other fstrim scheduling:  if the device is alive at midnight+idle,
483     * one gets run at the next available charging+idle time.  This final mandatory
484     * no-fstrim check kicks in only of the other scheduling criteria is never met.
485     */
486    private static final long DEFAULT_MANDATORY_FSTRIM_INTERVAL = 3 * DateUtils.DAY_IN_MILLIS;
487
488    /**
489     * Whether verification is enabled by default.
490     */
491    private static final boolean DEFAULT_VERIFY_ENABLE = true;
492
493    /**
494     * The default maximum time to wait for the verification agent to return in
495     * milliseconds.
496     */
497    private static final long DEFAULT_VERIFICATION_TIMEOUT = 10 * 1000;
498
499    /**
500     * The default response for package verification timeout.
501     *
502     * This can be either PackageManager.VERIFICATION_ALLOW or
503     * PackageManager.VERIFICATION_REJECT.
504     */
505    private static final int DEFAULT_VERIFICATION_RESPONSE = PackageManager.VERIFICATION_ALLOW;
506
507    static final String PLATFORM_PACKAGE_NAME = "android";
508
509    static final String DEFAULT_CONTAINER_PACKAGE = "com.android.defcontainer";
510
511    static final ComponentName DEFAULT_CONTAINER_COMPONENT = new ComponentName(
512            DEFAULT_CONTAINER_PACKAGE,
513            "com.android.defcontainer.DefaultContainerService");
514
515    private static final String KILL_APP_REASON_GIDS_CHANGED =
516            "permission grant or revoke changed gids";
517
518    private static final String KILL_APP_REASON_PERMISSIONS_REVOKED =
519            "permissions revoked";
520
521    private static final String PACKAGE_MIME_TYPE = "application/vnd.android.package-archive";
522
523    private static final String PACKAGE_SCHEME = "package";
524
525    private static final String VENDOR_OVERLAY_DIR = "/vendor/overlay";
526
527    /** Permission grant: not grant the permission. */
528    private static final int GRANT_DENIED = 1;
529
530    /** Permission grant: grant the permission as an install permission. */
531    private static final int GRANT_INSTALL = 2;
532
533    /** Permission grant: grant the permission as a runtime one. */
534    private static final int GRANT_RUNTIME = 3;
535
536    /** Permission grant: grant as runtime a permission that was granted as an install time one. */
537    private static final int GRANT_UPGRADE = 4;
538
539    /** Canonical intent used to identify what counts as a "web browser" app */
540    private static final Intent sBrowserIntent;
541    static {
542        sBrowserIntent = new Intent();
543        sBrowserIntent.setAction(Intent.ACTION_VIEW);
544        sBrowserIntent.addCategory(Intent.CATEGORY_BROWSABLE);
545        sBrowserIntent.setData(Uri.parse("http:"));
546    }
547
548    /**
549     * The set of all protected actions [i.e. those actions for which a high priority
550     * intent filter is disallowed].
551     */
552    private static final Set<String> PROTECTED_ACTIONS = new ArraySet<>();
553    static {
554        PROTECTED_ACTIONS.add(Intent.ACTION_SEND);
555        PROTECTED_ACTIONS.add(Intent.ACTION_SENDTO);
556        PROTECTED_ACTIONS.add(Intent.ACTION_SEND_MULTIPLE);
557        PROTECTED_ACTIONS.add(Intent.ACTION_VIEW);
558    }
559
560    // Compilation reasons.
561    public static final int REASON_FIRST_BOOT = 0;
562    public static final int REASON_BOOT = 1;
563    public static final int REASON_INSTALL = 2;
564    public static final int REASON_BACKGROUND_DEXOPT = 3;
565    public static final int REASON_AB_OTA = 4;
566    public static final int REASON_INACTIVE_PACKAGE_DOWNGRADE = 5;
567
568    public static final int REASON_LAST = REASON_INACTIVE_PACKAGE_DOWNGRADE;
569
570    /** All dangerous permission names in the same order as the events in MetricsEvent */
571    private static final List<String> ALL_DANGEROUS_PERMISSIONS = Arrays.asList(
572            Manifest.permission.READ_CALENDAR,
573            Manifest.permission.WRITE_CALENDAR,
574            Manifest.permission.CAMERA,
575            Manifest.permission.READ_CONTACTS,
576            Manifest.permission.WRITE_CONTACTS,
577            Manifest.permission.GET_ACCOUNTS,
578            Manifest.permission.ACCESS_FINE_LOCATION,
579            Manifest.permission.ACCESS_COARSE_LOCATION,
580            Manifest.permission.RECORD_AUDIO,
581            Manifest.permission.READ_PHONE_STATE,
582            Manifest.permission.CALL_PHONE,
583            Manifest.permission.READ_CALL_LOG,
584            Manifest.permission.WRITE_CALL_LOG,
585            Manifest.permission.ADD_VOICEMAIL,
586            Manifest.permission.USE_SIP,
587            Manifest.permission.PROCESS_OUTGOING_CALLS,
588            Manifest.permission.READ_CELL_BROADCASTS,
589            Manifest.permission.BODY_SENSORS,
590            Manifest.permission.SEND_SMS,
591            Manifest.permission.RECEIVE_SMS,
592            Manifest.permission.READ_SMS,
593            Manifest.permission.RECEIVE_WAP_PUSH,
594            Manifest.permission.RECEIVE_MMS,
595            Manifest.permission.READ_EXTERNAL_STORAGE,
596            Manifest.permission.WRITE_EXTERNAL_STORAGE,
597            Manifest.permission.READ_PHONE_NUMBERS,
598            Manifest.permission.ANSWER_PHONE_CALLS);
599
600
601    /**
602     * Version number for the package parser cache. Increment this whenever the format or
603     * extent of cached data changes. See {@code PackageParser#setCacheDir}.
604     */
605    private static final String PACKAGE_PARSER_CACHE_VERSION = "1";
606
607    /**
608     * Whether the package parser cache is enabled.
609     */
610    private static final boolean DEFAULT_PACKAGE_PARSER_CACHE_ENABLED = true;
611
612    final ServiceThread mHandlerThread;
613
614    final PackageHandler mHandler;
615
616    private final ProcessLoggingHandler mProcessLoggingHandler;
617
618    /**
619     * Messages for {@link #mHandler} that need to wait for system ready before
620     * being dispatched.
621     */
622    private ArrayList<Message> mPostSystemReadyMessages;
623
624    final int mSdkVersion = Build.VERSION.SDK_INT;
625
626    final Context mContext;
627    final boolean mFactoryTest;
628    final boolean mOnlyCore;
629    final DisplayMetrics mMetrics;
630    final int mDefParseFlags;
631    final String[] mSeparateProcesses;
632    final boolean mIsUpgrade;
633    final boolean mIsPreNUpgrade;
634    final boolean mIsPreNMR1Upgrade;
635
636    // Have we told the Activity Manager to whitelist the default container service by uid yet?
637    @GuardedBy("mPackages")
638    boolean mDefaultContainerWhitelisted = false;
639
640    @GuardedBy("mPackages")
641    private boolean mDexOptDialogShown;
642
643    /** The location for ASEC container files on internal storage. */
644    final String mAsecInternalPath;
645
646    // Used for privilege escalation. MUST NOT BE CALLED WITH mPackages
647    // LOCK HELD.  Can be called with mInstallLock held.
648    @GuardedBy("mInstallLock")
649    final Installer mInstaller;
650
651    /** Directory where installed third-party apps stored */
652    final File mAppInstallDir;
653
654    /**
655     * Directory to which applications installed internally have their
656     * 32 bit native libraries copied.
657     */
658    private File mAppLib32InstallDir;
659
660    // Directory containing the private parts (e.g. code and non-resource assets) of forward-locked
661    // apps.
662    final File mDrmAppPrivateInstallDir;
663
664    // ----------------------------------------------------------------
665
666    // Lock for state used when installing and doing other long running
667    // operations.  Methods that must be called with this lock held have
668    // the suffix "LI".
669    final Object mInstallLock = new Object();
670
671    // ----------------------------------------------------------------
672
673    // Keys are String (package name), values are Package.  This also serves
674    // as the lock for the global state.  Methods that must be called with
675    // this lock held have the prefix "LP".
676    @GuardedBy("mPackages")
677    final ArrayMap<String, PackageParser.Package> mPackages =
678            new ArrayMap<String, PackageParser.Package>();
679
680    final ArrayMap<String, Set<String>> mKnownCodebase =
681            new ArrayMap<String, Set<String>>();
682
683    // Keys are isolated uids and values are the uid of the application
684    // that created the isolated proccess.
685    @GuardedBy("mPackages")
686    final SparseIntArray mIsolatedOwners = new SparseIntArray();
687
688    /**
689     * Tracks new system packages [received in an OTA] that we expect to
690     * find updated user-installed versions. Keys are package name, values
691     * are package location.
692     */
693    final private ArrayMap<String, File> mExpectingBetter = new ArrayMap<>();
694    /**
695     * Tracks high priority intent filters for protected actions. During boot, certain
696     * filter actions are protected and should never be allowed to have a high priority
697     * intent filter for them. However, there is one, and only one exception -- the
698     * setup wizard. It must be able to define a high priority intent filter for these
699     * actions to ensure there are no escapes from the wizard. We need to delay processing
700     * of these during boot as we need to look at all of the system packages in order
701     * to know which component is the setup wizard.
702     */
703    private final List<PackageParser.ActivityIntentInfo> mProtectedFilters = new ArrayList<>();
704    /**
705     * Whether or not processing protected filters should be deferred.
706     */
707    private boolean mDeferProtectedFilters = true;
708
709    /**
710     * Tracks existing system packages prior to receiving an OTA. Keys are package name.
711     */
712    final private ArraySet<String> mExistingSystemPackages = new ArraySet<>();
713    /**
714     * Whether or not system app permissions should be promoted from install to runtime.
715     */
716    boolean mPromoteSystemApps;
717
718    @GuardedBy("mPackages")
719    final Settings mSettings;
720
721    /**
722     * Set of package names that are currently "frozen", which means active
723     * surgery is being done on the code/data for that package. The platform
724     * will refuse to launch frozen packages to avoid race conditions.
725     *
726     * @see PackageFreezer
727     */
728    @GuardedBy("mPackages")
729    final ArraySet<String> mFrozenPackages = new ArraySet<>();
730
731    final ProtectedPackages mProtectedPackages;
732
733    @GuardedBy("mLoadedVolumes")
734    final ArraySet<String> mLoadedVolumes = new ArraySet<>();
735
736    boolean mFirstBoot;
737
738    PackageManagerInternal.ExternalSourcesPolicy mExternalSourcesPolicy;
739
740    // System configuration read by SystemConfig.
741    final int[] mGlobalGids;
742    final SparseArray<ArraySet<String>> mSystemPermissions;
743    @GuardedBy("mAvailableFeatures")
744    final ArrayMap<String, FeatureInfo> mAvailableFeatures;
745
746    // If mac_permissions.xml was found for seinfo labeling.
747    boolean mFoundPolicyFile;
748
749    private final InstantAppRegistry mInstantAppRegistry;
750
751    @GuardedBy("mPackages")
752    int mChangedPackagesSequenceNumber;
753    /**
754     * List of changed [installed, removed or updated] packages.
755     * mapping from user id -> sequence number -> package name
756     */
757    @GuardedBy("mPackages")
758    final SparseArray<SparseArray<String>> mChangedPackages = new SparseArray<>();
759    /**
760     * The sequence number of the last change to a package.
761     * mapping from user id -> package name -> sequence number
762     */
763    @GuardedBy("mPackages")
764    final SparseArray<Map<String, Integer>> mChangedPackagesSequenceNumbers = new SparseArray<>();
765
766    class PackageParserCallback implements PackageParser.Callback {
767        @Override public final boolean hasFeature(String feature) {
768            return PackageManagerService.this.hasSystemFeature(feature, 0);
769        }
770
771        final List<PackageParser.Package> getStaticOverlayPackagesLocked(
772                Collection<PackageParser.Package> allPackages, String targetPackageName) {
773            List<PackageParser.Package> overlayPackages = null;
774            for (PackageParser.Package p : allPackages) {
775                if (targetPackageName.equals(p.mOverlayTarget) && p.mIsStaticOverlay) {
776                    if (overlayPackages == null) {
777                        overlayPackages = new ArrayList<PackageParser.Package>();
778                    }
779                    overlayPackages.add(p);
780                }
781            }
782            if (overlayPackages != null) {
783                Comparator<PackageParser.Package> cmp = new Comparator<PackageParser.Package>() {
784                    public int compare(PackageParser.Package p1, PackageParser.Package p2) {
785                        return p1.mOverlayPriority - p2.mOverlayPriority;
786                    }
787                };
788                Collections.sort(overlayPackages, cmp);
789            }
790            return overlayPackages;
791        }
792
793        final String[] getStaticOverlayPathsLocked(Collection<PackageParser.Package> allPackages,
794                String targetPackageName, String targetPath) {
795            if ("android".equals(targetPackageName)) {
796                // Static RROs targeting to "android", ie framework-res.apk, are already applied by
797                // native AssetManager.
798                return null;
799            }
800            List<PackageParser.Package> overlayPackages =
801                    getStaticOverlayPackagesLocked(allPackages, targetPackageName);
802            if (overlayPackages == null || overlayPackages.isEmpty()) {
803                return null;
804            }
805            List<String> overlayPathList = null;
806            for (PackageParser.Package overlayPackage : overlayPackages) {
807                if (targetPath == null) {
808                    if (overlayPathList == null) {
809                        overlayPathList = new ArrayList<String>();
810                    }
811                    overlayPathList.add(overlayPackage.baseCodePath);
812                    continue;
813                }
814
815                try {
816                    // Creates idmaps for system to parse correctly the Android manifest of the
817                    // target package.
818                    //
819                    // OverlayManagerService will update each of them with a correct gid from its
820                    // target package app id.
821                    mInstaller.idmap(targetPath, overlayPackage.baseCodePath,
822                            UserHandle.getSharedAppGid(
823                                    UserHandle.getUserGid(UserHandle.USER_SYSTEM)));
824                    if (overlayPathList == null) {
825                        overlayPathList = new ArrayList<String>();
826                    }
827                    overlayPathList.add(overlayPackage.baseCodePath);
828                } catch (InstallerException e) {
829                    Slog.e(TAG, "Failed to generate idmap for " + targetPath + " and " +
830                            overlayPackage.baseCodePath);
831                }
832            }
833            return overlayPathList == null ? null : overlayPathList.toArray(new String[0]);
834        }
835
836        String[] getStaticOverlayPaths(String targetPackageName, String targetPath) {
837            synchronized (mPackages) {
838                return getStaticOverlayPathsLocked(
839                        mPackages.values(), targetPackageName, targetPath);
840            }
841        }
842
843        @Override public final String[] getOverlayApks(String targetPackageName) {
844            return getStaticOverlayPaths(targetPackageName, null);
845        }
846
847        @Override public final String[] getOverlayPaths(String targetPackageName,
848                String targetPath) {
849            return getStaticOverlayPaths(targetPackageName, targetPath);
850        }
851    };
852
853    class ParallelPackageParserCallback extends PackageParserCallback {
854        List<PackageParser.Package> mOverlayPackages = null;
855
856        void findStaticOverlayPackages() {
857            synchronized (mPackages) {
858                for (PackageParser.Package p : mPackages.values()) {
859                    if (p.mIsStaticOverlay) {
860                        if (mOverlayPackages == null) {
861                            mOverlayPackages = new ArrayList<PackageParser.Package>();
862                        }
863                        mOverlayPackages.add(p);
864                    }
865                }
866            }
867        }
868
869        @Override
870        synchronized String[] getStaticOverlayPaths(String targetPackageName, String targetPath) {
871            // We can trust mOverlayPackages without holding mPackages because package uninstall
872            // can't happen while running parallel parsing.
873            // Moreover holding mPackages on each parsing thread causes dead-lock.
874            return mOverlayPackages == null ? null :
875                    getStaticOverlayPathsLocked(mOverlayPackages, targetPackageName, targetPath);
876        }
877    }
878
879    final PackageParser.Callback mPackageParserCallback = new PackageParserCallback();
880    final ParallelPackageParserCallback mParallelPackageParserCallback =
881            new ParallelPackageParserCallback();
882
883    public static final class SharedLibraryEntry {
884        public final @Nullable String path;
885        public final @Nullable String apk;
886        public final @NonNull SharedLibraryInfo info;
887
888        SharedLibraryEntry(String _path, String _apk, String name, int version, int type,
889                String declaringPackageName, int declaringPackageVersionCode) {
890            path = _path;
891            apk = _apk;
892            info = new SharedLibraryInfo(name, version, type, new VersionedPackage(
893                    declaringPackageName, declaringPackageVersionCode), null);
894        }
895    }
896
897    // Currently known shared libraries.
898    final ArrayMap<String, SparseArray<SharedLibraryEntry>> mSharedLibraries = new ArrayMap<>();
899    final ArrayMap<String, SparseArray<SharedLibraryEntry>> mStaticLibsByDeclaringPackage =
900            new ArrayMap<>();
901
902    // All available activities, for your resolving pleasure.
903    final ActivityIntentResolver mActivities =
904            new ActivityIntentResolver();
905
906    // All available receivers, for your resolving pleasure.
907    final ActivityIntentResolver mReceivers =
908            new ActivityIntentResolver();
909
910    // All available services, for your resolving pleasure.
911    final ServiceIntentResolver mServices = new ServiceIntentResolver();
912
913    // All available providers, for your resolving pleasure.
914    final ProviderIntentResolver mProviders = new ProviderIntentResolver();
915
916    // Mapping from provider base names (first directory in content URI codePath)
917    // to the provider information.
918    final ArrayMap<String, PackageParser.Provider> mProvidersByAuthority =
919            new ArrayMap<String, PackageParser.Provider>();
920
921    // Mapping from instrumentation class names to info about them.
922    final ArrayMap<ComponentName, PackageParser.Instrumentation> mInstrumentation =
923            new ArrayMap<ComponentName, PackageParser.Instrumentation>();
924
925    // Mapping from permission names to info about them.
926    final ArrayMap<String, PackageParser.PermissionGroup> mPermissionGroups =
927            new ArrayMap<String, PackageParser.PermissionGroup>();
928
929    // Packages whose data we have transfered into another package, thus
930    // should no longer exist.
931    final ArraySet<String> mTransferedPackages = new ArraySet<String>();
932
933    // Broadcast actions that are only available to the system.
934    @GuardedBy("mProtectedBroadcasts")
935    final ArraySet<String> mProtectedBroadcasts = new ArraySet<>();
936
937    /** List of packages waiting for verification. */
938    final SparseArray<PackageVerificationState> mPendingVerification
939            = new SparseArray<PackageVerificationState>();
940
941    /** Set of packages associated with each app op permission. */
942    final ArrayMap<String, ArraySet<String>> mAppOpPermissionPackages = new ArrayMap<>();
943
944    final PackageInstallerService mInstallerService;
945
946    private final PackageDexOptimizer mPackageDexOptimizer;
947    // DexManager handles the usage of dex files (e.g. secondary files, whether or not a package
948    // is used by other apps).
949    private final DexManager mDexManager;
950
951    private AtomicInteger mNextMoveId = new AtomicInteger();
952    private final MoveCallbacks mMoveCallbacks;
953
954    private final OnPermissionChangeListeners mOnPermissionChangeListeners;
955
956    // Cache of users who need badging.
957    SparseBooleanArray mUserNeedsBadging = new SparseBooleanArray();
958
959    /** Token for keys in mPendingVerification. */
960    private int mPendingVerificationToken = 0;
961
962    volatile boolean mSystemReady;
963    volatile boolean mSafeMode;
964    volatile boolean mHasSystemUidErrors;
965    private volatile boolean mEphemeralAppsDisabled;
966
967    ApplicationInfo mAndroidApplication;
968    final ActivityInfo mResolveActivity = new ActivityInfo();
969    final ResolveInfo mResolveInfo = new ResolveInfo();
970    ComponentName mResolveComponentName;
971    PackageParser.Package mPlatformPackage;
972    ComponentName mCustomResolverComponentName;
973
974    boolean mResolverReplaced = false;
975
976    private final @Nullable ComponentName mIntentFilterVerifierComponent;
977    private final @Nullable IntentFilterVerifier<ActivityIntentInfo> mIntentFilterVerifier;
978
979    private int mIntentFilterVerificationToken = 0;
980
981    /** The service connection to the ephemeral resolver */
982    final EphemeralResolverConnection mInstantAppResolverConnection;
983    /** Component used to show resolver settings for Instant Apps */
984    final ComponentName mInstantAppResolverSettingsComponent;
985
986    /** Activity used to install instant applications */
987    ActivityInfo mInstantAppInstallerActivity;
988    final ResolveInfo mInstantAppInstallerInfo = new ResolveInfo();
989
990    final SparseArray<IntentFilterVerificationState> mIntentFilterVerificationStates
991            = new SparseArray<IntentFilterVerificationState>();
992
993    final DefaultPermissionGrantPolicy mDefaultPermissionPolicy;
994
995    // List of packages names to keep cached, even if they are uninstalled for all users
996    private List<String> mKeepUninstalledPackages;
997
998    private UserManagerInternal mUserManagerInternal;
999
1000    private DeviceIdleController.LocalService mDeviceIdleController;
1001
1002    private File mCacheDir;
1003
1004    private ArraySet<String> mPrivappPermissionsViolations;
1005
1006    private Future<?> mPrepareAppDataFuture;
1007
1008    private static class IFVerificationParams {
1009        PackageParser.Package pkg;
1010        boolean replacing;
1011        int userId;
1012        int verifierUid;
1013
1014        public IFVerificationParams(PackageParser.Package _pkg, boolean _replacing,
1015                int _userId, int _verifierUid) {
1016            pkg = _pkg;
1017            replacing = _replacing;
1018            userId = _userId;
1019            replacing = _replacing;
1020            verifierUid = _verifierUid;
1021        }
1022    }
1023
1024    private interface IntentFilterVerifier<T extends IntentFilter> {
1025        boolean addOneIntentFilterVerification(int verifierId, int userId, int verificationId,
1026                                               T filter, String packageName);
1027        void startVerifications(int userId);
1028        void receiveVerificationResponse(int verificationId);
1029    }
1030
1031    private class IntentVerifierProxy implements IntentFilterVerifier<ActivityIntentInfo> {
1032        private Context mContext;
1033        private ComponentName mIntentFilterVerifierComponent;
1034        private ArrayList<Integer> mCurrentIntentFilterVerifications = new ArrayList<Integer>();
1035
1036        public IntentVerifierProxy(Context context, ComponentName verifierComponent) {
1037            mContext = context;
1038            mIntentFilterVerifierComponent = verifierComponent;
1039        }
1040
1041        private String getDefaultScheme() {
1042            return IntentFilter.SCHEME_HTTPS;
1043        }
1044
1045        @Override
1046        public void startVerifications(int userId) {
1047            // Launch verifications requests
1048            int count = mCurrentIntentFilterVerifications.size();
1049            for (int n=0; n<count; n++) {
1050                int verificationId = mCurrentIntentFilterVerifications.get(n);
1051                final IntentFilterVerificationState ivs =
1052                        mIntentFilterVerificationStates.get(verificationId);
1053
1054                String packageName = ivs.getPackageName();
1055
1056                ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters();
1057                final int filterCount = filters.size();
1058                ArraySet<String> domainsSet = new ArraySet<>();
1059                for (int m=0; m<filterCount; m++) {
1060                    PackageParser.ActivityIntentInfo filter = filters.get(m);
1061                    domainsSet.addAll(filter.getHostsList());
1062                }
1063                synchronized (mPackages) {
1064                    if (mSettings.createIntentFilterVerificationIfNeededLPw(
1065                            packageName, domainsSet) != null) {
1066                        scheduleWriteSettingsLocked();
1067                    }
1068                }
1069                sendVerificationRequest(verificationId, ivs);
1070            }
1071            mCurrentIntentFilterVerifications.clear();
1072        }
1073
1074        private void sendVerificationRequest(int verificationId, IntentFilterVerificationState ivs) {
1075            Intent verificationIntent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION);
1076            verificationIntent.putExtra(
1077                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_ID,
1078                    verificationId);
1079            verificationIntent.putExtra(
1080                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_URI_SCHEME,
1081                    getDefaultScheme());
1082            verificationIntent.putExtra(
1083                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_HOSTS,
1084                    ivs.getHostsString());
1085            verificationIntent.putExtra(
1086                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_PACKAGE_NAME,
1087                    ivs.getPackageName());
1088            verificationIntent.setComponent(mIntentFilterVerifierComponent);
1089            verificationIntent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
1090
1091            DeviceIdleController.LocalService idleController = getDeviceIdleController();
1092            idleController.addPowerSaveTempWhitelistApp(Process.myUid(),
1093                    mIntentFilterVerifierComponent.getPackageName(), getVerificationTimeout(),
1094                    UserHandle.USER_SYSTEM, true, "intent filter verifier");
1095
1096            mContext.sendBroadcastAsUser(verificationIntent, UserHandle.SYSTEM);
1097            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1098                    "Sending IntentFilter verification broadcast");
1099        }
1100
1101        public void receiveVerificationResponse(int verificationId) {
1102            IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId);
1103
1104            final boolean verified = ivs.isVerified();
1105
1106            ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters();
1107            final int count = filters.size();
1108            if (DEBUG_DOMAIN_VERIFICATION) {
1109                Slog.i(TAG, "Received verification response " + verificationId
1110                        + " for " + count + " filters, verified=" + verified);
1111            }
1112            for (int n=0; n<count; n++) {
1113                PackageParser.ActivityIntentInfo filter = filters.get(n);
1114                filter.setVerified(verified);
1115
1116                if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "IntentFilter " + filter.toString()
1117                        + " verified with result:" + verified + " and hosts:"
1118                        + ivs.getHostsString());
1119            }
1120
1121            mIntentFilterVerificationStates.remove(verificationId);
1122
1123            final String packageName = ivs.getPackageName();
1124            IntentFilterVerificationInfo ivi = null;
1125
1126            synchronized (mPackages) {
1127                ivi = mSettings.getIntentFilterVerificationLPr(packageName);
1128            }
1129            if (ivi == null) {
1130                Slog.w(TAG, "IntentFilterVerificationInfo not found for verificationId:"
1131                        + verificationId + " packageName:" + packageName);
1132                return;
1133            }
1134            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1135                    "Updating IntentFilterVerificationInfo for package " + packageName
1136                            +" verificationId:" + verificationId);
1137
1138            synchronized (mPackages) {
1139                if (verified) {
1140                    ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS);
1141                } else {
1142                    ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK);
1143                }
1144                scheduleWriteSettingsLocked();
1145
1146                final int userId = ivs.getUserId();
1147                if (userId != UserHandle.USER_ALL) {
1148                    final int userStatus =
1149                            mSettings.getIntentFilterVerificationStatusLPr(packageName, userId);
1150
1151                    int updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED;
1152                    boolean needUpdate = false;
1153
1154                    // We cannot override the STATUS_ALWAYS / STATUS_NEVER states if they have
1155                    // already been set by the User thru the Disambiguation dialog
1156                    switch (userStatus) {
1157                        case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED:
1158                            if (verified) {
1159                                updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS;
1160                            } else {
1161                                updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK;
1162                            }
1163                            needUpdate = true;
1164                            break;
1165
1166                        case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK:
1167                            if (verified) {
1168                                updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS;
1169                                needUpdate = true;
1170                            }
1171                            break;
1172
1173                        default:
1174                            // Nothing to do
1175                    }
1176
1177                    if (needUpdate) {
1178                        mSettings.updateIntentFilterVerificationStatusLPw(
1179                                packageName, updatedStatus, userId);
1180                        scheduleWritePackageRestrictionsLocked(userId);
1181                    }
1182                }
1183            }
1184        }
1185
1186        @Override
1187        public boolean addOneIntentFilterVerification(int verifierUid, int userId, int verificationId,
1188                    ActivityIntentInfo filter, String packageName) {
1189            if (!hasValidDomains(filter)) {
1190                return false;
1191            }
1192            IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId);
1193            if (ivs == null) {
1194                ivs = createDomainVerificationState(verifierUid, userId, verificationId,
1195                        packageName);
1196            }
1197            if (DEBUG_DOMAIN_VERIFICATION) {
1198                Slog.d(TAG, "Adding verification filter for " + packageName + ": " + filter);
1199            }
1200            ivs.addFilter(filter);
1201            return true;
1202        }
1203
1204        private IntentFilterVerificationState createDomainVerificationState(int verifierUid,
1205                int userId, int verificationId, String packageName) {
1206            IntentFilterVerificationState ivs = new IntentFilterVerificationState(
1207                    verifierUid, userId, packageName);
1208            ivs.setPendingState();
1209            synchronized (mPackages) {
1210                mIntentFilterVerificationStates.append(verificationId, ivs);
1211                mCurrentIntentFilterVerifications.add(verificationId);
1212            }
1213            return ivs;
1214        }
1215    }
1216
1217    private static boolean hasValidDomains(ActivityIntentInfo filter) {
1218        return filter.hasCategory(Intent.CATEGORY_BROWSABLE)
1219                && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) ||
1220                        filter.hasDataScheme(IntentFilter.SCHEME_HTTPS));
1221    }
1222
1223    // Set of pending broadcasts for aggregating enable/disable of components.
1224    static class PendingPackageBroadcasts {
1225        // for each user id, a map of <package name -> components within that package>
1226        final SparseArray<ArrayMap<String, ArrayList<String>>> mUidMap;
1227
1228        public PendingPackageBroadcasts() {
1229            mUidMap = new SparseArray<ArrayMap<String, ArrayList<String>>>(2);
1230        }
1231
1232        public ArrayList<String> get(int userId, String packageName) {
1233            ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId);
1234            return packages.get(packageName);
1235        }
1236
1237        public void put(int userId, String packageName, ArrayList<String> components) {
1238            ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId);
1239            packages.put(packageName, components);
1240        }
1241
1242        public void remove(int userId, String packageName) {
1243            ArrayMap<String, ArrayList<String>> packages = mUidMap.get(userId);
1244            if (packages != null) {
1245                packages.remove(packageName);
1246            }
1247        }
1248
1249        public void remove(int userId) {
1250            mUidMap.remove(userId);
1251        }
1252
1253        public int userIdCount() {
1254            return mUidMap.size();
1255        }
1256
1257        public int userIdAt(int n) {
1258            return mUidMap.keyAt(n);
1259        }
1260
1261        public ArrayMap<String, ArrayList<String>> packagesForUserId(int userId) {
1262            return mUidMap.get(userId);
1263        }
1264
1265        public int size() {
1266            // total number of pending broadcast entries across all userIds
1267            int num = 0;
1268            for (int i = 0; i< mUidMap.size(); i++) {
1269                num += mUidMap.valueAt(i).size();
1270            }
1271            return num;
1272        }
1273
1274        public void clear() {
1275            mUidMap.clear();
1276        }
1277
1278        private ArrayMap<String, ArrayList<String>> getOrAllocate(int userId) {
1279            ArrayMap<String, ArrayList<String>> map = mUidMap.get(userId);
1280            if (map == null) {
1281                map = new ArrayMap<String, ArrayList<String>>();
1282                mUidMap.put(userId, map);
1283            }
1284            return map;
1285        }
1286    }
1287    final PendingPackageBroadcasts mPendingBroadcasts = new PendingPackageBroadcasts();
1288
1289    // Service Connection to remote media container service to copy
1290    // package uri's from external media onto secure containers
1291    // or internal storage.
1292    private IMediaContainerService mContainerService = null;
1293
1294    static final int SEND_PENDING_BROADCAST = 1;
1295    static final int MCS_BOUND = 3;
1296    static final int END_COPY = 4;
1297    static final int INIT_COPY = 5;
1298    static final int MCS_UNBIND = 6;
1299    static final int START_CLEANING_PACKAGE = 7;
1300    static final int FIND_INSTALL_LOC = 8;
1301    static final int POST_INSTALL = 9;
1302    static final int MCS_RECONNECT = 10;
1303    static final int MCS_GIVE_UP = 11;
1304    static final int UPDATED_MEDIA_STATUS = 12;
1305    static final int WRITE_SETTINGS = 13;
1306    static final int WRITE_PACKAGE_RESTRICTIONS = 14;
1307    static final int PACKAGE_VERIFIED = 15;
1308    static final int CHECK_PENDING_VERIFICATION = 16;
1309    static final int START_INTENT_FILTER_VERIFICATIONS = 17;
1310    static final int INTENT_FILTER_VERIFIED = 18;
1311    static final int WRITE_PACKAGE_LIST = 19;
1312    static final int INSTANT_APP_RESOLUTION_PHASE_TWO = 20;
1313
1314    static final int WRITE_SETTINGS_DELAY = 10*1000;  // 10 seconds
1315
1316    // Delay time in millisecs
1317    static final int BROADCAST_DELAY = 10 * 1000;
1318
1319    private static final long DEFAULT_UNUSED_STATIC_SHARED_LIB_MIN_CACHE_PERIOD =
1320            2 * 60 * 60 * 1000L; /* two hours */
1321
1322    static UserManagerService sUserManager;
1323
1324    // Stores a list of users whose package restrictions file needs to be updated
1325    private ArraySet<Integer> mDirtyUsers = new ArraySet<Integer>();
1326
1327    final private DefaultContainerConnection mDefContainerConn =
1328            new DefaultContainerConnection();
1329    class DefaultContainerConnection implements ServiceConnection {
1330        public void onServiceConnected(ComponentName name, IBinder service) {
1331            if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceConnected");
1332            final IMediaContainerService imcs = IMediaContainerService.Stub
1333                    .asInterface(Binder.allowBlocking(service));
1334            mHandler.sendMessage(mHandler.obtainMessage(MCS_BOUND, imcs));
1335        }
1336
1337        public void onServiceDisconnected(ComponentName name) {
1338            if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceDisconnected");
1339        }
1340    }
1341
1342    // Recordkeeping of restore-after-install operations that are currently in flight
1343    // between the Package Manager and the Backup Manager
1344    static class PostInstallData {
1345        public InstallArgs args;
1346        public PackageInstalledInfo res;
1347
1348        PostInstallData(InstallArgs _a, PackageInstalledInfo _r) {
1349            args = _a;
1350            res = _r;
1351        }
1352    }
1353
1354    final SparseArray<PostInstallData> mRunningInstalls = new SparseArray<PostInstallData>();
1355    int mNextInstallToken = 1;  // nonzero; will be wrapped back to 1 when ++ overflows
1356
1357    // XML tags for backup/restore of various bits of state
1358    private static final String TAG_PREFERRED_BACKUP = "pa";
1359    private static final String TAG_DEFAULT_APPS = "da";
1360    private static final String TAG_INTENT_FILTER_VERIFICATION = "iv";
1361
1362    private static final String TAG_PERMISSION_BACKUP = "perm-grant-backup";
1363    private static final String TAG_ALL_GRANTS = "rt-grants";
1364    private static final String TAG_GRANT = "grant";
1365    private static final String ATTR_PACKAGE_NAME = "pkg";
1366
1367    private static final String TAG_PERMISSION = "perm";
1368    private static final String ATTR_PERMISSION_NAME = "name";
1369    private static final String ATTR_IS_GRANTED = "g";
1370    private static final String ATTR_USER_SET = "set";
1371    private static final String ATTR_USER_FIXED = "fixed";
1372    private static final String ATTR_REVOKE_ON_UPGRADE = "rou";
1373
1374    // System/policy permission grants are not backed up
1375    private static final int SYSTEM_RUNTIME_GRANT_MASK =
1376            FLAG_PERMISSION_POLICY_FIXED
1377            | FLAG_PERMISSION_SYSTEM_FIXED
1378            | FLAG_PERMISSION_GRANTED_BY_DEFAULT;
1379
1380    // And we back up these user-adjusted states
1381    private static final int USER_RUNTIME_GRANT_MASK =
1382            FLAG_PERMISSION_USER_SET
1383            | FLAG_PERMISSION_USER_FIXED
1384            | FLAG_PERMISSION_REVOKE_ON_UPGRADE;
1385
1386    final @Nullable String mRequiredVerifierPackage;
1387    final @NonNull String mRequiredInstallerPackage;
1388    final @NonNull String mRequiredUninstallerPackage;
1389    final @Nullable String mSetupWizardPackage;
1390    final @Nullable String mStorageManagerPackage;
1391    final @NonNull String mServicesSystemSharedLibraryPackageName;
1392    final @NonNull String mSharedSystemSharedLibraryPackageName;
1393
1394    final boolean mPermissionReviewRequired;
1395
1396    private final PackageUsage mPackageUsage = new PackageUsage();
1397    private final CompilerStats mCompilerStats = new CompilerStats();
1398
1399    class PackageHandler extends Handler {
1400        private boolean mBound = false;
1401        final ArrayList<HandlerParams> mPendingInstalls =
1402            new ArrayList<HandlerParams>();
1403
1404        private boolean connectToService() {
1405            if (DEBUG_SD_INSTALL) Log.i(TAG, "Trying to bind to" +
1406                    " DefaultContainerService");
1407            Intent service = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
1408            Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1409            if (mContext.bindServiceAsUser(service, mDefContainerConn,
1410                    Context.BIND_AUTO_CREATE, UserHandle.SYSTEM)) {
1411                Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1412                mBound = true;
1413                return true;
1414            }
1415            Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1416            return false;
1417        }
1418
1419        private void disconnectService() {
1420            mContainerService = null;
1421            mBound = false;
1422            Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1423            mContext.unbindService(mDefContainerConn);
1424            Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1425        }
1426
1427        PackageHandler(Looper looper) {
1428            super(looper);
1429        }
1430
1431        public void handleMessage(Message msg) {
1432            try {
1433                doHandleMessage(msg);
1434            } finally {
1435                Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1436            }
1437        }
1438
1439        void doHandleMessage(Message msg) {
1440            switch (msg.what) {
1441                case INIT_COPY: {
1442                    HandlerParams params = (HandlerParams) msg.obj;
1443                    int idx = mPendingInstalls.size();
1444                    if (DEBUG_INSTALL) Slog.i(TAG, "init_copy idx=" + idx + ": " + params);
1445                    // If a bind was already initiated we dont really
1446                    // need to do anything. The pending install
1447                    // will be processed later on.
1448                    if (!mBound) {
1449                        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS",
1450                                System.identityHashCode(mHandler));
1451                        // If this is the only one pending we might
1452                        // have to bind to the service again.
1453                        if (!connectToService()) {
1454                            Slog.e(TAG, "Failed to bind to media container service");
1455                            params.serviceError();
1456                            Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS",
1457                                    System.identityHashCode(mHandler));
1458                            if (params.traceMethod != null) {
1459                                Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, params.traceMethod,
1460                                        params.traceCookie);
1461                            }
1462                            return;
1463                        } else {
1464                            // Once we bind to the service, the first
1465                            // pending request will be processed.
1466                            mPendingInstalls.add(idx, params);
1467                        }
1468                    } else {
1469                        mPendingInstalls.add(idx, params);
1470                        // Already bound to the service. Just make
1471                        // sure we trigger off processing the first request.
1472                        if (idx == 0) {
1473                            mHandler.sendEmptyMessage(MCS_BOUND);
1474                        }
1475                    }
1476                    break;
1477                }
1478                case MCS_BOUND: {
1479                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_bound");
1480                    if (msg.obj != null) {
1481                        mContainerService = (IMediaContainerService) msg.obj;
1482                        Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS",
1483                                System.identityHashCode(mHandler));
1484                    }
1485                    if (mContainerService == null) {
1486                        if (!mBound) {
1487                            // Something seriously wrong since we are not bound and we are not
1488                            // waiting for connection. Bail out.
1489                            Slog.e(TAG, "Cannot bind to media container service");
1490                            for (HandlerParams params : mPendingInstalls) {
1491                                // Indicate service bind error
1492                                params.serviceError();
1493                                Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1494                                        System.identityHashCode(params));
1495                                if (params.traceMethod != null) {
1496                                    Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER,
1497                                            params.traceMethod, params.traceCookie);
1498                                }
1499                                return;
1500                            }
1501                            mPendingInstalls.clear();
1502                        } else {
1503                            Slog.w(TAG, "Waiting to connect to media container service");
1504                        }
1505                    } else if (mPendingInstalls.size() > 0) {
1506                        HandlerParams params = mPendingInstalls.get(0);
1507                        if (params != null) {
1508                            Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1509                                    System.identityHashCode(params));
1510                            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "startCopy");
1511                            if (params.startCopy()) {
1512                                // We are done...  look for more work or to
1513                                // go idle.
1514                                if (DEBUG_SD_INSTALL) Log.i(TAG,
1515                                        "Checking for more work or unbind...");
1516                                // Delete pending install
1517                                if (mPendingInstalls.size() > 0) {
1518                                    mPendingInstalls.remove(0);
1519                                }
1520                                if (mPendingInstalls.size() == 0) {
1521                                    if (mBound) {
1522                                        if (DEBUG_SD_INSTALL) Log.i(TAG,
1523                                                "Posting delayed MCS_UNBIND");
1524                                        removeMessages(MCS_UNBIND);
1525                                        Message ubmsg = obtainMessage(MCS_UNBIND);
1526                                        // Unbind after a little delay, to avoid
1527                                        // continual thrashing.
1528                                        sendMessageDelayed(ubmsg, 10000);
1529                                    }
1530                                } else {
1531                                    // There are more pending requests in queue.
1532                                    // Just post MCS_BOUND message to trigger processing
1533                                    // of next pending install.
1534                                    if (DEBUG_SD_INSTALL) Log.i(TAG,
1535                                            "Posting MCS_BOUND for next work");
1536                                    mHandler.sendEmptyMessage(MCS_BOUND);
1537                                }
1538                            }
1539                            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
1540                        }
1541                    } else {
1542                        // Should never happen ideally.
1543                        Slog.w(TAG, "Empty queue");
1544                    }
1545                    break;
1546                }
1547                case MCS_RECONNECT: {
1548                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_reconnect");
1549                    if (mPendingInstalls.size() > 0) {
1550                        if (mBound) {
1551                            disconnectService();
1552                        }
1553                        if (!connectToService()) {
1554                            Slog.e(TAG, "Failed to bind to media container service");
1555                            for (HandlerParams params : mPendingInstalls) {
1556                                // Indicate service bind error
1557                                params.serviceError();
1558                                Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1559                                        System.identityHashCode(params));
1560                            }
1561                            mPendingInstalls.clear();
1562                        }
1563                    }
1564                    break;
1565                }
1566                case MCS_UNBIND: {
1567                    // If there is no actual work left, then time to unbind.
1568                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_unbind");
1569
1570                    if (mPendingInstalls.size() == 0 && mPendingVerification.size() == 0) {
1571                        if (mBound) {
1572                            if (DEBUG_INSTALL) Slog.i(TAG, "calling disconnectService()");
1573
1574                            disconnectService();
1575                        }
1576                    } else if (mPendingInstalls.size() > 0) {
1577                        // There are more pending requests in queue.
1578                        // Just post MCS_BOUND message to trigger processing
1579                        // of next pending install.
1580                        mHandler.sendEmptyMessage(MCS_BOUND);
1581                    }
1582
1583                    break;
1584                }
1585                case MCS_GIVE_UP: {
1586                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_giveup too many retries");
1587                    HandlerParams params = mPendingInstalls.remove(0);
1588                    Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1589                            System.identityHashCode(params));
1590                    break;
1591                }
1592                case SEND_PENDING_BROADCAST: {
1593                    String packages[];
1594                    ArrayList<String> components[];
1595                    int size = 0;
1596                    int uids[];
1597                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1598                    synchronized (mPackages) {
1599                        if (mPendingBroadcasts == null) {
1600                            return;
1601                        }
1602                        size = mPendingBroadcasts.size();
1603                        if (size <= 0) {
1604                            // Nothing to be done. Just return
1605                            return;
1606                        }
1607                        packages = new String[size];
1608                        components = new ArrayList[size];
1609                        uids = new int[size];
1610                        int i = 0;  // filling out the above arrays
1611
1612                        for (int n = 0; n < mPendingBroadcasts.userIdCount(); n++) {
1613                            int packageUserId = mPendingBroadcasts.userIdAt(n);
1614                            Iterator<Map.Entry<String, ArrayList<String>>> it
1615                                    = mPendingBroadcasts.packagesForUserId(packageUserId)
1616                                            .entrySet().iterator();
1617                            while (it.hasNext() && i < size) {
1618                                Map.Entry<String, ArrayList<String>> ent = it.next();
1619                                packages[i] = ent.getKey();
1620                                components[i] = ent.getValue();
1621                                PackageSetting ps = mSettings.mPackages.get(ent.getKey());
1622                                uids[i] = (ps != null)
1623                                        ? UserHandle.getUid(packageUserId, ps.appId)
1624                                        : -1;
1625                                i++;
1626                            }
1627                        }
1628                        size = i;
1629                        mPendingBroadcasts.clear();
1630                    }
1631                    // Send broadcasts
1632                    for (int i = 0; i < size; i++) {
1633                        sendPackageChangedBroadcast(packages[i], true, components[i], uids[i]);
1634                    }
1635                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1636                    break;
1637                }
1638                case START_CLEANING_PACKAGE: {
1639                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1640                    final String packageName = (String)msg.obj;
1641                    final int userId = msg.arg1;
1642                    final boolean andCode = msg.arg2 != 0;
1643                    synchronized (mPackages) {
1644                        if (userId == UserHandle.USER_ALL) {
1645                            int[] users = sUserManager.getUserIds();
1646                            for (int user : users) {
1647                                mSettings.addPackageToCleanLPw(
1648                                        new PackageCleanItem(user, packageName, andCode));
1649                            }
1650                        } else {
1651                            mSettings.addPackageToCleanLPw(
1652                                    new PackageCleanItem(userId, packageName, andCode));
1653                        }
1654                    }
1655                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1656                    startCleaningPackages();
1657                } break;
1658                case POST_INSTALL: {
1659                    if (DEBUG_INSTALL) Log.v(TAG, "Handling post-install for " + msg.arg1);
1660
1661                    PostInstallData data = mRunningInstalls.get(msg.arg1);
1662                    final boolean didRestore = (msg.arg2 != 0);
1663                    mRunningInstalls.delete(msg.arg1);
1664
1665                    if (data != null) {
1666                        InstallArgs args = data.args;
1667                        PackageInstalledInfo parentRes = data.res;
1668
1669                        final boolean grantPermissions = (args.installFlags
1670                                & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0;
1671                        final boolean killApp = (args.installFlags
1672                                & PackageManager.INSTALL_DONT_KILL_APP) == 0;
1673                        final String[] grantedPermissions = args.installGrantPermissions;
1674
1675                        // Handle the parent package
1676                        handlePackagePostInstall(parentRes, grantPermissions, killApp,
1677                                grantedPermissions, didRestore, args.installerPackageName,
1678                                args.observer);
1679
1680                        // Handle the child packages
1681                        final int childCount = (parentRes.addedChildPackages != null)
1682                                ? parentRes.addedChildPackages.size() : 0;
1683                        for (int i = 0; i < childCount; i++) {
1684                            PackageInstalledInfo childRes = parentRes.addedChildPackages.valueAt(i);
1685                            handlePackagePostInstall(childRes, grantPermissions, killApp,
1686                                    grantedPermissions, false, args.installerPackageName,
1687                                    args.observer);
1688                        }
1689
1690                        // Log tracing if needed
1691                        if (args.traceMethod != null) {
1692                            Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, args.traceMethod,
1693                                    args.traceCookie);
1694                        }
1695                    } else {
1696                        Slog.e(TAG, "Bogus post-install token " + msg.arg1);
1697                    }
1698
1699                    Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "postInstall", msg.arg1);
1700                } break;
1701                case UPDATED_MEDIA_STATUS: {
1702                    if (DEBUG_SD_INSTALL) Log.i(TAG, "Got message UPDATED_MEDIA_STATUS");
1703                    boolean reportStatus = msg.arg1 == 1;
1704                    boolean doGc = msg.arg2 == 1;
1705                    if (DEBUG_SD_INSTALL) Log.i(TAG, "reportStatus=" + reportStatus + ", doGc = " + doGc);
1706                    if (doGc) {
1707                        // Force a gc to clear up stale containers.
1708                        Runtime.getRuntime().gc();
1709                    }
1710                    if (msg.obj != null) {
1711                        @SuppressWarnings("unchecked")
1712                        Set<AsecInstallArgs> args = (Set<AsecInstallArgs>) msg.obj;
1713                        if (DEBUG_SD_INSTALL) Log.i(TAG, "Unloading all containers");
1714                        // Unload containers
1715                        unloadAllContainers(args);
1716                    }
1717                    if (reportStatus) {
1718                        try {
1719                            if (DEBUG_SD_INSTALL) Log.i(TAG,
1720                                    "Invoking StorageManagerService call back");
1721                            PackageHelper.getStorageManager().finishMediaUpdate();
1722                        } catch (RemoteException e) {
1723                            Log.e(TAG, "StorageManagerService not running?");
1724                        }
1725                    }
1726                } break;
1727                case WRITE_SETTINGS: {
1728                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1729                    synchronized (mPackages) {
1730                        removeMessages(WRITE_SETTINGS);
1731                        removeMessages(WRITE_PACKAGE_RESTRICTIONS);
1732                        mSettings.writeLPr();
1733                        mDirtyUsers.clear();
1734                    }
1735                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1736                } break;
1737                case WRITE_PACKAGE_RESTRICTIONS: {
1738                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1739                    synchronized (mPackages) {
1740                        removeMessages(WRITE_PACKAGE_RESTRICTIONS);
1741                        for (int userId : mDirtyUsers) {
1742                            mSettings.writePackageRestrictionsLPr(userId);
1743                        }
1744                        mDirtyUsers.clear();
1745                    }
1746                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1747                } break;
1748                case WRITE_PACKAGE_LIST: {
1749                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1750                    synchronized (mPackages) {
1751                        removeMessages(WRITE_PACKAGE_LIST);
1752                        mSettings.writePackageListLPr(msg.arg1);
1753                    }
1754                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1755                } break;
1756                case CHECK_PENDING_VERIFICATION: {
1757                    final int verificationId = msg.arg1;
1758                    final PackageVerificationState state = mPendingVerification.get(verificationId);
1759
1760                    if ((state != null) && !state.timeoutExtended()) {
1761                        final InstallArgs args = state.getInstallArgs();
1762                        final Uri originUri = Uri.fromFile(args.origin.resolvedFile);
1763
1764                        Slog.i(TAG, "Verification timed out for " + originUri);
1765                        mPendingVerification.remove(verificationId);
1766
1767                        int ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
1768
1769                        final UserHandle user = args.getUser();
1770                        if (getDefaultVerificationResponse(user)
1771                                == PackageManager.VERIFICATION_ALLOW) {
1772                            Slog.i(TAG, "Continuing with installation of " + originUri);
1773                            state.setVerifierResponse(Binder.getCallingUid(),
1774                                    PackageManager.VERIFICATION_ALLOW_WITHOUT_SUFFICIENT);
1775                            broadcastPackageVerified(verificationId, originUri,
1776                                    PackageManager.VERIFICATION_ALLOW, user);
1777                            try {
1778                                ret = args.copyApk(mContainerService, true);
1779                            } catch (RemoteException e) {
1780                                Slog.e(TAG, "Could not contact the ContainerService");
1781                            }
1782                        } else {
1783                            broadcastPackageVerified(verificationId, originUri,
1784                                    PackageManager.VERIFICATION_REJECT, user);
1785                        }
1786
1787                        Trace.asyncTraceEnd(
1788                                TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId);
1789
1790                        processPendingInstall(args, ret);
1791                        mHandler.sendEmptyMessage(MCS_UNBIND);
1792                    }
1793                    break;
1794                }
1795                case PACKAGE_VERIFIED: {
1796                    final int verificationId = msg.arg1;
1797
1798                    final PackageVerificationState state = mPendingVerification.get(verificationId);
1799                    if (state == null) {
1800                        Slog.w(TAG, "Invalid verification token " + verificationId + " received");
1801                        break;
1802                    }
1803
1804                    final PackageVerificationResponse response = (PackageVerificationResponse) msg.obj;
1805
1806                    state.setVerifierResponse(response.callerUid, response.code);
1807
1808                    if (state.isVerificationComplete()) {
1809                        mPendingVerification.remove(verificationId);
1810
1811                        final InstallArgs args = state.getInstallArgs();
1812                        final Uri originUri = Uri.fromFile(args.origin.resolvedFile);
1813
1814                        int ret;
1815                        if (state.isInstallAllowed()) {
1816                            ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
1817                            broadcastPackageVerified(verificationId, originUri,
1818                                    response.code, state.getInstallArgs().getUser());
1819                            try {
1820                                ret = args.copyApk(mContainerService, true);
1821                            } catch (RemoteException e) {
1822                                Slog.e(TAG, "Could not contact the ContainerService");
1823                            }
1824                        } else {
1825                            ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
1826                        }
1827
1828                        Trace.asyncTraceEnd(
1829                                TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId);
1830
1831                        processPendingInstall(args, ret);
1832                        mHandler.sendEmptyMessage(MCS_UNBIND);
1833                    }
1834
1835                    break;
1836                }
1837                case START_INTENT_FILTER_VERIFICATIONS: {
1838                    IFVerificationParams params = (IFVerificationParams) msg.obj;
1839                    verifyIntentFiltersIfNeeded(params.userId, params.verifierUid,
1840                            params.replacing, params.pkg);
1841                    break;
1842                }
1843                case INTENT_FILTER_VERIFIED: {
1844                    final int verificationId = msg.arg1;
1845
1846                    final IntentFilterVerificationState state = mIntentFilterVerificationStates.get(
1847                            verificationId);
1848                    if (state == null) {
1849                        Slog.w(TAG, "Invalid IntentFilter verification token "
1850                                + verificationId + " received");
1851                        break;
1852                    }
1853
1854                    final int userId = state.getUserId();
1855
1856                    if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1857                            "Processing IntentFilter verification with token:"
1858                            + verificationId + " and userId:" + userId);
1859
1860                    final IntentFilterVerificationResponse response =
1861                            (IntentFilterVerificationResponse) msg.obj;
1862
1863                    state.setVerifierResponse(response.callerUid, response.code);
1864
1865                    if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1866                            "IntentFilter verification with token:" + verificationId
1867                            + " and userId:" + userId
1868                            + " is settings verifier response with response code:"
1869                            + response.code);
1870
1871                    if (response.code == PackageManager.INTENT_FILTER_VERIFICATION_FAILURE) {
1872                        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Domains failing verification: "
1873                                + response.getFailedDomainsString());
1874                    }
1875
1876                    if (state.isVerificationComplete()) {
1877                        mIntentFilterVerifier.receiveVerificationResponse(verificationId);
1878                    } else {
1879                        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1880                                "IntentFilter verification with token:" + verificationId
1881                                + " was not said to be complete");
1882                    }
1883
1884                    break;
1885                }
1886                case INSTANT_APP_RESOLUTION_PHASE_TWO: {
1887                    InstantAppResolver.doInstantAppResolutionPhaseTwo(mContext,
1888                            mInstantAppResolverConnection,
1889                            (InstantAppRequest) msg.obj,
1890                            mInstantAppInstallerActivity,
1891                            mHandler);
1892                }
1893            }
1894        }
1895    }
1896
1897    private void handlePackagePostInstall(PackageInstalledInfo res, boolean grantPermissions,
1898            boolean killApp, String[] grantedPermissions,
1899            boolean launchedForRestore, String installerPackage,
1900            IPackageInstallObserver2 installObserver) {
1901        if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
1902            // Send the removed broadcasts
1903            if (res.removedInfo != null) {
1904                res.removedInfo.sendPackageRemovedBroadcasts(killApp);
1905            }
1906
1907            // Now that we successfully installed the package, grant runtime
1908            // permissions if requested before broadcasting the install. Also
1909            // for legacy apps in permission review mode we clear the permission
1910            // review flag which is used to emulate runtime permissions for
1911            // legacy apps.
1912            if (grantPermissions) {
1913                grantRequestedRuntimePermissions(res.pkg, res.newUsers, grantedPermissions);
1914            }
1915
1916            final boolean update = res.removedInfo != null
1917                    && res.removedInfo.removedPackage != null;
1918            final String origInstallerPackageName = res.removedInfo != null
1919                    ? res.removedInfo.installerPackageName : null;
1920
1921            // If this is the first time we have child packages for a disabled privileged
1922            // app that had no children, we grant requested runtime permissions to the new
1923            // children if the parent on the system image had them already granted.
1924            if (res.pkg.parentPackage != null) {
1925                synchronized (mPackages) {
1926                    grantRuntimePermissionsGrantedToDisabledPrivSysPackageParentLPw(res.pkg);
1927                }
1928            }
1929
1930            synchronized (mPackages) {
1931                mInstantAppRegistry.onPackageInstalledLPw(res.pkg, res.newUsers);
1932            }
1933
1934            final String packageName = res.pkg.applicationInfo.packageName;
1935
1936            // Determine the set of users who are adding this package for
1937            // the first time vs. those who are seeing an update.
1938            int[] firstUsers = EMPTY_INT_ARRAY;
1939            int[] updateUsers = EMPTY_INT_ARRAY;
1940            final boolean allNewUsers = res.origUsers == null || res.origUsers.length == 0;
1941            final PackageSetting ps = (PackageSetting) res.pkg.mExtras;
1942            for (int newUser : res.newUsers) {
1943                if (ps.getInstantApp(newUser)) {
1944                    continue;
1945                }
1946                if (allNewUsers) {
1947                    firstUsers = ArrayUtils.appendInt(firstUsers, newUser);
1948                    continue;
1949                }
1950                boolean isNew = true;
1951                for (int origUser : res.origUsers) {
1952                    if (origUser == newUser) {
1953                        isNew = false;
1954                        break;
1955                    }
1956                }
1957                if (isNew) {
1958                    firstUsers = ArrayUtils.appendInt(firstUsers, newUser);
1959                } else {
1960                    updateUsers = ArrayUtils.appendInt(updateUsers, newUser);
1961                }
1962            }
1963
1964            // Send installed broadcasts if the package is not a static shared lib.
1965            if (res.pkg.staticSharedLibName == null) {
1966                mProcessLoggingHandler.invalidateProcessLoggingBaseApkHash(res.pkg.baseCodePath);
1967
1968                // Send added for users that see the package for the first time
1969                // sendPackageAddedForNewUsers also deals with system apps
1970                int appId = UserHandle.getAppId(res.uid);
1971                boolean isSystem = res.pkg.applicationInfo.isSystemApp();
1972                sendPackageAddedForNewUsers(packageName, isSystem, appId, firstUsers);
1973
1974                // Send added for users that don't see the package for the first time
1975                Bundle extras = new Bundle(1);
1976                extras.putInt(Intent.EXTRA_UID, res.uid);
1977                if (update) {
1978                    extras.putBoolean(Intent.EXTRA_REPLACING, true);
1979                }
1980                sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName,
1981                        extras, 0 /*flags*/,
1982                        null /*targetPackage*/, null /*finishedReceiver*/, updateUsers);
1983                if (origInstallerPackageName != null) {
1984                    sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName,
1985                            extras, 0 /*flags*/,
1986                            origInstallerPackageName, null /*finishedReceiver*/, updateUsers);
1987                }
1988
1989                // Send replaced for users that don't see the package for the first time
1990                if (update) {
1991                    sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED,
1992                            packageName, extras, 0 /*flags*/,
1993                            null /*targetPackage*/, null /*finishedReceiver*/,
1994                            updateUsers);
1995                    if (origInstallerPackageName != null) {
1996                        sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, packageName,
1997                                extras, 0 /*flags*/,
1998                                origInstallerPackageName, null /*finishedReceiver*/, updateUsers);
1999                    }
2000                    sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED,
2001                            null /*package*/, null /*extras*/, 0 /*flags*/,
2002                            packageName /*targetPackage*/,
2003                            null /*finishedReceiver*/, updateUsers);
2004                } else if (launchedForRestore && !isSystemApp(res.pkg)) {
2005                    // First-install and we did a restore, so we're responsible for the
2006                    // first-launch broadcast.
2007                    if (DEBUG_BACKUP) {
2008                        Slog.i(TAG, "Post-restore of " + packageName
2009                                + " sending FIRST_LAUNCH in " + Arrays.toString(firstUsers));
2010                    }
2011                    sendFirstLaunchBroadcast(packageName, installerPackage, firstUsers);
2012                }
2013
2014                // Send broadcast package appeared if forward locked/external for all users
2015                // treat asec-hosted packages like removable media on upgrade
2016                if (res.pkg.isForwardLocked() || isExternal(res.pkg)) {
2017                    if (DEBUG_INSTALL) {
2018                        Slog.i(TAG, "upgrading pkg " + res.pkg
2019                                + " is ASEC-hosted -> AVAILABLE");
2020                    }
2021                    final int[] uidArray = new int[]{res.pkg.applicationInfo.uid};
2022                    ArrayList<String> pkgList = new ArrayList<>(1);
2023                    pkgList.add(packageName);
2024                    sendResourcesChangedBroadcast(true, true, pkgList, uidArray, null);
2025                }
2026            }
2027
2028            // Work that needs to happen on first install within each user
2029            if (firstUsers != null && firstUsers.length > 0) {
2030                synchronized (mPackages) {
2031                    for (int userId : firstUsers) {
2032                        // If this app is a browser and it's newly-installed for some
2033                        // users, clear any default-browser state in those users. The
2034                        // app's nature doesn't depend on the user, so we can just check
2035                        // its browser nature in any user and generalize.
2036                        if (packageIsBrowser(packageName, userId)) {
2037                            mSettings.setDefaultBrowserPackageNameLPw(null, userId);
2038                        }
2039
2040                        // We may also need to apply pending (restored) runtime
2041                        // permission grants within these users.
2042                        mSettings.applyPendingPermissionGrantsLPw(packageName, userId);
2043                    }
2044                }
2045            }
2046
2047            // Log current value of "unknown sources" setting
2048            EventLog.writeEvent(EventLogTags.UNKNOWN_SOURCES_ENABLED,
2049                    getUnknownSourcesSettings());
2050
2051            // Remove the replaced package's older resources safely now
2052            // We delete after a gc for applications  on sdcard.
2053            if (res.removedInfo != null && res.removedInfo.args != null) {
2054                Runtime.getRuntime().gc();
2055                synchronized (mInstallLock) {
2056                    res.removedInfo.args.doPostDeleteLI(true);
2057                }
2058            } else {
2059                // Force a gc to clear up things. Ask for a background one, it's fine to go on
2060                // and not block here.
2061                VMRuntime.getRuntime().requestConcurrentGC();
2062            }
2063
2064            // Notify DexManager that the package was installed for new users.
2065            // The updated users should already be indexed and the package code paths
2066            // should not change.
2067            // Don't notify the manager for ephemeral apps as they are not expected to
2068            // survive long enough to benefit of background optimizations.
2069            for (int userId : firstUsers) {
2070                PackageInfo info = getPackageInfo(packageName, /*flags*/ 0, userId);
2071                // There's a race currently where some install events may interleave with an uninstall.
2072                // This can lead to package info being null (b/36642664).
2073                if (info != null) {
2074                    mDexManager.notifyPackageInstalled(info, userId);
2075                }
2076            }
2077        }
2078
2079        // If someone is watching installs - notify them
2080        if (installObserver != null) {
2081            try {
2082                Bundle extras = extrasForInstallResult(res);
2083                installObserver.onPackageInstalled(res.name, res.returnCode,
2084                        res.returnMsg, extras);
2085            } catch (RemoteException e) {
2086                Slog.i(TAG, "Observer no longer exists.");
2087            }
2088        }
2089    }
2090
2091    private void grantRuntimePermissionsGrantedToDisabledPrivSysPackageParentLPw(
2092            PackageParser.Package pkg) {
2093        if (pkg.parentPackage == null) {
2094            return;
2095        }
2096        if (pkg.requestedPermissions == null) {
2097            return;
2098        }
2099        final PackageSetting disabledSysParentPs = mSettings
2100                .getDisabledSystemPkgLPr(pkg.parentPackage.packageName);
2101        if (disabledSysParentPs == null || disabledSysParentPs.pkg == null
2102                || !disabledSysParentPs.isPrivileged()
2103                || (disabledSysParentPs.childPackageNames != null
2104                        && !disabledSysParentPs.childPackageNames.isEmpty())) {
2105            return;
2106        }
2107        final int[] allUserIds = sUserManager.getUserIds();
2108        final int permCount = pkg.requestedPermissions.size();
2109        for (int i = 0; i < permCount; i++) {
2110            String permission = pkg.requestedPermissions.get(i);
2111            BasePermission bp = mSettings.mPermissions.get(permission);
2112            if (bp == null || !(bp.isRuntime() || bp.isDevelopment())) {
2113                continue;
2114            }
2115            for (int userId : allUserIds) {
2116                if (disabledSysParentPs.getPermissionsState().hasRuntimePermission(
2117                        permission, userId)) {
2118                    grantRuntimePermission(pkg.packageName, permission, userId);
2119                }
2120            }
2121        }
2122    }
2123
2124    private StorageEventListener mStorageListener = new StorageEventListener() {
2125        @Override
2126        public void onVolumeStateChanged(VolumeInfo vol, int oldState, int newState) {
2127            if (vol.type == VolumeInfo.TYPE_PRIVATE) {
2128                if (vol.state == VolumeInfo.STATE_MOUNTED) {
2129                    final String volumeUuid = vol.getFsUuid();
2130
2131                    // Clean up any users or apps that were removed or recreated
2132                    // while this volume was missing
2133                    sUserManager.reconcileUsers(volumeUuid);
2134                    reconcileApps(volumeUuid);
2135
2136                    // Clean up any install sessions that expired or were
2137                    // cancelled while this volume was missing
2138                    mInstallerService.onPrivateVolumeMounted(volumeUuid);
2139
2140                    loadPrivatePackages(vol);
2141
2142                } else if (vol.state == VolumeInfo.STATE_EJECTING) {
2143                    unloadPrivatePackages(vol);
2144                }
2145            }
2146
2147            if (vol.type == VolumeInfo.TYPE_PUBLIC && vol.isPrimary()) {
2148                if (vol.state == VolumeInfo.STATE_MOUNTED) {
2149                    updateExternalMediaStatus(true, false);
2150                } else if (vol.state == VolumeInfo.STATE_EJECTING) {
2151                    updateExternalMediaStatus(false, false);
2152                }
2153            }
2154        }
2155
2156        @Override
2157        public void onVolumeForgotten(String fsUuid) {
2158            if (TextUtils.isEmpty(fsUuid)) {
2159                Slog.e(TAG, "Forgetting internal storage is probably a mistake; ignoring");
2160                return;
2161            }
2162
2163            // Remove any apps installed on the forgotten volume
2164            synchronized (mPackages) {
2165                final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(fsUuid);
2166                for (PackageSetting ps : packages) {
2167                    Slog.d(TAG, "Destroying " + ps.name + " because volume was forgotten");
2168                    deletePackageVersioned(new VersionedPackage(ps.name,
2169                            PackageManager.VERSION_CODE_HIGHEST),
2170                            new LegacyPackageDeleteObserver(null).getBinder(),
2171                            UserHandle.USER_SYSTEM, PackageManager.DELETE_ALL_USERS);
2172                    // Try very hard to release any references to this package
2173                    // so we don't risk the system server being killed due to
2174                    // open FDs
2175                    AttributeCache.instance().removePackage(ps.name);
2176                }
2177
2178                mSettings.onVolumeForgotten(fsUuid);
2179                mSettings.writeLPr();
2180            }
2181        }
2182    };
2183
2184    private void grantRequestedRuntimePermissions(PackageParser.Package pkg, int[] userIds,
2185            String[] grantedPermissions) {
2186        for (int userId : userIds) {
2187            grantRequestedRuntimePermissionsForUser(pkg, userId, grantedPermissions);
2188        }
2189    }
2190
2191    private void grantRequestedRuntimePermissionsForUser(PackageParser.Package pkg, int userId,
2192            String[] grantedPermissions) {
2193        PackageSetting ps = (PackageSetting) pkg.mExtras;
2194        if (ps == null) {
2195            return;
2196        }
2197
2198        PermissionsState permissionsState = ps.getPermissionsState();
2199
2200        final int immutableFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED
2201                | PackageManager.FLAG_PERMISSION_POLICY_FIXED;
2202
2203        final boolean supportsRuntimePermissions = pkg.applicationInfo.targetSdkVersion
2204                >= Build.VERSION_CODES.M;
2205
2206        final boolean instantApp = isInstantApp(pkg.packageName, userId);
2207
2208        for (String permission : pkg.requestedPermissions) {
2209            final BasePermission bp;
2210            synchronized (mPackages) {
2211                bp = mSettings.mPermissions.get(permission);
2212            }
2213            if (bp != null && (bp.isRuntime() || bp.isDevelopment())
2214                    && (!instantApp || bp.isInstant())
2215                    && (supportsRuntimePermissions || !bp.isRuntimeOnly())
2216                    && (grantedPermissions == null
2217                           || ArrayUtils.contains(grantedPermissions, permission))) {
2218                final int flags = permissionsState.getPermissionFlags(permission, userId);
2219                if (supportsRuntimePermissions) {
2220                    // Installer cannot change immutable permissions.
2221                    if ((flags & immutableFlags) == 0) {
2222                        grantRuntimePermission(pkg.packageName, permission, userId);
2223                    }
2224                } else if (mPermissionReviewRequired) {
2225                    // In permission review mode we clear the review flag when we
2226                    // are asked to install the app with all permissions granted.
2227                    if ((flags & PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED) != 0) {
2228                        updatePermissionFlags(permission, pkg.packageName,
2229                                PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED, 0, userId);
2230                    }
2231                }
2232            }
2233        }
2234    }
2235
2236    Bundle extrasForInstallResult(PackageInstalledInfo res) {
2237        Bundle extras = null;
2238        switch (res.returnCode) {
2239            case PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION: {
2240                extras = new Bundle();
2241                extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PERMISSION,
2242                        res.origPermission);
2243                extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PACKAGE,
2244                        res.origPackage);
2245                break;
2246            }
2247            case PackageManager.INSTALL_SUCCEEDED: {
2248                extras = new Bundle();
2249                extras.putBoolean(Intent.EXTRA_REPLACING,
2250                        res.removedInfo != null && res.removedInfo.removedPackage != null);
2251                break;
2252            }
2253        }
2254        return extras;
2255    }
2256
2257    void scheduleWriteSettingsLocked() {
2258        if (!mHandler.hasMessages(WRITE_SETTINGS)) {
2259            mHandler.sendEmptyMessageDelayed(WRITE_SETTINGS, WRITE_SETTINGS_DELAY);
2260        }
2261    }
2262
2263    void scheduleWritePackageListLocked(int userId) {
2264        if (!mHandler.hasMessages(WRITE_PACKAGE_LIST)) {
2265            Message msg = mHandler.obtainMessage(WRITE_PACKAGE_LIST);
2266            msg.arg1 = userId;
2267            mHandler.sendMessageDelayed(msg, WRITE_SETTINGS_DELAY);
2268        }
2269    }
2270
2271    void scheduleWritePackageRestrictionsLocked(UserHandle user) {
2272        final int userId = user == null ? UserHandle.USER_ALL : user.getIdentifier();
2273        scheduleWritePackageRestrictionsLocked(userId);
2274    }
2275
2276    void scheduleWritePackageRestrictionsLocked(int userId) {
2277        final int[] userIds = (userId == UserHandle.USER_ALL)
2278                ? sUserManager.getUserIds() : new int[]{userId};
2279        for (int nextUserId : userIds) {
2280            if (!sUserManager.exists(nextUserId)) return;
2281            mDirtyUsers.add(nextUserId);
2282            if (!mHandler.hasMessages(WRITE_PACKAGE_RESTRICTIONS)) {
2283                mHandler.sendEmptyMessageDelayed(WRITE_PACKAGE_RESTRICTIONS, WRITE_SETTINGS_DELAY);
2284            }
2285        }
2286    }
2287
2288    public static PackageManagerService main(Context context, Installer installer,
2289            boolean factoryTest, boolean onlyCore) {
2290        // Self-check for initial settings.
2291        PackageManagerServiceCompilerMapping.checkProperties();
2292
2293        PackageManagerService m = new PackageManagerService(context, installer,
2294                factoryTest, onlyCore);
2295        m.enableSystemUserPackages();
2296        ServiceManager.addService("package", m);
2297        return m;
2298    }
2299
2300    private void enableSystemUserPackages() {
2301        if (!UserManager.isSplitSystemUser()) {
2302            return;
2303        }
2304        // For system user, enable apps based on the following conditions:
2305        // - app is whitelisted or belong to one of these groups:
2306        //   -- system app which has no launcher icons
2307        //   -- system app which has INTERACT_ACROSS_USERS permission
2308        //   -- system IME app
2309        // - app is not in the blacklist
2310        AppsQueryHelper queryHelper = new AppsQueryHelper(this);
2311        Set<String> enableApps = new ArraySet<>();
2312        enableApps.addAll(queryHelper.queryApps(AppsQueryHelper.GET_NON_LAUNCHABLE_APPS
2313                | AppsQueryHelper.GET_APPS_WITH_INTERACT_ACROSS_USERS_PERM
2314                | AppsQueryHelper.GET_IMES, /* systemAppsOnly */ true, UserHandle.SYSTEM));
2315        ArraySet<String> wlApps = SystemConfig.getInstance().getSystemUserWhitelistedApps();
2316        enableApps.addAll(wlApps);
2317        enableApps.addAll(queryHelper.queryApps(AppsQueryHelper.GET_REQUIRED_FOR_SYSTEM_USER,
2318                /* systemAppsOnly */ false, UserHandle.SYSTEM));
2319        ArraySet<String> blApps = SystemConfig.getInstance().getSystemUserBlacklistedApps();
2320        enableApps.removeAll(blApps);
2321        Log.i(TAG, "Applications installed for system user: " + enableApps);
2322        List<String> allAps = queryHelper.queryApps(0, /* systemAppsOnly */ false,
2323                UserHandle.SYSTEM);
2324        final int allAppsSize = allAps.size();
2325        synchronized (mPackages) {
2326            for (int i = 0; i < allAppsSize; i++) {
2327                String pName = allAps.get(i);
2328                PackageSetting pkgSetting = mSettings.mPackages.get(pName);
2329                // Should not happen, but we shouldn't be failing if it does
2330                if (pkgSetting == null) {
2331                    continue;
2332                }
2333                boolean install = enableApps.contains(pName);
2334                if (pkgSetting.getInstalled(UserHandle.USER_SYSTEM) != install) {
2335                    Log.i(TAG, (install ? "Installing " : "Uninstalling ") + pName
2336                            + " for system user");
2337                    pkgSetting.setInstalled(install, UserHandle.USER_SYSTEM);
2338                }
2339            }
2340            scheduleWritePackageRestrictionsLocked(UserHandle.USER_SYSTEM);
2341        }
2342    }
2343
2344    private static void getDefaultDisplayMetrics(Context context, DisplayMetrics metrics) {
2345        DisplayManager displayManager = (DisplayManager) context.getSystemService(
2346                Context.DISPLAY_SERVICE);
2347        displayManager.getDisplay(Display.DEFAULT_DISPLAY).getMetrics(metrics);
2348    }
2349
2350    /**
2351     * Requests that files preopted on a secondary system partition be copied to the data partition
2352     * if possible.  Note that the actual copying of the files is accomplished by init for security
2353     * reasons. This simply requests that the copy takes place and awaits confirmation of its
2354     * completion. See platform/system/extras/cppreopt/ for the implementation of the actual copy.
2355     */
2356    private static void requestCopyPreoptedFiles() {
2357        final int WAIT_TIME_MS = 100;
2358        final String CP_PREOPT_PROPERTY = "sys.cppreopt";
2359        if (SystemProperties.getInt("ro.cp_system_other_odex", 0) == 1) {
2360            SystemProperties.set(CP_PREOPT_PROPERTY, "requested");
2361            // We will wait for up to 100 seconds.
2362            final long timeStart = SystemClock.uptimeMillis();
2363            final long timeEnd = timeStart + 100 * 1000;
2364            long timeNow = timeStart;
2365            while (!SystemProperties.get(CP_PREOPT_PROPERTY).equals("finished")) {
2366                try {
2367                    Thread.sleep(WAIT_TIME_MS);
2368                } catch (InterruptedException e) {
2369                    // Do nothing
2370                }
2371                timeNow = SystemClock.uptimeMillis();
2372                if (timeNow > timeEnd) {
2373                    SystemProperties.set(CP_PREOPT_PROPERTY, "timed-out");
2374                    Slog.wtf(TAG, "cppreopt did not finish!");
2375                    break;
2376                }
2377            }
2378
2379            Slog.i(TAG, "cppreopts took " + (timeNow - timeStart) + " ms");
2380        }
2381    }
2382
2383    public PackageManagerService(Context context, Installer installer,
2384            boolean factoryTest, boolean onlyCore) {
2385        LockGuard.installLock(mPackages, LockGuard.INDEX_PACKAGES);
2386        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "create package manager");
2387        EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_START,
2388                SystemClock.uptimeMillis());
2389
2390        if (mSdkVersion <= 0) {
2391            Slog.w(TAG, "**** ro.build.version.sdk not set!");
2392        }
2393
2394        mContext = context;
2395
2396        mPermissionReviewRequired = context.getResources().getBoolean(
2397                R.bool.config_permissionReviewRequired);
2398
2399        mFactoryTest = factoryTest;
2400        mOnlyCore = onlyCore;
2401        mMetrics = new DisplayMetrics();
2402        mSettings = new Settings(mPackages);
2403        mSettings.addSharedUserLPw("android.uid.system", Process.SYSTEM_UID,
2404                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2405        mSettings.addSharedUserLPw("android.uid.phone", RADIO_UID,
2406                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2407        mSettings.addSharedUserLPw("android.uid.log", LOG_UID,
2408                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2409        mSettings.addSharedUserLPw("android.uid.nfc", NFC_UID,
2410                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2411        mSettings.addSharedUserLPw("android.uid.bluetooth", BLUETOOTH_UID,
2412                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2413        mSettings.addSharedUserLPw("android.uid.shell", SHELL_UID,
2414                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2415
2416        String separateProcesses = SystemProperties.get("debug.separate_processes");
2417        if (separateProcesses != null && separateProcesses.length() > 0) {
2418            if ("*".equals(separateProcesses)) {
2419                mDefParseFlags = PackageParser.PARSE_IGNORE_PROCESSES;
2420                mSeparateProcesses = null;
2421                Slog.w(TAG, "Running with debug.separate_processes: * (ALL)");
2422            } else {
2423                mDefParseFlags = 0;
2424                mSeparateProcesses = separateProcesses.split(",");
2425                Slog.w(TAG, "Running with debug.separate_processes: "
2426                        + separateProcesses);
2427            }
2428        } else {
2429            mDefParseFlags = 0;
2430            mSeparateProcesses = null;
2431        }
2432
2433        mInstaller = installer;
2434        mPackageDexOptimizer = new PackageDexOptimizer(installer, mInstallLock, context,
2435                "*dexopt*");
2436        mDexManager = new DexManager(this, mPackageDexOptimizer, installer, mInstallLock);
2437        mMoveCallbacks = new MoveCallbacks(FgThread.get().getLooper());
2438
2439        mOnPermissionChangeListeners = new OnPermissionChangeListeners(
2440                FgThread.get().getLooper());
2441
2442        getDefaultDisplayMetrics(context, mMetrics);
2443
2444        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "get system config");
2445        SystemConfig systemConfig = SystemConfig.getInstance();
2446        mGlobalGids = systemConfig.getGlobalGids();
2447        mSystemPermissions = systemConfig.getSystemPermissions();
2448        mAvailableFeatures = systemConfig.getAvailableFeatures();
2449        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
2450
2451        mProtectedPackages = new ProtectedPackages(mContext);
2452
2453        synchronized (mInstallLock) {
2454        // writer
2455        synchronized (mPackages) {
2456            mHandlerThread = new ServiceThread(TAG,
2457                    Process.THREAD_PRIORITY_BACKGROUND, true /*allowIo*/);
2458            mHandlerThread.start();
2459            mHandler = new PackageHandler(mHandlerThread.getLooper());
2460            mProcessLoggingHandler = new ProcessLoggingHandler();
2461            Watchdog.getInstance().addThread(mHandler, WATCHDOG_TIMEOUT);
2462
2463            mDefaultPermissionPolicy = new DefaultPermissionGrantPolicy(this);
2464            mInstantAppRegistry = new InstantAppRegistry(this);
2465
2466            File dataDir = Environment.getDataDirectory();
2467            mAppInstallDir = new File(dataDir, "app");
2468            mAppLib32InstallDir = new File(dataDir, "app-lib");
2469            mAsecInternalPath = new File(dataDir, "app-asec").getPath();
2470            mDrmAppPrivateInstallDir = new File(dataDir, "app-private");
2471            sUserManager = new UserManagerService(context, this,
2472                    new UserDataPreparer(mInstaller, mInstallLock, mContext, mOnlyCore), mPackages);
2473
2474            // Propagate permission configuration in to package manager.
2475            ArrayMap<String, SystemConfig.PermissionEntry> permConfig
2476                    = systemConfig.getPermissions();
2477            for (int i=0; i<permConfig.size(); i++) {
2478                SystemConfig.PermissionEntry perm = permConfig.valueAt(i);
2479                BasePermission bp = mSettings.mPermissions.get(perm.name);
2480                if (bp == null) {
2481                    bp = new BasePermission(perm.name, "android", BasePermission.TYPE_BUILTIN);
2482                    mSettings.mPermissions.put(perm.name, bp);
2483                }
2484                if (perm.gids != null) {
2485                    bp.setGids(perm.gids, perm.perUser);
2486                }
2487            }
2488
2489            ArrayMap<String, String> libConfig = systemConfig.getSharedLibraries();
2490            final int builtInLibCount = libConfig.size();
2491            for (int i = 0; i < builtInLibCount; i++) {
2492                String name = libConfig.keyAt(i);
2493                String path = libConfig.valueAt(i);
2494                addSharedLibraryLPw(path, null, name, SharedLibraryInfo.VERSION_UNDEFINED,
2495                        SharedLibraryInfo.TYPE_BUILTIN, PLATFORM_PACKAGE_NAME, 0);
2496            }
2497
2498            mFoundPolicyFile = SELinuxMMAC.readInstallPolicy();
2499
2500            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "read user settings");
2501            mFirstBoot = !mSettings.readLPw(sUserManager.getUsers(false));
2502            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
2503
2504            // Clean up orphaned packages for which the code path doesn't exist
2505            // and they are an update to a system app - caused by bug/32321269
2506            final int packageSettingCount = mSettings.mPackages.size();
2507            for (int i = packageSettingCount - 1; i >= 0; i--) {
2508                PackageSetting ps = mSettings.mPackages.valueAt(i);
2509                if (!isExternal(ps) && (ps.codePath == null || !ps.codePath.exists())
2510                        && mSettings.getDisabledSystemPkgLPr(ps.name) != null) {
2511                    mSettings.mPackages.removeAt(i);
2512                    mSettings.enableSystemPackageLPw(ps.name);
2513                }
2514            }
2515
2516            if (mFirstBoot) {
2517                requestCopyPreoptedFiles();
2518            }
2519
2520            String customResolverActivity = Resources.getSystem().getString(
2521                    R.string.config_customResolverActivity);
2522            if (TextUtils.isEmpty(customResolverActivity)) {
2523                customResolverActivity = null;
2524            } else {
2525                mCustomResolverComponentName = ComponentName.unflattenFromString(
2526                        customResolverActivity);
2527            }
2528
2529            long startTime = SystemClock.uptimeMillis();
2530
2531            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SYSTEM_SCAN_START,
2532                    startTime);
2533
2534            final String bootClassPath = System.getenv("BOOTCLASSPATH");
2535            final String systemServerClassPath = System.getenv("SYSTEMSERVERCLASSPATH");
2536
2537            if (bootClassPath == null) {
2538                Slog.w(TAG, "No BOOTCLASSPATH found!");
2539            }
2540
2541            if (systemServerClassPath == null) {
2542                Slog.w(TAG, "No SYSTEMSERVERCLASSPATH found!");
2543            }
2544
2545            File frameworkDir = new File(Environment.getRootDirectory(), "framework");
2546
2547            final VersionInfo ver = mSettings.getInternalVersion();
2548            mIsUpgrade = !Build.FINGERPRINT.equals(ver.fingerprint);
2549            if (mIsUpgrade) {
2550                logCriticalInfo(Log.INFO,
2551                        "Upgrading from " + ver.fingerprint + " to " + Build.FINGERPRINT);
2552            }
2553
2554            // when upgrading from pre-M, promote system app permissions from install to runtime
2555            mPromoteSystemApps =
2556                    mIsUpgrade && ver.sdkVersion <= Build.VERSION_CODES.LOLLIPOP_MR1;
2557
2558            // When upgrading from pre-N, we need to handle package extraction like first boot,
2559            // as there is no profiling data available.
2560            mIsPreNUpgrade = mIsUpgrade && ver.sdkVersion < Build.VERSION_CODES.N;
2561
2562            mIsPreNMR1Upgrade = mIsUpgrade && ver.sdkVersion < Build.VERSION_CODES.N_MR1;
2563
2564            // save off the names of pre-existing system packages prior to scanning; we don't
2565            // want to automatically grant runtime permissions for new system apps
2566            if (mPromoteSystemApps) {
2567                Iterator<PackageSetting> pkgSettingIter = mSettings.mPackages.values().iterator();
2568                while (pkgSettingIter.hasNext()) {
2569                    PackageSetting ps = pkgSettingIter.next();
2570                    if (isSystemApp(ps)) {
2571                        mExistingSystemPackages.add(ps.name);
2572                    }
2573                }
2574            }
2575
2576            mCacheDir = preparePackageParserCache(mIsUpgrade);
2577
2578            // Set flag to monitor and not change apk file paths when
2579            // scanning install directories.
2580            int scanFlags = SCAN_BOOTING | SCAN_INITIAL;
2581
2582            if (mIsUpgrade || mFirstBoot) {
2583                scanFlags = scanFlags | SCAN_FIRST_BOOT_OR_UPGRADE;
2584            }
2585
2586            // Collect vendor overlay packages. (Do this before scanning any apps.)
2587            // For security and version matching reason, only consider
2588            // overlay packages if they reside in the right directory.
2589            scanDirTracedLI(new File(VENDOR_OVERLAY_DIR), mDefParseFlags
2590                    | PackageParser.PARSE_IS_SYSTEM
2591                    | PackageParser.PARSE_IS_SYSTEM_DIR
2592                    | PackageParser.PARSE_TRUSTED_OVERLAY, scanFlags | SCAN_TRUSTED_OVERLAY, 0);
2593
2594            mParallelPackageParserCallback.findStaticOverlayPackages();
2595
2596            // Find base frameworks (resource packages without code).
2597            scanDirTracedLI(frameworkDir, mDefParseFlags
2598                    | PackageParser.PARSE_IS_SYSTEM
2599                    | PackageParser.PARSE_IS_SYSTEM_DIR
2600                    | PackageParser.PARSE_IS_PRIVILEGED,
2601                    scanFlags | SCAN_NO_DEX, 0);
2602
2603            // Collected privileged system packages.
2604            final File privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app");
2605            scanDirTracedLI(privilegedAppDir, mDefParseFlags
2606                    | PackageParser.PARSE_IS_SYSTEM
2607                    | PackageParser.PARSE_IS_SYSTEM_DIR
2608                    | PackageParser.PARSE_IS_PRIVILEGED, scanFlags, 0);
2609
2610            // Collect ordinary system packages.
2611            final File systemAppDir = new File(Environment.getRootDirectory(), "app");
2612            scanDirTracedLI(systemAppDir, mDefParseFlags
2613                    | PackageParser.PARSE_IS_SYSTEM
2614                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
2615
2616            // Collect all vendor packages.
2617            File vendorAppDir = new File("/vendor/app");
2618            try {
2619                vendorAppDir = vendorAppDir.getCanonicalFile();
2620            } catch (IOException e) {
2621                // failed to look up canonical path, continue with original one
2622            }
2623            scanDirTracedLI(vendorAppDir, mDefParseFlags
2624                    | PackageParser.PARSE_IS_SYSTEM
2625                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
2626
2627            // Collect all OEM packages.
2628            final File oemAppDir = new File(Environment.getOemDirectory(), "app");
2629            scanDirTracedLI(oemAppDir, mDefParseFlags
2630                    | PackageParser.PARSE_IS_SYSTEM
2631                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
2632
2633            // Prune any system packages that no longer exist.
2634            final List<String> possiblyDeletedUpdatedSystemApps = new ArrayList<String>();
2635            if (!mOnlyCore) {
2636                Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator();
2637                while (psit.hasNext()) {
2638                    PackageSetting ps = psit.next();
2639
2640                    /*
2641                     * If this is not a system app, it can't be a
2642                     * disable system app.
2643                     */
2644                    if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0) {
2645                        continue;
2646                    }
2647
2648                    /*
2649                     * If the package is scanned, it's not erased.
2650                     */
2651                    final PackageParser.Package scannedPkg = mPackages.get(ps.name);
2652                    if (scannedPkg != null) {
2653                        /*
2654                         * If the system app is both scanned and in the
2655                         * disabled packages list, then it must have been
2656                         * added via OTA. Remove it from the currently
2657                         * scanned package so the previously user-installed
2658                         * application can be scanned.
2659                         */
2660                        if (mSettings.isDisabledSystemPackageLPr(ps.name)) {
2661                            logCriticalInfo(Log.WARN, "Expecting better updated system app for "
2662                                    + ps.name + "; removing system app.  Last known codePath="
2663                                    + ps.codePathString + ", installStatus=" + ps.installStatus
2664                                    + ", versionCode=" + ps.versionCode + "; scanned versionCode="
2665                                    + scannedPkg.mVersionCode);
2666                            removePackageLI(scannedPkg, true);
2667                            mExpectingBetter.put(ps.name, ps.codePath);
2668                        }
2669
2670                        continue;
2671                    }
2672
2673                    if (!mSettings.isDisabledSystemPackageLPr(ps.name)) {
2674                        psit.remove();
2675                        logCriticalInfo(Log.WARN, "System package " + ps.name
2676                                + " no longer exists; it's data will be wiped");
2677                        // Actual deletion of code and data will be handled by later
2678                        // reconciliation step
2679                    } else {
2680                        final PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(ps.name);
2681                        if (disabledPs.codePath == null || !disabledPs.codePath.exists()) {
2682                            possiblyDeletedUpdatedSystemApps.add(ps.name);
2683                        }
2684                    }
2685                }
2686            }
2687
2688            //look for any incomplete package installations
2689            ArrayList<PackageSetting> deletePkgsList = mSettings.getListOfIncompleteInstallPackagesLPr();
2690            for (int i = 0; i < deletePkgsList.size(); i++) {
2691                // Actual deletion of code and data will be handled by later
2692                // reconciliation step
2693                final String packageName = deletePkgsList.get(i).name;
2694                logCriticalInfo(Log.WARN, "Cleaning up incompletely installed app: " + packageName);
2695                synchronized (mPackages) {
2696                    mSettings.removePackageLPw(packageName);
2697                }
2698            }
2699
2700            //delete tmp files
2701            deleteTempPackageFiles();
2702
2703            // Remove any shared userIDs that have no associated packages
2704            mSettings.pruneSharedUsersLPw();
2705            final long systemScanTime = SystemClock.uptimeMillis() - startTime;
2706            final int systemPackagesCount = mPackages.size();
2707            Slog.i(TAG, "Finished scanning system apps. Time: " + systemScanTime
2708                    + " ms, packageCount: " + systemPackagesCount
2709                    + " ms, timePerPackage: "
2710                    + (systemPackagesCount == 0 ? 0 : systemScanTime / systemPackagesCount));
2711            if (mIsUpgrade && systemPackagesCount > 0) {
2712                MetricsLogger.histogram(null, "ota_package_manager_system_app_avg_scan_time",
2713                        ((int) systemScanTime) / systemPackagesCount);
2714            }
2715            if (!mOnlyCore) {
2716                EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_DATA_SCAN_START,
2717                        SystemClock.uptimeMillis());
2718                scanDirTracedLI(mAppInstallDir, 0, scanFlags | SCAN_REQUIRE_KNOWN, 0);
2719
2720                scanDirTracedLI(mDrmAppPrivateInstallDir, mDefParseFlags
2721                        | PackageParser.PARSE_FORWARD_LOCK,
2722                        scanFlags | SCAN_REQUIRE_KNOWN, 0);
2723
2724                /**
2725                 * Remove disable package settings for any updated system
2726                 * apps that were removed via an OTA. If they're not a
2727                 * previously-updated app, remove them completely.
2728                 * Otherwise, just revoke their system-level permissions.
2729                 */
2730                for (String deletedAppName : possiblyDeletedUpdatedSystemApps) {
2731                    PackageParser.Package deletedPkg = mPackages.get(deletedAppName);
2732                    mSettings.removeDisabledSystemPackageLPw(deletedAppName);
2733
2734                    String msg;
2735                    if (deletedPkg == null) {
2736                        msg = "Updated system package " + deletedAppName
2737                                + " no longer exists; it's data will be wiped";
2738                        // Actual deletion of code and data will be handled by later
2739                        // reconciliation step
2740                    } else {
2741                        msg = "Updated system app + " + deletedAppName
2742                                + " no longer present; removing system privileges for "
2743                                + deletedAppName;
2744
2745                        deletedPkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_SYSTEM;
2746
2747                        PackageSetting deletedPs = mSettings.mPackages.get(deletedAppName);
2748                        deletedPs.pkgFlags &= ~ApplicationInfo.FLAG_SYSTEM;
2749                    }
2750                    logCriticalInfo(Log.WARN, msg);
2751                }
2752
2753                /**
2754                 * Make sure all system apps that we expected to appear on
2755                 * the userdata partition actually showed up. If they never
2756                 * appeared, crawl back and revive the system version.
2757                 */
2758                for (int i = 0; i < mExpectingBetter.size(); i++) {
2759                    final String packageName = mExpectingBetter.keyAt(i);
2760                    if (!mPackages.containsKey(packageName)) {
2761                        final File scanFile = mExpectingBetter.valueAt(i);
2762
2763                        logCriticalInfo(Log.WARN, "Expected better " + packageName
2764                                + " but never showed up; reverting to system");
2765
2766                        int reparseFlags = mDefParseFlags;
2767                        if (FileUtils.contains(privilegedAppDir, scanFile)) {
2768                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2769                                    | PackageParser.PARSE_IS_SYSTEM_DIR
2770                                    | PackageParser.PARSE_IS_PRIVILEGED;
2771                        } else if (FileUtils.contains(systemAppDir, scanFile)) {
2772                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2773                                    | PackageParser.PARSE_IS_SYSTEM_DIR;
2774                        } else if (FileUtils.contains(vendorAppDir, scanFile)) {
2775                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2776                                    | PackageParser.PARSE_IS_SYSTEM_DIR;
2777                        } else if (FileUtils.contains(oemAppDir, scanFile)) {
2778                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2779                                    | PackageParser.PARSE_IS_SYSTEM_DIR;
2780                        } else {
2781                            Slog.e(TAG, "Ignoring unexpected fallback path " + scanFile);
2782                            continue;
2783                        }
2784
2785                        mSettings.enableSystemPackageLPw(packageName);
2786
2787                        try {
2788                            scanPackageTracedLI(scanFile, reparseFlags, scanFlags, 0, null);
2789                        } catch (PackageManagerException e) {
2790                            Slog.e(TAG, "Failed to parse original system package: "
2791                                    + e.getMessage());
2792                        }
2793                    }
2794                }
2795                final long dataScanTime = SystemClock.uptimeMillis() - systemScanTime - startTime;
2796                final int dataPackagesCount = mPackages.size() - systemPackagesCount;
2797                Slog.i(TAG, "Finished scanning non-system apps. Time: " + dataScanTime
2798                        + " ms, packageCount: " + dataPackagesCount
2799                        + " ms, timePerPackage: "
2800                        + (dataPackagesCount == 0 ? 0 : dataScanTime / dataPackagesCount));
2801                if (mIsUpgrade && dataPackagesCount > 0) {
2802                    MetricsLogger.histogram(null, "ota_package_manager_data_app_avg_scan_time",
2803                            ((int) dataScanTime) / dataPackagesCount);
2804                }
2805            }
2806            mExpectingBetter.clear();
2807
2808            // Resolve the storage manager.
2809            mStorageManagerPackage = getStorageManagerPackageName();
2810
2811            // Resolve protected action filters. Only the setup wizard is allowed to
2812            // have a high priority filter for these actions.
2813            mSetupWizardPackage = getSetupWizardPackageName();
2814            if (mProtectedFilters.size() > 0) {
2815                if (DEBUG_FILTERS && mSetupWizardPackage == null) {
2816                    Slog.i(TAG, "No setup wizard;"
2817                        + " All protected intents capped to priority 0");
2818                }
2819                for (ActivityIntentInfo filter : mProtectedFilters) {
2820                    if (filter.activity.info.packageName.equals(mSetupWizardPackage)) {
2821                        if (DEBUG_FILTERS) {
2822                            Slog.i(TAG, "Found setup wizard;"
2823                                + " allow priority " + filter.getPriority() + ";"
2824                                + " package: " + filter.activity.info.packageName
2825                                + " activity: " + filter.activity.className
2826                                + " priority: " + filter.getPriority());
2827                        }
2828                        // skip setup wizard; allow it to keep the high priority filter
2829                        continue;
2830                    }
2831                    if (DEBUG_FILTERS) {
2832                        Slog.i(TAG, "Protected action; cap priority to 0;"
2833                                + " package: " + filter.activity.info.packageName
2834                                + " activity: " + filter.activity.className
2835                                + " origPrio: " + filter.getPriority());
2836                    }
2837                    filter.setPriority(0);
2838                }
2839            }
2840            mDeferProtectedFilters = false;
2841            mProtectedFilters.clear();
2842
2843            // Now that we know all of the shared libraries, update all clients to have
2844            // the correct library paths.
2845            updateAllSharedLibrariesLPw(null);
2846
2847            for (SharedUserSetting setting : mSettings.getAllSharedUsersLPw()) {
2848                // NOTE: We ignore potential failures here during a system scan (like
2849                // the rest of the commands above) because there's precious little we
2850                // can do about it. A settings error is reported, though.
2851                adjustCpuAbisForSharedUserLPw(setting.packages, null /*scannedPackage*/);
2852            }
2853
2854            // Now that we know all the packages we are keeping,
2855            // read and update their last usage times.
2856            mPackageUsage.read(mPackages);
2857            mCompilerStats.read();
2858
2859            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SCAN_END,
2860                    SystemClock.uptimeMillis());
2861            Slog.i(TAG, "Time to scan packages: "
2862                    + ((SystemClock.uptimeMillis()-startTime)/1000f)
2863                    + " seconds");
2864
2865            // If the platform SDK has changed since the last time we booted,
2866            // we need to re-grant app permission to catch any new ones that
2867            // appear.  This is really a hack, and means that apps can in some
2868            // cases get permissions that the user didn't initially explicitly
2869            // allow...  it would be nice to have some better way to handle
2870            // this situation.
2871            int updateFlags = UPDATE_PERMISSIONS_ALL;
2872            if (ver.sdkVersion != mSdkVersion) {
2873                Slog.i(TAG, "Platform changed from " + ver.sdkVersion + " to "
2874                        + mSdkVersion + "; regranting permissions for internal storage");
2875                updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL;
2876            }
2877            updatePermissionsLPw(null, null, StorageManager.UUID_PRIVATE_INTERNAL, updateFlags);
2878            ver.sdkVersion = mSdkVersion;
2879
2880            // If this is the first boot or an update from pre-M, and it is a normal
2881            // boot, then we need to initialize the default preferred apps across
2882            // all defined users.
2883            if (!onlyCore && (mPromoteSystemApps || mFirstBoot)) {
2884                for (UserInfo user : sUserManager.getUsers(true)) {
2885                    mSettings.applyDefaultPreferredAppsLPw(this, user.id);
2886                    applyFactoryDefaultBrowserLPw(user.id);
2887                    primeDomainVerificationsLPw(user.id);
2888                }
2889            }
2890
2891            // Prepare storage for system user really early during boot,
2892            // since core system apps like SettingsProvider and SystemUI
2893            // can't wait for user to start
2894            final int storageFlags;
2895            if (StorageManager.isFileEncryptedNativeOrEmulated()) {
2896                storageFlags = StorageManager.FLAG_STORAGE_DE;
2897            } else {
2898                storageFlags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
2899            }
2900            List<String> deferPackages = reconcileAppsDataLI(StorageManager.UUID_PRIVATE_INTERNAL,
2901                    UserHandle.USER_SYSTEM, storageFlags, true /* migrateAppData */,
2902                    true /* onlyCoreApps */);
2903            mPrepareAppDataFuture = SystemServerInitThreadPool.get().submit(() -> {
2904                BootTimingsTraceLog traceLog = new BootTimingsTraceLog("SystemServerTimingAsync",
2905                        Trace.TRACE_TAG_PACKAGE_MANAGER);
2906                traceLog.traceBegin("AppDataFixup");
2907                try {
2908                    mInstaller.fixupAppData(StorageManager.UUID_PRIVATE_INTERNAL,
2909                            StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
2910                } catch (InstallerException e) {
2911                    Slog.w(TAG, "Trouble fixing GIDs", e);
2912                }
2913                traceLog.traceEnd();
2914
2915                traceLog.traceBegin("AppDataPrepare");
2916                if (deferPackages == null || deferPackages.isEmpty()) {
2917                    return;
2918                }
2919                int count = 0;
2920                for (String pkgName : deferPackages) {
2921                    PackageParser.Package pkg = null;
2922                    synchronized (mPackages) {
2923                        PackageSetting ps = mSettings.getPackageLPr(pkgName);
2924                        if (ps != null && ps.getInstalled(UserHandle.USER_SYSTEM)) {
2925                            pkg = ps.pkg;
2926                        }
2927                    }
2928                    if (pkg != null) {
2929                        synchronized (mInstallLock) {
2930                            prepareAppDataAndMigrateLIF(pkg, UserHandle.USER_SYSTEM, storageFlags,
2931                                    true /* maybeMigrateAppData */);
2932                        }
2933                        count++;
2934                    }
2935                }
2936                traceLog.traceEnd();
2937                Slog.i(TAG, "Deferred reconcileAppsData finished " + count + " packages");
2938            }, "prepareAppData");
2939
2940            // If this is first boot after an OTA, and a normal boot, then
2941            // we need to clear code cache directories.
2942            // Note that we do *not* clear the application profiles. These remain valid
2943            // across OTAs and are used to drive profile verification (post OTA) and
2944            // profile compilation (without waiting to collect a fresh set of profiles).
2945            if (mIsUpgrade && !onlyCore) {
2946                Slog.i(TAG, "Build fingerprint changed; clearing code caches");
2947                for (int i = 0; i < mSettings.mPackages.size(); i++) {
2948                    final PackageSetting ps = mSettings.mPackages.valueAt(i);
2949                    if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, ps.volumeUuid)) {
2950                        // No apps are running this early, so no need to freeze
2951                        clearAppDataLIF(ps.pkg, UserHandle.USER_ALL,
2952                                StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE
2953                                        | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
2954                    }
2955                }
2956                ver.fingerprint = Build.FINGERPRINT;
2957            }
2958
2959            checkDefaultBrowser();
2960
2961            // clear only after permissions and other defaults have been updated
2962            mExistingSystemPackages.clear();
2963            mPromoteSystemApps = false;
2964
2965            // All the changes are done during package scanning.
2966            ver.databaseVersion = Settings.CURRENT_DATABASE_VERSION;
2967
2968            // can downgrade to reader
2969            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "write settings");
2970            mSettings.writeLPr();
2971            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
2972            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_READY,
2973                    SystemClock.uptimeMillis());
2974
2975            if (!mOnlyCore) {
2976                mRequiredVerifierPackage = getRequiredButNotReallyRequiredVerifierLPr();
2977                mRequiredInstallerPackage = getRequiredInstallerLPr();
2978                mRequiredUninstallerPackage = getRequiredUninstallerLPr();
2979                mIntentFilterVerifierComponent = getIntentFilterVerifierComponentNameLPr();
2980                if (mIntentFilterVerifierComponent != null) {
2981                    mIntentFilterVerifier = new IntentVerifierProxy(mContext,
2982                            mIntentFilterVerifierComponent);
2983                } else {
2984                    mIntentFilterVerifier = null;
2985                }
2986                mServicesSystemSharedLibraryPackageName = getRequiredSharedLibraryLPr(
2987                        PackageManager.SYSTEM_SHARED_LIBRARY_SERVICES,
2988                        SharedLibraryInfo.VERSION_UNDEFINED);
2989                mSharedSystemSharedLibraryPackageName = getRequiredSharedLibraryLPr(
2990                        PackageManager.SYSTEM_SHARED_LIBRARY_SHARED,
2991                        SharedLibraryInfo.VERSION_UNDEFINED);
2992            } else {
2993                mRequiredVerifierPackage = null;
2994                mRequiredInstallerPackage = null;
2995                mRequiredUninstallerPackage = null;
2996                mIntentFilterVerifierComponent = null;
2997                mIntentFilterVerifier = null;
2998                mServicesSystemSharedLibraryPackageName = null;
2999                mSharedSystemSharedLibraryPackageName = null;
3000            }
3001
3002            mInstallerService = new PackageInstallerService(context, this);
3003            final Pair<ComponentName, String> instantAppResolverComponent =
3004                    getInstantAppResolverLPr();
3005            if (instantAppResolverComponent != null) {
3006                if (DEBUG_EPHEMERAL) {
3007                    Slog.d(TAG, "Set ephemeral resolver: " + instantAppResolverComponent);
3008                }
3009                mInstantAppResolverConnection = new EphemeralResolverConnection(
3010                        mContext, instantAppResolverComponent.first,
3011                        instantAppResolverComponent.second);
3012                mInstantAppResolverSettingsComponent =
3013                        getInstantAppResolverSettingsLPr(instantAppResolverComponent.first);
3014            } else {
3015                mInstantAppResolverConnection = null;
3016                mInstantAppResolverSettingsComponent = null;
3017            }
3018            updateInstantAppInstallerLocked(null);
3019
3020            // Read and update the usage of dex files.
3021            // Do this at the end of PM init so that all the packages have their
3022            // data directory reconciled.
3023            // At this point we know the code paths of the packages, so we can validate
3024            // the disk file and build the internal cache.
3025            // The usage file is expected to be small so loading and verifying it
3026            // should take a fairly small time compare to the other activities (e.g. package
3027            // scanning).
3028            final Map<Integer, List<PackageInfo>> userPackages = new HashMap<>();
3029            final int[] currentUserIds = UserManagerService.getInstance().getUserIds();
3030            for (int userId : currentUserIds) {
3031                userPackages.put(userId, getInstalledPackages(/*flags*/ 0, userId).getList());
3032            }
3033            mDexManager.load(userPackages);
3034            if (mIsUpgrade) {
3035                MetricsLogger.histogram(null, "ota_package_manager_init_time",
3036                        (int) (SystemClock.uptimeMillis() - startTime));
3037            }
3038        } // synchronized (mPackages)
3039        } // synchronized (mInstallLock)
3040
3041        // Now after opening every single application zip, make sure they
3042        // are all flushed.  Not really needed, but keeps things nice and
3043        // tidy.
3044        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "GC");
3045        Runtime.getRuntime().gc();
3046        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
3047
3048        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "loadFallbacks");
3049        FallbackCategoryProvider.loadFallbacks();
3050        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
3051
3052        // The initial scanning above does many calls into installd while
3053        // holding the mPackages lock, but we're mostly interested in yelling
3054        // once we have a booted system.
3055        mInstaller.setWarnIfHeld(mPackages);
3056
3057        // Expose private service for system components to use.
3058        LocalServices.addService(PackageManagerInternal.class, new PackageManagerInternalImpl());
3059        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
3060    }
3061
3062    private void updateInstantAppInstallerLocked(String modifiedPackage) {
3063        // we're only interested in updating the installer appliction when 1) it's not
3064        // already set or 2) the modified package is the installer
3065        if (mInstantAppInstallerActivity != null
3066                && !mInstantAppInstallerActivity.getComponentName().getPackageName()
3067                        .equals(modifiedPackage)) {
3068            return;
3069        }
3070        setUpInstantAppInstallerActivityLP(getInstantAppInstallerLPr());
3071    }
3072
3073    private static File preparePackageParserCache(boolean isUpgrade) {
3074        if (!DEFAULT_PACKAGE_PARSER_CACHE_ENABLED) {
3075            return null;
3076        }
3077
3078        // Disable package parsing on eng builds to allow for faster incremental development.
3079        if (Build.IS_ENG) {
3080            return null;
3081        }
3082
3083        if (SystemProperties.getBoolean("pm.boot.disable_package_cache", false)) {
3084            Slog.i(TAG, "Disabling package parser cache due to system property.");
3085            return null;
3086        }
3087
3088        // The base directory for the package parser cache lives under /data/system/.
3089        final File cacheBaseDir = FileUtils.createDir(Environment.getDataSystemDirectory(),
3090                "package_cache");
3091        if (cacheBaseDir == null) {
3092            return null;
3093        }
3094
3095        // If this is a system upgrade scenario, delete the contents of the package cache dir.
3096        // This also serves to "GC" unused entries when the package cache version changes (which
3097        // can only happen during upgrades).
3098        if (isUpgrade) {
3099            FileUtils.deleteContents(cacheBaseDir);
3100        }
3101
3102
3103        // Return the versioned package cache directory. This is something like
3104        // "/data/system/package_cache/1"
3105        File cacheDir = FileUtils.createDir(cacheBaseDir, PACKAGE_PARSER_CACHE_VERSION);
3106
3107        // The following is a workaround to aid development on non-numbered userdebug
3108        // builds or cases where "adb sync" is used on userdebug builds. If we detect that
3109        // the system partition is newer.
3110        //
3111        // NOTE: When no BUILD_NUMBER is set by the build system, it defaults to a build
3112        // that starts with "eng." to signify that this is an engineering build and not
3113        // destined for release.
3114        if (Build.IS_USERDEBUG && Build.VERSION.INCREMENTAL.startsWith("eng.")) {
3115            Slog.w(TAG, "Wiping cache directory because the system partition changed.");
3116
3117            // Heuristic: If the /system directory has been modified recently due to an "adb sync"
3118            // or a regular make, then blow away the cache. Note that mtimes are *NOT* reliable
3119            // in general and should not be used for production changes. In this specific case,
3120            // we know that they will work.
3121            File frameworkDir = new File(Environment.getRootDirectory(), "framework");
3122            if (cacheDir.lastModified() < frameworkDir.lastModified()) {
3123                FileUtils.deleteContents(cacheBaseDir);
3124                cacheDir = FileUtils.createDir(cacheBaseDir, PACKAGE_PARSER_CACHE_VERSION);
3125            }
3126        }
3127
3128        return cacheDir;
3129    }
3130
3131    @Override
3132    public boolean isFirstBoot() {
3133        // allow instant applications
3134        return mFirstBoot;
3135    }
3136
3137    @Override
3138    public boolean isOnlyCoreApps() {
3139        // allow instant applications
3140        return mOnlyCore;
3141    }
3142
3143    @Override
3144    public boolean isUpgrade() {
3145        // allow instant applications
3146        return mIsUpgrade;
3147    }
3148
3149    private @Nullable String getRequiredButNotReallyRequiredVerifierLPr() {
3150        final Intent intent = new Intent(Intent.ACTION_PACKAGE_NEEDS_VERIFICATION);
3151
3152        final List<ResolveInfo> matches = queryIntentReceiversInternal(intent, PACKAGE_MIME_TYPE,
3153                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
3154                UserHandle.USER_SYSTEM);
3155        if (matches.size() == 1) {
3156            return matches.get(0).getComponentInfo().packageName;
3157        } else if (matches.size() == 0) {
3158            Log.e(TAG, "There should probably be a verifier, but, none were found");
3159            return null;
3160        }
3161        throw new RuntimeException("There must be exactly one verifier; found " + matches);
3162    }
3163
3164    private @NonNull String getRequiredSharedLibraryLPr(String name, int version) {
3165        synchronized (mPackages) {
3166            SharedLibraryEntry libraryEntry = getSharedLibraryEntryLPr(name, version);
3167            if (libraryEntry == null) {
3168                throw new IllegalStateException("Missing required shared library:" + name);
3169            }
3170            return libraryEntry.apk;
3171        }
3172    }
3173
3174    private @NonNull String getRequiredInstallerLPr() {
3175        final Intent intent = new Intent(Intent.ACTION_INSTALL_PACKAGE);
3176        intent.addCategory(Intent.CATEGORY_DEFAULT);
3177        intent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE);
3178
3179        final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, PACKAGE_MIME_TYPE,
3180                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
3181                UserHandle.USER_SYSTEM);
3182        if (matches.size() == 1) {
3183            ResolveInfo resolveInfo = matches.get(0);
3184            if (!resolveInfo.activityInfo.applicationInfo.isPrivilegedApp()) {
3185                throw new RuntimeException("The installer must be a privileged app");
3186            }
3187            return matches.get(0).getComponentInfo().packageName;
3188        } else {
3189            throw new RuntimeException("There must be exactly one installer; found " + matches);
3190        }
3191    }
3192
3193    private @NonNull String getRequiredUninstallerLPr() {
3194        final Intent intent = new Intent(Intent.ACTION_UNINSTALL_PACKAGE);
3195        intent.addCategory(Intent.CATEGORY_DEFAULT);
3196        intent.setData(Uri.fromParts(PACKAGE_SCHEME, "foo.bar", null));
3197
3198        final ResolveInfo resolveInfo = resolveIntent(intent, null,
3199                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
3200                UserHandle.USER_SYSTEM);
3201        if (resolveInfo == null ||
3202                mResolveActivity.name.equals(resolveInfo.getComponentInfo().name)) {
3203            throw new RuntimeException("There must be exactly one uninstaller; found "
3204                    + resolveInfo);
3205        }
3206        return resolveInfo.getComponentInfo().packageName;
3207    }
3208
3209    private @NonNull ComponentName getIntentFilterVerifierComponentNameLPr() {
3210        final Intent intent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION);
3211
3212        final List<ResolveInfo> matches = queryIntentReceiversInternal(intent, PACKAGE_MIME_TYPE,
3213                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
3214                UserHandle.USER_SYSTEM);
3215        ResolveInfo best = null;
3216        final int N = matches.size();
3217        for (int i = 0; i < N; i++) {
3218            final ResolveInfo cur = matches.get(i);
3219            final String packageName = cur.getComponentInfo().packageName;
3220            if (checkPermission(android.Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT,
3221                    packageName, UserHandle.USER_SYSTEM) != PackageManager.PERMISSION_GRANTED) {
3222                continue;
3223            }
3224
3225            if (best == null || cur.priority > best.priority) {
3226                best = cur;
3227            }
3228        }
3229
3230        if (best != null) {
3231            return best.getComponentInfo().getComponentName();
3232        }
3233        Slog.w(TAG, "Intent filter verifier not found");
3234        return null;
3235    }
3236
3237    @Override
3238    public @Nullable ComponentName getInstantAppResolverComponent() {
3239        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
3240            return null;
3241        }
3242        synchronized (mPackages) {
3243            final Pair<ComponentName, String> instantAppResolver = getInstantAppResolverLPr();
3244            if (instantAppResolver == null) {
3245                return null;
3246            }
3247            return instantAppResolver.first;
3248        }
3249    }
3250
3251    private @Nullable Pair<ComponentName, String> getInstantAppResolverLPr() {
3252        final String[] packageArray =
3253                mContext.getResources().getStringArray(R.array.config_ephemeralResolverPackage);
3254        if (packageArray.length == 0 && !Build.IS_DEBUGGABLE) {
3255            if (DEBUG_EPHEMERAL) {
3256                Slog.d(TAG, "Ephemeral resolver NOT found; empty package list");
3257            }
3258            return null;
3259        }
3260
3261        final int callingUid = Binder.getCallingUid();
3262        final int resolveFlags =
3263                MATCH_DIRECT_BOOT_AWARE
3264                | MATCH_DIRECT_BOOT_UNAWARE
3265                | (!Build.IS_DEBUGGABLE ? MATCH_SYSTEM_ONLY : 0);
3266        String actionName = Intent.ACTION_RESOLVE_INSTANT_APP_PACKAGE;
3267        final Intent resolverIntent = new Intent(actionName);
3268        List<ResolveInfo> resolvers = queryIntentServicesInternal(resolverIntent, null,
3269                resolveFlags, UserHandle.USER_SYSTEM, callingUid, false /*includeInstantApps*/);
3270        // temporarily look for the old action
3271        if (resolvers.size() == 0) {
3272            if (DEBUG_EPHEMERAL) {
3273                Slog.d(TAG, "Ephemeral resolver not found with new action; try old one");
3274            }
3275            actionName = Intent.ACTION_RESOLVE_EPHEMERAL_PACKAGE;
3276            resolverIntent.setAction(actionName);
3277            resolvers = queryIntentServicesInternal(resolverIntent, null,
3278                    resolveFlags, UserHandle.USER_SYSTEM, callingUid, false /*includeInstantApps*/);
3279        }
3280        final int N = resolvers.size();
3281        if (N == 0) {
3282            if (DEBUG_EPHEMERAL) {
3283                Slog.d(TAG, "Ephemeral resolver NOT found; no matching intent filters");
3284            }
3285            return null;
3286        }
3287
3288        final Set<String> possiblePackages = new ArraySet<>(Arrays.asList(packageArray));
3289        for (int i = 0; i < N; i++) {
3290            final ResolveInfo info = resolvers.get(i);
3291
3292            if (info.serviceInfo == null) {
3293                continue;
3294            }
3295
3296            final String packageName = info.serviceInfo.packageName;
3297            if (!possiblePackages.contains(packageName) && !Build.IS_DEBUGGABLE) {
3298                if (DEBUG_EPHEMERAL) {
3299                    Slog.d(TAG, "Ephemeral resolver not in allowed package list;"
3300                            + " pkg: " + packageName + ", info:" + info);
3301                }
3302                continue;
3303            }
3304
3305            if (DEBUG_EPHEMERAL) {
3306                Slog.v(TAG, "Ephemeral resolver found;"
3307                        + " pkg: " + packageName + ", info:" + info);
3308            }
3309            return new Pair<>(new ComponentName(packageName, info.serviceInfo.name), actionName);
3310        }
3311        if (DEBUG_EPHEMERAL) {
3312            Slog.v(TAG, "Ephemeral resolver NOT found");
3313        }
3314        return null;
3315    }
3316
3317    private @Nullable ActivityInfo getInstantAppInstallerLPr() {
3318        final Intent intent = new Intent(Intent.ACTION_INSTALL_INSTANT_APP_PACKAGE);
3319        intent.addCategory(Intent.CATEGORY_DEFAULT);
3320        intent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE);
3321
3322        final int resolveFlags =
3323                MATCH_DIRECT_BOOT_AWARE
3324                | MATCH_DIRECT_BOOT_UNAWARE
3325                | (!Build.IS_DEBUGGABLE ? MATCH_SYSTEM_ONLY : 0);
3326        List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, PACKAGE_MIME_TYPE,
3327                resolveFlags, UserHandle.USER_SYSTEM);
3328        // temporarily look for the old action
3329        if (matches.isEmpty()) {
3330            if (DEBUG_EPHEMERAL) {
3331                Slog.d(TAG, "Ephemeral installer not found with new action; try old one");
3332            }
3333            intent.setAction(Intent.ACTION_INSTALL_EPHEMERAL_PACKAGE);
3334            matches = queryIntentActivitiesInternal(intent, PACKAGE_MIME_TYPE,
3335                    resolveFlags, UserHandle.USER_SYSTEM);
3336        }
3337        Iterator<ResolveInfo> iter = matches.iterator();
3338        while (iter.hasNext()) {
3339            final ResolveInfo rInfo = iter.next();
3340            final PackageSetting ps = mSettings.mPackages.get(rInfo.activityInfo.packageName);
3341            if (ps != null) {
3342                final PermissionsState permissionsState = ps.getPermissionsState();
3343                if (permissionsState.hasPermission(Manifest.permission.INSTALL_PACKAGES, 0)) {
3344                    continue;
3345                }
3346            }
3347            iter.remove();
3348        }
3349        if (matches.size() == 0) {
3350            return null;
3351        } else if (matches.size() == 1) {
3352            return (ActivityInfo) matches.get(0).getComponentInfo();
3353        } else {
3354            throw new RuntimeException(
3355                    "There must be at most one ephemeral installer; found " + matches);
3356        }
3357    }
3358
3359    private @Nullable ComponentName getInstantAppResolverSettingsLPr(
3360            @NonNull ComponentName resolver) {
3361        final Intent intent =  new Intent(Intent.ACTION_INSTANT_APP_RESOLVER_SETTINGS)
3362                .addCategory(Intent.CATEGORY_DEFAULT)
3363                .setPackage(resolver.getPackageName());
3364        final int resolveFlags = MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE;
3365        List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, null, resolveFlags,
3366                UserHandle.USER_SYSTEM);
3367        // temporarily look for the old action
3368        if (matches.isEmpty()) {
3369            if (DEBUG_EPHEMERAL) {
3370                Slog.d(TAG, "Ephemeral resolver settings not found with new action; try old one");
3371            }
3372            intent.setAction(Intent.ACTION_EPHEMERAL_RESOLVER_SETTINGS);
3373            matches = queryIntentActivitiesInternal(intent, null, resolveFlags,
3374                    UserHandle.USER_SYSTEM);
3375        }
3376        if (matches.isEmpty()) {
3377            return null;
3378        }
3379        return matches.get(0).getComponentInfo().getComponentName();
3380    }
3381
3382    private void primeDomainVerificationsLPw(int userId) {
3383        if (DEBUG_DOMAIN_VERIFICATION) {
3384            Slog.d(TAG, "Priming domain verifications in user " + userId);
3385        }
3386
3387        SystemConfig systemConfig = SystemConfig.getInstance();
3388        ArraySet<String> packages = systemConfig.getLinkedApps();
3389
3390        for (String packageName : packages) {
3391            PackageParser.Package pkg = mPackages.get(packageName);
3392            if (pkg != null) {
3393                if (!pkg.isSystemApp()) {
3394                    Slog.w(TAG, "Non-system app '" + packageName + "' in sysconfig <app-link>");
3395                    continue;
3396                }
3397
3398                ArraySet<String> domains = null;
3399                for (PackageParser.Activity a : pkg.activities) {
3400                    for (ActivityIntentInfo filter : a.intents) {
3401                        if (hasValidDomains(filter)) {
3402                            if (domains == null) {
3403                                domains = new ArraySet<String>();
3404                            }
3405                            domains.addAll(filter.getHostsList());
3406                        }
3407                    }
3408                }
3409
3410                if (domains != null && domains.size() > 0) {
3411                    if (DEBUG_DOMAIN_VERIFICATION) {
3412                        Slog.v(TAG, "      + " + packageName);
3413                    }
3414                    // 'Undefined' in the global IntentFilterVerificationInfo, i.e. the usual
3415                    // state w.r.t. the formal app-linkage "no verification attempted" state;
3416                    // and then 'always' in the per-user state actually used for intent resolution.
3417                    final IntentFilterVerificationInfo ivi;
3418                    ivi = mSettings.createIntentFilterVerificationIfNeededLPw(packageName, domains);
3419                    ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED);
3420                    mSettings.updateIntentFilterVerificationStatusLPw(packageName,
3421                            INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS, userId);
3422                } else {
3423                    Slog.w(TAG, "Sysconfig <app-link> package '" + packageName
3424                            + "' does not handle web links");
3425                }
3426            } else {
3427                Slog.w(TAG, "Unknown package " + packageName + " in sysconfig <app-link>");
3428            }
3429        }
3430
3431        scheduleWritePackageRestrictionsLocked(userId);
3432        scheduleWriteSettingsLocked();
3433    }
3434
3435    private void applyFactoryDefaultBrowserLPw(int userId) {
3436        // The default browser app's package name is stored in a string resource,
3437        // with a product-specific overlay used for vendor customization.
3438        String browserPkg = mContext.getResources().getString(
3439                com.android.internal.R.string.default_browser);
3440        if (!TextUtils.isEmpty(browserPkg)) {
3441            // non-empty string => required to be a known package
3442            PackageSetting ps = mSettings.mPackages.get(browserPkg);
3443            if (ps == null) {
3444                Slog.e(TAG, "Product default browser app does not exist: " + browserPkg);
3445                browserPkg = null;
3446            } else {
3447                mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId);
3448            }
3449        }
3450
3451        // Nothing valid explicitly set? Make the factory-installed browser the explicit
3452        // default.  If there's more than one, just leave everything alone.
3453        if (browserPkg == null) {
3454            calculateDefaultBrowserLPw(userId);
3455        }
3456    }
3457
3458    private void calculateDefaultBrowserLPw(int userId) {
3459        List<String> allBrowsers = resolveAllBrowserApps(userId);
3460        final String browserPkg = (allBrowsers.size() == 1) ? allBrowsers.get(0) : null;
3461        mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId);
3462    }
3463
3464    private List<String> resolveAllBrowserApps(int userId) {
3465        // Resolve the canonical browser intent and check that the handleAllWebDataURI boolean is set
3466        List<ResolveInfo> list = queryIntentActivitiesInternal(sBrowserIntent, null,
3467                PackageManager.MATCH_ALL, userId);
3468
3469        final int count = list.size();
3470        List<String> result = new ArrayList<String>(count);
3471        for (int i=0; i<count; i++) {
3472            ResolveInfo info = list.get(i);
3473            if (info.activityInfo == null
3474                    || !info.handleAllWebDataURI
3475                    || (info.activityInfo.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) == 0
3476                    || result.contains(info.activityInfo.packageName)) {
3477                continue;
3478            }
3479            result.add(info.activityInfo.packageName);
3480        }
3481
3482        return result;
3483    }
3484
3485    private boolean packageIsBrowser(String packageName, int userId) {
3486        List<ResolveInfo> list = queryIntentActivitiesInternal(sBrowserIntent, null,
3487                PackageManager.MATCH_ALL, userId);
3488        final int N = list.size();
3489        for (int i = 0; i < N; i++) {
3490            ResolveInfo info = list.get(i);
3491            if (packageName.equals(info.activityInfo.packageName)) {
3492                return true;
3493            }
3494        }
3495        return false;
3496    }
3497
3498    private void checkDefaultBrowser() {
3499        final int myUserId = UserHandle.myUserId();
3500        final String packageName = getDefaultBrowserPackageName(myUserId);
3501        if (packageName != null) {
3502            PackageInfo info = getPackageInfo(packageName, 0, myUserId);
3503            if (info == null) {
3504                Slog.w(TAG, "Default browser no longer installed: " + packageName);
3505                synchronized (mPackages) {
3506                    applyFactoryDefaultBrowserLPw(myUserId);    // leaves ambiguous when > 1
3507                }
3508            }
3509        }
3510    }
3511
3512    @Override
3513    public boolean onTransact(int code, Parcel data, Parcel reply, int flags)
3514            throws RemoteException {
3515        try {
3516            return super.onTransact(code, data, reply, flags);
3517        } catch (RuntimeException e) {
3518            if (!(e instanceof SecurityException) && !(e instanceof IllegalArgumentException)) {
3519                Slog.wtf(TAG, "Package Manager Crash", e);
3520            }
3521            throw e;
3522        }
3523    }
3524
3525    static int[] appendInts(int[] cur, int[] add) {
3526        if (add == null) return cur;
3527        if (cur == null) return add;
3528        final int N = add.length;
3529        for (int i=0; i<N; i++) {
3530            cur = appendInt(cur, add[i]);
3531        }
3532        return cur;
3533    }
3534
3535    /**
3536     * Returns whether or not a full application can see an instant application.
3537     * <p>
3538     * Currently, there are three cases in which this can occur:
3539     * <ol>
3540     * <li>The calling application is a "special" process. The special
3541     *     processes are {@link Process#SYSTEM_UID}, {@link Process#SHELL_UID}
3542     *     and {@code 0}</li>
3543     * <li>The calling application has the permission
3544     *     {@link android.Manifest.permission#ACCESS_INSTANT_APPS}</li>
3545     * <li>The calling application is the default launcher on the
3546     *     system partition.</li>
3547     * </ol>
3548     */
3549    private boolean canViewInstantApps(int callingUid, int userId) {
3550        if (callingUid == Process.SYSTEM_UID
3551                || callingUid == Process.SHELL_UID
3552                || callingUid == Process.ROOT_UID) {
3553            return true;
3554        }
3555        if (mContext.checkCallingOrSelfPermission(
3556                android.Manifest.permission.ACCESS_INSTANT_APPS) == PERMISSION_GRANTED) {
3557            return true;
3558        }
3559        if (mContext.checkCallingOrSelfPermission(
3560                android.Manifest.permission.VIEW_INSTANT_APPS) == PERMISSION_GRANTED) {
3561            final ComponentName homeComponent = getDefaultHomeActivity(userId);
3562            if (homeComponent != null
3563                    && isCallerSameApp(homeComponent.getPackageName(), callingUid)) {
3564                return true;
3565            }
3566        }
3567        return false;
3568    }
3569
3570    private PackageInfo generatePackageInfo(PackageSetting ps, int flags, int userId) {
3571        if (!sUserManager.exists(userId)) return null;
3572        if (ps == null) {
3573            return null;
3574        }
3575        PackageParser.Package p = ps.pkg;
3576        if (p == null) {
3577            return null;
3578        }
3579        final int callingUid = Binder.getCallingUid();
3580        // Filter out ephemeral app metadata:
3581        //   * The system/shell/root can see metadata for any app
3582        //   * An installed app can see metadata for 1) other installed apps
3583        //     and 2) ephemeral apps that have explicitly interacted with it
3584        //   * Ephemeral apps can only see their own data and exposed installed apps
3585        //   * Holding a signature permission allows seeing instant apps
3586        if (filterAppAccessLPr(ps, callingUid, userId)) {
3587            return null;
3588        }
3589
3590        final PermissionsState permissionsState = ps.getPermissionsState();
3591
3592        // Compute GIDs only if requested
3593        final int[] gids = (flags & PackageManager.GET_GIDS) == 0
3594                ? EMPTY_INT_ARRAY : permissionsState.computeGids(userId);
3595        // Compute granted permissions only if package has requested permissions
3596        final Set<String> permissions = ArrayUtils.isEmpty(p.requestedPermissions)
3597                ? Collections.<String>emptySet() : permissionsState.getPermissions(userId);
3598        final PackageUserState state = ps.readUserState(userId);
3599
3600        if ((flags & MATCH_UNINSTALLED_PACKAGES) != 0
3601                && ps.isSystem()) {
3602            flags |= MATCH_ANY_USER;
3603        }
3604
3605        PackageInfo packageInfo = PackageParser.generatePackageInfo(p, gids, flags,
3606                ps.firstInstallTime, ps.lastUpdateTime, permissions, state, userId);
3607
3608        if (packageInfo == null) {
3609            return null;
3610        }
3611
3612        packageInfo.packageName = packageInfo.applicationInfo.packageName =
3613                resolveExternalPackageNameLPr(p);
3614
3615        return packageInfo;
3616    }
3617
3618    @Override
3619    public void checkPackageStartable(String packageName, int userId) {
3620        final int callingUid = Binder.getCallingUid();
3621        if (getInstantAppPackageName(callingUid) != null) {
3622            throw new SecurityException("Instant applications don't have access to this method");
3623        }
3624        final boolean userKeyUnlocked = StorageManager.isUserKeyUnlocked(userId);
3625        synchronized (mPackages) {
3626            final PackageSetting ps = mSettings.mPackages.get(packageName);
3627            if (ps == null || filterAppAccessLPr(ps, callingUid, userId)) {
3628                throw new SecurityException("Package " + packageName + " was not found!");
3629            }
3630
3631            if (!ps.getInstalled(userId)) {
3632                throw new SecurityException(
3633                        "Package " + packageName + " was not installed for user " + userId + "!");
3634            }
3635
3636            if (mSafeMode && !ps.isSystem()) {
3637                throw new SecurityException("Package " + packageName + " not a system app!");
3638            }
3639
3640            if (mFrozenPackages.contains(packageName)) {
3641                throw new SecurityException("Package " + packageName + " is currently frozen!");
3642            }
3643
3644            if (!userKeyUnlocked && !(ps.pkg.applicationInfo.isDirectBootAware()
3645                    || ps.pkg.applicationInfo.isPartiallyDirectBootAware())) {
3646                throw new SecurityException("Package " + packageName + " is not encryption aware!");
3647            }
3648        }
3649    }
3650
3651    @Override
3652    public boolean isPackageAvailable(String packageName, int userId) {
3653        if (!sUserManager.exists(userId)) return false;
3654        final int callingUid = Binder.getCallingUid();
3655        enforceCrossUserPermission(callingUid, userId,
3656                false /*requireFullPermission*/, false /*checkShell*/, "is package available");
3657        synchronized (mPackages) {
3658            PackageParser.Package p = mPackages.get(packageName);
3659            if (p != null) {
3660                final PackageSetting ps = (PackageSetting) p.mExtras;
3661                if (filterAppAccessLPr(ps, callingUid, userId)) {
3662                    return false;
3663                }
3664                if (ps != null) {
3665                    final PackageUserState state = ps.readUserState(userId);
3666                    if (state != null) {
3667                        return PackageParser.isAvailable(state);
3668                    }
3669                }
3670            }
3671        }
3672        return false;
3673    }
3674
3675    @Override
3676    public PackageInfo getPackageInfo(String packageName, int flags, int userId) {
3677        return getPackageInfoInternal(packageName, PackageManager.VERSION_CODE_HIGHEST,
3678                flags, Binder.getCallingUid(), userId);
3679    }
3680
3681    @Override
3682    public PackageInfo getPackageInfoVersioned(VersionedPackage versionedPackage,
3683            int flags, int userId) {
3684        return getPackageInfoInternal(versionedPackage.getPackageName(),
3685                versionedPackage.getVersionCode(), flags, Binder.getCallingUid(), userId);
3686    }
3687
3688    /**
3689     * Important: The provided filterCallingUid is used exclusively to filter out packages
3690     * that can be seen based on user state. It's typically the original caller uid prior
3691     * to clearing. Because it can only be provided by trusted code, it's value can be
3692     * trusted and will be used as-is; unlike userId which will be validated by this method.
3693     */
3694    private PackageInfo getPackageInfoInternal(String packageName, int versionCode,
3695            int flags, int filterCallingUid, int userId) {
3696        if (!sUserManager.exists(userId)) return null;
3697        flags = updateFlagsForPackage(flags, userId, packageName);
3698        enforceCrossUserPermission(Binder.getCallingUid(), userId,
3699                false /* requireFullPermission */, false /* checkShell */, "get package info");
3700
3701        // reader
3702        synchronized (mPackages) {
3703            // Normalize package name to handle renamed packages and static libs
3704            packageName = resolveInternalPackageNameLPr(packageName, versionCode);
3705
3706            final boolean matchFactoryOnly = (flags & MATCH_FACTORY_ONLY) != 0;
3707            if (matchFactoryOnly) {
3708                final PackageSetting ps = mSettings.getDisabledSystemPkgLPr(packageName);
3709                if (ps != null) {
3710                    if (filterSharedLibPackageLPr(ps, filterCallingUid, userId, flags)) {
3711                        return null;
3712                    }
3713                    if (filterAppAccessLPr(ps, filterCallingUid, userId)) {
3714                        return null;
3715                    }
3716                    return generatePackageInfo(ps, flags, userId);
3717                }
3718            }
3719
3720            PackageParser.Package p = mPackages.get(packageName);
3721            if (matchFactoryOnly && p != null && !isSystemApp(p)) {
3722                return null;
3723            }
3724            if (DEBUG_PACKAGE_INFO)
3725                Log.v(TAG, "getPackageInfo " + packageName + ": " + p);
3726            if (p != null) {
3727                final PackageSetting ps = (PackageSetting) p.mExtras;
3728                if (filterSharedLibPackageLPr(ps, filterCallingUid, userId, flags)) {
3729                    return null;
3730                }
3731                if (ps != null && filterAppAccessLPr(ps, filterCallingUid, userId)) {
3732                    return null;
3733                }
3734                return generatePackageInfo((PackageSetting)p.mExtras, flags, userId);
3735            }
3736            if (!matchFactoryOnly && (flags & MATCH_KNOWN_PACKAGES) != 0) {
3737                final PackageSetting ps = mSettings.mPackages.get(packageName);
3738                if (ps == null) return null;
3739                if (filterSharedLibPackageLPr(ps, filterCallingUid, userId, flags)) {
3740                    return null;
3741                }
3742                if (filterAppAccessLPr(ps, filterCallingUid, userId)) {
3743                    return null;
3744                }
3745                return generatePackageInfo(ps, flags, userId);
3746            }
3747        }
3748        return null;
3749    }
3750
3751    private boolean isComponentVisibleToInstantApp(@Nullable ComponentName component) {
3752        if (isComponentVisibleToInstantApp(component, TYPE_ACTIVITY)) {
3753            return true;
3754        }
3755        if (isComponentVisibleToInstantApp(component, TYPE_SERVICE)) {
3756            return true;
3757        }
3758        if (isComponentVisibleToInstantApp(component, TYPE_PROVIDER)) {
3759            return true;
3760        }
3761        return false;
3762    }
3763
3764    private boolean isComponentVisibleToInstantApp(
3765            @Nullable ComponentName component, @ComponentType int type) {
3766        if (type == TYPE_ACTIVITY) {
3767            final PackageParser.Activity activity = mActivities.mActivities.get(component);
3768            return activity != null
3769                    ? (activity.info.flags & ActivityInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0
3770                    : false;
3771        } else if (type == TYPE_RECEIVER) {
3772            final PackageParser.Activity activity = mReceivers.mActivities.get(component);
3773            return activity != null
3774                    ? (activity.info.flags & ActivityInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0
3775                    : false;
3776        } else if (type == TYPE_SERVICE) {
3777            final PackageParser.Service service = mServices.mServices.get(component);
3778            return service != null
3779                    ? (service.info.flags & ServiceInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0
3780                    : false;
3781        } else if (type == TYPE_PROVIDER) {
3782            final PackageParser.Provider provider = mProviders.mProviders.get(component);
3783            return provider != null
3784                    ? (provider.info.flags & ProviderInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0
3785                    : false;
3786        } else if (type == TYPE_UNKNOWN) {
3787            return isComponentVisibleToInstantApp(component);
3788        }
3789        return false;
3790    }
3791
3792    /**
3793     * Returns whether or not access to the application should be filtered.
3794     * <p>
3795     * Access may be limited based upon whether the calling or target applications
3796     * are instant applications.
3797     *
3798     * @see #canAccessInstantApps(int)
3799     */
3800    private boolean filterAppAccessLPr(@Nullable PackageSetting ps, int callingUid,
3801            @Nullable ComponentName component, @ComponentType int componentType, int userId) {
3802        // if we're in an isolated process, get the real calling UID
3803        if (Process.isIsolated(callingUid)) {
3804            callingUid = mIsolatedOwners.get(callingUid);
3805        }
3806        final String instantAppPkgName = getInstantAppPackageName(callingUid);
3807        final boolean callerIsInstantApp = instantAppPkgName != null;
3808        if (ps == null) {
3809            if (callerIsInstantApp) {
3810                // pretend the application exists, but, needs to be filtered
3811                return true;
3812            }
3813            return false;
3814        }
3815        // if the target and caller are the same application, don't filter
3816        if (isCallerSameApp(ps.name, callingUid)) {
3817            return false;
3818        }
3819        if (callerIsInstantApp) {
3820            // request for a specific component; if it hasn't been explicitly exposed, filter
3821            if (component != null) {
3822                return !isComponentVisibleToInstantApp(component, componentType);
3823            }
3824            // request for application; if no components have been explicitly exposed, filter
3825            return ps.getInstantApp(userId) || !ps.pkg.visibleToInstantApps;
3826        }
3827        if (ps.getInstantApp(userId)) {
3828            // caller can see all components of all instant applications, don't filter
3829            if (canViewInstantApps(callingUid, userId)) {
3830                return false;
3831            }
3832            // request for a specific instant application component, filter
3833            if (component != null) {
3834                return true;
3835            }
3836            // request for an instant application; if the caller hasn't been granted access, filter
3837            return !mInstantAppRegistry.isInstantAccessGranted(
3838                    userId, UserHandle.getAppId(callingUid), ps.appId);
3839        }
3840        return false;
3841    }
3842
3843    /**
3844     * @see #filterAppAccessLPr(PackageSetting, int, ComponentName, boolean, int)
3845     */
3846    private boolean filterAppAccessLPr(@Nullable PackageSetting ps, int callingUid, int userId) {
3847        return filterAppAccessLPr(ps, callingUid, null, TYPE_UNKNOWN, userId);
3848    }
3849
3850    private boolean filterSharedLibPackageLPr(@Nullable PackageSetting ps, int uid, int userId,
3851            int flags) {
3852        // Callers can access only the libs they depend on, otherwise they need to explicitly
3853        // ask for the shared libraries given the caller is allowed to access all static libs.
3854        if ((flags & PackageManager.MATCH_STATIC_SHARED_LIBRARIES) != 0) {
3855            // System/shell/root get to see all static libs
3856            final int appId = UserHandle.getAppId(uid);
3857            if (appId == Process.SYSTEM_UID || appId == Process.SHELL_UID
3858                    || appId == Process.ROOT_UID) {
3859                return false;
3860            }
3861        }
3862
3863        // No package means no static lib as it is always on internal storage
3864        if (ps == null || ps.pkg == null || !ps.pkg.applicationInfo.isStaticSharedLibrary()) {
3865            return false;
3866        }
3867
3868        final SharedLibraryEntry libEntry = getSharedLibraryEntryLPr(ps.pkg.staticSharedLibName,
3869                ps.pkg.staticSharedLibVersion);
3870        if (libEntry == null) {
3871            return false;
3872        }
3873
3874        final int resolvedUid = UserHandle.getUid(userId, UserHandle.getAppId(uid));
3875        final String[] uidPackageNames = getPackagesForUid(resolvedUid);
3876        if (uidPackageNames == null) {
3877            return true;
3878        }
3879
3880        for (String uidPackageName : uidPackageNames) {
3881            if (ps.name.equals(uidPackageName)) {
3882                return false;
3883            }
3884            PackageSetting uidPs = mSettings.getPackageLPr(uidPackageName);
3885            if (uidPs != null) {
3886                final int index = ArrayUtils.indexOf(uidPs.usesStaticLibraries,
3887                        libEntry.info.getName());
3888                if (index < 0) {
3889                    continue;
3890                }
3891                if (uidPs.pkg.usesStaticLibrariesVersions[index] == libEntry.info.getVersion()) {
3892                    return false;
3893                }
3894            }
3895        }
3896        return true;
3897    }
3898
3899    @Override
3900    public String[] currentToCanonicalPackageNames(String[] names) {
3901        final int callingUid = Binder.getCallingUid();
3902        if (getInstantAppPackageName(callingUid) != null) {
3903            return names;
3904        }
3905        final String[] out = new String[names.length];
3906        // reader
3907        synchronized (mPackages) {
3908            final int callingUserId = UserHandle.getUserId(callingUid);
3909            final boolean canViewInstantApps = canViewInstantApps(callingUid, callingUserId);
3910            for (int i=names.length-1; i>=0; i--) {
3911                final PackageSetting ps = mSettings.mPackages.get(names[i]);
3912                boolean translateName = false;
3913                if (ps != null && ps.realName != null) {
3914                    final boolean targetIsInstantApp = ps.getInstantApp(callingUserId);
3915                    translateName = !targetIsInstantApp
3916                            || canViewInstantApps
3917                            || mInstantAppRegistry.isInstantAccessGranted(callingUserId,
3918                                    UserHandle.getAppId(callingUid), ps.appId);
3919                }
3920                out[i] = translateName ? ps.realName : names[i];
3921            }
3922        }
3923        return out;
3924    }
3925
3926    @Override
3927    public String[] canonicalToCurrentPackageNames(String[] names) {
3928        final int callingUid = Binder.getCallingUid();
3929        if (getInstantAppPackageName(callingUid) != null) {
3930            return names;
3931        }
3932        final String[] out = new String[names.length];
3933        // reader
3934        synchronized (mPackages) {
3935            final int callingUserId = UserHandle.getUserId(callingUid);
3936            final boolean canViewInstantApps = canViewInstantApps(callingUid, callingUserId);
3937            for (int i=names.length-1; i>=0; i--) {
3938                final String cur = mSettings.getRenamedPackageLPr(names[i]);
3939                boolean translateName = false;
3940                if (cur != null) {
3941                    final PackageSetting ps = mSettings.mPackages.get(names[i]);
3942                    final boolean targetIsInstantApp =
3943                            ps != null && ps.getInstantApp(callingUserId);
3944                    translateName = !targetIsInstantApp
3945                            || canViewInstantApps
3946                            || mInstantAppRegistry.isInstantAccessGranted(callingUserId,
3947                                    UserHandle.getAppId(callingUid), ps.appId);
3948                }
3949                out[i] = translateName ? cur : names[i];
3950            }
3951        }
3952        return out;
3953    }
3954
3955    @Override
3956    public int getPackageUid(String packageName, int flags, int userId) {
3957        if (!sUserManager.exists(userId)) return -1;
3958        final int callingUid = Binder.getCallingUid();
3959        flags = updateFlagsForPackage(flags, userId, packageName);
3960        enforceCrossUserPermission(callingUid, userId,
3961                false /*requireFullPermission*/, false /*checkShell*/, "getPackageUid");
3962
3963        // reader
3964        synchronized (mPackages) {
3965            final PackageParser.Package p = mPackages.get(packageName);
3966            if (p != null && p.isMatch(flags)) {
3967                PackageSetting ps = (PackageSetting) p.mExtras;
3968                if (filterAppAccessLPr(ps, callingUid, userId)) {
3969                    return -1;
3970                }
3971                return UserHandle.getUid(userId, p.applicationInfo.uid);
3972            }
3973            if ((flags & MATCH_KNOWN_PACKAGES) != 0) {
3974                final PackageSetting ps = mSettings.mPackages.get(packageName);
3975                if (ps != null && ps.isMatch(flags)
3976                        && !filterAppAccessLPr(ps, callingUid, userId)) {
3977                    return UserHandle.getUid(userId, ps.appId);
3978                }
3979            }
3980        }
3981
3982        return -1;
3983    }
3984
3985    @Override
3986    public int[] getPackageGids(String packageName, int flags, int userId) {
3987        if (!sUserManager.exists(userId)) return null;
3988        final int callingUid = Binder.getCallingUid();
3989        flags = updateFlagsForPackage(flags, userId, packageName);
3990        enforceCrossUserPermission(callingUid, userId,
3991                false /*requireFullPermission*/, false /*checkShell*/, "getPackageGids");
3992
3993        // reader
3994        synchronized (mPackages) {
3995            final PackageParser.Package p = mPackages.get(packageName);
3996            if (p != null && p.isMatch(flags)) {
3997                PackageSetting ps = (PackageSetting) p.mExtras;
3998                if (filterAppAccessLPr(ps, callingUid, userId)) {
3999                    return null;
4000                }
4001                // TODO: Shouldn't this be checking for package installed state for userId and
4002                // return null?
4003                return ps.getPermissionsState().computeGids(userId);
4004            }
4005            if ((flags & MATCH_KNOWN_PACKAGES) != 0) {
4006                final PackageSetting ps = mSettings.mPackages.get(packageName);
4007                if (ps != null && ps.isMatch(flags)
4008                        && !filterAppAccessLPr(ps, callingUid, userId)) {
4009                    return ps.getPermissionsState().computeGids(userId);
4010                }
4011            }
4012        }
4013
4014        return null;
4015    }
4016
4017    static PermissionInfo generatePermissionInfo(BasePermission bp, int flags) {
4018        if (bp.perm != null) {
4019            return PackageParser.generatePermissionInfo(bp.perm, flags);
4020        }
4021        PermissionInfo pi = new PermissionInfo();
4022        pi.name = bp.name;
4023        pi.packageName = bp.sourcePackage;
4024        pi.nonLocalizedLabel = bp.name;
4025        pi.protectionLevel = bp.protectionLevel;
4026        return pi;
4027    }
4028
4029    @Override
4030    public PermissionInfo getPermissionInfo(String name, int flags) {
4031        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
4032            return null;
4033        }
4034        // reader
4035        synchronized (mPackages) {
4036            final BasePermission p = mSettings.mPermissions.get(name);
4037            if (p != null) {
4038                return generatePermissionInfo(p, flags);
4039            }
4040            return null;
4041        }
4042    }
4043
4044    @Override
4045    public @Nullable ParceledListSlice<PermissionInfo> queryPermissionsByGroup(String group,
4046            int flags) {
4047        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
4048            return null;
4049        }
4050        // reader
4051        synchronized (mPackages) {
4052            if (group != null && !mPermissionGroups.containsKey(group)) {
4053                // This is thrown as NameNotFoundException
4054                return null;
4055            }
4056
4057            ArrayList<PermissionInfo> out = new ArrayList<PermissionInfo>(10);
4058            for (BasePermission p : mSettings.mPermissions.values()) {
4059                if (group == null) {
4060                    if (p.perm == null || p.perm.info.group == null) {
4061                        out.add(generatePermissionInfo(p, flags));
4062                    }
4063                } else {
4064                    if (p.perm != null && group.equals(p.perm.info.group)) {
4065                        out.add(PackageParser.generatePermissionInfo(p.perm, flags));
4066                    }
4067                }
4068            }
4069            return new ParceledListSlice<>(out);
4070        }
4071    }
4072
4073    @Override
4074    public PermissionGroupInfo getPermissionGroupInfo(String name, int flags) {
4075        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
4076            return null;
4077        }
4078        // reader
4079        synchronized (mPackages) {
4080            return PackageParser.generatePermissionGroupInfo(
4081                    mPermissionGroups.get(name), flags);
4082        }
4083    }
4084
4085    @Override
4086    public @NonNull ParceledListSlice<PermissionGroupInfo> getAllPermissionGroups(int flags) {
4087        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
4088            return ParceledListSlice.emptyList();
4089        }
4090        // reader
4091        synchronized (mPackages) {
4092            final int N = mPermissionGroups.size();
4093            ArrayList<PermissionGroupInfo> out
4094                    = new ArrayList<PermissionGroupInfo>(N);
4095            for (PackageParser.PermissionGroup pg : mPermissionGroups.values()) {
4096                out.add(PackageParser.generatePermissionGroupInfo(pg, flags));
4097            }
4098            return new ParceledListSlice<>(out);
4099        }
4100    }
4101
4102    private ApplicationInfo generateApplicationInfoFromSettingsLPw(String packageName, int flags,
4103            int filterCallingUid, int userId) {
4104        if (!sUserManager.exists(userId)) return null;
4105        PackageSetting ps = mSettings.mPackages.get(packageName);
4106        if (ps != null) {
4107            if (filterSharedLibPackageLPr(ps, filterCallingUid, userId, flags)) {
4108                return null;
4109            }
4110            if (filterAppAccessLPr(ps, filterCallingUid, userId)) {
4111                return null;
4112            }
4113            if (ps.pkg == null) {
4114                final PackageInfo pInfo = generatePackageInfo(ps, flags, userId);
4115                if (pInfo != null) {
4116                    return pInfo.applicationInfo;
4117                }
4118                return null;
4119            }
4120            ApplicationInfo ai = PackageParser.generateApplicationInfo(ps.pkg, flags,
4121                    ps.readUserState(userId), userId);
4122            if (ai != null) {
4123                ai.packageName = resolveExternalPackageNameLPr(ps.pkg);
4124            }
4125            return ai;
4126        }
4127        return null;
4128    }
4129
4130    @Override
4131    public ApplicationInfo getApplicationInfo(String packageName, int flags, int userId) {
4132        return getApplicationInfoInternal(packageName, flags, Binder.getCallingUid(), userId);
4133    }
4134
4135    /**
4136     * Important: The provided filterCallingUid is used exclusively to filter out applications
4137     * that can be seen based on user state. It's typically the original caller uid prior
4138     * to clearing. Because it can only be provided by trusted code, it's value can be
4139     * trusted and will be used as-is; unlike userId which will be validated by this method.
4140     */
4141    private ApplicationInfo getApplicationInfoInternal(String packageName, int flags,
4142            int filterCallingUid, int userId) {
4143        if (!sUserManager.exists(userId)) return null;
4144        flags = updateFlagsForApplication(flags, userId, packageName);
4145        enforceCrossUserPermission(Binder.getCallingUid(), userId,
4146                false /* requireFullPermission */, false /* checkShell */, "get application info");
4147
4148        // writer
4149        synchronized (mPackages) {
4150            // Normalize package name to handle renamed packages and static libs
4151            packageName = resolveInternalPackageNameLPr(packageName,
4152                    PackageManager.VERSION_CODE_HIGHEST);
4153
4154            PackageParser.Package p = mPackages.get(packageName);
4155            if (DEBUG_PACKAGE_INFO) Log.v(
4156                    TAG, "getApplicationInfo " + packageName
4157                    + ": " + p);
4158            if (p != null) {
4159                PackageSetting ps = mSettings.mPackages.get(packageName);
4160                if (ps == null) return null;
4161                if (filterSharedLibPackageLPr(ps, filterCallingUid, userId, flags)) {
4162                    return null;
4163                }
4164                if (filterAppAccessLPr(ps, filterCallingUid, userId)) {
4165                    return null;
4166                }
4167                // Note: isEnabledLP() does not apply here - always return info
4168                ApplicationInfo ai = PackageParser.generateApplicationInfo(
4169                        p, flags, ps.readUserState(userId), userId);
4170                if (ai != null) {
4171                    ai.packageName = resolveExternalPackageNameLPr(p);
4172                }
4173                return ai;
4174            }
4175            if ("android".equals(packageName)||"system".equals(packageName)) {
4176                return mAndroidApplication;
4177            }
4178            if ((flags & MATCH_KNOWN_PACKAGES) != 0) {
4179                // Already generates the external package name
4180                return generateApplicationInfoFromSettingsLPw(packageName,
4181                        flags, filterCallingUid, userId);
4182            }
4183        }
4184        return null;
4185    }
4186
4187    private String normalizePackageNameLPr(String packageName) {
4188        String normalizedPackageName = mSettings.getRenamedPackageLPr(packageName);
4189        return normalizedPackageName != null ? normalizedPackageName : packageName;
4190    }
4191
4192    @Override
4193    public void deletePreloadsFileCache() {
4194        if (!UserHandle.isSameApp(Binder.getCallingUid(), Process.SYSTEM_UID)) {
4195            throw new SecurityException("Only system or settings may call deletePreloadsFileCache");
4196        }
4197        File dir = Environment.getDataPreloadsFileCacheDirectory();
4198        Slog.i(TAG, "Deleting preloaded file cache " + dir);
4199        FileUtils.deleteContents(dir);
4200    }
4201
4202    @Override
4203    public void freeStorageAndNotify(final String volumeUuid, final long freeStorageSize,
4204            final int storageFlags, final IPackageDataObserver observer) {
4205        mContext.enforceCallingOrSelfPermission(
4206                android.Manifest.permission.CLEAR_APP_CACHE, null);
4207        mHandler.post(() -> {
4208            boolean success = false;
4209            try {
4210                freeStorage(volumeUuid, freeStorageSize, storageFlags);
4211                success = true;
4212            } catch (IOException e) {
4213                Slog.w(TAG, e);
4214            }
4215            if (observer != null) {
4216                try {
4217                    observer.onRemoveCompleted(null, success);
4218                } catch (RemoteException e) {
4219                    Slog.w(TAG, e);
4220                }
4221            }
4222        });
4223    }
4224
4225    @Override
4226    public void freeStorage(final String volumeUuid, final long freeStorageSize,
4227            final int storageFlags, final IntentSender pi) {
4228        mContext.enforceCallingOrSelfPermission(
4229                android.Manifest.permission.CLEAR_APP_CACHE, TAG);
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 (pi != null) {
4239                try {
4240                    pi.sendIntent(null, success ? 1 : 0, null, null, null);
4241                } catch (SendIntentException e) {
4242                    Slog.w(TAG, e);
4243                }
4244            }
4245        });
4246    }
4247
4248    /**
4249     * Blocking call to clear various types of cached data across the system
4250     * until the requested bytes are available.
4251     */
4252    public void freeStorage(String volumeUuid, long bytes, int storageFlags) throws IOException {
4253        final StorageManager storage = mContext.getSystemService(StorageManager.class);
4254        final File file = storage.findPathForUuid(volumeUuid);
4255        if (file.getUsableSpace() >= bytes) return;
4256
4257        if (ENABLE_FREE_CACHE_V2) {
4258            final boolean internalVolume = Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL,
4259                    volumeUuid);
4260            final boolean aggressive = (storageFlags
4261                    & StorageManager.FLAG_ALLOCATE_AGGRESSIVE) != 0;
4262            final long reservedBytes = storage.getStorageCacheBytes(file, storageFlags);
4263
4264            // 1. Pre-flight to determine if we have any chance to succeed
4265            // 2. Consider preloaded data (after 1w honeymoon, unless aggressive)
4266            if (internalVolume && (aggressive || SystemProperties
4267                    .getBoolean("persist.sys.preloads.file_cache_expired", false))) {
4268                deletePreloadsFileCache();
4269                if (file.getUsableSpace() >= bytes) return;
4270            }
4271
4272            // 3. Consider parsed APK data (aggressive only)
4273            if (internalVolume && aggressive) {
4274                FileUtils.deleteContents(mCacheDir);
4275                if (file.getUsableSpace() >= bytes) return;
4276            }
4277
4278            // 4. Consider cached app data (above quotas)
4279            try {
4280                mInstaller.freeCache(volumeUuid, bytes, reservedBytes,
4281                        Installer.FLAG_FREE_CACHE_V2);
4282            } catch (InstallerException ignored) {
4283            }
4284            if (file.getUsableSpace() >= bytes) return;
4285
4286            // 5. Consider shared libraries with refcount=0 and age>min cache period
4287            if (internalVolume && pruneUnusedStaticSharedLibraries(bytes,
4288                    android.provider.Settings.Global.getLong(mContext.getContentResolver(),
4289                            Global.UNUSED_STATIC_SHARED_LIB_MIN_CACHE_PERIOD,
4290                            DEFAULT_UNUSED_STATIC_SHARED_LIB_MIN_CACHE_PERIOD))) {
4291                return;
4292            }
4293
4294            // 6. Consider dexopt output (aggressive only)
4295            // TODO: Implement
4296
4297            // 7. Consider installed instant apps unused longer than min cache period
4298            if (internalVolume && mInstantAppRegistry.pruneInstalledInstantApps(bytes,
4299                    android.provider.Settings.Global.getLong(mContext.getContentResolver(),
4300                            Global.INSTALLED_INSTANT_APP_MIN_CACHE_PERIOD,
4301                            InstantAppRegistry.DEFAULT_INSTALLED_INSTANT_APP_MIN_CACHE_PERIOD))) {
4302                return;
4303            }
4304
4305            // 8. Consider cached app data (below quotas)
4306            try {
4307                mInstaller.freeCache(volumeUuid, bytes, reservedBytes,
4308                        Installer.FLAG_FREE_CACHE_V2 | Installer.FLAG_FREE_CACHE_V2_DEFY_QUOTA);
4309            } catch (InstallerException ignored) {
4310            }
4311            if (file.getUsableSpace() >= bytes) return;
4312
4313            // 9. Consider DropBox entries
4314            // TODO: Implement
4315
4316            // 10. Consider instant meta-data (uninstalled apps) older that min cache period
4317            if (internalVolume && mInstantAppRegistry.pruneUninstalledInstantApps(bytes,
4318                    android.provider.Settings.Global.getLong(mContext.getContentResolver(),
4319                            Global.UNINSTALLED_INSTANT_APP_MIN_CACHE_PERIOD,
4320                            InstantAppRegistry.DEFAULT_UNINSTALLED_INSTANT_APP_MIN_CACHE_PERIOD))) {
4321                return;
4322            }
4323        } else {
4324            try {
4325                mInstaller.freeCache(volumeUuid, bytes, 0, 0);
4326            } catch (InstallerException ignored) {
4327            }
4328            if (file.getUsableSpace() >= bytes) return;
4329        }
4330
4331        throw new IOException("Failed to free " + bytes + " on storage device at " + file);
4332    }
4333
4334    private boolean pruneUnusedStaticSharedLibraries(long neededSpace, long maxCachePeriod)
4335            throws IOException {
4336        final StorageManager storage = mContext.getSystemService(StorageManager.class);
4337        final File volume = storage.findPathForUuid(StorageManager.UUID_PRIVATE_INTERNAL);
4338
4339        List<VersionedPackage> packagesToDelete = null;
4340        final long now = System.currentTimeMillis();
4341
4342        synchronized (mPackages) {
4343            final int[] allUsers = sUserManager.getUserIds();
4344            final int libCount = mSharedLibraries.size();
4345            for (int i = 0; i < libCount; i++) {
4346                final SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.valueAt(i);
4347                if (versionedLib == null) {
4348                    continue;
4349                }
4350                final int versionCount = versionedLib.size();
4351                for (int j = 0; j < versionCount; j++) {
4352                    SharedLibraryInfo libInfo = versionedLib.valueAt(j).info;
4353                    // Skip packages that are not static shared libs.
4354                    if (!libInfo.isStatic()) {
4355                        break;
4356                    }
4357                    // Important: We skip static shared libs used for some user since
4358                    // in such a case we need to keep the APK on the device. The check for
4359                    // a lib being used for any user is performed by the uninstall call.
4360                    final VersionedPackage declaringPackage = libInfo.getDeclaringPackage();
4361                    // Resolve the package name - we use synthetic package names internally
4362                    final String internalPackageName = resolveInternalPackageNameLPr(
4363                            declaringPackage.getPackageName(), declaringPackage.getVersionCode());
4364                    final PackageSetting ps = mSettings.getPackageLPr(internalPackageName);
4365                    // Skip unused static shared libs cached less than the min period
4366                    // to prevent pruning a lib needed by a subsequently installed package.
4367                    if (ps == null || now - ps.lastUpdateTime < maxCachePeriod) {
4368                        continue;
4369                    }
4370                    if (packagesToDelete == null) {
4371                        packagesToDelete = new ArrayList<>();
4372                    }
4373                    packagesToDelete.add(new VersionedPackage(internalPackageName,
4374                            declaringPackage.getVersionCode()));
4375                }
4376            }
4377        }
4378
4379        if (packagesToDelete != null) {
4380            final int packageCount = packagesToDelete.size();
4381            for (int i = 0; i < packageCount; i++) {
4382                final VersionedPackage pkgToDelete = packagesToDelete.get(i);
4383                // Delete the package synchronously (will fail of the lib used for any user).
4384                if (deletePackageX(pkgToDelete.getPackageName(), pkgToDelete.getVersionCode(),
4385                        UserHandle.USER_SYSTEM, PackageManager.DELETE_ALL_USERS)
4386                                == PackageManager.DELETE_SUCCEEDED) {
4387                    if (volume.getUsableSpace() >= neededSpace) {
4388                        return true;
4389                    }
4390                }
4391            }
4392        }
4393
4394        return false;
4395    }
4396
4397    /**
4398     * Update given flags based on encryption status of current user.
4399     */
4400    private int updateFlags(int flags, int userId) {
4401        if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE
4402                | PackageManager.MATCH_DIRECT_BOOT_AWARE)) != 0) {
4403            // Caller expressed an explicit opinion about what encryption
4404            // aware/unaware components they want to see, so fall through and
4405            // give them what they want
4406        } else {
4407            // Caller expressed no opinion, so match based on user state
4408            if (getUserManagerInternal().isUserUnlockingOrUnlocked(userId)) {
4409                flags |= PackageManager.MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE;
4410            } else {
4411                flags |= PackageManager.MATCH_DIRECT_BOOT_AWARE;
4412            }
4413        }
4414        return flags;
4415    }
4416
4417    private UserManagerInternal getUserManagerInternal() {
4418        if (mUserManagerInternal == null) {
4419            mUserManagerInternal = LocalServices.getService(UserManagerInternal.class);
4420        }
4421        return mUserManagerInternal;
4422    }
4423
4424    private DeviceIdleController.LocalService getDeviceIdleController() {
4425        if (mDeviceIdleController == null) {
4426            mDeviceIdleController =
4427                    LocalServices.getService(DeviceIdleController.LocalService.class);
4428        }
4429        return mDeviceIdleController;
4430    }
4431
4432    /**
4433     * Update given flags when being used to request {@link PackageInfo}.
4434     */
4435    private int updateFlagsForPackage(int flags, int userId, Object cookie) {
4436        final boolean isCallerSystemUser = UserHandle.getCallingUserId() == UserHandle.USER_SYSTEM;
4437        boolean triaged = true;
4438        if ((flags & (PackageManager.GET_ACTIVITIES | PackageManager.GET_RECEIVERS
4439                | PackageManager.GET_SERVICES | PackageManager.GET_PROVIDERS)) != 0) {
4440            // Caller is asking for component details, so they'd better be
4441            // asking for specific encryption matching behavior, or be triaged
4442            if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE
4443                    | PackageManager.MATCH_DIRECT_BOOT_AWARE
4444                    | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) {
4445                triaged = false;
4446            }
4447        }
4448        if ((flags & (PackageManager.MATCH_UNINSTALLED_PACKAGES
4449                | PackageManager.MATCH_SYSTEM_ONLY
4450                | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) {
4451            triaged = false;
4452        }
4453        if ((flags & PackageManager.MATCH_ANY_USER) != 0) {
4454            enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false,
4455                    "MATCH_ANY_USER flag requires INTERACT_ACROSS_USERS permission at "
4456                    + Debug.getCallers(5));
4457        } else if ((flags & PackageManager.MATCH_UNINSTALLED_PACKAGES) != 0 && isCallerSystemUser
4458                && sUserManager.hasManagedProfile(UserHandle.USER_SYSTEM)) {
4459            // If the caller wants all packages and has a restricted profile associated with it,
4460            // then match all users. This is to make sure that launchers that need to access work
4461            // profile apps don't start breaking. TODO: Remove this hack when launchers stop using
4462            // MATCH_UNINSTALLED_PACKAGES to query apps in other profiles. b/31000380
4463            flags |= PackageManager.MATCH_ANY_USER;
4464        }
4465        if (DEBUG_TRIAGED_MISSING && (Binder.getCallingUid() == Process.SYSTEM_UID) && !triaged) {
4466            Log.w(TAG, "Caller hasn't been triaged for missing apps; they asked about " + cookie
4467                    + " with flags 0x" + Integer.toHexString(flags), new Throwable());
4468        }
4469        return updateFlags(flags, userId);
4470    }
4471
4472    /**
4473     * Update given flags when being used to request {@link ApplicationInfo}.
4474     */
4475    private int updateFlagsForApplication(int flags, int userId, Object cookie) {
4476        return updateFlagsForPackage(flags, userId, cookie);
4477    }
4478
4479    /**
4480     * Update given flags when being used to request {@link ComponentInfo}.
4481     */
4482    private int updateFlagsForComponent(int flags, int userId, Object cookie) {
4483        if (cookie instanceof Intent) {
4484            if ((((Intent) cookie).getFlags() & Intent.FLAG_DEBUG_TRIAGED_MISSING) != 0) {
4485                flags |= PackageManager.MATCH_DEBUG_TRIAGED_MISSING;
4486            }
4487        }
4488
4489        boolean triaged = true;
4490        // Caller is asking for component details, so they'd better be
4491        // asking for specific encryption matching behavior, or be triaged
4492        if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE
4493                | PackageManager.MATCH_DIRECT_BOOT_AWARE
4494                | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) {
4495            triaged = false;
4496        }
4497        if (DEBUG_TRIAGED_MISSING && (Binder.getCallingUid() == Process.SYSTEM_UID) && !triaged) {
4498            Log.w(TAG, "Caller hasn't been triaged for missing apps; they asked about " + cookie
4499                    + " with flags 0x" + Integer.toHexString(flags), new Throwable());
4500        }
4501
4502        return updateFlags(flags, userId);
4503    }
4504
4505    /**
4506     * Update given intent when being used to request {@link ResolveInfo}.
4507     */
4508    private Intent updateIntentForResolve(Intent intent) {
4509        if (intent.getSelector() != null) {
4510            intent = intent.getSelector();
4511        }
4512        if (DEBUG_PREFERRED) {
4513            intent.addFlags(Intent.FLAG_DEBUG_LOG_RESOLUTION);
4514        }
4515        return intent;
4516    }
4517
4518    /**
4519     * Update given flags when being used to request {@link ResolveInfo}.
4520     * <p>Instant apps are resolved specially, depending upon context. Minimally,
4521     * {@code}flags{@code} must have the {@link PackageManager#MATCH_INSTANT}
4522     * flag set. However, this flag is only honoured in three circumstances:
4523     * <ul>
4524     * <li>when called from a system process</li>
4525     * <li>when the caller holds the permission {@code android.permission.ACCESS_INSTANT_APPS}</li>
4526     * <li>when resolution occurs to start an activity with a {@code android.intent.action.VIEW}
4527     * action and a {@code android.intent.category.BROWSABLE} category</li>
4528     * </ul>
4529     */
4530    int updateFlagsForResolve(int flags, int userId, Intent intent, int callingUid) {
4531        return updateFlagsForResolve(flags, userId, intent, callingUid,
4532                false /*wantInstantApps*/, false /*onlyExposedExplicitly*/);
4533    }
4534    int updateFlagsForResolve(int flags, int userId, Intent intent, int callingUid,
4535            boolean wantInstantApps) {
4536        return updateFlagsForResolve(flags, userId, intent, callingUid,
4537                wantInstantApps, false /*onlyExposedExplicitly*/);
4538    }
4539    int updateFlagsForResolve(int flags, int userId, Intent intent, int callingUid,
4540            boolean wantInstantApps, boolean onlyExposedExplicitly) {
4541        // Safe mode means we shouldn't match any third-party components
4542        if (mSafeMode) {
4543            flags |= PackageManager.MATCH_SYSTEM_ONLY;
4544        }
4545        if (getInstantAppPackageName(callingUid) != null) {
4546            // But, ephemeral apps see both ephemeral and exposed, non-ephemeral components
4547            if (onlyExposedExplicitly) {
4548                flags |= PackageManager.MATCH_EXPLICITLY_VISIBLE_ONLY;
4549            }
4550            flags |= PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY;
4551            flags |= PackageManager.MATCH_INSTANT;
4552        } else {
4553            final boolean wantMatchInstant = (flags & PackageManager.MATCH_INSTANT) != 0;
4554            final boolean allowMatchInstant =
4555                    (wantInstantApps
4556                            && Intent.ACTION_VIEW.equals(intent.getAction())
4557                            && hasWebURI(intent))
4558                    || (wantMatchInstant && canViewInstantApps(callingUid, userId));
4559            flags &= ~(PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY
4560                    | PackageManager.MATCH_EXPLICITLY_VISIBLE_ONLY);
4561            if (!allowMatchInstant) {
4562                flags &= ~PackageManager.MATCH_INSTANT;
4563            }
4564        }
4565        return updateFlagsForComponent(flags, userId, intent /*cookie*/);
4566    }
4567
4568    @Override
4569    public ActivityInfo getActivityInfo(ComponentName component, int flags, int userId) {
4570        return getActivityInfoInternal(component, flags, Binder.getCallingUid(), userId);
4571    }
4572
4573    /**
4574     * Important: The provided filterCallingUid is used exclusively to filter out activities
4575     * that can be seen based on user state. It's typically the original caller uid prior
4576     * to clearing. Because it can only be provided by trusted code, it's value can be
4577     * trusted and will be used as-is; unlike userId which will be validated by this method.
4578     */
4579    private ActivityInfo getActivityInfoInternal(ComponentName component, int flags,
4580            int filterCallingUid, int userId) {
4581        if (!sUserManager.exists(userId)) return null;
4582        flags = updateFlagsForComponent(flags, userId, component);
4583        enforceCrossUserPermission(Binder.getCallingUid(), userId,
4584                false /* requireFullPermission */, false /* checkShell */, "get activity info");
4585        synchronized (mPackages) {
4586            PackageParser.Activity a = mActivities.mActivities.get(component);
4587
4588            if (DEBUG_PACKAGE_INFO) Log.v(TAG, "getActivityInfo " + component + ": " + a);
4589            if (a != null && mSettings.isEnabledAndMatchLPr(a.info, flags, userId)) {
4590                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
4591                if (ps == null) return null;
4592                if (filterAppAccessLPr(ps, filterCallingUid, component, TYPE_ACTIVITY, userId)) {
4593                    return null;
4594                }
4595                return PackageParser.generateActivityInfo(
4596                        a, flags, ps.readUserState(userId), userId);
4597            }
4598            if (mResolveComponentName.equals(component)) {
4599                return PackageParser.generateActivityInfo(
4600                        mResolveActivity, flags, new PackageUserState(), userId);
4601            }
4602        }
4603        return null;
4604    }
4605
4606    @Override
4607    public boolean activitySupportsIntent(ComponentName component, Intent intent,
4608            String resolvedType) {
4609        synchronized (mPackages) {
4610            if (component.equals(mResolveComponentName)) {
4611                // The resolver supports EVERYTHING!
4612                return true;
4613            }
4614            final int callingUid = Binder.getCallingUid();
4615            final int callingUserId = UserHandle.getUserId(callingUid);
4616            PackageParser.Activity a = mActivities.mActivities.get(component);
4617            if (a == null) {
4618                return false;
4619            }
4620            PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
4621            if (ps == null) {
4622                return false;
4623            }
4624            if (filterAppAccessLPr(ps, callingUid, component, TYPE_ACTIVITY, callingUserId)) {
4625                return false;
4626            }
4627            for (int i=0; i<a.intents.size(); i++) {
4628                if (a.intents.get(i).match(intent.getAction(), resolvedType, intent.getScheme(),
4629                        intent.getData(), intent.getCategories(), TAG) >= 0) {
4630                    return true;
4631                }
4632            }
4633            return false;
4634        }
4635    }
4636
4637    @Override
4638    public ActivityInfo getReceiverInfo(ComponentName component, int flags, int userId) {
4639        if (!sUserManager.exists(userId)) return null;
4640        final int callingUid = Binder.getCallingUid();
4641        flags = updateFlagsForComponent(flags, userId, component);
4642        enforceCrossUserPermission(callingUid, userId,
4643                false /* requireFullPermission */, false /* checkShell */, "get receiver info");
4644        synchronized (mPackages) {
4645            PackageParser.Activity a = mReceivers.mActivities.get(component);
4646            if (DEBUG_PACKAGE_INFO) Log.v(
4647                TAG, "getReceiverInfo " + component + ": " + a);
4648            if (a != null && mSettings.isEnabledAndMatchLPr(a.info, flags, userId)) {
4649                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
4650                if (ps == null) return null;
4651                if (filterAppAccessLPr(ps, callingUid, component, TYPE_RECEIVER, userId)) {
4652                    return null;
4653                }
4654                return PackageParser.generateActivityInfo(
4655                        a, flags, ps.readUserState(userId), userId);
4656            }
4657        }
4658        return null;
4659    }
4660
4661    @Override
4662    public ParceledListSlice<SharedLibraryInfo> getSharedLibraries(String packageName,
4663            int flags, int userId) {
4664        if (!sUserManager.exists(userId)) return null;
4665        Preconditions.checkArgumentNonnegative(userId, "userId must be >= 0");
4666        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
4667            return null;
4668        }
4669
4670        flags = updateFlagsForPackage(flags, userId, null);
4671
4672        final boolean canSeeStaticLibraries =
4673                mContext.checkCallingOrSelfPermission(INSTALL_PACKAGES)
4674                        == PERMISSION_GRANTED
4675                || mContext.checkCallingOrSelfPermission(DELETE_PACKAGES)
4676                        == PERMISSION_GRANTED
4677                || canRequestPackageInstallsInternal(packageName,
4678                        PackageManager.MATCH_STATIC_SHARED_LIBRARIES, userId,
4679                        false  /* throwIfPermNotDeclared*/)
4680                || mContext.checkCallingOrSelfPermission(REQUEST_DELETE_PACKAGES)
4681                        == PERMISSION_GRANTED;
4682
4683        synchronized (mPackages) {
4684            List<SharedLibraryInfo> result = null;
4685
4686            final int libCount = mSharedLibraries.size();
4687            for (int i = 0; i < libCount; i++) {
4688                SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.valueAt(i);
4689                if (versionedLib == null) {
4690                    continue;
4691                }
4692
4693                final int versionCount = versionedLib.size();
4694                for (int j = 0; j < versionCount; j++) {
4695                    SharedLibraryInfo libInfo = versionedLib.valueAt(j).info;
4696                    if (!canSeeStaticLibraries && libInfo.isStatic()) {
4697                        break;
4698                    }
4699                    final long identity = Binder.clearCallingIdentity();
4700                    try {
4701                        PackageInfo packageInfo = getPackageInfoVersioned(
4702                                libInfo.getDeclaringPackage(), flags
4703                                        | PackageManager.MATCH_STATIC_SHARED_LIBRARIES, userId);
4704                        if (packageInfo == null) {
4705                            continue;
4706                        }
4707                    } finally {
4708                        Binder.restoreCallingIdentity(identity);
4709                    }
4710
4711                    SharedLibraryInfo resLibInfo = new SharedLibraryInfo(libInfo.getName(),
4712                            libInfo.getVersion(), libInfo.getType(),
4713                            libInfo.getDeclaringPackage(), getPackagesUsingSharedLibraryLPr(libInfo,
4714                            flags, userId));
4715
4716                    if (result == null) {
4717                        result = new ArrayList<>();
4718                    }
4719                    result.add(resLibInfo);
4720                }
4721            }
4722
4723            return result != null ? new ParceledListSlice<>(result) : null;
4724        }
4725    }
4726
4727    private List<VersionedPackage> getPackagesUsingSharedLibraryLPr(
4728            SharedLibraryInfo libInfo, int flags, int userId) {
4729        List<VersionedPackage> versionedPackages = null;
4730        final int packageCount = mSettings.mPackages.size();
4731        for (int i = 0; i < packageCount; i++) {
4732            PackageSetting ps = mSettings.mPackages.valueAt(i);
4733
4734            if (ps == null) {
4735                continue;
4736            }
4737
4738            if (!ps.getUserState().get(userId).isAvailable(flags)) {
4739                continue;
4740            }
4741
4742            final String libName = libInfo.getName();
4743            if (libInfo.isStatic()) {
4744                final int libIdx = ArrayUtils.indexOf(ps.usesStaticLibraries, libName);
4745                if (libIdx < 0) {
4746                    continue;
4747                }
4748                if (ps.usesStaticLibrariesVersions[libIdx] != libInfo.getVersion()) {
4749                    continue;
4750                }
4751                if (versionedPackages == null) {
4752                    versionedPackages = new ArrayList<>();
4753                }
4754                // If the dependent is a static shared lib, use the public package name
4755                String dependentPackageName = ps.name;
4756                if (ps.pkg != null && ps.pkg.applicationInfo.isStaticSharedLibrary()) {
4757                    dependentPackageName = ps.pkg.manifestPackageName;
4758                }
4759                versionedPackages.add(new VersionedPackage(dependentPackageName, ps.versionCode));
4760            } else if (ps.pkg != null) {
4761                if (ArrayUtils.contains(ps.pkg.usesLibraries, libName)
4762                        || ArrayUtils.contains(ps.pkg.usesOptionalLibraries, libName)) {
4763                    if (versionedPackages == null) {
4764                        versionedPackages = new ArrayList<>();
4765                    }
4766                    versionedPackages.add(new VersionedPackage(ps.name, ps.versionCode));
4767                }
4768            }
4769        }
4770
4771        return versionedPackages;
4772    }
4773
4774    @Override
4775    public ServiceInfo getServiceInfo(ComponentName component, int flags, int userId) {
4776        if (!sUserManager.exists(userId)) return null;
4777        final int callingUid = Binder.getCallingUid();
4778        flags = updateFlagsForComponent(flags, userId, component);
4779        enforceCrossUserPermission(callingUid, userId,
4780                false /* requireFullPermission */, false /* checkShell */, "get service info");
4781        synchronized (mPackages) {
4782            PackageParser.Service s = mServices.mServices.get(component);
4783            if (DEBUG_PACKAGE_INFO) Log.v(
4784                TAG, "getServiceInfo " + component + ": " + s);
4785            if (s != null && mSettings.isEnabledAndMatchLPr(s.info, flags, userId)) {
4786                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
4787                if (ps == null) return null;
4788                if (filterAppAccessLPr(ps, callingUid, component, TYPE_SERVICE, userId)) {
4789                    return null;
4790                }
4791                return PackageParser.generateServiceInfo(
4792                        s, flags, ps.readUserState(userId), userId);
4793            }
4794        }
4795        return null;
4796    }
4797
4798    @Override
4799    public ProviderInfo getProviderInfo(ComponentName component, int flags, int userId) {
4800        if (!sUserManager.exists(userId)) return null;
4801        final int callingUid = Binder.getCallingUid();
4802        flags = updateFlagsForComponent(flags, userId, component);
4803        enforceCrossUserPermission(callingUid, userId,
4804                false /* requireFullPermission */, false /* checkShell */, "get provider info");
4805        synchronized (mPackages) {
4806            PackageParser.Provider p = mProviders.mProviders.get(component);
4807            if (DEBUG_PACKAGE_INFO) Log.v(
4808                TAG, "getProviderInfo " + component + ": " + p);
4809            if (p != null && mSettings.isEnabledAndMatchLPr(p.info, flags, userId)) {
4810                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
4811                if (ps == null) return null;
4812                if (filterAppAccessLPr(ps, callingUid, component, TYPE_PROVIDER, userId)) {
4813                    return null;
4814                }
4815                return PackageParser.generateProviderInfo(
4816                        p, flags, ps.readUserState(userId), userId);
4817            }
4818        }
4819        return null;
4820    }
4821
4822    @Override
4823    public String[] getSystemSharedLibraryNames() {
4824        // allow instant applications
4825        synchronized (mPackages) {
4826            Set<String> libs = null;
4827            final int libCount = mSharedLibraries.size();
4828            for (int i = 0; i < libCount; i++) {
4829                SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.valueAt(i);
4830                if (versionedLib == null) {
4831                    continue;
4832                }
4833                final int versionCount = versionedLib.size();
4834                for (int j = 0; j < versionCount; j++) {
4835                    SharedLibraryEntry libEntry = versionedLib.valueAt(j);
4836                    if (!libEntry.info.isStatic()) {
4837                        if (libs == null) {
4838                            libs = new ArraySet<>();
4839                        }
4840                        libs.add(libEntry.info.getName());
4841                        break;
4842                    }
4843                    PackageSetting ps = mSettings.getPackageLPr(libEntry.apk);
4844                    if (ps != null && !filterSharedLibPackageLPr(ps, Binder.getCallingUid(),
4845                            UserHandle.getUserId(Binder.getCallingUid()),
4846                            PackageManager.MATCH_STATIC_SHARED_LIBRARIES)) {
4847                        if (libs == null) {
4848                            libs = new ArraySet<>();
4849                        }
4850                        libs.add(libEntry.info.getName());
4851                        break;
4852                    }
4853                }
4854            }
4855
4856            if (libs != null) {
4857                String[] libsArray = new String[libs.size()];
4858                libs.toArray(libsArray);
4859                return libsArray;
4860            }
4861
4862            return null;
4863        }
4864    }
4865
4866    @Override
4867    public @NonNull String getServicesSystemSharedLibraryPackageName() {
4868        // allow instant applications
4869        synchronized (mPackages) {
4870            return mServicesSystemSharedLibraryPackageName;
4871        }
4872    }
4873
4874    @Override
4875    public @NonNull String getSharedSystemSharedLibraryPackageName() {
4876        // allow instant applications
4877        synchronized (mPackages) {
4878            return mSharedSystemSharedLibraryPackageName;
4879        }
4880    }
4881
4882    private void updateSequenceNumberLP(PackageSetting pkgSetting, int[] userList) {
4883        for (int i = userList.length - 1; i >= 0; --i) {
4884            final int userId = userList[i];
4885            // don't add instant app to the list of updates
4886            if (pkgSetting.getInstantApp(userId)) {
4887                continue;
4888            }
4889            SparseArray<String> changedPackages = mChangedPackages.get(userId);
4890            if (changedPackages == null) {
4891                changedPackages = new SparseArray<>();
4892                mChangedPackages.put(userId, changedPackages);
4893            }
4894            Map<String, Integer> sequenceNumbers = mChangedPackagesSequenceNumbers.get(userId);
4895            if (sequenceNumbers == null) {
4896                sequenceNumbers = new HashMap<>();
4897                mChangedPackagesSequenceNumbers.put(userId, sequenceNumbers);
4898            }
4899            final Integer sequenceNumber = sequenceNumbers.get(pkgSetting.name);
4900            if (sequenceNumber != null) {
4901                changedPackages.remove(sequenceNumber);
4902            }
4903            changedPackages.put(mChangedPackagesSequenceNumber, pkgSetting.name);
4904            sequenceNumbers.put(pkgSetting.name, mChangedPackagesSequenceNumber);
4905        }
4906        mChangedPackagesSequenceNumber++;
4907    }
4908
4909    @Override
4910    public ChangedPackages getChangedPackages(int sequenceNumber, int userId) {
4911        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
4912            return null;
4913        }
4914        synchronized (mPackages) {
4915            if (sequenceNumber >= mChangedPackagesSequenceNumber) {
4916                return null;
4917            }
4918            final SparseArray<String> changedPackages = mChangedPackages.get(userId);
4919            if (changedPackages == null) {
4920                return null;
4921            }
4922            final List<String> packageNames =
4923                    new ArrayList<>(mChangedPackagesSequenceNumber - sequenceNumber);
4924            for (int i = sequenceNumber; i < mChangedPackagesSequenceNumber; i++) {
4925                final String packageName = changedPackages.get(i);
4926                if (packageName != null) {
4927                    packageNames.add(packageName);
4928                }
4929            }
4930            return packageNames.isEmpty()
4931                    ? null : new ChangedPackages(mChangedPackagesSequenceNumber, packageNames);
4932        }
4933    }
4934
4935    @Override
4936    public @NonNull ParceledListSlice<FeatureInfo> getSystemAvailableFeatures() {
4937        // allow instant applications
4938        ArrayList<FeatureInfo> res;
4939        synchronized (mAvailableFeatures) {
4940            res = new ArrayList<>(mAvailableFeatures.size() + 1);
4941            res.addAll(mAvailableFeatures.values());
4942        }
4943        final FeatureInfo fi = new FeatureInfo();
4944        fi.reqGlEsVersion = SystemProperties.getInt("ro.opengles.version",
4945                FeatureInfo.GL_ES_VERSION_UNDEFINED);
4946        res.add(fi);
4947
4948        return new ParceledListSlice<>(res);
4949    }
4950
4951    @Override
4952    public boolean hasSystemFeature(String name, int version) {
4953        // allow instant applications
4954        synchronized (mAvailableFeatures) {
4955            final FeatureInfo feat = mAvailableFeatures.get(name);
4956            if (feat == null) {
4957                return false;
4958            } else {
4959                return feat.version >= version;
4960            }
4961        }
4962    }
4963
4964    @Override
4965    public int checkPermission(String permName, String pkgName, int userId) {
4966        if (!sUserManager.exists(userId)) {
4967            return PackageManager.PERMISSION_DENIED;
4968        }
4969        final int callingUid = Binder.getCallingUid();
4970
4971        synchronized (mPackages) {
4972            final PackageParser.Package p = mPackages.get(pkgName);
4973            if (p != null && p.mExtras != null) {
4974                final PackageSetting ps = (PackageSetting) p.mExtras;
4975                if (filterAppAccessLPr(ps, callingUid, userId)) {
4976                    return PackageManager.PERMISSION_DENIED;
4977                }
4978                final boolean instantApp = ps.getInstantApp(userId);
4979                final PermissionsState permissionsState = ps.getPermissionsState();
4980                if (permissionsState.hasPermission(permName, userId)) {
4981                    if (instantApp) {
4982                        BasePermission bp = mSettings.mPermissions.get(permName);
4983                        if (bp != null && bp.isInstant()) {
4984                            return PackageManager.PERMISSION_GRANTED;
4985                        }
4986                    } else {
4987                        return PackageManager.PERMISSION_GRANTED;
4988                    }
4989                }
4990                // Special case: ACCESS_FINE_LOCATION permission includes ACCESS_COARSE_LOCATION
4991                if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && permissionsState
4992                        .hasPermission(Manifest.permission.ACCESS_FINE_LOCATION, userId)) {
4993                    return PackageManager.PERMISSION_GRANTED;
4994                }
4995            }
4996        }
4997
4998        return PackageManager.PERMISSION_DENIED;
4999    }
5000
5001    @Override
5002    public int checkUidPermission(String permName, int uid) {
5003        final int callingUid = Binder.getCallingUid();
5004        final int callingUserId = UserHandle.getUserId(callingUid);
5005        final boolean isCallerInstantApp = getInstantAppPackageName(callingUid) != null;
5006        final boolean isUidInstantApp = getInstantAppPackageName(uid) != null;
5007        final int userId = UserHandle.getUserId(uid);
5008        if (!sUserManager.exists(userId)) {
5009            return PackageManager.PERMISSION_DENIED;
5010        }
5011
5012        synchronized (mPackages) {
5013            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
5014            if (obj != null) {
5015                if (obj instanceof SharedUserSetting) {
5016                    if (isCallerInstantApp) {
5017                        return PackageManager.PERMISSION_DENIED;
5018                    }
5019                } else if (obj instanceof PackageSetting) {
5020                    final PackageSetting ps = (PackageSetting) obj;
5021                    if (filterAppAccessLPr(ps, callingUid, callingUserId)) {
5022                        return PackageManager.PERMISSION_DENIED;
5023                    }
5024                }
5025                final SettingBase settingBase = (SettingBase) obj;
5026                final PermissionsState permissionsState = settingBase.getPermissionsState();
5027                if (permissionsState.hasPermission(permName, userId)) {
5028                    if (isUidInstantApp) {
5029                        BasePermission bp = mSettings.mPermissions.get(permName);
5030                        if (bp != null && bp.isInstant()) {
5031                            return PackageManager.PERMISSION_GRANTED;
5032                        }
5033                    } else {
5034                        return PackageManager.PERMISSION_GRANTED;
5035                    }
5036                }
5037                // Special case: ACCESS_FINE_LOCATION permission includes ACCESS_COARSE_LOCATION
5038                if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && permissionsState
5039                        .hasPermission(Manifest.permission.ACCESS_FINE_LOCATION, userId)) {
5040                    return PackageManager.PERMISSION_GRANTED;
5041                }
5042            } else {
5043                ArraySet<String> perms = mSystemPermissions.get(uid);
5044                if (perms != null) {
5045                    if (perms.contains(permName)) {
5046                        return PackageManager.PERMISSION_GRANTED;
5047                    }
5048                    if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && perms
5049                            .contains(Manifest.permission.ACCESS_FINE_LOCATION)) {
5050                        return PackageManager.PERMISSION_GRANTED;
5051                    }
5052                }
5053            }
5054        }
5055
5056        return PackageManager.PERMISSION_DENIED;
5057    }
5058
5059    @Override
5060    public boolean isPermissionRevokedByPolicy(String permission, String packageName, int userId) {
5061        if (UserHandle.getCallingUserId() != userId) {
5062            mContext.enforceCallingPermission(
5063                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
5064                    "isPermissionRevokedByPolicy for user " + userId);
5065        }
5066
5067        if (checkPermission(permission, packageName, userId)
5068                == PackageManager.PERMISSION_GRANTED) {
5069            return false;
5070        }
5071
5072        final int callingUid = Binder.getCallingUid();
5073        if (getInstantAppPackageName(callingUid) != null) {
5074            if (!isCallerSameApp(packageName, callingUid)) {
5075                return false;
5076            }
5077        } else {
5078            if (isInstantApp(packageName, userId)) {
5079                return false;
5080            }
5081        }
5082
5083        final long identity = Binder.clearCallingIdentity();
5084        try {
5085            final int flags = getPermissionFlags(permission, packageName, userId);
5086            return (flags & PackageManager.FLAG_PERMISSION_POLICY_FIXED) != 0;
5087        } finally {
5088            Binder.restoreCallingIdentity(identity);
5089        }
5090    }
5091
5092    @Override
5093    public String getPermissionControllerPackageName() {
5094        synchronized (mPackages) {
5095            return mRequiredInstallerPackage;
5096        }
5097    }
5098
5099    /**
5100     * Checks if the request is from the system or an app that has INTERACT_ACROSS_USERS
5101     * or INTERACT_ACROSS_USERS_FULL permissions, if the userid is not for the caller.
5102     * @param checkShell whether to prevent shell from access if there's a debugging restriction
5103     * @param message the message to log on security exception
5104     */
5105    void enforceCrossUserPermission(int callingUid, int userId, boolean requireFullPermission,
5106            boolean checkShell, String message) {
5107        if (userId < 0) {
5108            throw new IllegalArgumentException("Invalid userId " + userId);
5109        }
5110        if (checkShell) {
5111            enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, userId);
5112        }
5113        if (userId == UserHandle.getUserId(callingUid)) return;
5114        if (callingUid != Process.SYSTEM_UID && callingUid != 0) {
5115            if (requireFullPermission) {
5116                mContext.enforceCallingOrSelfPermission(
5117                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message);
5118            } else {
5119                try {
5120                    mContext.enforceCallingOrSelfPermission(
5121                            android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message);
5122                } catch (SecurityException se) {
5123                    mContext.enforceCallingOrSelfPermission(
5124                            android.Manifest.permission.INTERACT_ACROSS_USERS, message);
5125                }
5126            }
5127        }
5128    }
5129
5130    void enforceShellRestriction(String restriction, int callingUid, int userHandle) {
5131        if (callingUid == Process.SHELL_UID) {
5132            if (userHandle >= 0
5133                    && sUserManager.hasUserRestriction(restriction, userHandle)) {
5134                throw new SecurityException("Shell does not have permission to access user "
5135                        + userHandle);
5136            } else if (userHandle < 0) {
5137                Slog.e(TAG, "Unable to check shell permission for user " + userHandle + "\n\t"
5138                        + Debug.getCallers(3));
5139            }
5140        }
5141    }
5142
5143    private BasePermission findPermissionTreeLP(String permName) {
5144        for(BasePermission bp : mSettings.mPermissionTrees.values()) {
5145            if (permName.startsWith(bp.name) &&
5146                    permName.length() > bp.name.length() &&
5147                    permName.charAt(bp.name.length()) == '.') {
5148                return bp;
5149            }
5150        }
5151        return null;
5152    }
5153
5154    private BasePermission checkPermissionTreeLP(String permName) {
5155        if (permName != null) {
5156            BasePermission bp = findPermissionTreeLP(permName);
5157            if (bp != null) {
5158                if (bp.uid == UserHandle.getAppId(Binder.getCallingUid())) {
5159                    return bp;
5160                }
5161                throw new SecurityException("Calling uid "
5162                        + Binder.getCallingUid()
5163                        + " is not allowed to add to permission tree "
5164                        + bp.name + " owned by uid " + bp.uid);
5165            }
5166        }
5167        throw new SecurityException("No permission tree found for " + permName);
5168    }
5169
5170    static boolean compareStrings(CharSequence s1, CharSequence s2) {
5171        if (s1 == null) {
5172            return s2 == null;
5173        }
5174        if (s2 == null) {
5175            return false;
5176        }
5177        if (s1.getClass() != s2.getClass()) {
5178            return false;
5179        }
5180        return s1.equals(s2);
5181    }
5182
5183    static boolean comparePermissionInfos(PermissionInfo pi1, PermissionInfo pi2) {
5184        if (pi1.icon != pi2.icon) return false;
5185        if (pi1.logo != pi2.logo) return false;
5186        if (pi1.protectionLevel != pi2.protectionLevel) return false;
5187        if (!compareStrings(pi1.name, pi2.name)) return false;
5188        if (!compareStrings(pi1.nonLocalizedLabel, pi2.nonLocalizedLabel)) return false;
5189        // We'll take care of setting this one.
5190        if (!compareStrings(pi1.packageName, pi2.packageName)) return false;
5191        // These are not currently stored in settings.
5192        //if (!compareStrings(pi1.group, pi2.group)) return false;
5193        //if (!compareStrings(pi1.nonLocalizedDescription, pi2.nonLocalizedDescription)) return false;
5194        //if (pi1.labelRes != pi2.labelRes) return false;
5195        //if (pi1.descriptionRes != pi2.descriptionRes) return false;
5196        return true;
5197    }
5198
5199    int permissionInfoFootprint(PermissionInfo info) {
5200        int size = info.name.length();
5201        if (info.nonLocalizedLabel != null) size += info.nonLocalizedLabel.length();
5202        if (info.nonLocalizedDescription != null) size += info.nonLocalizedDescription.length();
5203        return size;
5204    }
5205
5206    int calculateCurrentPermissionFootprintLocked(BasePermission tree) {
5207        int size = 0;
5208        for (BasePermission perm : mSettings.mPermissions.values()) {
5209            if (perm.uid == tree.uid) {
5210                size += perm.name.length() + permissionInfoFootprint(perm.perm.info);
5211            }
5212        }
5213        return size;
5214    }
5215
5216    void enforcePermissionCapLocked(PermissionInfo info, BasePermission tree) {
5217        // We calculate the max size of permissions defined by this uid and throw
5218        // if that plus the size of 'info' would exceed our stated maximum.
5219        if (tree.uid != Process.SYSTEM_UID) {
5220            final int curTreeSize = calculateCurrentPermissionFootprintLocked(tree);
5221            if (curTreeSize + permissionInfoFootprint(info) > MAX_PERMISSION_TREE_FOOTPRINT) {
5222                throw new SecurityException("Permission tree size cap exceeded");
5223            }
5224        }
5225    }
5226
5227    boolean addPermissionLocked(PermissionInfo info, boolean async) {
5228        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
5229            throw new SecurityException("Instant apps can't add permissions");
5230        }
5231        if (info.labelRes == 0 && info.nonLocalizedLabel == null) {
5232            throw new SecurityException("Label must be specified in permission");
5233        }
5234        BasePermission tree = checkPermissionTreeLP(info.name);
5235        BasePermission bp = mSettings.mPermissions.get(info.name);
5236        boolean added = bp == null;
5237        boolean changed = true;
5238        int fixedLevel = PermissionInfo.fixProtectionLevel(info.protectionLevel);
5239        if (added) {
5240            enforcePermissionCapLocked(info, tree);
5241            bp = new BasePermission(info.name, tree.sourcePackage,
5242                    BasePermission.TYPE_DYNAMIC);
5243        } else if (bp.type != BasePermission.TYPE_DYNAMIC) {
5244            throw new SecurityException(
5245                    "Not allowed to modify non-dynamic permission "
5246                    + info.name);
5247        } else {
5248            if (bp.protectionLevel == fixedLevel
5249                    && bp.perm.owner.equals(tree.perm.owner)
5250                    && bp.uid == tree.uid
5251                    && comparePermissionInfos(bp.perm.info, info)) {
5252                changed = false;
5253            }
5254        }
5255        bp.protectionLevel = fixedLevel;
5256        info = new PermissionInfo(info);
5257        info.protectionLevel = fixedLevel;
5258        bp.perm = new PackageParser.Permission(tree.perm.owner, info);
5259        bp.perm.info.packageName = tree.perm.info.packageName;
5260        bp.uid = tree.uid;
5261        if (added) {
5262            mSettings.mPermissions.put(info.name, bp);
5263        }
5264        if (changed) {
5265            if (!async) {
5266                mSettings.writeLPr();
5267            } else {
5268                scheduleWriteSettingsLocked();
5269            }
5270        }
5271        return added;
5272    }
5273
5274    @Override
5275    public boolean addPermission(PermissionInfo info) {
5276        synchronized (mPackages) {
5277            return addPermissionLocked(info, false);
5278        }
5279    }
5280
5281    @Override
5282    public boolean addPermissionAsync(PermissionInfo info) {
5283        synchronized (mPackages) {
5284            return addPermissionLocked(info, true);
5285        }
5286    }
5287
5288    @Override
5289    public void removePermission(String name) {
5290        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
5291            throw new SecurityException("Instant applications don't have access to this method");
5292        }
5293        synchronized (mPackages) {
5294            checkPermissionTreeLP(name);
5295            BasePermission bp = mSettings.mPermissions.get(name);
5296            if (bp != null) {
5297                if (bp.type != BasePermission.TYPE_DYNAMIC) {
5298                    throw new SecurityException(
5299                            "Not allowed to modify non-dynamic permission "
5300                            + name);
5301                }
5302                mSettings.mPermissions.remove(name);
5303                mSettings.writeLPr();
5304            }
5305        }
5306    }
5307
5308    private static void enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(
5309            PackageParser.Package pkg, BasePermission bp) {
5310        int index = pkg.requestedPermissions.indexOf(bp.name);
5311        if (index == -1) {
5312            throw new SecurityException("Package " + pkg.packageName
5313                    + " has not requested permission " + bp.name);
5314        }
5315        if (!bp.isRuntime() && !bp.isDevelopment()) {
5316            throw new SecurityException("Permission " + bp.name
5317                    + " is not a changeable permission type");
5318        }
5319    }
5320
5321    @Override
5322    public void grantRuntimePermission(String packageName, String name, final int userId) {
5323        grantRuntimePermission(packageName, name, userId, false /* Only if not fixed by policy */);
5324    }
5325
5326    private void grantRuntimePermission(String packageName, String name, final int userId,
5327            boolean overridePolicy) {
5328        if (!sUserManager.exists(userId)) {
5329            Log.e(TAG, "No such user:" + userId);
5330            return;
5331        }
5332        final int callingUid = Binder.getCallingUid();
5333
5334        mContext.enforceCallingOrSelfPermission(
5335                android.Manifest.permission.GRANT_RUNTIME_PERMISSIONS,
5336                "grantRuntimePermission");
5337
5338        enforceCrossUserPermission(callingUid, userId,
5339                true /* requireFullPermission */, true /* checkShell */,
5340                "grantRuntimePermission");
5341
5342        final int uid;
5343        final PackageSetting ps;
5344
5345        synchronized (mPackages) {
5346            final PackageParser.Package pkg = mPackages.get(packageName);
5347            if (pkg == null) {
5348                throw new IllegalArgumentException("Unknown package: " + packageName);
5349            }
5350            final BasePermission bp = mSettings.mPermissions.get(name);
5351            if (bp == null) {
5352                throw new IllegalArgumentException("Unknown permission: " + name);
5353            }
5354            ps = (PackageSetting) pkg.mExtras;
5355            if (ps == null
5356                    || filterAppAccessLPr(ps, callingUid, userId)) {
5357                throw new IllegalArgumentException("Unknown package: " + packageName);
5358            }
5359
5360            enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(pkg, bp);
5361
5362            // If a permission review is required for legacy apps we represent
5363            // their permissions as always granted runtime ones since we need
5364            // to keep the review required permission flag per user while an
5365            // install permission's state is shared across all users.
5366            if (mPermissionReviewRequired
5367                    && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M
5368                    && bp.isRuntime()) {
5369                return;
5370            }
5371
5372            uid = UserHandle.getUid(userId, pkg.applicationInfo.uid);
5373
5374            final PermissionsState permissionsState = ps.getPermissionsState();
5375
5376            final int flags = permissionsState.getPermissionFlags(name, userId);
5377            if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) {
5378                throw new SecurityException("Cannot grant system fixed permission "
5379                        + name + " for package " + packageName);
5380            }
5381            if (!overridePolicy && (flags & PackageManager.FLAG_PERMISSION_POLICY_FIXED) != 0) {
5382                throw new SecurityException("Cannot grant policy fixed permission "
5383                        + name + " for package " + packageName);
5384            }
5385
5386            if (bp.isDevelopment()) {
5387                // Development permissions must be handled specially, since they are not
5388                // normal runtime permissions.  For now they apply to all users.
5389                if (permissionsState.grantInstallPermission(bp) !=
5390                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
5391                    scheduleWriteSettingsLocked();
5392                }
5393                return;
5394            }
5395
5396            if (ps.getInstantApp(userId) && !bp.isInstant()) {
5397                throw new SecurityException("Cannot grant non-ephemeral permission"
5398                        + name + " for package " + packageName);
5399            }
5400
5401            if (pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) {
5402                Slog.w(TAG, "Cannot grant runtime permission to a legacy app");
5403                return;
5404            }
5405
5406            final int result = permissionsState.grantRuntimePermission(bp, userId);
5407            switch (result) {
5408                case PermissionsState.PERMISSION_OPERATION_FAILURE: {
5409                    return;
5410                }
5411
5412                case PermissionsState.PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: {
5413                    final int appId = UserHandle.getAppId(pkg.applicationInfo.uid);
5414                    mHandler.post(new Runnable() {
5415                        @Override
5416                        public void run() {
5417                            killUid(appId, userId, KILL_APP_REASON_GIDS_CHANGED);
5418                        }
5419                    });
5420                }
5421                break;
5422            }
5423
5424            if (bp.isRuntime()) {
5425                logPermissionGranted(mContext, name, packageName);
5426            }
5427
5428            mOnPermissionChangeListeners.onPermissionsChanged(uid);
5429
5430            // Not critical if that is lost - app has to request again.
5431            mSettings.writeRuntimePermissionsForUserLPr(userId, false);
5432        }
5433
5434        // Only need to do this if user is initialized. Otherwise it's a new user
5435        // and there are no processes running as the user yet and there's no need
5436        // to make an expensive call to remount processes for the changed permissions.
5437        if (READ_EXTERNAL_STORAGE.equals(name)
5438                || WRITE_EXTERNAL_STORAGE.equals(name)) {
5439            final long token = Binder.clearCallingIdentity();
5440            try {
5441                if (sUserManager.isInitialized(userId)) {
5442                    StorageManagerInternal storageManagerInternal = LocalServices.getService(
5443                            StorageManagerInternal.class);
5444                    storageManagerInternal.onExternalStoragePolicyChanged(uid, packageName);
5445                }
5446            } finally {
5447                Binder.restoreCallingIdentity(token);
5448            }
5449        }
5450    }
5451
5452    @Override
5453    public void revokeRuntimePermission(String packageName, String name, int userId) {
5454        revokeRuntimePermission(packageName, name, userId, false /* Only if not fixed by policy */);
5455    }
5456
5457    private void revokeRuntimePermission(String packageName, String name, int userId,
5458            boolean overridePolicy) {
5459        if (!sUserManager.exists(userId)) {
5460            Log.e(TAG, "No such user:" + userId);
5461            return;
5462        }
5463
5464        mContext.enforceCallingOrSelfPermission(
5465                android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS,
5466                "revokeRuntimePermission");
5467
5468        enforceCrossUserPermission(Binder.getCallingUid(), userId,
5469                true /* requireFullPermission */, true /* checkShell */,
5470                "revokeRuntimePermission");
5471
5472        final int appId;
5473
5474        synchronized (mPackages) {
5475            final PackageParser.Package pkg = mPackages.get(packageName);
5476            if (pkg == null) {
5477                throw new IllegalArgumentException("Unknown package: " + packageName);
5478            }
5479            final PackageSetting ps = (PackageSetting) pkg.mExtras;
5480            if (ps == null
5481                    || filterAppAccessLPr(ps, Binder.getCallingUid(), userId)) {
5482                throw new IllegalArgumentException("Unknown package: " + packageName);
5483            }
5484            final BasePermission bp = mSettings.mPermissions.get(name);
5485            if (bp == null) {
5486                throw new IllegalArgumentException("Unknown permission: " + name);
5487            }
5488
5489            enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(pkg, bp);
5490
5491            // If a permission review is required for legacy apps we represent
5492            // their permissions as always granted runtime ones since we need
5493            // to keep the review required permission flag per user while an
5494            // install permission's state is shared across all users.
5495            if (mPermissionReviewRequired
5496                    && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M
5497                    && bp.isRuntime()) {
5498                return;
5499            }
5500
5501            final PermissionsState permissionsState = ps.getPermissionsState();
5502
5503            final int flags = permissionsState.getPermissionFlags(name, userId);
5504            if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) {
5505                throw new SecurityException("Cannot revoke system fixed permission "
5506                        + name + " for package " + packageName);
5507            }
5508            if (!overridePolicy && (flags & PackageManager.FLAG_PERMISSION_POLICY_FIXED) != 0) {
5509                throw new SecurityException("Cannot revoke policy fixed permission "
5510                        + name + " for package " + packageName);
5511            }
5512
5513            if (bp.isDevelopment()) {
5514                // Development permissions must be handled specially, since they are not
5515                // normal runtime permissions.  For now they apply to all users.
5516                if (permissionsState.revokeInstallPermission(bp) !=
5517                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
5518                    scheduleWriteSettingsLocked();
5519                }
5520                return;
5521            }
5522
5523            if (permissionsState.revokeRuntimePermission(bp, userId) ==
5524                    PermissionsState.PERMISSION_OPERATION_FAILURE) {
5525                return;
5526            }
5527
5528            if (bp.isRuntime()) {
5529                logPermissionRevoked(mContext, name, packageName);
5530            }
5531
5532            mOnPermissionChangeListeners.onPermissionsChanged(pkg.applicationInfo.uid);
5533
5534            // Critical, after this call app should never have the permission.
5535            mSettings.writeRuntimePermissionsForUserLPr(userId, true);
5536
5537            appId = UserHandle.getAppId(pkg.applicationInfo.uid);
5538        }
5539
5540        killUid(appId, userId, KILL_APP_REASON_PERMISSIONS_REVOKED);
5541    }
5542
5543    /**
5544     * Get the first event id for the permission.
5545     *
5546     * <p>There are four events for each permission: <ul>
5547     *     <li>Request permission: first id + 0</li>
5548     *     <li>Grant permission: first id + 1</li>
5549     *     <li>Request for permission denied: first id + 2</li>
5550     *     <li>Revoke permission: first id + 3</li>
5551     * </ul></p>
5552     *
5553     * @param name name of the permission
5554     *
5555     * @return The first event id for the permission
5556     */
5557    private static int getBaseEventId(@NonNull String name) {
5558        int eventIdIndex = ALL_DANGEROUS_PERMISSIONS.indexOf(name);
5559
5560        if (eventIdIndex == -1) {
5561            if (AppOpsManager.permissionToOpCode(name) == AppOpsManager.OP_NONE
5562                    || Build.IS_USER) {
5563                Log.i(TAG, "Unknown permission " + name);
5564
5565                return MetricsEvent.ACTION_PERMISSION_REQUEST_UNKNOWN;
5566            } else {
5567                // Most likely #ALL_DANGEROUS_PERMISSIONS needs to be updated.
5568                //
5569                // Also update
5570                // - EventLogger#ALL_DANGEROUS_PERMISSIONS
5571                // - metrics_constants.proto
5572                throw new IllegalStateException("Unknown permission " + name);
5573            }
5574        }
5575
5576        return MetricsEvent.ACTION_PERMISSION_REQUEST_READ_CALENDAR + eventIdIndex * 4;
5577    }
5578
5579    /**
5580     * Log that a permission was revoked.
5581     *
5582     * @param context Context of the caller
5583     * @param name name of the permission
5584     * @param packageName package permission if for
5585     */
5586    private static void logPermissionRevoked(@NonNull Context context, @NonNull String name,
5587            @NonNull String packageName) {
5588        MetricsLogger.action(context, getBaseEventId(name) + 3, packageName);
5589    }
5590
5591    /**
5592     * Log that a permission request was granted.
5593     *
5594     * @param context Context of the caller
5595     * @param name name of the permission
5596     * @param packageName package permission if for
5597     */
5598    private static void logPermissionGranted(@NonNull Context context, @NonNull String name,
5599            @NonNull String packageName) {
5600        MetricsLogger.action(context, getBaseEventId(name) + 1, packageName);
5601    }
5602
5603    @Override
5604    public void resetRuntimePermissions() {
5605        mContext.enforceCallingOrSelfPermission(
5606                android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS,
5607                "revokeRuntimePermission");
5608
5609        int callingUid = Binder.getCallingUid();
5610        if (callingUid != Process.SYSTEM_UID && callingUid != 0) {
5611            mContext.enforceCallingOrSelfPermission(
5612                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
5613                    "resetRuntimePermissions");
5614        }
5615
5616        synchronized (mPackages) {
5617            updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL);
5618            for (int userId : UserManagerService.getInstance().getUserIds()) {
5619                final int packageCount = mPackages.size();
5620                for (int i = 0; i < packageCount; i++) {
5621                    PackageParser.Package pkg = mPackages.valueAt(i);
5622                    if (!(pkg.mExtras instanceof PackageSetting)) {
5623                        continue;
5624                    }
5625                    PackageSetting ps = (PackageSetting) pkg.mExtras;
5626                    resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
5627                }
5628            }
5629        }
5630    }
5631
5632    @Override
5633    public int getPermissionFlags(String name, String packageName, int userId) {
5634        if (!sUserManager.exists(userId)) {
5635            return 0;
5636        }
5637
5638        enforceGrantRevokeRuntimePermissionPermissions("getPermissionFlags");
5639
5640        final int callingUid = Binder.getCallingUid();
5641        enforceCrossUserPermission(callingUid, userId,
5642                true /* requireFullPermission */, false /* checkShell */,
5643                "getPermissionFlags");
5644
5645        synchronized (mPackages) {
5646            final PackageParser.Package pkg = mPackages.get(packageName);
5647            if (pkg == null) {
5648                return 0;
5649            }
5650            final BasePermission bp = mSettings.mPermissions.get(name);
5651            if (bp == null) {
5652                return 0;
5653            }
5654            final PackageSetting ps = (PackageSetting) pkg.mExtras;
5655            if (ps == null
5656                    || filterAppAccessLPr(ps, callingUid, userId)) {
5657                return 0;
5658            }
5659            PermissionsState permissionsState = ps.getPermissionsState();
5660            return permissionsState.getPermissionFlags(name, userId);
5661        }
5662    }
5663
5664    @Override
5665    public void updatePermissionFlags(String name, String packageName, int flagMask,
5666            int flagValues, int userId) {
5667        if (!sUserManager.exists(userId)) {
5668            return;
5669        }
5670
5671        enforceGrantRevokeRuntimePermissionPermissions("updatePermissionFlags");
5672
5673        final int callingUid = Binder.getCallingUid();
5674        enforceCrossUserPermission(callingUid, userId,
5675                true /* requireFullPermission */, true /* checkShell */,
5676                "updatePermissionFlags");
5677
5678        // Only the system can change these flags and nothing else.
5679        if (getCallingUid() != Process.SYSTEM_UID) {
5680            flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
5681            flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
5682            flagMask &= ~PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT;
5683            flagValues &= ~PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT;
5684            flagValues &= ~PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED;
5685        }
5686
5687        synchronized (mPackages) {
5688            final PackageParser.Package pkg = mPackages.get(packageName);
5689            if (pkg == null) {
5690                throw new IllegalArgumentException("Unknown package: " + packageName);
5691            }
5692            final PackageSetting ps = (PackageSetting) pkg.mExtras;
5693            if (ps == null
5694                    || filterAppAccessLPr(ps, callingUid, userId)) {
5695                throw new IllegalArgumentException("Unknown package: " + packageName);
5696            }
5697
5698            final BasePermission bp = mSettings.mPermissions.get(name);
5699            if (bp == null) {
5700                throw new IllegalArgumentException("Unknown permission: " + name);
5701            }
5702
5703            PermissionsState permissionsState = ps.getPermissionsState();
5704
5705            boolean hadState = permissionsState.getRuntimePermissionState(name, userId) != null;
5706
5707            if (permissionsState.updatePermissionFlags(bp, userId, flagMask, flagValues)) {
5708                // Install and runtime permissions are stored in different places,
5709                // so figure out what permission changed and persist the change.
5710                if (permissionsState.getInstallPermissionState(name) != null) {
5711                    scheduleWriteSettingsLocked();
5712                } else if (permissionsState.getRuntimePermissionState(name, userId) != null
5713                        || hadState) {
5714                    mSettings.writeRuntimePermissionsForUserLPr(userId, false);
5715                }
5716            }
5717        }
5718    }
5719
5720    /**
5721     * Update the permission flags for all packages and runtime permissions of a user in order
5722     * to allow device or profile owner to remove POLICY_FIXED.
5723     */
5724    @Override
5725    public void updatePermissionFlagsForAllApps(int flagMask, int flagValues, int userId) {
5726        if (!sUserManager.exists(userId)) {
5727            return;
5728        }
5729
5730        enforceGrantRevokeRuntimePermissionPermissions("updatePermissionFlagsForAllApps");
5731
5732        enforceCrossUserPermission(Binder.getCallingUid(), userId,
5733                true /* requireFullPermission */, true /* checkShell */,
5734                "updatePermissionFlagsForAllApps");
5735
5736        // Only the system can change system fixed flags.
5737        if (getCallingUid() != Process.SYSTEM_UID) {
5738            flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
5739            flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
5740        }
5741
5742        synchronized (mPackages) {
5743            boolean changed = false;
5744            final int packageCount = mPackages.size();
5745            for (int pkgIndex = 0; pkgIndex < packageCount; pkgIndex++) {
5746                final PackageParser.Package pkg = mPackages.valueAt(pkgIndex);
5747                final PackageSetting ps = (PackageSetting) pkg.mExtras;
5748                if (ps == null) {
5749                    continue;
5750                }
5751                PermissionsState permissionsState = ps.getPermissionsState();
5752                changed |= permissionsState.updatePermissionFlagsForAllPermissions(
5753                        userId, flagMask, flagValues);
5754            }
5755            if (changed) {
5756                mSettings.writeRuntimePermissionsForUserLPr(userId, false);
5757            }
5758        }
5759    }
5760
5761    private void enforceGrantRevokeRuntimePermissionPermissions(String message) {
5762        if (mContext.checkCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS)
5763                != PackageManager.PERMISSION_GRANTED
5764            && mContext.checkCallingOrSelfPermission(Manifest.permission.REVOKE_RUNTIME_PERMISSIONS)
5765                != PackageManager.PERMISSION_GRANTED) {
5766            throw new SecurityException(message + " requires "
5767                    + Manifest.permission.GRANT_RUNTIME_PERMISSIONS + " or "
5768                    + Manifest.permission.REVOKE_RUNTIME_PERMISSIONS);
5769        }
5770    }
5771
5772    @Override
5773    public boolean shouldShowRequestPermissionRationale(String permissionName,
5774            String packageName, int userId) {
5775        if (UserHandle.getCallingUserId() != userId) {
5776            mContext.enforceCallingPermission(
5777                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
5778                    "canShowRequestPermissionRationale for user " + userId);
5779        }
5780
5781        final int uid = getPackageUid(packageName, MATCH_DEBUG_TRIAGED_MISSING, userId);
5782        if (UserHandle.getAppId(getCallingUid()) != UserHandle.getAppId(uid)) {
5783            return false;
5784        }
5785
5786        if (checkPermission(permissionName, packageName, userId)
5787                == PackageManager.PERMISSION_GRANTED) {
5788            return false;
5789        }
5790
5791        final int flags;
5792
5793        final long identity = Binder.clearCallingIdentity();
5794        try {
5795            flags = getPermissionFlags(permissionName,
5796                    packageName, userId);
5797        } finally {
5798            Binder.restoreCallingIdentity(identity);
5799        }
5800
5801        final int fixedFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED
5802                | PackageManager.FLAG_PERMISSION_POLICY_FIXED
5803                | PackageManager.FLAG_PERMISSION_USER_FIXED;
5804
5805        if ((flags & fixedFlags) != 0) {
5806            return false;
5807        }
5808
5809        return (flags & PackageManager.FLAG_PERMISSION_USER_SET) != 0;
5810    }
5811
5812    @Override
5813    public void addOnPermissionsChangeListener(IOnPermissionsChangeListener listener) {
5814        mContext.enforceCallingOrSelfPermission(
5815                Manifest.permission.OBSERVE_GRANT_REVOKE_PERMISSIONS,
5816                "addOnPermissionsChangeListener");
5817
5818        synchronized (mPackages) {
5819            mOnPermissionChangeListeners.addListenerLocked(listener);
5820        }
5821    }
5822
5823    @Override
5824    public void removeOnPermissionsChangeListener(IOnPermissionsChangeListener listener) {
5825        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
5826            throw new SecurityException("Instant applications don't have access to this method");
5827        }
5828        synchronized (mPackages) {
5829            mOnPermissionChangeListeners.removeListenerLocked(listener);
5830        }
5831    }
5832
5833    @Override
5834    public boolean isProtectedBroadcast(String actionName) {
5835        // allow instant applications
5836        synchronized (mProtectedBroadcasts) {
5837            if (mProtectedBroadcasts.contains(actionName)) {
5838                return true;
5839            } else if (actionName != null) {
5840                // TODO: remove these terrible hacks
5841                if (actionName.startsWith("android.net.netmon.lingerExpired")
5842                        || actionName.startsWith("com.android.server.sip.SipWakeupTimer")
5843                        || actionName.startsWith("com.android.internal.telephony.data-reconnect")
5844                        || actionName.startsWith("android.net.netmon.launchCaptivePortalApp")) {
5845                    return true;
5846                }
5847            }
5848        }
5849        return false;
5850    }
5851
5852    @Override
5853    public int checkSignatures(String pkg1, String pkg2) {
5854        synchronized (mPackages) {
5855            final PackageParser.Package p1 = mPackages.get(pkg1);
5856            final PackageParser.Package p2 = mPackages.get(pkg2);
5857            if (p1 == null || p1.mExtras == null
5858                    || p2 == null || p2.mExtras == null) {
5859                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5860            }
5861            final int callingUid = Binder.getCallingUid();
5862            final int callingUserId = UserHandle.getUserId(callingUid);
5863            final PackageSetting ps1 = (PackageSetting) p1.mExtras;
5864            final PackageSetting ps2 = (PackageSetting) p2.mExtras;
5865            if (filterAppAccessLPr(ps1, callingUid, callingUserId)
5866                    || filterAppAccessLPr(ps2, callingUid, callingUserId)) {
5867                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5868            }
5869            return compareSignatures(p1.mSignatures, p2.mSignatures);
5870        }
5871    }
5872
5873    @Override
5874    public int checkUidSignatures(int uid1, int uid2) {
5875        final int callingUid = Binder.getCallingUid();
5876        final int callingUserId = UserHandle.getUserId(callingUid);
5877        final boolean isCallerInstantApp = getInstantAppPackageName(callingUid) != null;
5878        // Map to base uids.
5879        uid1 = UserHandle.getAppId(uid1);
5880        uid2 = UserHandle.getAppId(uid2);
5881        // reader
5882        synchronized (mPackages) {
5883            Signature[] s1;
5884            Signature[] s2;
5885            Object obj = mSettings.getUserIdLPr(uid1);
5886            if (obj != null) {
5887                if (obj instanceof SharedUserSetting) {
5888                    if (isCallerInstantApp) {
5889                        return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5890                    }
5891                    s1 = ((SharedUserSetting)obj).signatures.mSignatures;
5892                } else if (obj instanceof PackageSetting) {
5893                    final PackageSetting ps = (PackageSetting) obj;
5894                    if (filterAppAccessLPr(ps, callingUid, callingUserId)) {
5895                        return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5896                    }
5897                    s1 = ps.signatures.mSignatures;
5898                } else {
5899                    return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5900                }
5901            } else {
5902                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5903            }
5904            obj = mSettings.getUserIdLPr(uid2);
5905            if (obj != null) {
5906                if (obj instanceof SharedUserSetting) {
5907                    if (isCallerInstantApp) {
5908                        return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5909                    }
5910                    s2 = ((SharedUserSetting)obj).signatures.mSignatures;
5911                } else if (obj instanceof PackageSetting) {
5912                    final PackageSetting ps = (PackageSetting) obj;
5913                    if (filterAppAccessLPr(ps, callingUid, callingUserId)) {
5914                        return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5915                    }
5916                    s2 = ps.signatures.mSignatures;
5917                } else {
5918                    return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5919                }
5920            } else {
5921                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5922            }
5923            return compareSignatures(s1, s2);
5924        }
5925    }
5926
5927    /**
5928     * This method should typically only be used when granting or revoking
5929     * permissions, since the app may immediately restart after this call.
5930     * <p>
5931     * If you're doing surgery on app code/data, use {@link PackageFreezer} to
5932     * guard your work against the app being relaunched.
5933     */
5934    private void killUid(int appId, int userId, String reason) {
5935        final long identity = Binder.clearCallingIdentity();
5936        try {
5937            IActivityManager am = ActivityManager.getService();
5938            if (am != null) {
5939                try {
5940                    am.killUid(appId, userId, reason);
5941                } catch (RemoteException e) {
5942                    /* ignore - same process */
5943                }
5944            }
5945        } finally {
5946            Binder.restoreCallingIdentity(identity);
5947        }
5948    }
5949
5950    /**
5951     * Compares two sets of signatures. Returns:
5952     * <br />
5953     * {@link PackageManager#SIGNATURE_NEITHER_SIGNED}: if both signature sets are null,
5954     * <br />
5955     * {@link PackageManager#SIGNATURE_FIRST_NOT_SIGNED}: if the first signature set is null,
5956     * <br />
5957     * {@link PackageManager#SIGNATURE_SECOND_NOT_SIGNED}: if the second signature set is null,
5958     * <br />
5959     * {@link PackageManager#SIGNATURE_MATCH}: if the two signature sets are identical,
5960     * <br />
5961     * {@link PackageManager#SIGNATURE_NO_MATCH}: if the two signature sets differ.
5962     */
5963    static int compareSignatures(Signature[] s1, Signature[] s2) {
5964        if (s1 == null) {
5965            return s2 == null
5966                    ? PackageManager.SIGNATURE_NEITHER_SIGNED
5967                    : PackageManager.SIGNATURE_FIRST_NOT_SIGNED;
5968        }
5969
5970        if (s2 == null) {
5971            return PackageManager.SIGNATURE_SECOND_NOT_SIGNED;
5972        }
5973
5974        if (s1.length != s2.length) {
5975            return PackageManager.SIGNATURE_NO_MATCH;
5976        }
5977
5978        // Since both signature sets are of size 1, we can compare without HashSets.
5979        if (s1.length == 1) {
5980            return s1[0].equals(s2[0]) ?
5981                    PackageManager.SIGNATURE_MATCH :
5982                    PackageManager.SIGNATURE_NO_MATCH;
5983        }
5984
5985        ArraySet<Signature> set1 = new ArraySet<Signature>();
5986        for (Signature sig : s1) {
5987            set1.add(sig);
5988        }
5989        ArraySet<Signature> set2 = new ArraySet<Signature>();
5990        for (Signature sig : s2) {
5991            set2.add(sig);
5992        }
5993        // Make sure s2 contains all signatures in s1.
5994        if (set1.equals(set2)) {
5995            return PackageManager.SIGNATURE_MATCH;
5996        }
5997        return PackageManager.SIGNATURE_NO_MATCH;
5998    }
5999
6000    /**
6001     * If the database version for this type of package (internal storage or
6002     * external storage) is less than the version where package signatures
6003     * were updated, return true.
6004     */
6005    private boolean isCompatSignatureUpdateNeeded(PackageParser.Package scannedPkg) {
6006        final VersionInfo ver = getSettingsVersionForPackage(scannedPkg);
6007        return ver.databaseVersion < DatabaseVersion.SIGNATURE_END_ENTITY;
6008    }
6009
6010    /**
6011     * Used for backward compatibility to make sure any packages with
6012     * certificate chains get upgraded to the new style. {@code existingSigs}
6013     * will be in the old format (since they were stored on disk from before the
6014     * system upgrade) and {@code scannedSigs} will be in the newer format.
6015     */
6016    private int compareSignaturesCompat(PackageSignatures existingSigs,
6017            PackageParser.Package scannedPkg) {
6018        if (!isCompatSignatureUpdateNeeded(scannedPkg)) {
6019            return PackageManager.SIGNATURE_NO_MATCH;
6020        }
6021
6022        ArraySet<Signature> existingSet = new ArraySet<Signature>();
6023        for (Signature sig : existingSigs.mSignatures) {
6024            existingSet.add(sig);
6025        }
6026        ArraySet<Signature> scannedCompatSet = new ArraySet<Signature>();
6027        for (Signature sig : scannedPkg.mSignatures) {
6028            try {
6029                Signature[] chainSignatures = sig.getChainSignatures();
6030                for (Signature chainSig : chainSignatures) {
6031                    scannedCompatSet.add(chainSig);
6032                }
6033            } catch (CertificateEncodingException e) {
6034                scannedCompatSet.add(sig);
6035            }
6036        }
6037        /*
6038         * Make sure the expanded scanned set contains all signatures in the
6039         * existing one.
6040         */
6041        if (scannedCompatSet.equals(existingSet)) {
6042            // Migrate the old signatures to the new scheme.
6043            existingSigs.assignSignatures(scannedPkg.mSignatures);
6044            // The new KeySets will be re-added later in the scanning process.
6045            synchronized (mPackages) {
6046                mSettings.mKeySetManagerService.removeAppKeySetDataLPw(scannedPkg.packageName);
6047            }
6048            return PackageManager.SIGNATURE_MATCH;
6049        }
6050        return PackageManager.SIGNATURE_NO_MATCH;
6051    }
6052
6053    private boolean isRecoverSignatureUpdateNeeded(PackageParser.Package scannedPkg) {
6054        final VersionInfo ver = getSettingsVersionForPackage(scannedPkg);
6055        return ver.databaseVersion < DatabaseVersion.SIGNATURE_MALFORMED_RECOVER;
6056    }
6057
6058    private int compareSignaturesRecover(PackageSignatures existingSigs,
6059            PackageParser.Package scannedPkg) {
6060        if (!isRecoverSignatureUpdateNeeded(scannedPkg)) {
6061            return PackageManager.SIGNATURE_NO_MATCH;
6062        }
6063
6064        String msg = null;
6065        try {
6066            if (Signature.areEffectiveMatch(existingSigs.mSignatures, scannedPkg.mSignatures)) {
6067                logCriticalInfo(Log.INFO, "Recovered effectively matching certificates for "
6068                        + scannedPkg.packageName);
6069                return PackageManager.SIGNATURE_MATCH;
6070            }
6071        } catch (CertificateException e) {
6072            msg = e.getMessage();
6073        }
6074
6075        logCriticalInfo(Log.INFO,
6076                "Failed to recover certificates for " + scannedPkg.packageName + ": " + msg);
6077        return PackageManager.SIGNATURE_NO_MATCH;
6078    }
6079
6080    @Override
6081    public List<String> getAllPackages() {
6082        final int callingUid = Binder.getCallingUid();
6083        final int callingUserId = UserHandle.getUserId(callingUid);
6084        synchronized (mPackages) {
6085            if (canViewInstantApps(callingUid, callingUserId)) {
6086                return new ArrayList<String>(mPackages.keySet());
6087            }
6088            final String instantAppPkgName = getInstantAppPackageName(callingUid);
6089            final List<String> result = new ArrayList<>();
6090            if (instantAppPkgName != null) {
6091                // caller is an instant application; filter unexposed applications
6092                for (PackageParser.Package pkg : mPackages.values()) {
6093                    if (!pkg.visibleToInstantApps) {
6094                        continue;
6095                    }
6096                    result.add(pkg.packageName);
6097                }
6098            } else {
6099                // caller is a normal application; filter instant applications
6100                for (PackageParser.Package pkg : mPackages.values()) {
6101                    final PackageSetting ps =
6102                            pkg.mExtras != null ? (PackageSetting) pkg.mExtras : null;
6103                    if (ps != null
6104                            && ps.getInstantApp(callingUserId)
6105                            && !mInstantAppRegistry.isInstantAccessGranted(
6106                                    callingUserId, UserHandle.getAppId(callingUid), ps.appId)) {
6107                        continue;
6108                    }
6109                    result.add(pkg.packageName);
6110                }
6111            }
6112            return result;
6113        }
6114    }
6115
6116    @Override
6117    public String[] getPackagesForUid(int uid) {
6118        final int callingUid = Binder.getCallingUid();
6119        final boolean isCallerInstantApp = getInstantAppPackageName(callingUid) != null;
6120        final int userId = UserHandle.getUserId(uid);
6121        uid = UserHandle.getAppId(uid);
6122        // reader
6123        synchronized (mPackages) {
6124            Object obj = mSettings.getUserIdLPr(uid);
6125            if (obj instanceof SharedUserSetting) {
6126                if (isCallerInstantApp) {
6127                    return null;
6128                }
6129                final SharedUserSetting sus = (SharedUserSetting) obj;
6130                final int N = sus.packages.size();
6131                String[] res = new String[N];
6132                final Iterator<PackageSetting> it = sus.packages.iterator();
6133                int i = 0;
6134                while (it.hasNext()) {
6135                    PackageSetting ps = it.next();
6136                    if (ps.getInstalled(userId)) {
6137                        res[i++] = ps.name;
6138                    } else {
6139                        res = ArrayUtils.removeElement(String.class, res, res[i]);
6140                    }
6141                }
6142                return res;
6143            } else if (obj instanceof PackageSetting) {
6144                final PackageSetting ps = (PackageSetting) obj;
6145                if (ps.getInstalled(userId) && !filterAppAccessLPr(ps, callingUid, userId)) {
6146                    return new String[]{ps.name};
6147                }
6148            }
6149        }
6150        return null;
6151    }
6152
6153    @Override
6154    public String getNameForUid(int uid) {
6155        final int callingUid = Binder.getCallingUid();
6156        if (getInstantAppPackageName(callingUid) != null) {
6157            return null;
6158        }
6159        synchronized (mPackages) {
6160            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
6161            if (obj instanceof SharedUserSetting) {
6162                final SharedUserSetting sus = (SharedUserSetting) obj;
6163                return sus.name + ":" + sus.userId;
6164            } else if (obj instanceof PackageSetting) {
6165                final PackageSetting ps = (PackageSetting) obj;
6166                if (filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
6167                    return null;
6168                }
6169                return ps.name;
6170            }
6171        }
6172        return null;
6173    }
6174
6175    @Override
6176    public int getUidForSharedUser(String sharedUserName) {
6177        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
6178            return -1;
6179        }
6180        if (sharedUserName == null) {
6181            return -1;
6182        }
6183        // reader
6184        synchronized (mPackages) {
6185            SharedUserSetting suid;
6186            try {
6187                suid = mSettings.getSharedUserLPw(sharedUserName, 0, 0, false);
6188                if (suid != null) {
6189                    return suid.userId;
6190                }
6191            } catch (PackageManagerException ignore) {
6192                // can't happen, but, still need to catch it
6193            }
6194            return -1;
6195        }
6196    }
6197
6198    @Override
6199    public int getFlagsForUid(int uid) {
6200        final int callingUid = Binder.getCallingUid();
6201        if (getInstantAppPackageName(callingUid) != null) {
6202            return 0;
6203        }
6204        synchronized (mPackages) {
6205            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
6206            if (obj instanceof SharedUserSetting) {
6207                final SharedUserSetting sus = (SharedUserSetting) obj;
6208                return sus.pkgFlags;
6209            } else if (obj instanceof PackageSetting) {
6210                final PackageSetting ps = (PackageSetting) obj;
6211                if (filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
6212                    return 0;
6213                }
6214                return ps.pkgFlags;
6215            }
6216        }
6217        return 0;
6218    }
6219
6220    @Override
6221    public int getPrivateFlagsForUid(int uid) {
6222        final int callingUid = Binder.getCallingUid();
6223        if (getInstantAppPackageName(callingUid) != null) {
6224            return 0;
6225        }
6226        synchronized (mPackages) {
6227            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
6228            if (obj instanceof SharedUserSetting) {
6229                final SharedUserSetting sus = (SharedUserSetting) obj;
6230                return sus.pkgPrivateFlags;
6231            } else if (obj instanceof PackageSetting) {
6232                final PackageSetting ps = (PackageSetting) obj;
6233                if (filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
6234                    return 0;
6235                }
6236                return ps.pkgPrivateFlags;
6237            }
6238        }
6239        return 0;
6240    }
6241
6242    @Override
6243    public boolean isUidPrivileged(int uid) {
6244        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
6245            return false;
6246        }
6247        uid = UserHandle.getAppId(uid);
6248        // reader
6249        synchronized (mPackages) {
6250            Object obj = mSettings.getUserIdLPr(uid);
6251            if (obj instanceof SharedUserSetting) {
6252                final SharedUserSetting sus = (SharedUserSetting) obj;
6253                final Iterator<PackageSetting> it = sus.packages.iterator();
6254                while (it.hasNext()) {
6255                    if (it.next().isPrivileged()) {
6256                        return true;
6257                    }
6258                }
6259            } else if (obj instanceof PackageSetting) {
6260                final PackageSetting ps = (PackageSetting) obj;
6261                return ps.isPrivileged();
6262            }
6263        }
6264        return false;
6265    }
6266
6267    @Override
6268    public String[] getAppOpPermissionPackages(String permissionName) {
6269        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
6270            return null;
6271        }
6272        synchronized (mPackages) {
6273            ArraySet<String> pkgs = mAppOpPermissionPackages.get(permissionName);
6274            if (pkgs == null) {
6275                return null;
6276            }
6277            return pkgs.toArray(new String[pkgs.size()]);
6278        }
6279    }
6280
6281    @Override
6282    public ResolveInfo resolveIntent(Intent intent, String resolvedType,
6283            int flags, int userId) {
6284        return resolveIntentInternal(
6285                intent, resolvedType, flags, userId, false /*includeInstantApps*/);
6286    }
6287
6288    private ResolveInfo resolveIntentInternal(Intent intent, String resolvedType,
6289            int flags, int userId, boolean resolveForStart) {
6290        try {
6291            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "resolveIntent");
6292
6293            if (!sUserManager.exists(userId)) return null;
6294            final int callingUid = Binder.getCallingUid();
6295            flags = updateFlagsForResolve(flags, userId, intent, callingUid, resolveForStart);
6296            enforceCrossUserPermission(callingUid, userId,
6297                    false /*requireFullPermission*/, false /*checkShell*/, "resolve intent");
6298
6299            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "queryIntentActivities");
6300            final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType,
6301                    flags, callingUid, userId, resolveForStart);
6302            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
6303
6304            final ResolveInfo bestChoice =
6305                    chooseBestActivity(intent, resolvedType, flags, query, userId);
6306            return bestChoice;
6307        } finally {
6308            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
6309        }
6310    }
6311
6312    @Override
6313    public ResolveInfo findPersistentPreferredActivity(Intent intent, int userId) {
6314        if (!UserHandle.isSameApp(Binder.getCallingUid(), Process.SYSTEM_UID)) {
6315            throw new SecurityException(
6316                    "findPersistentPreferredActivity can only be run by the system");
6317        }
6318        if (!sUserManager.exists(userId)) {
6319            return null;
6320        }
6321        final int callingUid = Binder.getCallingUid();
6322        intent = updateIntentForResolve(intent);
6323        final String resolvedType = intent.resolveTypeIfNeeded(mContext.getContentResolver());
6324        final int flags = updateFlagsForResolve(
6325                0, userId, intent, callingUid, false /*includeInstantApps*/);
6326        final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags,
6327                userId);
6328        synchronized (mPackages) {
6329            return findPersistentPreferredActivityLP(intent, resolvedType, flags, query, false,
6330                    userId);
6331        }
6332    }
6333
6334    @Override
6335    public void setLastChosenActivity(Intent intent, String resolvedType, int flags,
6336            IntentFilter filter, int match, ComponentName activity) {
6337        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
6338            return;
6339        }
6340        final int userId = UserHandle.getCallingUserId();
6341        if (DEBUG_PREFERRED) {
6342            Log.v(TAG, "setLastChosenActivity intent=" + intent
6343                + " resolvedType=" + resolvedType
6344                + " flags=" + flags
6345                + " filter=" + filter
6346                + " match=" + match
6347                + " activity=" + activity);
6348            filter.dump(new PrintStreamPrinter(System.out), "    ");
6349        }
6350        intent.setComponent(null);
6351        final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags,
6352                userId);
6353        // Find any earlier preferred or last chosen entries and nuke them
6354        findPreferredActivity(intent, resolvedType,
6355                flags, query, 0, false, true, false, userId);
6356        // Add the new activity as the last chosen for this filter
6357        addPreferredActivityInternal(filter, match, null, activity, false, userId,
6358                "Setting last chosen");
6359    }
6360
6361    @Override
6362    public ResolveInfo getLastChosenActivity(Intent intent, String resolvedType, int flags) {
6363        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
6364            return null;
6365        }
6366        final int userId = UserHandle.getCallingUserId();
6367        if (DEBUG_PREFERRED) Log.v(TAG, "Querying last chosen activity for " + intent);
6368        final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags,
6369                userId);
6370        return findPreferredActivity(intent, resolvedType, flags, query, 0,
6371                false, false, false, userId);
6372    }
6373
6374    /**
6375     * Returns whether or not instant apps have been disabled remotely.
6376     */
6377    private boolean isEphemeralDisabled() {
6378        return mEphemeralAppsDisabled;
6379    }
6380
6381    private boolean isInstantAppAllowed(
6382            Intent intent, List<ResolveInfo> resolvedActivities, int userId,
6383            boolean skipPackageCheck) {
6384        if (mInstantAppResolverConnection == null) {
6385            return false;
6386        }
6387        if (mInstantAppInstallerActivity == null) {
6388            return false;
6389        }
6390        if (intent.getComponent() != null) {
6391            return false;
6392        }
6393        if ((intent.getFlags() & Intent.FLAG_IGNORE_EPHEMERAL) != 0) {
6394            return false;
6395        }
6396        if (!skipPackageCheck && intent.getPackage() != null) {
6397            return false;
6398        }
6399        final boolean isWebUri = hasWebURI(intent);
6400        if (!isWebUri || intent.getData().getHost() == null) {
6401            return false;
6402        }
6403        // Deny ephemeral apps if the user chose _ALWAYS or _ALWAYS_ASK for intent resolution.
6404        // Or if there's already an ephemeral app installed that handles the action
6405        synchronized (mPackages) {
6406            final int count = (resolvedActivities == null ? 0 : resolvedActivities.size());
6407            for (int n = 0; n < count; n++) {
6408                final ResolveInfo info = resolvedActivities.get(n);
6409                final String packageName = info.activityInfo.packageName;
6410                final PackageSetting ps = mSettings.mPackages.get(packageName);
6411                if (ps != null) {
6412                    // only check domain verification status if the app is not a browser
6413                    if (!info.handleAllWebDataURI) {
6414                        // Try to get the status from User settings first
6415                        final long packedStatus = getDomainVerificationStatusLPr(ps, userId);
6416                        final int status = (int) (packedStatus >> 32);
6417                        if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS
6418                            || status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) {
6419                            if (DEBUG_EPHEMERAL) {
6420                                Slog.v(TAG, "DENY instant app;"
6421                                    + " pkg: " + packageName + ", status: " + status);
6422                            }
6423                            return false;
6424                        }
6425                    }
6426                    if (ps.getInstantApp(userId)) {
6427                        if (DEBUG_EPHEMERAL) {
6428                            Slog.v(TAG, "DENY instant app installed;"
6429                                    + " pkg: " + packageName);
6430                        }
6431                        return false;
6432                    }
6433                }
6434            }
6435        }
6436        // We've exhausted all ways to deny ephemeral application; let the system look for them.
6437        return true;
6438    }
6439
6440    private void requestInstantAppResolutionPhaseTwo(AuxiliaryResolveInfo responseObj,
6441            Intent origIntent, String resolvedType, String callingPackage,
6442            Bundle verificationBundle, int userId) {
6443        final Message msg = mHandler.obtainMessage(INSTANT_APP_RESOLUTION_PHASE_TWO,
6444                new InstantAppRequest(responseObj, origIntent, resolvedType,
6445                        callingPackage, userId, verificationBundle));
6446        mHandler.sendMessage(msg);
6447    }
6448
6449    private ResolveInfo chooseBestActivity(Intent intent, String resolvedType,
6450            int flags, List<ResolveInfo> query, int userId) {
6451        if (query != null) {
6452            final int N = query.size();
6453            if (N == 1) {
6454                return query.get(0);
6455            } else if (N > 1) {
6456                final boolean debug = ((intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0);
6457                // If there is more than one activity with the same priority,
6458                // then let the user decide between them.
6459                ResolveInfo r0 = query.get(0);
6460                ResolveInfo r1 = query.get(1);
6461                if (DEBUG_INTENT_MATCHING || debug) {
6462                    Slog.v(TAG, r0.activityInfo.name + "=" + r0.priority + " vs "
6463                            + r1.activityInfo.name + "=" + r1.priority);
6464                }
6465                // If the first activity has a higher priority, or a different
6466                // default, then it is always desirable to pick it.
6467                if (r0.priority != r1.priority
6468                        || r0.preferredOrder != r1.preferredOrder
6469                        || r0.isDefault != r1.isDefault) {
6470                    return query.get(0);
6471                }
6472                // If we have saved a preference for a preferred activity for
6473                // this Intent, use that.
6474                ResolveInfo ri = findPreferredActivity(intent, resolvedType,
6475                        flags, query, r0.priority, true, false, debug, userId);
6476                if (ri != null) {
6477                    return ri;
6478                }
6479                // If we have an ephemeral app, use it
6480                for (int i = 0; i < N; i++) {
6481                    ri = query.get(i);
6482                    if (ri.activityInfo.applicationInfo.isInstantApp()) {
6483                        final String packageName = ri.activityInfo.packageName;
6484                        final PackageSetting ps = mSettings.mPackages.get(packageName);
6485                        final long packedStatus = getDomainVerificationStatusLPr(ps, userId);
6486                        final int status = (int)(packedStatus >> 32);
6487                        if (status != INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) {
6488                            return ri;
6489                        }
6490                    }
6491                }
6492                ri = new ResolveInfo(mResolveInfo);
6493                ri.activityInfo = new ActivityInfo(ri.activityInfo);
6494                ri.activityInfo.labelRes = ResolverActivity.getLabelRes(intent.getAction());
6495                // If all of the options come from the same package, show the application's
6496                // label and icon instead of the generic resolver's.
6497                // Some calls like Intent.resolveActivityInfo query the ResolveInfo from here
6498                // and then throw away the ResolveInfo itself, meaning that the caller loses
6499                // the resolvePackageName. Therefore the activityInfo.labelRes above provides
6500                // a fallback for this case; we only set the target package's resources on
6501                // the ResolveInfo, not the ActivityInfo.
6502                final String intentPackage = intent.getPackage();
6503                if (!TextUtils.isEmpty(intentPackage) && allHavePackage(query, intentPackage)) {
6504                    final ApplicationInfo appi = query.get(0).activityInfo.applicationInfo;
6505                    ri.resolvePackageName = intentPackage;
6506                    if (userNeedsBadging(userId)) {
6507                        ri.noResourceId = true;
6508                    } else {
6509                        ri.icon = appi.icon;
6510                    }
6511                    ri.iconResourceId = appi.icon;
6512                    ri.labelRes = appi.labelRes;
6513                }
6514                ri.activityInfo.applicationInfo = new ApplicationInfo(
6515                        ri.activityInfo.applicationInfo);
6516                if (userId != 0) {
6517                    ri.activityInfo.applicationInfo.uid = UserHandle.getUid(userId,
6518                            UserHandle.getAppId(ri.activityInfo.applicationInfo.uid));
6519                }
6520                // Make sure that the resolver is displayable in car mode
6521                if (ri.activityInfo.metaData == null) ri.activityInfo.metaData = new Bundle();
6522                ri.activityInfo.metaData.putBoolean(Intent.METADATA_DOCK_HOME, true);
6523                return ri;
6524            }
6525        }
6526        return null;
6527    }
6528
6529    /**
6530     * Return true if the given list is not empty and all of its contents have
6531     * an activityInfo with the given package name.
6532     */
6533    private boolean allHavePackage(List<ResolveInfo> list, String packageName) {
6534        if (ArrayUtils.isEmpty(list)) {
6535            return false;
6536        }
6537        for (int i = 0, N = list.size(); i < N; i++) {
6538            final ResolveInfo ri = list.get(i);
6539            final ActivityInfo ai = ri != null ? ri.activityInfo : null;
6540            if (ai == null || !packageName.equals(ai.packageName)) {
6541                return false;
6542            }
6543        }
6544        return true;
6545    }
6546
6547    private ResolveInfo findPersistentPreferredActivityLP(Intent intent, String resolvedType,
6548            int flags, List<ResolveInfo> query, boolean debug, int userId) {
6549        final int N = query.size();
6550        PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities
6551                .get(userId);
6552        // Get the list of persistent preferred activities that handle the intent
6553        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for presistent preferred activities...");
6554        List<PersistentPreferredActivity> pprefs = ppir != null
6555                ? ppir.queryIntent(intent, resolvedType,
6556                        (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0,
6557                        userId)
6558                : null;
6559        if (pprefs != null && pprefs.size() > 0) {
6560            final int M = pprefs.size();
6561            for (int i=0; i<M; i++) {
6562                final PersistentPreferredActivity ppa = pprefs.get(i);
6563                if (DEBUG_PREFERRED || debug) {
6564                    Slog.v(TAG, "Checking PersistentPreferredActivity ds="
6565                            + (ppa.countDataSchemes() > 0 ? ppa.getDataScheme(0) : "<none>")
6566                            + "\n  component=" + ppa.mComponent);
6567                    ppa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
6568                }
6569                final ActivityInfo ai = getActivityInfo(ppa.mComponent,
6570                        flags | MATCH_DISABLED_COMPONENTS, userId);
6571                if (DEBUG_PREFERRED || debug) {
6572                    Slog.v(TAG, "Found persistent preferred activity:");
6573                    if (ai != null) {
6574                        ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
6575                    } else {
6576                        Slog.v(TAG, "  null");
6577                    }
6578                }
6579                if (ai == null) {
6580                    // This previously registered persistent preferred activity
6581                    // component is no longer known. Ignore it and do NOT remove it.
6582                    continue;
6583                }
6584                for (int j=0; j<N; j++) {
6585                    final ResolveInfo ri = query.get(j);
6586                    if (!ri.activityInfo.applicationInfo.packageName
6587                            .equals(ai.applicationInfo.packageName)) {
6588                        continue;
6589                    }
6590                    if (!ri.activityInfo.name.equals(ai.name)) {
6591                        continue;
6592                    }
6593                    //  Found a persistent preference that can handle the intent.
6594                    if (DEBUG_PREFERRED || debug) {
6595                        Slog.v(TAG, "Returning persistent preferred activity: " +
6596                                ri.activityInfo.packageName + "/" + ri.activityInfo.name);
6597                    }
6598                    return ri;
6599                }
6600            }
6601        }
6602        return null;
6603    }
6604
6605    // TODO: handle preferred activities missing while user has amnesia
6606    ResolveInfo findPreferredActivity(Intent intent, String resolvedType, int flags,
6607            List<ResolveInfo> query, int priority, boolean always,
6608            boolean removeMatches, boolean debug, int userId) {
6609        if (!sUserManager.exists(userId)) return null;
6610        final int callingUid = Binder.getCallingUid();
6611        flags = updateFlagsForResolve(
6612                flags, userId, intent, callingUid, false /*includeInstantApps*/);
6613        intent = updateIntentForResolve(intent);
6614        // writer
6615        synchronized (mPackages) {
6616            // Try to find a matching persistent preferred activity.
6617            ResolveInfo pri = findPersistentPreferredActivityLP(intent, resolvedType, flags, query,
6618                    debug, userId);
6619
6620            // If a persistent preferred activity matched, use it.
6621            if (pri != null) {
6622                return pri;
6623            }
6624
6625            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
6626            // Get the list of preferred activities that handle the intent
6627            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for preferred activities...");
6628            List<PreferredActivity> prefs = pir != null
6629                    ? pir.queryIntent(intent, resolvedType,
6630                            (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0,
6631                            userId)
6632                    : null;
6633            if (prefs != null && prefs.size() > 0) {
6634                boolean changed = false;
6635                try {
6636                    // First figure out how good the original match set is.
6637                    // We will only allow preferred activities that came
6638                    // from the same match quality.
6639                    int match = 0;
6640
6641                    if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Figuring out best match...");
6642
6643                    final int N = query.size();
6644                    for (int j=0; j<N; j++) {
6645                        final ResolveInfo ri = query.get(j);
6646                        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Match for " + ri.activityInfo
6647                                + ": 0x" + Integer.toHexString(match));
6648                        if (ri.match > match) {
6649                            match = ri.match;
6650                        }
6651                    }
6652
6653                    if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Best match: 0x"
6654                            + Integer.toHexString(match));
6655
6656                    match &= IntentFilter.MATCH_CATEGORY_MASK;
6657                    final int M = prefs.size();
6658                    for (int i=0; i<M; i++) {
6659                        final PreferredActivity pa = prefs.get(i);
6660                        if (DEBUG_PREFERRED || debug) {
6661                            Slog.v(TAG, "Checking PreferredActivity ds="
6662                                    + (pa.countDataSchemes() > 0 ? pa.getDataScheme(0) : "<none>")
6663                                    + "\n  component=" + pa.mPref.mComponent);
6664                            pa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
6665                        }
6666                        if (pa.mPref.mMatch != match) {
6667                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping bad match "
6668                                    + Integer.toHexString(pa.mPref.mMatch));
6669                            continue;
6670                        }
6671                        // If it's not an "always" type preferred activity and that's what we're
6672                        // looking for, skip it.
6673                        if (always && !pa.mPref.mAlways) {
6674                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping mAlways=false entry");
6675                            continue;
6676                        }
6677                        final ActivityInfo ai = getActivityInfo(
6678                                pa.mPref.mComponent, flags | MATCH_DISABLED_COMPONENTS
6679                                        | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
6680                                userId);
6681                        if (DEBUG_PREFERRED || debug) {
6682                            Slog.v(TAG, "Found preferred activity:");
6683                            if (ai != null) {
6684                                ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
6685                            } else {
6686                                Slog.v(TAG, "  null");
6687                            }
6688                        }
6689                        if (ai == null) {
6690                            // This previously registered preferred activity
6691                            // component is no longer known.  Most likely an update
6692                            // to the app was installed and in the new version this
6693                            // component no longer exists.  Clean it up by removing
6694                            // it from the preferred activities list, and skip it.
6695                            Slog.w(TAG, "Removing dangling preferred activity: "
6696                                    + pa.mPref.mComponent);
6697                            pir.removeFilter(pa);
6698                            changed = true;
6699                            continue;
6700                        }
6701                        for (int j=0; j<N; j++) {
6702                            final ResolveInfo ri = query.get(j);
6703                            if (!ri.activityInfo.applicationInfo.packageName
6704                                    .equals(ai.applicationInfo.packageName)) {
6705                                continue;
6706                            }
6707                            if (!ri.activityInfo.name.equals(ai.name)) {
6708                                continue;
6709                            }
6710
6711                            if (removeMatches) {
6712                                pir.removeFilter(pa);
6713                                changed = true;
6714                                if (DEBUG_PREFERRED) {
6715                                    Slog.v(TAG, "Removing match " + pa.mPref.mComponent);
6716                                }
6717                                break;
6718                            }
6719
6720                            // Okay we found a previously set preferred or last chosen app.
6721                            // If the result set is different from when this
6722                            // was created, we need to clear it and re-ask the
6723                            // user their preference, if we're looking for an "always" type entry.
6724                            if (always && !pa.mPref.sameSet(query)) {
6725                                Slog.i(TAG, "Result set changed, dropping preferred activity for "
6726                                        + intent + " type " + resolvedType);
6727                                if (DEBUG_PREFERRED) {
6728                                    Slog.v(TAG, "Removing preferred activity since set changed "
6729                                            + pa.mPref.mComponent);
6730                                }
6731                                pir.removeFilter(pa);
6732                                // Re-add the filter as a "last chosen" entry (!always)
6733                                PreferredActivity lastChosen = new PreferredActivity(
6734                                        pa, pa.mPref.mMatch, null, pa.mPref.mComponent, false);
6735                                pir.addFilter(lastChosen);
6736                                changed = true;
6737                                return null;
6738                            }
6739
6740                            // Yay! Either the set matched or we're looking for the last chosen
6741                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Returning preferred activity: "
6742                                    + ri.activityInfo.packageName + "/" + ri.activityInfo.name);
6743                            return ri;
6744                        }
6745                    }
6746                } finally {
6747                    if (changed) {
6748                        if (DEBUG_PREFERRED) {
6749                            Slog.v(TAG, "Preferred activity bookkeeping changed; writing restrictions");
6750                        }
6751                        scheduleWritePackageRestrictionsLocked(userId);
6752                    }
6753                }
6754            }
6755        }
6756        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "No preferred activity to return");
6757        return null;
6758    }
6759
6760    /*
6761     * Returns if intent can be forwarded from the sourceUserId to the targetUserId
6762     */
6763    @Override
6764    public boolean canForwardTo(Intent intent, String resolvedType, int sourceUserId,
6765            int targetUserId) {
6766        mContext.enforceCallingOrSelfPermission(
6767                android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
6768        List<CrossProfileIntentFilter> matches =
6769                getMatchingCrossProfileIntentFilters(intent, resolvedType, sourceUserId);
6770        if (matches != null) {
6771            int size = matches.size();
6772            for (int i = 0; i < size; i++) {
6773                if (matches.get(i).getTargetUserId() == targetUserId) return true;
6774            }
6775        }
6776        if (hasWebURI(intent)) {
6777            // cross-profile app linking works only towards the parent.
6778            final int callingUid = Binder.getCallingUid();
6779            final UserInfo parent = getProfileParent(sourceUserId);
6780            synchronized(mPackages) {
6781                int flags = updateFlagsForResolve(0, parent.id, intent, callingUid,
6782                        false /*includeInstantApps*/);
6783                CrossProfileDomainInfo xpDomainInfo = getCrossProfileDomainPreferredLpr(
6784                        intent, resolvedType, flags, sourceUserId, parent.id);
6785                return xpDomainInfo != null;
6786            }
6787        }
6788        return false;
6789    }
6790
6791    private UserInfo getProfileParent(int userId) {
6792        final long identity = Binder.clearCallingIdentity();
6793        try {
6794            return sUserManager.getProfileParent(userId);
6795        } finally {
6796            Binder.restoreCallingIdentity(identity);
6797        }
6798    }
6799
6800    private List<CrossProfileIntentFilter> getMatchingCrossProfileIntentFilters(Intent intent,
6801            String resolvedType, int userId) {
6802        CrossProfileIntentResolver resolver = mSettings.mCrossProfileIntentResolvers.get(userId);
6803        if (resolver != null) {
6804            return resolver.queryIntent(intent, resolvedType, false /*defaultOnly*/, userId);
6805        }
6806        return null;
6807    }
6808
6809    @Override
6810    public @NonNull ParceledListSlice<ResolveInfo> queryIntentActivities(Intent intent,
6811            String resolvedType, int flags, int userId) {
6812        try {
6813            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "queryIntentActivities");
6814
6815            return new ParceledListSlice<>(
6816                    queryIntentActivitiesInternal(intent, resolvedType, flags, userId));
6817        } finally {
6818            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
6819        }
6820    }
6821
6822    /**
6823     * Returns the package name of the calling Uid if it's an instant app. If it isn't
6824     * instant, returns {@code null}.
6825     */
6826    private String getInstantAppPackageName(int callingUid) {
6827        synchronized (mPackages) {
6828            // If the caller is an isolated app use the owner's uid for the lookup.
6829            if (Process.isIsolated(callingUid)) {
6830                callingUid = mIsolatedOwners.get(callingUid);
6831            }
6832            final int appId = UserHandle.getAppId(callingUid);
6833            final Object obj = mSettings.getUserIdLPr(appId);
6834            if (obj instanceof PackageSetting) {
6835                final PackageSetting ps = (PackageSetting) obj;
6836                final boolean isInstantApp = ps.getInstantApp(UserHandle.getUserId(callingUid));
6837                return isInstantApp ? ps.pkg.packageName : null;
6838            }
6839        }
6840        return null;
6841    }
6842
6843    private @NonNull List<ResolveInfo> queryIntentActivitiesInternal(Intent intent,
6844            String resolvedType, int flags, int userId) {
6845        return queryIntentActivitiesInternal(
6846                intent, resolvedType, flags, Binder.getCallingUid(), userId, false);
6847    }
6848
6849    private @NonNull List<ResolveInfo> queryIntentActivitiesInternal(Intent intent,
6850            String resolvedType, int flags, int filterCallingUid, int userId,
6851            boolean resolveForStart) {
6852        if (!sUserManager.exists(userId)) return Collections.emptyList();
6853        final String instantAppPkgName = getInstantAppPackageName(filterCallingUid);
6854        enforceCrossUserPermission(Binder.getCallingUid(), userId,
6855                false /* requireFullPermission */, false /* checkShell */,
6856                "query intent activities");
6857        final String pkgName = intent.getPackage();
6858        ComponentName comp = intent.getComponent();
6859        if (comp == null) {
6860            if (intent.getSelector() != null) {
6861                intent = intent.getSelector();
6862                comp = intent.getComponent();
6863            }
6864        }
6865
6866        flags = updateFlagsForResolve(flags, userId, intent, filterCallingUid, resolveForStart,
6867                comp != null || pkgName != null /*onlyExposedExplicitly*/);
6868        if (comp != null) {
6869            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
6870            final ActivityInfo ai = getActivityInfo(comp, flags, userId);
6871            if (ai != null) {
6872                // When specifying an explicit component, we prevent the activity from being
6873                // used when either 1) the calling package is normal and the activity is within
6874                // an ephemeral application or 2) the calling package is ephemeral and the
6875                // activity is not visible to ephemeral applications.
6876                final boolean matchInstantApp =
6877                        (flags & PackageManager.MATCH_INSTANT) != 0;
6878                final boolean matchVisibleToInstantAppOnly =
6879                        (flags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
6880                final boolean matchExplicitlyVisibleOnly =
6881                        (flags & PackageManager.MATCH_EXPLICITLY_VISIBLE_ONLY) != 0;
6882                final boolean isCallerInstantApp =
6883                        instantAppPkgName != null;
6884                final boolean isTargetSameInstantApp =
6885                        comp.getPackageName().equals(instantAppPkgName);
6886                final boolean isTargetInstantApp =
6887                        (ai.applicationInfo.privateFlags
6888                                & ApplicationInfo.PRIVATE_FLAG_INSTANT) != 0;
6889                final boolean isTargetVisibleToInstantApp =
6890                        (ai.flags & ActivityInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0;
6891                final boolean isTargetExplicitlyVisibleToInstantApp =
6892                        isTargetVisibleToInstantApp
6893                        && (ai.flags & ActivityInfo.FLAG_IMPLICITLY_VISIBLE_TO_INSTANT_APP) == 0;
6894                final boolean isTargetHiddenFromInstantApp =
6895                        !isTargetVisibleToInstantApp
6896                        || (matchExplicitlyVisibleOnly && !isTargetExplicitlyVisibleToInstantApp);
6897                final boolean blockResolution =
6898                        !isTargetSameInstantApp
6899                        && ((!matchInstantApp && !isCallerInstantApp && isTargetInstantApp)
6900                                || (matchVisibleToInstantAppOnly && isCallerInstantApp
6901                                        && isTargetHiddenFromInstantApp));
6902                if (!blockResolution) {
6903                    final ResolveInfo ri = new ResolveInfo();
6904                    ri.activityInfo = ai;
6905                    list.add(ri);
6906                }
6907            }
6908            return applyPostResolutionFilter(list, instantAppPkgName);
6909        }
6910
6911        // reader
6912        boolean sortResult = false;
6913        boolean addEphemeral = false;
6914        List<ResolveInfo> result;
6915        final boolean ephemeralDisabled = isEphemeralDisabled();
6916        synchronized (mPackages) {
6917            if (pkgName == null) {
6918                List<CrossProfileIntentFilter> matchingFilters =
6919                        getMatchingCrossProfileIntentFilters(intent, resolvedType, userId);
6920                // Check for results that need to skip the current profile.
6921                ResolveInfo xpResolveInfo  = querySkipCurrentProfileIntents(matchingFilters, intent,
6922                        resolvedType, flags, userId);
6923                if (xpResolveInfo != null) {
6924                    List<ResolveInfo> xpResult = new ArrayList<ResolveInfo>(1);
6925                    xpResult.add(xpResolveInfo);
6926                    return applyPostResolutionFilter(
6927                            filterIfNotSystemUser(xpResult, userId), instantAppPkgName);
6928                }
6929
6930                // Check for results in the current profile.
6931                result = filterIfNotSystemUser(mActivities.queryIntent(
6932                        intent, resolvedType, flags, userId), userId);
6933                addEphemeral = !ephemeralDisabled
6934                        && isInstantAppAllowed(intent, result, userId, false /*skipPackageCheck*/);
6935                // Check for cross profile results.
6936                boolean hasNonNegativePriorityResult = hasNonNegativePriority(result);
6937                xpResolveInfo = queryCrossProfileIntents(
6938                        matchingFilters, intent, resolvedType, flags, userId,
6939                        hasNonNegativePriorityResult);
6940                if (xpResolveInfo != null && isUserEnabled(xpResolveInfo.targetUserId)) {
6941                    boolean isVisibleToUser = filterIfNotSystemUser(
6942                            Collections.singletonList(xpResolveInfo), userId).size() > 0;
6943                    if (isVisibleToUser) {
6944                        result.add(xpResolveInfo);
6945                        sortResult = true;
6946                    }
6947                }
6948                if (hasWebURI(intent)) {
6949                    CrossProfileDomainInfo xpDomainInfo = null;
6950                    final UserInfo parent = getProfileParent(userId);
6951                    if (parent != null) {
6952                        xpDomainInfo = getCrossProfileDomainPreferredLpr(intent, resolvedType,
6953                                flags, userId, parent.id);
6954                    }
6955                    if (xpDomainInfo != null) {
6956                        if (xpResolveInfo != null) {
6957                            // If we didn't remove it, the cross-profile ResolveInfo would be twice
6958                            // in the result.
6959                            result.remove(xpResolveInfo);
6960                        }
6961                        if (result.size() == 0 && !addEphemeral) {
6962                            // No result in current profile, but found candidate in parent user.
6963                            // And we are not going to add emphemeral app, so we can return the
6964                            // result straight away.
6965                            result.add(xpDomainInfo.resolveInfo);
6966                            return applyPostResolutionFilter(result, instantAppPkgName);
6967                        }
6968                    } else if (result.size() <= 1 && !addEphemeral) {
6969                        // No result in parent user and <= 1 result in current profile, and we
6970                        // are not going to add emphemeral app, so we can return the result without
6971                        // further processing.
6972                        return applyPostResolutionFilter(result, instantAppPkgName);
6973                    }
6974                    // We have more than one candidate (combining results from current and parent
6975                    // profile), so we need filtering and sorting.
6976                    result = filterCandidatesWithDomainPreferredActivitiesLPr(
6977                            intent, flags, result, xpDomainInfo, userId);
6978                    sortResult = true;
6979                }
6980            } else {
6981                final PackageParser.Package pkg = mPackages.get(pkgName);
6982                result = null;
6983                if (pkg != null) {
6984                    result = filterIfNotSystemUser(
6985                            mActivities.queryIntentForPackage(
6986                                    intent, resolvedType, flags, pkg.activities, userId),
6987                            userId);
6988                }
6989                if (result == null || result.size() == 0) {
6990                    // the caller wants to resolve for a particular package; however, there
6991                    // were no installed results, so, try to find an ephemeral result
6992                    addEphemeral = !ephemeralDisabled
6993                            && isInstantAppAllowed(
6994                                    intent, null /*result*/, userId, true /*skipPackageCheck*/);
6995                    if (result == null) {
6996                        result = new ArrayList<>();
6997                    }
6998                }
6999            }
7000        }
7001        if (addEphemeral) {
7002            result = maybeAddInstantAppInstaller(result, intent, resolvedType, flags, userId);
7003        }
7004        if (sortResult) {
7005            Collections.sort(result, mResolvePrioritySorter);
7006        }
7007        return applyPostResolutionFilter(result, instantAppPkgName);
7008    }
7009
7010    private List<ResolveInfo> maybeAddInstantAppInstaller(List<ResolveInfo> result, Intent intent,
7011            String resolvedType, int flags, int userId) {
7012        // first, check to see if we've got an instant app already installed
7013        final boolean alreadyResolvedLocally = (flags & PackageManager.MATCH_INSTANT) != 0;
7014        ResolveInfo localInstantApp = null;
7015        boolean blockResolution = false;
7016        if (!alreadyResolvedLocally) {
7017            final List<ResolveInfo> instantApps = mActivities.queryIntent(intent, resolvedType,
7018                    flags
7019                        | PackageManager.GET_RESOLVED_FILTER
7020                        | PackageManager.MATCH_INSTANT
7021                        | PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY,
7022                    userId);
7023            for (int i = instantApps.size() - 1; i >= 0; --i) {
7024                final ResolveInfo info = instantApps.get(i);
7025                final String packageName = info.activityInfo.packageName;
7026                final PackageSetting ps = mSettings.mPackages.get(packageName);
7027                if (ps.getInstantApp(userId)) {
7028                    final long packedStatus = getDomainVerificationStatusLPr(ps, userId);
7029                    final int status = (int)(packedStatus >> 32);
7030                    final int linkGeneration = (int)(packedStatus & 0xFFFFFFFF);
7031                    if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
7032                        // there's a local instant application installed, but, the user has
7033                        // chosen to never use it; skip resolution and don't acknowledge
7034                        // an instant application is even available
7035                        if (DEBUG_EPHEMERAL) {
7036                            Slog.v(TAG, "Instant app marked to never run; pkg: " + packageName);
7037                        }
7038                        blockResolution = true;
7039                        break;
7040                    } else {
7041                        // we have a locally installed instant application; skip resolution
7042                        // but acknowledge there's an instant application available
7043                        if (DEBUG_EPHEMERAL) {
7044                            Slog.v(TAG, "Found installed instant app; pkg: " + packageName);
7045                        }
7046                        localInstantApp = info;
7047                        break;
7048                    }
7049                }
7050            }
7051        }
7052        // no app installed, let's see if one's available
7053        AuxiliaryResolveInfo auxiliaryResponse = null;
7054        if (!blockResolution) {
7055            if (localInstantApp == null) {
7056                // we don't have an instant app locally, resolve externally
7057                Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "resolveEphemeral");
7058                final InstantAppRequest requestObject = new InstantAppRequest(
7059                        null /*responseObj*/, intent /*origIntent*/, resolvedType,
7060                        null /*callingPackage*/, userId, null /*verificationBundle*/);
7061                auxiliaryResponse =
7062                        InstantAppResolver.doInstantAppResolutionPhaseOne(
7063                                mContext, mInstantAppResolverConnection, requestObject);
7064                Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
7065            } else {
7066                // we have an instant application locally, but, we can't admit that since
7067                // callers shouldn't be able to determine prior browsing. create a dummy
7068                // auxiliary response so the downstream code behaves as if there's an
7069                // instant application available externally. when it comes time to start
7070                // the instant application, we'll do the right thing.
7071                final ApplicationInfo ai = localInstantApp.activityInfo.applicationInfo;
7072                auxiliaryResponse = new AuxiliaryResolveInfo(
7073                        ai.packageName, null /*splitName*/, ai.versionCode, null /*failureIntent*/);
7074            }
7075        }
7076        if (auxiliaryResponse != null) {
7077            if (DEBUG_EPHEMERAL) {
7078                Slog.v(TAG, "Adding ephemeral installer to the ResolveInfo list");
7079            }
7080            final ResolveInfo ephemeralInstaller = new ResolveInfo(mInstantAppInstallerInfo);
7081            final PackageSetting ps =
7082                    mSettings.mPackages.get(mInstantAppInstallerActivity.packageName);
7083            if (ps != null) {
7084                ephemeralInstaller.activityInfo = PackageParser.generateActivityInfo(
7085                        mInstantAppInstallerActivity, 0, ps.readUserState(userId), userId);
7086                ephemeralInstaller.activityInfo.launchToken = auxiliaryResponse.token;
7087                ephemeralInstaller.auxiliaryInfo = auxiliaryResponse;
7088                // make sure this resolver is the default
7089                ephemeralInstaller.isDefault = true;
7090                ephemeralInstaller.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART
7091                        | IntentFilter.MATCH_ADJUSTMENT_NORMAL;
7092                // add a non-generic filter
7093                ephemeralInstaller.filter = new IntentFilter(intent.getAction());
7094                ephemeralInstaller.filter.addDataPath(
7095                        intent.getData().getPath(), PatternMatcher.PATTERN_LITERAL);
7096                ephemeralInstaller.isInstantAppAvailable = true;
7097                result.add(ephemeralInstaller);
7098            }
7099        }
7100        return result;
7101    }
7102
7103    private static class CrossProfileDomainInfo {
7104        /* ResolveInfo for IntentForwarderActivity to send the intent to the other profile */
7105        ResolveInfo resolveInfo;
7106        /* Best domain verification status of the activities found in the other profile */
7107        int bestDomainVerificationStatus;
7108    }
7109
7110    private CrossProfileDomainInfo getCrossProfileDomainPreferredLpr(Intent intent,
7111            String resolvedType, int flags, int sourceUserId, int parentUserId) {
7112        if (!sUserManager.hasUserRestriction(UserManager.ALLOW_PARENT_PROFILE_APP_LINKING,
7113                sourceUserId)) {
7114            return null;
7115        }
7116        List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent,
7117                resolvedType, flags, parentUserId);
7118
7119        if (resultTargetUser == null || resultTargetUser.isEmpty()) {
7120            return null;
7121        }
7122        CrossProfileDomainInfo result = null;
7123        int size = resultTargetUser.size();
7124        for (int i = 0; i < size; i++) {
7125            ResolveInfo riTargetUser = resultTargetUser.get(i);
7126            // Intent filter verification is only for filters that specify a host. So don't return
7127            // those that handle all web uris.
7128            if (riTargetUser.handleAllWebDataURI) {
7129                continue;
7130            }
7131            String packageName = riTargetUser.activityInfo.packageName;
7132            PackageSetting ps = mSettings.mPackages.get(packageName);
7133            if (ps == null) {
7134                continue;
7135            }
7136            long verificationState = getDomainVerificationStatusLPr(ps, parentUserId);
7137            int status = (int)(verificationState >> 32);
7138            if (result == null) {
7139                result = new CrossProfileDomainInfo();
7140                result.resolveInfo = createForwardingResolveInfoUnchecked(new IntentFilter(),
7141                        sourceUserId, parentUserId);
7142                result.bestDomainVerificationStatus = status;
7143            } else {
7144                result.bestDomainVerificationStatus = bestDomainVerificationStatus(status,
7145                        result.bestDomainVerificationStatus);
7146            }
7147        }
7148        // Don't consider matches with status NEVER across profiles.
7149        if (result != null && result.bestDomainVerificationStatus
7150                == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
7151            return null;
7152        }
7153        return result;
7154    }
7155
7156    /**
7157     * Verification statuses are ordered from the worse to the best, except for
7158     * INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER, which is the worse.
7159     */
7160    private int bestDomainVerificationStatus(int status1, int status2) {
7161        if (status1 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
7162            return status2;
7163        }
7164        if (status2 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
7165            return status1;
7166        }
7167        return (int) MathUtils.max(status1, status2);
7168    }
7169
7170    private boolean isUserEnabled(int userId) {
7171        long callingId = Binder.clearCallingIdentity();
7172        try {
7173            UserInfo userInfo = sUserManager.getUserInfo(userId);
7174            return userInfo != null && userInfo.isEnabled();
7175        } finally {
7176            Binder.restoreCallingIdentity(callingId);
7177        }
7178    }
7179
7180    /**
7181     * Filter out activities with systemUserOnly flag set, when current user is not System.
7182     *
7183     * @return filtered list
7184     */
7185    private List<ResolveInfo> filterIfNotSystemUser(List<ResolveInfo> resolveInfos, int userId) {
7186        if (userId == UserHandle.USER_SYSTEM) {
7187            return resolveInfos;
7188        }
7189        for (int i = resolveInfos.size() - 1; i >= 0; i--) {
7190            ResolveInfo info = resolveInfos.get(i);
7191            if ((info.activityInfo.flags & ActivityInfo.FLAG_SYSTEM_USER_ONLY) != 0) {
7192                resolveInfos.remove(i);
7193            }
7194        }
7195        return resolveInfos;
7196    }
7197
7198    /**
7199     * Filters out ephemeral activities.
7200     * <p>When resolving for an ephemeral app, only activities that 1) are defined in the
7201     * ephemeral app or 2) marked with {@code visibleToEphemeral} are returned.
7202     *
7203     * @param resolveInfos The pre-filtered list of resolved activities
7204     * @param ephemeralPkgName The ephemeral package name. If {@code null}, no filtering
7205     *          is performed.
7206     * @return A filtered list of resolved activities.
7207     */
7208    private List<ResolveInfo> applyPostResolutionFilter(List<ResolveInfo> resolveInfos,
7209            String ephemeralPkgName) {
7210        for (int i = resolveInfos.size() - 1; i >= 0; i--) {
7211            final ResolveInfo info = resolveInfos.get(i);
7212            // TODO: When adding on-demand split support for non-instant apps, remove this check
7213            // and always apply post filtering
7214            // allow activities that are defined in the provided package
7215            if (info.activityInfo.splitName != null
7216                    && !ArrayUtils.contains(info.activityInfo.applicationInfo.splitNames,
7217                            info.activityInfo.splitName)) {
7218                // requested activity is defined in a split that hasn't been installed yet.
7219                // add the installer to the resolve list
7220                if (DEBUG_INSTALL) {
7221                    Slog.v(TAG, "Adding installer to the ResolveInfo list");
7222                }
7223                final ResolveInfo installerInfo = new ResolveInfo(mInstantAppInstallerInfo);
7224                installerInfo.auxiliaryInfo = new AuxiliaryResolveInfo(
7225                        info.activityInfo.packageName, info.activityInfo.splitName,
7226                        info.activityInfo.applicationInfo.versionCode, null /*failureIntent*/);
7227                // make sure this resolver is the default
7228                installerInfo.isDefault = true;
7229                installerInfo.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART
7230                        | IntentFilter.MATCH_ADJUSTMENT_NORMAL;
7231                // add a non-generic filter
7232                installerInfo.filter = new IntentFilter();
7233                // load resources from the correct package
7234                installerInfo.resolvePackageName = info.getComponentInfo().packageName;
7235                resolveInfos.set(i, installerInfo);
7236                continue;
7237            }
7238            // caller is a full app, don't need to apply any other filtering
7239            if (ephemeralPkgName == null) {
7240                continue;
7241            } else if (ephemeralPkgName.equals(info.activityInfo.packageName)) {
7242                // caller is same app; don't need to apply any other filtering
7243                continue;
7244            }
7245            // allow activities that have been explicitly exposed to ephemeral apps
7246            final boolean isEphemeralApp = info.activityInfo.applicationInfo.isInstantApp();
7247            if (!isEphemeralApp
7248                    && ((info.activityInfo.flags & ActivityInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0)) {
7249                continue;
7250            }
7251            resolveInfos.remove(i);
7252        }
7253        return resolveInfos;
7254    }
7255
7256    /**
7257     * @param resolveInfos list of resolve infos in descending priority order
7258     * @return if the list contains a resolve info with non-negative priority
7259     */
7260    private boolean hasNonNegativePriority(List<ResolveInfo> resolveInfos) {
7261        return resolveInfos.size() > 0 && resolveInfos.get(0).priority >= 0;
7262    }
7263
7264    private static boolean hasWebURI(Intent intent) {
7265        if (intent.getData() == null) {
7266            return false;
7267        }
7268        final String scheme = intent.getScheme();
7269        if (TextUtils.isEmpty(scheme)) {
7270            return false;
7271        }
7272        return scheme.equals(IntentFilter.SCHEME_HTTP) || scheme.equals(IntentFilter.SCHEME_HTTPS);
7273    }
7274
7275    private List<ResolveInfo> filterCandidatesWithDomainPreferredActivitiesLPr(Intent intent,
7276            int matchFlags, List<ResolveInfo> candidates, CrossProfileDomainInfo xpDomainInfo,
7277            int userId) {
7278        final boolean debug = (intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0;
7279
7280        if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) {
7281            Slog.v(TAG, "Filtering results with preferred activities. Candidates count: " +
7282                    candidates.size());
7283        }
7284
7285        ArrayList<ResolveInfo> result = new ArrayList<ResolveInfo>();
7286        ArrayList<ResolveInfo> alwaysList = new ArrayList<ResolveInfo>();
7287        ArrayList<ResolveInfo> undefinedList = new ArrayList<ResolveInfo>();
7288        ArrayList<ResolveInfo> alwaysAskList = new ArrayList<ResolveInfo>();
7289        ArrayList<ResolveInfo> neverList = new ArrayList<ResolveInfo>();
7290        ArrayList<ResolveInfo> matchAllList = new ArrayList<ResolveInfo>();
7291
7292        synchronized (mPackages) {
7293            final int count = candidates.size();
7294            // First, try to use linked apps. Partition the candidates into four lists:
7295            // one for the final results, one for the "do not use ever", one for "undefined status"
7296            // and finally one for "browser app type".
7297            for (int n=0; n<count; n++) {
7298                ResolveInfo info = candidates.get(n);
7299                String packageName = info.activityInfo.packageName;
7300                PackageSetting ps = mSettings.mPackages.get(packageName);
7301                if (ps != null) {
7302                    // Add to the special match all list (Browser use case)
7303                    if (info.handleAllWebDataURI) {
7304                        matchAllList.add(info);
7305                        continue;
7306                    }
7307                    // Try to get the status from User settings first
7308                    long packedStatus = getDomainVerificationStatusLPr(ps, userId);
7309                    int status = (int)(packedStatus >> 32);
7310                    int linkGeneration = (int)(packedStatus & 0xFFFFFFFF);
7311                    if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS) {
7312                        if (DEBUG_DOMAIN_VERIFICATION || debug) {
7313                            Slog.i(TAG, "  + always: " + info.activityInfo.packageName
7314                                    + " : linkgen=" + linkGeneration);
7315                        }
7316                        // Use link-enabled generation as preferredOrder, i.e.
7317                        // prefer newly-enabled over earlier-enabled.
7318                        info.preferredOrder = linkGeneration;
7319                        alwaysList.add(info);
7320                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
7321                        if (DEBUG_DOMAIN_VERIFICATION || debug) {
7322                            Slog.i(TAG, "  + never: " + info.activityInfo.packageName);
7323                        }
7324                        neverList.add(info);
7325                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) {
7326                        if (DEBUG_DOMAIN_VERIFICATION || debug) {
7327                            Slog.i(TAG, "  + always-ask: " + info.activityInfo.packageName);
7328                        }
7329                        alwaysAskList.add(info);
7330                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED ||
7331                            status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK) {
7332                        if (DEBUG_DOMAIN_VERIFICATION || debug) {
7333                            Slog.i(TAG, "  + ask: " + info.activityInfo.packageName);
7334                        }
7335                        undefinedList.add(info);
7336                    }
7337                }
7338            }
7339
7340            // We'll want to include browser possibilities in a few cases
7341            boolean includeBrowser = false;
7342
7343            // First try to add the "always" resolution(s) for the current user, if any
7344            if (alwaysList.size() > 0) {
7345                result.addAll(alwaysList);
7346            } else {
7347                // Add all undefined apps as we want them to appear in the disambiguation dialog.
7348                result.addAll(undefinedList);
7349                // Maybe add one for the other profile.
7350                if (xpDomainInfo != null && (
7351                        xpDomainInfo.bestDomainVerificationStatus
7352                        != INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER)) {
7353                    result.add(xpDomainInfo.resolveInfo);
7354                }
7355                includeBrowser = true;
7356            }
7357
7358            // The presence of any 'always ask' alternatives means we'll also offer browsers.
7359            // If there were 'always' entries their preferred order has been set, so we also
7360            // back that off to make the alternatives equivalent
7361            if (alwaysAskList.size() > 0) {
7362                for (ResolveInfo i : result) {
7363                    i.preferredOrder = 0;
7364                }
7365                result.addAll(alwaysAskList);
7366                includeBrowser = true;
7367            }
7368
7369            if (includeBrowser) {
7370                // Also add browsers (all of them or only the default one)
7371                if (DEBUG_DOMAIN_VERIFICATION) {
7372                    Slog.v(TAG, "   ...including browsers in candidate set");
7373                }
7374                if ((matchFlags & MATCH_ALL) != 0) {
7375                    result.addAll(matchAllList);
7376                } else {
7377                    // Browser/generic handling case.  If there's a default browser, go straight
7378                    // to that (but only if there is no other higher-priority match).
7379                    final String defaultBrowserPackageName = getDefaultBrowserPackageName(userId);
7380                    int maxMatchPrio = 0;
7381                    ResolveInfo defaultBrowserMatch = null;
7382                    final int numCandidates = matchAllList.size();
7383                    for (int n = 0; n < numCandidates; n++) {
7384                        ResolveInfo info = matchAllList.get(n);
7385                        // track the highest overall match priority...
7386                        if (info.priority > maxMatchPrio) {
7387                            maxMatchPrio = info.priority;
7388                        }
7389                        // ...and the highest-priority default browser match
7390                        if (info.activityInfo.packageName.equals(defaultBrowserPackageName)) {
7391                            if (defaultBrowserMatch == null
7392                                    || (defaultBrowserMatch.priority < info.priority)) {
7393                                if (debug) {
7394                                    Slog.v(TAG, "Considering default browser match " + info);
7395                                }
7396                                defaultBrowserMatch = info;
7397                            }
7398                        }
7399                    }
7400                    if (defaultBrowserMatch != null
7401                            && defaultBrowserMatch.priority >= maxMatchPrio
7402                            && !TextUtils.isEmpty(defaultBrowserPackageName))
7403                    {
7404                        if (debug) {
7405                            Slog.v(TAG, "Default browser match " + defaultBrowserMatch);
7406                        }
7407                        result.add(defaultBrowserMatch);
7408                    } else {
7409                        result.addAll(matchAllList);
7410                    }
7411                }
7412
7413                // If there is nothing selected, add all candidates and remove the ones that the user
7414                // has explicitly put into the INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER state
7415                if (result.size() == 0) {
7416                    result.addAll(candidates);
7417                    result.removeAll(neverList);
7418                }
7419            }
7420        }
7421        if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) {
7422            Slog.v(TAG, "Filtered results with preferred activities. New candidates count: " +
7423                    result.size());
7424            for (ResolveInfo info : result) {
7425                Slog.v(TAG, "  + " + info.activityInfo);
7426            }
7427        }
7428        return result;
7429    }
7430
7431    // Returns a packed value as a long:
7432    //
7433    // high 'int'-sized word: link status: undefined/ask/never/always.
7434    // low 'int'-sized word: relative priority among 'always' results.
7435    private long getDomainVerificationStatusLPr(PackageSetting ps, int userId) {
7436        long result = ps.getDomainVerificationStatusForUser(userId);
7437        // if none available, get the master status
7438        if (result >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) {
7439            if (ps.getIntentFilterVerificationInfo() != null) {
7440                result = ((long)ps.getIntentFilterVerificationInfo().getStatus()) << 32;
7441            }
7442        }
7443        return result;
7444    }
7445
7446    private ResolveInfo querySkipCurrentProfileIntents(
7447            List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType,
7448            int flags, int sourceUserId) {
7449        if (matchingFilters != null) {
7450            int size = matchingFilters.size();
7451            for (int i = 0; i < size; i ++) {
7452                CrossProfileIntentFilter filter = matchingFilters.get(i);
7453                if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0) {
7454                    // Checking if there are activities in the target user that can handle the
7455                    // intent.
7456                    ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent,
7457                            resolvedType, flags, sourceUserId);
7458                    if (resolveInfo != null) {
7459                        return resolveInfo;
7460                    }
7461                }
7462            }
7463        }
7464        return null;
7465    }
7466
7467    // Return matching ResolveInfo in target user if any.
7468    private ResolveInfo queryCrossProfileIntents(
7469            List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType,
7470            int flags, int sourceUserId, boolean matchInCurrentProfile) {
7471        if (matchingFilters != null) {
7472            // Two {@link CrossProfileIntentFilter}s can have the same targetUserId and
7473            // match the same intent. For performance reasons, it is better not to
7474            // run queryIntent twice for the same userId
7475            SparseBooleanArray alreadyTriedUserIds = new SparseBooleanArray();
7476            int size = matchingFilters.size();
7477            for (int i = 0; i < size; i++) {
7478                CrossProfileIntentFilter filter = matchingFilters.get(i);
7479                int targetUserId = filter.getTargetUserId();
7480                boolean skipCurrentProfile =
7481                        (filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0;
7482                boolean skipCurrentProfileIfNoMatchFound =
7483                        (filter.getFlags() & PackageManager.ONLY_IF_NO_MATCH_FOUND) != 0;
7484                if (!skipCurrentProfile && !alreadyTriedUserIds.get(targetUserId)
7485                        && (!skipCurrentProfileIfNoMatchFound || !matchInCurrentProfile)) {
7486                    // Checking if there are activities in the target user that can handle the
7487                    // intent.
7488                    ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent,
7489                            resolvedType, flags, sourceUserId);
7490                    if (resolveInfo != null) return resolveInfo;
7491                    alreadyTriedUserIds.put(targetUserId, true);
7492                }
7493            }
7494        }
7495        return null;
7496    }
7497
7498    /**
7499     * If the filter's target user can handle the intent and is enabled: returns a ResolveInfo that
7500     * will forward the intent to the filter's target user.
7501     * Otherwise, returns null.
7502     */
7503    private ResolveInfo createForwardingResolveInfo(CrossProfileIntentFilter filter, Intent intent,
7504            String resolvedType, int flags, int sourceUserId) {
7505        int targetUserId = filter.getTargetUserId();
7506        List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent,
7507                resolvedType, flags, targetUserId);
7508        if (resultTargetUser != null && isUserEnabled(targetUserId)) {
7509            // If all the matches in the target profile are suspended, return null.
7510            for (int i = resultTargetUser.size() - 1; i >= 0; i--) {
7511                if ((resultTargetUser.get(i).activityInfo.applicationInfo.flags
7512                        & ApplicationInfo.FLAG_SUSPENDED) == 0) {
7513                    return createForwardingResolveInfoUnchecked(filter, sourceUserId,
7514                            targetUserId);
7515                }
7516            }
7517        }
7518        return null;
7519    }
7520
7521    private ResolveInfo createForwardingResolveInfoUnchecked(IntentFilter filter,
7522            int sourceUserId, int targetUserId) {
7523        ResolveInfo forwardingResolveInfo = new ResolveInfo();
7524        long ident = Binder.clearCallingIdentity();
7525        boolean targetIsProfile;
7526        try {
7527            targetIsProfile = sUserManager.getUserInfo(targetUserId).isManagedProfile();
7528        } finally {
7529            Binder.restoreCallingIdentity(ident);
7530        }
7531        String className;
7532        if (targetIsProfile) {
7533            className = FORWARD_INTENT_TO_MANAGED_PROFILE;
7534        } else {
7535            className = FORWARD_INTENT_TO_PARENT;
7536        }
7537        ComponentName forwardingActivityComponentName = new ComponentName(
7538                mAndroidApplication.packageName, className);
7539        ActivityInfo forwardingActivityInfo = getActivityInfo(forwardingActivityComponentName, 0,
7540                sourceUserId);
7541        if (!targetIsProfile) {
7542            forwardingActivityInfo.showUserIcon = targetUserId;
7543            forwardingResolveInfo.noResourceId = true;
7544        }
7545        forwardingResolveInfo.activityInfo = forwardingActivityInfo;
7546        forwardingResolveInfo.priority = 0;
7547        forwardingResolveInfo.preferredOrder = 0;
7548        forwardingResolveInfo.match = 0;
7549        forwardingResolveInfo.isDefault = true;
7550        forwardingResolveInfo.filter = filter;
7551        forwardingResolveInfo.targetUserId = targetUserId;
7552        return forwardingResolveInfo;
7553    }
7554
7555    @Override
7556    public @NonNull ParceledListSlice<ResolveInfo> queryIntentActivityOptions(ComponentName caller,
7557            Intent[] specifics, String[] specificTypes, Intent intent,
7558            String resolvedType, int flags, int userId) {
7559        return new ParceledListSlice<>(queryIntentActivityOptionsInternal(caller, specifics,
7560                specificTypes, intent, resolvedType, flags, userId));
7561    }
7562
7563    private @NonNull List<ResolveInfo> queryIntentActivityOptionsInternal(ComponentName caller,
7564            Intent[] specifics, String[] specificTypes, Intent intent,
7565            String resolvedType, int flags, int userId) {
7566        if (!sUserManager.exists(userId)) return Collections.emptyList();
7567        final int callingUid = Binder.getCallingUid();
7568        flags = updateFlagsForResolve(flags, userId, intent, callingUid,
7569                false /*includeInstantApps*/);
7570        enforceCrossUserPermission(callingUid, userId,
7571                false /*requireFullPermission*/, false /*checkShell*/,
7572                "query intent activity options");
7573        final String resultsAction = intent.getAction();
7574
7575        final List<ResolveInfo> results = queryIntentActivitiesInternal(intent, resolvedType, flags
7576                | PackageManager.GET_RESOLVED_FILTER, userId);
7577
7578        if (DEBUG_INTENT_MATCHING) {
7579            Log.v(TAG, "Query " + intent + ": " + results);
7580        }
7581
7582        int specificsPos = 0;
7583        int N;
7584
7585        // todo: note that the algorithm used here is O(N^2).  This
7586        // isn't a problem in our current environment, but if we start running
7587        // into situations where we have more than 5 or 10 matches then this
7588        // should probably be changed to something smarter...
7589
7590        // First we go through and resolve each of the specific items
7591        // that were supplied, taking care of removing any corresponding
7592        // duplicate items in the generic resolve list.
7593        if (specifics != null) {
7594            for (int i=0; i<specifics.length; i++) {
7595                final Intent sintent = specifics[i];
7596                if (sintent == null) {
7597                    continue;
7598                }
7599
7600                if (DEBUG_INTENT_MATCHING) {
7601                    Log.v(TAG, "Specific #" + i + ": " + sintent);
7602                }
7603
7604                String action = sintent.getAction();
7605                if (resultsAction != null && resultsAction.equals(action)) {
7606                    // If this action was explicitly requested, then don't
7607                    // remove things that have it.
7608                    action = null;
7609                }
7610
7611                ResolveInfo ri = null;
7612                ActivityInfo ai = null;
7613
7614                ComponentName comp = sintent.getComponent();
7615                if (comp == null) {
7616                    ri = resolveIntent(
7617                        sintent,
7618                        specificTypes != null ? specificTypes[i] : null,
7619                            flags, userId);
7620                    if (ri == null) {
7621                        continue;
7622                    }
7623                    if (ri == mResolveInfo) {
7624                        // ACK!  Must do something better with this.
7625                    }
7626                    ai = ri.activityInfo;
7627                    comp = new ComponentName(ai.applicationInfo.packageName,
7628                            ai.name);
7629                } else {
7630                    ai = getActivityInfo(comp, flags, userId);
7631                    if (ai == null) {
7632                        continue;
7633                    }
7634                }
7635
7636                // Look for any generic query activities that are duplicates
7637                // of this specific one, and remove them from the results.
7638                if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Specific #" + i + ": " + ai);
7639                N = results.size();
7640                int j;
7641                for (j=specificsPos; j<N; j++) {
7642                    ResolveInfo sri = results.get(j);
7643                    if ((sri.activityInfo.name.equals(comp.getClassName())
7644                            && sri.activityInfo.applicationInfo.packageName.equals(
7645                                    comp.getPackageName()))
7646                        || (action != null && sri.filter.matchAction(action))) {
7647                        results.remove(j);
7648                        if (DEBUG_INTENT_MATCHING) Log.v(
7649                            TAG, "Removing duplicate item from " + j
7650                            + " due to specific " + specificsPos);
7651                        if (ri == null) {
7652                            ri = sri;
7653                        }
7654                        j--;
7655                        N--;
7656                    }
7657                }
7658
7659                // Add this specific item to its proper place.
7660                if (ri == null) {
7661                    ri = new ResolveInfo();
7662                    ri.activityInfo = ai;
7663                }
7664                results.add(specificsPos, ri);
7665                ri.specificIndex = i;
7666                specificsPos++;
7667            }
7668        }
7669
7670        // Now we go through the remaining generic results and remove any
7671        // duplicate actions that are found here.
7672        N = results.size();
7673        for (int i=specificsPos; i<N-1; i++) {
7674            final ResolveInfo rii = results.get(i);
7675            if (rii.filter == null) {
7676                continue;
7677            }
7678
7679            // Iterate over all of the actions of this result's intent
7680            // filter...  typically this should be just one.
7681            final Iterator<String> it = rii.filter.actionsIterator();
7682            if (it == null) {
7683                continue;
7684            }
7685            while (it.hasNext()) {
7686                final String action = it.next();
7687                if (resultsAction != null && resultsAction.equals(action)) {
7688                    // If this action was explicitly requested, then don't
7689                    // remove things that have it.
7690                    continue;
7691                }
7692                for (int j=i+1; j<N; j++) {
7693                    final ResolveInfo rij = results.get(j);
7694                    if (rij.filter != null && rij.filter.hasAction(action)) {
7695                        results.remove(j);
7696                        if (DEBUG_INTENT_MATCHING) Log.v(
7697                            TAG, "Removing duplicate item from " + j
7698                            + " due to action " + action + " at " + i);
7699                        j--;
7700                        N--;
7701                    }
7702                }
7703            }
7704
7705            // If the caller didn't request filter information, drop it now
7706            // so we don't have to marshall/unmarshall it.
7707            if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
7708                rii.filter = null;
7709            }
7710        }
7711
7712        // Filter out the caller activity if so requested.
7713        if (caller != null) {
7714            N = results.size();
7715            for (int i=0; i<N; i++) {
7716                ActivityInfo ainfo = results.get(i).activityInfo;
7717                if (caller.getPackageName().equals(ainfo.applicationInfo.packageName)
7718                        && caller.getClassName().equals(ainfo.name)) {
7719                    results.remove(i);
7720                    break;
7721                }
7722            }
7723        }
7724
7725        // If the caller didn't request filter information,
7726        // drop them now so we don't have to
7727        // marshall/unmarshall it.
7728        if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
7729            N = results.size();
7730            for (int i=0; i<N; i++) {
7731                results.get(i).filter = null;
7732            }
7733        }
7734
7735        if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Result: " + results);
7736        return results;
7737    }
7738
7739    @Override
7740    public @NonNull ParceledListSlice<ResolveInfo> queryIntentReceivers(Intent intent,
7741            String resolvedType, int flags, int userId) {
7742        return new ParceledListSlice<>(
7743                queryIntentReceiversInternal(intent, resolvedType, flags, userId));
7744    }
7745
7746    private @NonNull List<ResolveInfo> queryIntentReceiversInternal(Intent intent,
7747            String resolvedType, int flags, int userId) {
7748        if (!sUserManager.exists(userId)) return Collections.emptyList();
7749        final int callingUid = Binder.getCallingUid();
7750        final String instantAppPkgName = getInstantAppPackageName(callingUid);
7751        flags = updateFlagsForResolve(flags, userId, intent, callingUid,
7752                false /*includeInstantApps*/);
7753        ComponentName comp = intent.getComponent();
7754        if (comp == null) {
7755            if (intent.getSelector() != null) {
7756                intent = intent.getSelector();
7757                comp = intent.getComponent();
7758            }
7759        }
7760        if (comp != null) {
7761            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
7762            final ActivityInfo ai = getReceiverInfo(comp, flags, userId);
7763            if (ai != null) {
7764                // When specifying an explicit component, we prevent the activity from being
7765                // used when either 1) the calling package is normal and the activity is within
7766                // an instant application or 2) the calling package is ephemeral and the
7767                // activity is not visible to instant applications.
7768                final boolean matchInstantApp =
7769                        (flags & PackageManager.MATCH_INSTANT) != 0;
7770                final boolean matchVisibleToInstantAppOnly =
7771                        (flags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
7772                final boolean matchExplicitlyVisibleOnly =
7773                        (flags & PackageManager.MATCH_EXPLICITLY_VISIBLE_ONLY) != 0;
7774                final boolean isCallerInstantApp =
7775                        instantAppPkgName != null;
7776                final boolean isTargetSameInstantApp =
7777                        comp.getPackageName().equals(instantAppPkgName);
7778                final boolean isTargetInstantApp =
7779                        (ai.applicationInfo.privateFlags
7780                                & ApplicationInfo.PRIVATE_FLAG_INSTANT) != 0;
7781                final boolean isTargetVisibleToInstantApp =
7782                        (ai.flags & ActivityInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0;
7783                final boolean isTargetExplicitlyVisibleToInstantApp =
7784                        isTargetVisibleToInstantApp
7785                        && (ai.flags & ActivityInfo.FLAG_IMPLICITLY_VISIBLE_TO_INSTANT_APP) == 0;
7786                final boolean isTargetHiddenFromInstantApp =
7787                        !isTargetVisibleToInstantApp
7788                        || (matchExplicitlyVisibleOnly && !isTargetExplicitlyVisibleToInstantApp);
7789                final boolean blockResolution =
7790                        !isTargetSameInstantApp
7791                        && ((!matchInstantApp && !isCallerInstantApp && isTargetInstantApp)
7792                                || (matchVisibleToInstantAppOnly && isCallerInstantApp
7793                                        && isTargetHiddenFromInstantApp));
7794                if (!blockResolution) {
7795                    ResolveInfo ri = new ResolveInfo();
7796                    ri.activityInfo = ai;
7797                    list.add(ri);
7798                }
7799            }
7800            return applyPostResolutionFilter(list, instantAppPkgName);
7801        }
7802
7803        // reader
7804        synchronized (mPackages) {
7805            String pkgName = intent.getPackage();
7806            if (pkgName == null) {
7807                final List<ResolveInfo> result =
7808                        mReceivers.queryIntent(intent, resolvedType, flags, userId);
7809                return applyPostResolutionFilter(result, instantAppPkgName);
7810            }
7811            final PackageParser.Package pkg = mPackages.get(pkgName);
7812            if (pkg != null) {
7813                final List<ResolveInfo> result = mReceivers.queryIntentForPackage(
7814                        intent, resolvedType, flags, pkg.receivers, userId);
7815                return applyPostResolutionFilter(result, instantAppPkgName);
7816            }
7817            return Collections.emptyList();
7818        }
7819    }
7820
7821    @Override
7822    public ResolveInfo resolveService(Intent intent, String resolvedType, int flags, int userId) {
7823        final int callingUid = Binder.getCallingUid();
7824        return resolveServiceInternal(intent, resolvedType, flags, userId, callingUid);
7825    }
7826
7827    private ResolveInfo resolveServiceInternal(Intent intent, String resolvedType, int flags,
7828            int userId, int callingUid) {
7829        if (!sUserManager.exists(userId)) return null;
7830        flags = updateFlagsForResolve(
7831                flags, userId, intent, callingUid, false /*includeInstantApps*/);
7832        List<ResolveInfo> query = queryIntentServicesInternal(
7833                intent, resolvedType, flags, userId, callingUid, false /*includeInstantApps*/);
7834        if (query != null) {
7835            if (query.size() >= 1) {
7836                // If there is more than one service with the same priority,
7837                // just arbitrarily pick the first one.
7838                return query.get(0);
7839            }
7840        }
7841        return null;
7842    }
7843
7844    @Override
7845    public @NonNull ParceledListSlice<ResolveInfo> queryIntentServices(Intent intent,
7846            String resolvedType, int flags, int userId) {
7847        final int callingUid = Binder.getCallingUid();
7848        return new ParceledListSlice<>(queryIntentServicesInternal(
7849                intent, resolvedType, flags, userId, callingUid, false /*includeInstantApps*/));
7850    }
7851
7852    private @NonNull List<ResolveInfo> queryIntentServicesInternal(Intent intent,
7853            String resolvedType, int flags, int userId, int callingUid,
7854            boolean includeInstantApps) {
7855        if (!sUserManager.exists(userId)) return Collections.emptyList();
7856        final String instantAppPkgName = getInstantAppPackageName(callingUid);
7857        flags = updateFlagsForResolve(flags, userId, intent, callingUid, includeInstantApps);
7858        ComponentName comp = intent.getComponent();
7859        if (comp == null) {
7860            if (intent.getSelector() != null) {
7861                intent = intent.getSelector();
7862                comp = intent.getComponent();
7863            }
7864        }
7865        if (comp != null) {
7866            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
7867            final ServiceInfo si = getServiceInfo(comp, flags, userId);
7868            if (si != null) {
7869                // When specifying an explicit component, we prevent the service from being
7870                // used when either 1) the service is in an instant application and the
7871                // caller is not the same instant application or 2) the calling package is
7872                // ephemeral and the activity is not visible to ephemeral applications.
7873                final boolean matchInstantApp =
7874                        (flags & PackageManager.MATCH_INSTANT) != 0;
7875                final boolean matchVisibleToInstantAppOnly =
7876                        (flags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
7877                final boolean isCallerInstantApp =
7878                        instantAppPkgName != null;
7879                final boolean isTargetSameInstantApp =
7880                        comp.getPackageName().equals(instantAppPkgName);
7881                final boolean isTargetInstantApp =
7882                        (si.applicationInfo.privateFlags
7883                                & ApplicationInfo.PRIVATE_FLAG_INSTANT) != 0;
7884                final boolean isTargetHiddenFromInstantApp =
7885                        (si.flags & ServiceInfo.FLAG_VISIBLE_TO_INSTANT_APP) == 0;
7886                final boolean blockResolution =
7887                        !isTargetSameInstantApp
7888                        && ((!matchInstantApp && !isCallerInstantApp && isTargetInstantApp)
7889                                || (matchVisibleToInstantAppOnly && isCallerInstantApp
7890                                        && isTargetHiddenFromInstantApp));
7891                if (!blockResolution) {
7892                    final ResolveInfo ri = new ResolveInfo();
7893                    ri.serviceInfo = si;
7894                    list.add(ri);
7895                }
7896            }
7897            return list;
7898        }
7899
7900        // reader
7901        synchronized (mPackages) {
7902            String pkgName = intent.getPackage();
7903            if (pkgName == null) {
7904                return applyPostServiceResolutionFilter(
7905                        mServices.queryIntent(intent, resolvedType, flags, userId),
7906                        instantAppPkgName);
7907            }
7908            final PackageParser.Package pkg = mPackages.get(pkgName);
7909            if (pkg != null) {
7910                return applyPostServiceResolutionFilter(
7911                        mServices.queryIntentForPackage(intent, resolvedType, flags, pkg.services,
7912                                userId),
7913                        instantAppPkgName);
7914            }
7915            return Collections.emptyList();
7916        }
7917    }
7918
7919    private List<ResolveInfo> applyPostServiceResolutionFilter(List<ResolveInfo> resolveInfos,
7920            String instantAppPkgName) {
7921        // TODO: When adding on-demand split support for non-instant apps, remove this check
7922        // and always apply post filtering
7923        if (instantAppPkgName == null) {
7924            return resolveInfos;
7925        }
7926        for (int i = resolveInfos.size() - 1; i >= 0; i--) {
7927            final ResolveInfo info = resolveInfos.get(i);
7928            final boolean isEphemeralApp = info.serviceInfo.applicationInfo.isInstantApp();
7929            // allow services that are defined in the provided package
7930            if (isEphemeralApp && instantAppPkgName.equals(info.serviceInfo.packageName)) {
7931                if (info.serviceInfo.splitName != null
7932                        && !ArrayUtils.contains(info.serviceInfo.applicationInfo.splitNames,
7933                                info.serviceInfo.splitName)) {
7934                    // requested service is defined in a split that hasn't been installed yet.
7935                    // add the installer to the resolve list
7936                    if (DEBUG_EPHEMERAL) {
7937                        Slog.v(TAG, "Adding ephemeral installer to the ResolveInfo list");
7938                    }
7939                    final ResolveInfo installerInfo = new ResolveInfo(mInstantAppInstallerInfo);
7940                    installerInfo.auxiliaryInfo = new AuxiliaryResolveInfo(
7941                            info.serviceInfo.packageName, info.serviceInfo.splitName,
7942                            info.serviceInfo.applicationInfo.versionCode, null /*failureIntent*/);
7943                    // make sure this resolver is the default
7944                    installerInfo.isDefault = true;
7945                    installerInfo.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART
7946                            | IntentFilter.MATCH_ADJUSTMENT_NORMAL;
7947                    // add a non-generic filter
7948                    installerInfo.filter = new IntentFilter();
7949                    // load resources from the correct package
7950                    installerInfo.resolvePackageName = info.getComponentInfo().packageName;
7951                    resolveInfos.set(i, installerInfo);
7952                }
7953                continue;
7954            }
7955            // allow services that have been explicitly exposed to ephemeral apps
7956            if (!isEphemeralApp
7957                    && ((info.serviceInfo.flags & ServiceInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0)) {
7958                continue;
7959            }
7960            resolveInfos.remove(i);
7961        }
7962        return resolveInfos;
7963    }
7964
7965    @Override
7966    public @NonNull ParceledListSlice<ResolveInfo> queryIntentContentProviders(Intent intent,
7967            String resolvedType, int flags, int userId) {
7968        return new ParceledListSlice<>(
7969                queryIntentContentProvidersInternal(intent, resolvedType, flags, userId));
7970    }
7971
7972    private @NonNull List<ResolveInfo> queryIntentContentProvidersInternal(
7973            Intent intent, String resolvedType, int flags, int userId) {
7974        if (!sUserManager.exists(userId)) return Collections.emptyList();
7975        final int callingUid = Binder.getCallingUid();
7976        final String instantAppPkgName = getInstantAppPackageName(callingUid);
7977        flags = updateFlagsForResolve(flags, userId, intent, callingUid,
7978                false /*includeInstantApps*/);
7979        ComponentName comp = intent.getComponent();
7980        if (comp == null) {
7981            if (intent.getSelector() != null) {
7982                intent = intent.getSelector();
7983                comp = intent.getComponent();
7984            }
7985        }
7986        if (comp != null) {
7987            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
7988            final ProviderInfo pi = getProviderInfo(comp, flags, userId);
7989            if (pi != null) {
7990                // When specifying an explicit component, we prevent the provider from being
7991                // used when either 1) the provider is in an instant application and the
7992                // caller is not the same instant application or 2) the calling package is an
7993                // instant application and the provider is not visible to instant applications.
7994                final boolean matchInstantApp =
7995                        (flags & PackageManager.MATCH_INSTANT) != 0;
7996                final boolean matchVisibleToInstantAppOnly =
7997                        (flags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
7998                final boolean isCallerInstantApp =
7999                        instantAppPkgName != null;
8000                final boolean isTargetSameInstantApp =
8001                        comp.getPackageName().equals(instantAppPkgName);
8002                final boolean isTargetInstantApp =
8003                        (pi.applicationInfo.privateFlags
8004                                & ApplicationInfo.PRIVATE_FLAG_INSTANT) != 0;
8005                final boolean isTargetHiddenFromInstantApp =
8006                        (pi.flags & ProviderInfo.FLAG_VISIBLE_TO_INSTANT_APP) == 0;
8007                final boolean blockResolution =
8008                        !isTargetSameInstantApp
8009                        && ((!matchInstantApp && !isCallerInstantApp && isTargetInstantApp)
8010                                || (matchVisibleToInstantAppOnly && isCallerInstantApp
8011                                        && isTargetHiddenFromInstantApp));
8012                if (!blockResolution) {
8013                    final ResolveInfo ri = new ResolveInfo();
8014                    ri.providerInfo = pi;
8015                    list.add(ri);
8016                }
8017            }
8018            return list;
8019        }
8020
8021        // reader
8022        synchronized (mPackages) {
8023            String pkgName = intent.getPackage();
8024            if (pkgName == null) {
8025                return applyPostContentProviderResolutionFilter(
8026                        mProviders.queryIntent(intent, resolvedType, flags, userId),
8027                        instantAppPkgName);
8028            }
8029            final PackageParser.Package pkg = mPackages.get(pkgName);
8030            if (pkg != null) {
8031                return applyPostContentProviderResolutionFilter(
8032                        mProviders.queryIntentForPackage(
8033                        intent, resolvedType, flags, pkg.providers, userId),
8034                        instantAppPkgName);
8035            }
8036            return Collections.emptyList();
8037        }
8038    }
8039
8040    private List<ResolveInfo> applyPostContentProviderResolutionFilter(
8041            List<ResolveInfo> resolveInfos, String instantAppPkgName) {
8042        // TODO: When adding on-demand split support for non-instant applications, remove
8043        // this check and always apply post filtering
8044        if (instantAppPkgName == null) {
8045            return resolveInfos;
8046        }
8047        for (int i = resolveInfos.size() - 1; i >= 0; i--) {
8048            final ResolveInfo info = resolveInfos.get(i);
8049            final boolean isEphemeralApp = info.providerInfo.applicationInfo.isInstantApp();
8050            // allow providers that are defined in the provided package
8051            if (isEphemeralApp && instantAppPkgName.equals(info.providerInfo.packageName)) {
8052                if (info.providerInfo.splitName != null
8053                        && !ArrayUtils.contains(info.providerInfo.applicationInfo.splitNames,
8054                                info.providerInfo.splitName)) {
8055                    // requested provider is defined in a split that hasn't been installed yet.
8056                    // add the installer to the resolve list
8057                    if (DEBUG_EPHEMERAL) {
8058                        Slog.v(TAG, "Adding ephemeral installer to the ResolveInfo list");
8059                    }
8060                    final ResolveInfo installerInfo = new ResolveInfo(mInstantAppInstallerInfo);
8061                    installerInfo.auxiliaryInfo = new AuxiliaryResolveInfo(
8062                            info.providerInfo.packageName, info.providerInfo.splitName,
8063                            info.providerInfo.applicationInfo.versionCode, null /*failureIntent*/);
8064                    // make sure this resolver is the default
8065                    installerInfo.isDefault = true;
8066                    installerInfo.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART
8067                            | IntentFilter.MATCH_ADJUSTMENT_NORMAL;
8068                    // add a non-generic filter
8069                    installerInfo.filter = new IntentFilter();
8070                    // load resources from the correct package
8071                    installerInfo.resolvePackageName = info.getComponentInfo().packageName;
8072                    resolveInfos.set(i, installerInfo);
8073                }
8074                continue;
8075            }
8076            // allow providers that have been explicitly exposed to instant applications
8077            if (!isEphemeralApp
8078                    && ((info.providerInfo.flags & ProviderInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0)) {
8079                continue;
8080            }
8081            resolveInfos.remove(i);
8082        }
8083        return resolveInfos;
8084    }
8085
8086    @Override
8087    public ParceledListSlice<PackageInfo> getInstalledPackages(int flags, int userId) {
8088        final int callingUid = Binder.getCallingUid();
8089        if (getInstantAppPackageName(callingUid) != null) {
8090            return ParceledListSlice.emptyList();
8091        }
8092        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
8093        flags = updateFlagsForPackage(flags, userId, null);
8094        final boolean listUninstalled = (flags & MATCH_KNOWN_PACKAGES) != 0;
8095        enforceCrossUserPermission(callingUid, userId,
8096                true /* requireFullPermission */, false /* checkShell */,
8097                "get installed packages");
8098
8099        // writer
8100        synchronized (mPackages) {
8101            ArrayList<PackageInfo> list;
8102            if (listUninstalled) {
8103                list = new ArrayList<>(mSettings.mPackages.size());
8104                for (PackageSetting ps : mSettings.mPackages.values()) {
8105                    if (filterSharedLibPackageLPr(ps, callingUid, userId, flags)) {
8106                        continue;
8107                    }
8108                    if (filterAppAccessLPr(ps, callingUid, userId)) {
8109                        return null;
8110                    }
8111                    final PackageInfo pi = generatePackageInfo(ps, flags, userId);
8112                    if (pi != null) {
8113                        list.add(pi);
8114                    }
8115                }
8116            } else {
8117                list = new ArrayList<>(mPackages.size());
8118                for (PackageParser.Package p : mPackages.values()) {
8119                    final PackageSetting ps = (PackageSetting) p.mExtras;
8120                    if (filterSharedLibPackageLPr(ps, callingUid, userId, flags)) {
8121                        continue;
8122                    }
8123                    if (filterAppAccessLPr(ps, callingUid, userId)) {
8124                        return null;
8125                    }
8126                    final PackageInfo pi = generatePackageInfo((PackageSetting)
8127                            p.mExtras, flags, userId);
8128                    if (pi != null) {
8129                        list.add(pi);
8130                    }
8131                }
8132            }
8133
8134            return new ParceledListSlice<>(list);
8135        }
8136    }
8137
8138    private void addPackageHoldingPermissions(ArrayList<PackageInfo> list, PackageSetting ps,
8139            String[] permissions, boolean[] tmp, int flags, int userId) {
8140        int numMatch = 0;
8141        final PermissionsState permissionsState = ps.getPermissionsState();
8142        for (int i=0; i<permissions.length; i++) {
8143            final String permission = permissions[i];
8144            if (permissionsState.hasPermission(permission, userId)) {
8145                tmp[i] = true;
8146                numMatch++;
8147            } else {
8148                tmp[i] = false;
8149            }
8150        }
8151        if (numMatch == 0) {
8152            return;
8153        }
8154        final PackageInfo pi = generatePackageInfo(ps, flags, userId);
8155
8156        // The above might return null in cases of uninstalled apps or install-state
8157        // skew across users/profiles.
8158        if (pi != null) {
8159            if ((flags&PackageManager.GET_PERMISSIONS) == 0) {
8160                if (numMatch == permissions.length) {
8161                    pi.requestedPermissions = permissions;
8162                } else {
8163                    pi.requestedPermissions = new String[numMatch];
8164                    numMatch = 0;
8165                    for (int i=0; i<permissions.length; i++) {
8166                        if (tmp[i]) {
8167                            pi.requestedPermissions[numMatch] = permissions[i];
8168                            numMatch++;
8169                        }
8170                    }
8171                }
8172            }
8173            list.add(pi);
8174        }
8175    }
8176
8177    @Override
8178    public ParceledListSlice<PackageInfo> getPackagesHoldingPermissions(
8179            String[] permissions, int flags, int userId) {
8180        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
8181        flags = updateFlagsForPackage(flags, userId, permissions);
8182        enforceCrossUserPermission(Binder.getCallingUid(), userId,
8183                true /* requireFullPermission */, false /* checkShell */,
8184                "get packages holding permissions");
8185        final boolean listUninstalled = (flags & MATCH_KNOWN_PACKAGES) != 0;
8186
8187        // writer
8188        synchronized (mPackages) {
8189            ArrayList<PackageInfo> list = new ArrayList<PackageInfo>();
8190            boolean[] tmpBools = new boolean[permissions.length];
8191            if (listUninstalled) {
8192                for (PackageSetting ps : mSettings.mPackages.values()) {
8193                    addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags,
8194                            userId);
8195                }
8196            } else {
8197                for (PackageParser.Package pkg : mPackages.values()) {
8198                    PackageSetting ps = (PackageSetting)pkg.mExtras;
8199                    if (ps != null) {
8200                        addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags,
8201                                userId);
8202                    }
8203                }
8204            }
8205
8206            return new ParceledListSlice<PackageInfo>(list);
8207        }
8208    }
8209
8210    @Override
8211    public ParceledListSlice<ApplicationInfo> getInstalledApplications(int flags, int userId) {
8212        final int callingUid = Binder.getCallingUid();
8213        if (getInstantAppPackageName(callingUid) != null) {
8214            return ParceledListSlice.emptyList();
8215        }
8216        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
8217        flags = updateFlagsForApplication(flags, userId, null);
8218        final boolean listUninstalled = (flags & MATCH_KNOWN_PACKAGES) != 0;
8219
8220        // writer
8221        synchronized (mPackages) {
8222            ArrayList<ApplicationInfo> list;
8223            if (listUninstalled) {
8224                list = new ArrayList<>(mSettings.mPackages.size());
8225                for (PackageSetting ps : mSettings.mPackages.values()) {
8226                    ApplicationInfo ai;
8227                    int effectiveFlags = flags;
8228                    if (ps.isSystem()) {
8229                        effectiveFlags |= PackageManager.MATCH_ANY_USER;
8230                    }
8231                    if (ps.pkg != null) {
8232                        if (filterSharedLibPackageLPr(ps, callingUid, userId, flags)) {
8233                            continue;
8234                        }
8235                        if (filterAppAccessLPr(ps, callingUid, userId)) {
8236                            return null;
8237                        }
8238                        ai = PackageParser.generateApplicationInfo(ps.pkg, effectiveFlags,
8239                                ps.readUserState(userId), userId);
8240                        if (ai != null) {
8241                            ai.packageName = resolveExternalPackageNameLPr(ps.pkg);
8242                        }
8243                    } else {
8244                        // Shared lib filtering done in generateApplicationInfoFromSettingsLPw
8245                        // and already converts to externally visible package name
8246                        ai = generateApplicationInfoFromSettingsLPw(ps.name,
8247                                callingUid, effectiveFlags, userId);
8248                    }
8249                    if (ai != null) {
8250                        list.add(ai);
8251                    }
8252                }
8253            } else {
8254                list = new ArrayList<>(mPackages.size());
8255                for (PackageParser.Package p : mPackages.values()) {
8256                    if (p.mExtras != null) {
8257                        PackageSetting ps = (PackageSetting) p.mExtras;
8258                        if (filterSharedLibPackageLPr(ps, Binder.getCallingUid(), userId, flags)) {
8259                            continue;
8260                        }
8261                        if (filterAppAccessLPr(ps, callingUid, userId)) {
8262                            return null;
8263                        }
8264                        ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags,
8265                                ps.readUserState(userId), userId);
8266                        if (ai != null) {
8267                            ai.packageName = resolveExternalPackageNameLPr(p);
8268                            list.add(ai);
8269                        }
8270                    }
8271                }
8272            }
8273
8274            return new ParceledListSlice<>(list);
8275        }
8276    }
8277
8278    @Override
8279    public ParceledListSlice<InstantAppInfo> getInstantApps(int userId) {
8280        if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) {
8281            return null;
8282        }
8283        mContext.enforceCallingOrSelfPermission(Manifest.permission.ACCESS_INSTANT_APPS,
8284                "getEphemeralApplications");
8285        enforceCrossUserPermission(Binder.getCallingUid(), userId,
8286                true /* requireFullPermission */, false /* checkShell */,
8287                "getEphemeralApplications");
8288        synchronized (mPackages) {
8289            List<InstantAppInfo> instantApps = mInstantAppRegistry
8290                    .getInstantAppsLPr(userId);
8291            if (instantApps != null) {
8292                return new ParceledListSlice<>(instantApps);
8293            }
8294        }
8295        return null;
8296    }
8297
8298    @Override
8299    public boolean isInstantApp(String packageName, int userId) {
8300        enforceCrossUserPermission(Binder.getCallingUid(), userId,
8301                true /* requireFullPermission */, false /* checkShell */,
8302                "isInstantApp");
8303        if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) {
8304            return false;
8305        }
8306
8307        synchronized (mPackages) {
8308            int callingUid = Binder.getCallingUid();
8309            if (Process.isIsolated(callingUid)) {
8310                callingUid = mIsolatedOwners.get(callingUid);
8311            }
8312            final PackageSetting ps = mSettings.mPackages.get(packageName);
8313            PackageParser.Package pkg = mPackages.get(packageName);
8314            final boolean returnAllowed =
8315                    ps != null
8316                    && (isCallerSameApp(packageName, callingUid)
8317                            || canViewInstantApps(callingUid, userId)
8318                            || mInstantAppRegistry.isInstantAccessGranted(
8319                                    userId, UserHandle.getAppId(callingUid), ps.appId));
8320            if (returnAllowed) {
8321                return ps.getInstantApp(userId);
8322            }
8323        }
8324        return false;
8325    }
8326
8327    @Override
8328    public byte[] getInstantAppCookie(String packageName, int userId) {
8329        if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) {
8330            return null;
8331        }
8332
8333        enforceCrossUserPermission(Binder.getCallingUid(), userId,
8334                true /* requireFullPermission */, false /* checkShell */,
8335                "getInstantAppCookie");
8336        if (!isCallerSameApp(packageName, Binder.getCallingUid())) {
8337            return null;
8338        }
8339        synchronized (mPackages) {
8340            return mInstantAppRegistry.getInstantAppCookieLPw(
8341                    packageName, userId);
8342        }
8343    }
8344
8345    @Override
8346    public boolean setInstantAppCookie(String packageName, byte[] cookie, int userId) {
8347        if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) {
8348            return true;
8349        }
8350
8351        enforceCrossUserPermission(Binder.getCallingUid(), userId,
8352                true /* requireFullPermission */, true /* checkShell */,
8353                "setInstantAppCookie");
8354        if (!isCallerSameApp(packageName, Binder.getCallingUid())) {
8355            return false;
8356        }
8357        synchronized (mPackages) {
8358            return mInstantAppRegistry.setInstantAppCookieLPw(
8359                    packageName, cookie, userId);
8360        }
8361    }
8362
8363    @Override
8364    public Bitmap getInstantAppIcon(String packageName, int userId) {
8365        if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) {
8366            return null;
8367        }
8368
8369        mContext.enforceCallingOrSelfPermission(Manifest.permission.ACCESS_INSTANT_APPS,
8370                "getInstantAppIcon");
8371
8372        enforceCrossUserPermission(Binder.getCallingUid(), userId,
8373                true /* requireFullPermission */, false /* checkShell */,
8374                "getInstantAppIcon");
8375
8376        synchronized (mPackages) {
8377            return mInstantAppRegistry.getInstantAppIconLPw(
8378                    packageName, userId);
8379        }
8380    }
8381
8382    private boolean isCallerSameApp(String packageName, int uid) {
8383        PackageParser.Package pkg = mPackages.get(packageName);
8384        return pkg != null
8385                && UserHandle.getAppId(uid) == pkg.applicationInfo.uid;
8386    }
8387
8388    @Override
8389    public @NonNull ParceledListSlice<ApplicationInfo> getPersistentApplications(int flags) {
8390        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
8391            return ParceledListSlice.emptyList();
8392        }
8393        return new ParceledListSlice<>(getPersistentApplicationsInternal(flags));
8394    }
8395
8396    private @NonNull List<ApplicationInfo> getPersistentApplicationsInternal(int flags) {
8397        final ArrayList<ApplicationInfo> finalList = new ArrayList<ApplicationInfo>();
8398
8399        // reader
8400        synchronized (mPackages) {
8401            final Iterator<PackageParser.Package> i = mPackages.values().iterator();
8402            final int userId = UserHandle.getCallingUserId();
8403            while (i.hasNext()) {
8404                final PackageParser.Package p = i.next();
8405                if (p.applicationInfo == null) continue;
8406
8407                final boolean matchesUnaware = ((flags & MATCH_DIRECT_BOOT_UNAWARE) != 0)
8408                        && !p.applicationInfo.isDirectBootAware();
8409                final boolean matchesAware = ((flags & MATCH_DIRECT_BOOT_AWARE) != 0)
8410                        && p.applicationInfo.isDirectBootAware();
8411
8412                if ((p.applicationInfo.flags & ApplicationInfo.FLAG_PERSISTENT) != 0
8413                        && (!mSafeMode || isSystemApp(p))
8414                        && (matchesUnaware || matchesAware)) {
8415                    PackageSetting ps = mSettings.mPackages.get(p.packageName);
8416                    if (ps != null) {
8417                        ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags,
8418                                ps.readUserState(userId), userId);
8419                        if (ai != null) {
8420                            finalList.add(ai);
8421                        }
8422                    }
8423                }
8424            }
8425        }
8426
8427        return finalList;
8428    }
8429
8430    @Override
8431    public ProviderInfo resolveContentProvider(String name, int flags, int userId) {
8432        if (!sUserManager.exists(userId)) return null;
8433        flags = updateFlagsForComponent(flags, userId, name);
8434        final String instantAppPkgName = getInstantAppPackageName(Binder.getCallingUid());
8435        // reader
8436        synchronized (mPackages) {
8437            final PackageParser.Provider provider = mProvidersByAuthority.get(name);
8438            PackageSetting ps = provider != null
8439                    ? mSettings.mPackages.get(provider.owner.packageName)
8440                    : null;
8441            if (ps != null) {
8442                final boolean isInstantApp = ps.getInstantApp(userId);
8443                // normal application; filter out instant application provider
8444                if (instantAppPkgName == null && isInstantApp) {
8445                    return null;
8446                }
8447                // instant application; filter out other instant applications
8448                if (instantAppPkgName != null
8449                        && isInstantApp
8450                        && !provider.owner.packageName.equals(instantAppPkgName)) {
8451                    return null;
8452                }
8453                // instant application; filter out non-exposed provider
8454                if (instantAppPkgName != null
8455                        && !isInstantApp
8456                        && (provider.info.flags & ProviderInfo.FLAG_VISIBLE_TO_INSTANT_APP) == 0) {
8457                    return null;
8458                }
8459                // provider not enabled
8460                if (!mSettings.isEnabledAndMatchLPr(provider.info, flags, userId)) {
8461                    return null;
8462                }
8463                return PackageParser.generateProviderInfo(
8464                        provider, flags, ps.readUserState(userId), userId);
8465            }
8466            return null;
8467        }
8468    }
8469
8470    /**
8471     * @deprecated
8472     */
8473    @Deprecated
8474    public void querySyncProviders(List<String> outNames, List<ProviderInfo> outInfo) {
8475        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
8476            return;
8477        }
8478        // reader
8479        synchronized (mPackages) {
8480            final Iterator<Map.Entry<String, PackageParser.Provider>> i = mProvidersByAuthority
8481                    .entrySet().iterator();
8482            final int userId = UserHandle.getCallingUserId();
8483            while (i.hasNext()) {
8484                Map.Entry<String, PackageParser.Provider> entry = i.next();
8485                PackageParser.Provider p = entry.getValue();
8486                PackageSetting ps = mSettings.mPackages.get(p.owner.packageName);
8487
8488                if (ps != null && p.syncable
8489                        && (!mSafeMode || (p.info.applicationInfo.flags
8490                                &ApplicationInfo.FLAG_SYSTEM) != 0)) {
8491                    ProviderInfo info = PackageParser.generateProviderInfo(p, 0,
8492                            ps.readUserState(userId), userId);
8493                    if (info != null) {
8494                        outNames.add(entry.getKey());
8495                        outInfo.add(info);
8496                    }
8497                }
8498            }
8499        }
8500    }
8501
8502    @Override
8503    public @NonNull ParceledListSlice<ProviderInfo> queryContentProviders(String processName,
8504            int uid, int flags, String metaDataKey) {
8505        final int callingUid = Binder.getCallingUid();
8506        final int userId = processName != null ? UserHandle.getUserId(uid)
8507                : UserHandle.getCallingUserId();
8508        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
8509        flags = updateFlagsForComponent(flags, userId, processName);
8510        ArrayList<ProviderInfo> finalList = null;
8511        // reader
8512        synchronized (mPackages) {
8513            final Iterator<PackageParser.Provider> i = mProviders.mProviders.values().iterator();
8514            while (i.hasNext()) {
8515                final PackageParser.Provider p = i.next();
8516                PackageSetting ps = mSettings.mPackages.get(p.owner.packageName);
8517                if (ps != null && p.info.authority != null
8518                        && (processName == null
8519                                || (p.info.processName.equals(processName)
8520                                        && UserHandle.isSameApp(p.info.applicationInfo.uid, uid)))
8521                        && mSettings.isEnabledAndMatchLPr(p.info, flags, userId)) {
8522
8523                    // See PM.queryContentProviders()'s javadoc for why we have the metaData
8524                    // parameter.
8525                    if (metaDataKey != null
8526                            && (p.metaData == null || !p.metaData.containsKey(metaDataKey))) {
8527                        continue;
8528                    }
8529                    final ComponentName component =
8530                            new ComponentName(p.info.packageName, p.info.name);
8531                    if (filterAppAccessLPr(ps, callingUid, component, TYPE_PROVIDER, userId)) {
8532                        continue;
8533                    }
8534                    if (finalList == null) {
8535                        finalList = new ArrayList<ProviderInfo>(3);
8536                    }
8537                    ProviderInfo info = PackageParser.generateProviderInfo(p, flags,
8538                            ps.readUserState(userId), userId);
8539                    if (info != null) {
8540                        finalList.add(info);
8541                    }
8542                }
8543            }
8544        }
8545
8546        if (finalList != null) {
8547            Collections.sort(finalList, mProviderInitOrderSorter);
8548            return new ParceledListSlice<ProviderInfo>(finalList);
8549        }
8550
8551        return ParceledListSlice.emptyList();
8552    }
8553
8554    @Override
8555    public InstrumentationInfo getInstrumentationInfo(ComponentName component, int flags) {
8556        // reader
8557        synchronized (mPackages) {
8558            final int callingUid = Binder.getCallingUid();
8559            final int callingUserId = UserHandle.getUserId(callingUid);
8560            final PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
8561            if (ps == null) return null;
8562            if (filterAppAccessLPr(ps, callingUid, component, TYPE_UNKNOWN, callingUserId)) {
8563                return null;
8564            }
8565            final PackageParser.Instrumentation i = mInstrumentation.get(component);
8566            return PackageParser.generateInstrumentationInfo(i, flags);
8567        }
8568    }
8569
8570    @Override
8571    public @NonNull ParceledListSlice<InstrumentationInfo> queryInstrumentation(
8572            String targetPackage, int flags) {
8573        final int callingUid = Binder.getCallingUid();
8574        final int callingUserId = UserHandle.getUserId(callingUid);
8575        final PackageSetting ps = mSettings.mPackages.get(targetPackage);
8576        if (filterAppAccessLPr(ps, callingUid, callingUserId)) {
8577            return ParceledListSlice.emptyList();
8578        }
8579        return new ParceledListSlice<>(queryInstrumentationInternal(targetPackage, flags));
8580    }
8581
8582    private @NonNull List<InstrumentationInfo> queryInstrumentationInternal(String targetPackage,
8583            int flags) {
8584        ArrayList<InstrumentationInfo> finalList = new ArrayList<InstrumentationInfo>();
8585
8586        // reader
8587        synchronized (mPackages) {
8588            final Iterator<PackageParser.Instrumentation> i = mInstrumentation.values().iterator();
8589            while (i.hasNext()) {
8590                final PackageParser.Instrumentation p = i.next();
8591                if (targetPackage == null
8592                        || targetPackage.equals(p.info.targetPackage)) {
8593                    InstrumentationInfo ii = PackageParser.generateInstrumentationInfo(p,
8594                            flags);
8595                    if (ii != null) {
8596                        finalList.add(ii);
8597                    }
8598                }
8599            }
8600        }
8601
8602        return finalList;
8603    }
8604
8605    private void scanDirTracedLI(File dir, final int parseFlags, int scanFlags, long currentTime) {
8606        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanDir [" + dir.getAbsolutePath() + "]");
8607        try {
8608            scanDirLI(dir, parseFlags, scanFlags, currentTime);
8609        } finally {
8610            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
8611        }
8612    }
8613
8614    private void scanDirLI(File dir, int parseFlags, int scanFlags, long currentTime) {
8615        final File[] files = dir.listFiles();
8616        if (ArrayUtils.isEmpty(files)) {
8617            Log.d(TAG, "No files in app dir " + dir);
8618            return;
8619        }
8620
8621        if (DEBUG_PACKAGE_SCANNING) {
8622            Log.d(TAG, "Scanning app dir " + dir + " scanFlags=" + scanFlags
8623                    + " flags=0x" + Integer.toHexString(parseFlags));
8624        }
8625        ParallelPackageParser parallelPackageParser = new ParallelPackageParser(
8626                mSeparateProcesses, mOnlyCore, mMetrics, mCacheDir,
8627                mParallelPackageParserCallback);
8628
8629        // Submit files for parsing in parallel
8630        int fileCount = 0;
8631        for (File file : files) {
8632            final boolean isPackage = (isApkFile(file) || file.isDirectory())
8633                    && !PackageInstallerService.isStageName(file.getName());
8634            if (!isPackage) {
8635                // Ignore entries which are not packages
8636                continue;
8637            }
8638            parallelPackageParser.submit(file, parseFlags);
8639            fileCount++;
8640        }
8641
8642        // Process results one by one
8643        for (; fileCount > 0; fileCount--) {
8644            ParallelPackageParser.ParseResult parseResult = parallelPackageParser.take();
8645            Throwable throwable = parseResult.throwable;
8646            int errorCode = PackageManager.INSTALL_SUCCEEDED;
8647
8648            if (throwable == null) {
8649                // Static shared libraries have synthetic package names
8650                if (parseResult.pkg.applicationInfo.isStaticSharedLibrary()) {
8651                    renameStaticSharedLibraryPackage(parseResult.pkg);
8652                }
8653                try {
8654                    if (errorCode == PackageManager.INSTALL_SUCCEEDED) {
8655                        scanPackageLI(parseResult.pkg, parseResult.scanFile, parseFlags, scanFlags,
8656                                currentTime, null);
8657                    }
8658                } catch (PackageManagerException e) {
8659                    errorCode = e.error;
8660                    Slog.w(TAG, "Failed to scan " + parseResult.scanFile + ": " + e.getMessage());
8661                }
8662            } else if (throwable instanceof PackageParser.PackageParserException) {
8663                PackageParser.PackageParserException e = (PackageParser.PackageParserException)
8664                        throwable;
8665                errorCode = e.error;
8666                Slog.w(TAG, "Failed to parse " + parseResult.scanFile + ": " + e.getMessage());
8667            } else {
8668                throw new IllegalStateException("Unexpected exception occurred while parsing "
8669                        + parseResult.scanFile, throwable);
8670            }
8671
8672            // Delete invalid userdata apps
8673            if ((parseFlags & PackageParser.PARSE_IS_SYSTEM) == 0 &&
8674                    errorCode == PackageManager.INSTALL_FAILED_INVALID_APK) {
8675                logCriticalInfo(Log.WARN,
8676                        "Deleting invalid package at " + parseResult.scanFile);
8677                removeCodePathLI(parseResult.scanFile);
8678            }
8679        }
8680        parallelPackageParser.close();
8681    }
8682
8683    private static File getSettingsProblemFile() {
8684        File dataDir = Environment.getDataDirectory();
8685        File systemDir = new File(dataDir, "system");
8686        File fname = new File(systemDir, "uiderrors.txt");
8687        return fname;
8688    }
8689
8690    static void reportSettingsProblem(int priority, String msg) {
8691        logCriticalInfo(priority, msg);
8692    }
8693
8694    public static void logCriticalInfo(int priority, String msg) {
8695        Slog.println(priority, TAG, msg);
8696        EventLogTags.writePmCriticalInfo(msg);
8697        try {
8698            File fname = getSettingsProblemFile();
8699            FileOutputStream out = new FileOutputStream(fname, true);
8700            PrintWriter pw = new FastPrintWriter(out);
8701            SimpleDateFormat formatter = new SimpleDateFormat();
8702            String dateString = formatter.format(new Date(System.currentTimeMillis()));
8703            pw.println(dateString + ": " + msg);
8704            pw.close();
8705            FileUtils.setPermissions(
8706                    fname.toString(),
8707                    FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IROTH,
8708                    -1, -1);
8709        } catch (java.io.IOException e) {
8710        }
8711    }
8712
8713    private long getLastModifiedTime(PackageParser.Package pkg, File srcFile) {
8714        if (srcFile.isDirectory()) {
8715            final File baseFile = new File(pkg.baseCodePath);
8716            long maxModifiedTime = baseFile.lastModified();
8717            if (pkg.splitCodePaths != null) {
8718                for (int i = pkg.splitCodePaths.length - 1; i >=0; --i) {
8719                    final File splitFile = new File(pkg.splitCodePaths[i]);
8720                    maxModifiedTime = Math.max(maxModifiedTime, splitFile.lastModified());
8721                }
8722            }
8723            return maxModifiedTime;
8724        }
8725        return srcFile.lastModified();
8726    }
8727
8728    private void collectCertificatesLI(PackageSetting ps, PackageParser.Package pkg, File srcFile,
8729            final int policyFlags) throws PackageManagerException {
8730        // When upgrading from pre-N MR1, verify the package time stamp using the package
8731        // directory and not the APK file.
8732        final long lastModifiedTime = mIsPreNMR1Upgrade
8733                ? new File(pkg.codePath).lastModified() : getLastModifiedTime(pkg, srcFile);
8734        if (ps != null
8735                && ps.codePath.equals(srcFile)
8736                && ps.timeStamp == lastModifiedTime
8737                && !isCompatSignatureUpdateNeeded(pkg)
8738                && !isRecoverSignatureUpdateNeeded(pkg)) {
8739            long mSigningKeySetId = ps.keySetData.getProperSigningKeySet();
8740            KeySetManagerService ksms = mSettings.mKeySetManagerService;
8741            ArraySet<PublicKey> signingKs;
8742            synchronized (mPackages) {
8743                signingKs = ksms.getPublicKeysFromKeySetLPr(mSigningKeySetId);
8744            }
8745            if (ps.signatures.mSignatures != null
8746                    && ps.signatures.mSignatures.length != 0
8747                    && signingKs != null) {
8748                // Optimization: reuse the existing cached certificates
8749                // if the package appears to be unchanged.
8750                pkg.mSignatures = ps.signatures.mSignatures;
8751                pkg.mSigningKeys = signingKs;
8752                return;
8753            }
8754
8755            Slog.w(TAG, "PackageSetting for " + ps.name
8756                    + " is missing signatures.  Collecting certs again to recover them.");
8757        } else {
8758            Slog.i(TAG, srcFile.toString() + " changed; collecting certs");
8759        }
8760
8761        try {
8762            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "collectCertificates");
8763            PackageParser.collectCertificates(pkg, policyFlags);
8764        } catch (PackageParserException e) {
8765            throw PackageManagerException.from(e);
8766        } finally {
8767            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
8768        }
8769    }
8770
8771    /**
8772     *  Traces a package scan.
8773     *  @see #scanPackageLI(File, int, int, long, UserHandle)
8774     */
8775    private PackageParser.Package scanPackageTracedLI(File scanFile, final int parseFlags,
8776            int scanFlags, long currentTime, UserHandle user) throws PackageManagerException {
8777        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage [" + scanFile.toString() + "]");
8778        try {
8779            return scanPackageLI(scanFile, parseFlags, scanFlags, currentTime, user);
8780        } finally {
8781            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
8782        }
8783    }
8784
8785    /**
8786     *  Scans a package and returns the newly parsed package.
8787     *  Returns {@code null} in case of errors and the error code is stored in mLastScanError
8788     */
8789    private PackageParser.Package scanPackageLI(File scanFile, int parseFlags, int scanFlags,
8790            long currentTime, UserHandle user) throws PackageManagerException {
8791        if (DEBUG_INSTALL) Slog.d(TAG, "Parsing: " + scanFile);
8792        PackageParser pp = new PackageParser();
8793        pp.setSeparateProcesses(mSeparateProcesses);
8794        pp.setOnlyCoreApps(mOnlyCore);
8795        pp.setDisplayMetrics(mMetrics);
8796        pp.setCallback(mPackageParserCallback);
8797
8798        if ((scanFlags & SCAN_TRUSTED_OVERLAY) != 0) {
8799            parseFlags |= PackageParser.PARSE_TRUSTED_OVERLAY;
8800        }
8801
8802        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "parsePackage");
8803        final PackageParser.Package pkg;
8804        try {
8805            pkg = pp.parsePackage(scanFile, parseFlags);
8806        } catch (PackageParserException e) {
8807            throw PackageManagerException.from(e);
8808        } finally {
8809            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
8810        }
8811
8812        // Static shared libraries have synthetic package names
8813        if (pkg.applicationInfo.isStaticSharedLibrary()) {
8814            renameStaticSharedLibraryPackage(pkg);
8815        }
8816
8817        return scanPackageLI(pkg, scanFile, parseFlags, scanFlags, currentTime, user);
8818    }
8819
8820    /**
8821     *  Scans a package and returns the newly parsed package.
8822     *  @throws PackageManagerException on a parse error.
8823     */
8824    private PackageParser.Package scanPackageLI(PackageParser.Package pkg, File scanFile,
8825            final int policyFlags, int scanFlags, long currentTime, @Nullable UserHandle user)
8826            throws PackageManagerException {
8827        // If the package has children and this is the first dive in the function
8828        // we scan the package with the SCAN_CHECK_ONLY flag set to see whether all
8829        // packages (parent and children) would be successfully scanned before the
8830        // actual scan since scanning mutates internal state and we want to atomically
8831        // install the package and its children.
8832        if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
8833            if (pkg.childPackages != null && pkg.childPackages.size() > 0) {
8834                scanFlags |= SCAN_CHECK_ONLY;
8835            }
8836        } else {
8837            scanFlags &= ~SCAN_CHECK_ONLY;
8838        }
8839
8840        // Scan the parent
8841        PackageParser.Package scannedPkg = scanPackageInternalLI(pkg, scanFile, policyFlags,
8842                scanFlags, currentTime, user);
8843
8844        // Scan the children
8845        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
8846        for (int i = 0; i < childCount; i++) {
8847            PackageParser.Package childPackage = pkg.childPackages.get(i);
8848            scanPackageInternalLI(childPackage, scanFile, policyFlags, scanFlags,
8849                    currentTime, user);
8850        }
8851
8852
8853        if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
8854            return scanPackageLI(pkg, scanFile, policyFlags, scanFlags, currentTime, user);
8855        }
8856
8857        return scannedPkg;
8858    }
8859
8860    /**
8861     *  Scans a package and returns the newly parsed package.
8862     *  @throws PackageManagerException on a parse error.
8863     */
8864    private PackageParser.Package scanPackageInternalLI(PackageParser.Package pkg, File scanFile,
8865            int policyFlags, int scanFlags, long currentTime, @Nullable UserHandle user)
8866            throws PackageManagerException {
8867        PackageSetting ps = null;
8868        PackageSetting updatedPkg;
8869        // reader
8870        synchronized (mPackages) {
8871            // Look to see if we already know about this package.
8872            String oldName = mSettings.getRenamedPackageLPr(pkg.packageName);
8873            if (pkg.mOriginalPackages != null && pkg.mOriginalPackages.contains(oldName)) {
8874                // This package has been renamed to its original name.  Let's
8875                // use that.
8876                ps = mSettings.getPackageLPr(oldName);
8877            }
8878            // If there was no original package, see one for the real package name.
8879            if (ps == null) {
8880                ps = mSettings.getPackageLPr(pkg.packageName);
8881            }
8882            // Check to see if this package could be hiding/updating a system
8883            // package.  Must look for it either under the original or real
8884            // package name depending on our state.
8885            updatedPkg = mSettings.getDisabledSystemPkgLPr(ps != null ? ps.name : pkg.packageName);
8886            if (DEBUG_INSTALL && updatedPkg != null) Slog.d(TAG, "updatedPkg = " + updatedPkg);
8887
8888            // If this is a package we don't know about on the system partition, we
8889            // may need to remove disabled child packages on the system partition
8890            // or may need to not add child packages if the parent apk is updated
8891            // on the data partition and no longer defines this child package.
8892            if ((policyFlags & PackageParser.PARSE_IS_SYSTEM) != 0) {
8893                // If this is a parent package for an updated system app and this system
8894                // app got an OTA update which no longer defines some of the child packages
8895                // we have to prune them from the disabled system packages.
8896                PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(pkg.packageName);
8897                if (disabledPs != null) {
8898                    final int scannedChildCount = (pkg.childPackages != null)
8899                            ? pkg.childPackages.size() : 0;
8900                    final int disabledChildCount = disabledPs.childPackageNames != null
8901                            ? disabledPs.childPackageNames.size() : 0;
8902                    for (int i = 0; i < disabledChildCount; i++) {
8903                        String disabledChildPackageName = disabledPs.childPackageNames.get(i);
8904                        boolean disabledPackageAvailable = false;
8905                        for (int j = 0; j < scannedChildCount; j++) {
8906                            PackageParser.Package childPkg = pkg.childPackages.get(j);
8907                            if (childPkg.packageName.equals(disabledChildPackageName)) {
8908                                disabledPackageAvailable = true;
8909                                break;
8910                            }
8911                         }
8912                         if (!disabledPackageAvailable) {
8913                             mSettings.removeDisabledSystemPackageLPw(disabledChildPackageName);
8914                         }
8915                    }
8916                }
8917            }
8918        }
8919
8920        final boolean isUpdatedPkg = updatedPkg != null;
8921        final boolean isUpdatedSystemPkg = isUpdatedPkg
8922                && (policyFlags & PackageParser.PARSE_IS_SYSTEM) != 0;
8923        boolean isUpdatedPkgBetter = false;
8924        // First check if this is a system package that may involve an update
8925        if (isUpdatedSystemPkg) {
8926            // If new package is not located in "/system/priv-app" (e.g. due to an OTA),
8927            // it needs to drop FLAG_PRIVILEGED.
8928            if (locationIsPrivileged(scanFile)) {
8929                updatedPkg.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
8930            } else {
8931                updatedPkg.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
8932            }
8933
8934            if (ps != null && !ps.codePath.equals(scanFile)) {
8935                // The path has changed from what was last scanned...  check the
8936                // version of the new path against what we have stored to determine
8937                // what to do.
8938                if (DEBUG_INSTALL) Slog.d(TAG, "Path changing from " + ps.codePath);
8939                if (pkg.mVersionCode <= ps.versionCode) {
8940                    // The system package has been updated and the code path does not match
8941                    // Ignore entry. Skip it.
8942                    if (DEBUG_INSTALL) Slog.i(TAG, "Package " + ps.name + " at " + scanFile
8943                            + " ignored: updated version " + ps.versionCode
8944                            + " better than this " + pkg.mVersionCode);
8945                    if (!updatedPkg.codePath.equals(scanFile)) {
8946                        Slog.w(PackageManagerService.TAG, "Code path for hidden system pkg "
8947                                + ps.name + " changing from " + updatedPkg.codePathString
8948                                + " to " + scanFile);
8949                        updatedPkg.codePath = scanFile;
8950                        updatedPkg.codePathString = scanFile.toString();
8951                        updatedPkg.resourcePath = scanFile;
8952                        updatedPkg.resourcePathString = scanFile.toString();
8953                    }
8954                    updatedPkg.pkg = pkg;
8955                    updatedPkg.versionCode = pkg.mVersionCode;
8956
8957                    // Update the disabled system child packages to point to the package too.
8958                    final int childCount = updatedPkg.childPackageNames != null
8959                            ? updatedPkg.childPackageNames.size() : 0;
8960                    for (int i = 0; i < childCount; i++) {
8961                        String childPackageName = updatedPkg.childPackageNames.get(i);
8962                        PackageSetting updatedChildPkg = mSettings.getDisabledSystemPkgLPr(
8963                                childPackageName);
8964                        if (updatedChildPkg != null) {
8965                            updatedChildPkg.pkg = pkg;
8966                            updatedChildPkg.versionCode = pkg.mVersionCode;
8967                        }
8968                    }
8969                } else {
8970                    // The current app on the system partition is better than
8971                    // what we have updated to on the data partition; switch
8972                    // back to the system partition version.
8973                    // At this point, its safely assumed that package installation for
8974                    // apps in system partition will go through. If not there won't be a working
8975                    // version of the app
8976                    // writer
8977                    synchronized (mPackages) {
8978                        // Just remove the loaded entries from package lists.
8979                        mPackages.remove(ps.name);
8980                    }
8981
8982                    logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile
8983                            + " reverting from " + ps.codePathString
8984                            + ": new version " + pkg.mVersionCode
8985                            + " better than installed " + ps.versionCode);
8986
8987                    InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
8988                            ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
8989                    synchronized (mInstallLock) {
8990                        args.cleanUpResourcesLI();
8991                    }
8992                    synchronized (mPackages) {
8993                        mSettings.enableSystemPackageLPw(ps.name);
8994                    }
8995                    isUpdatedPkgBetter = true;
8996                }
8997            }
8998        }
8999
9000        String resourcePath = null;
9001        String baseResourcePath = null;
9002        if ((policyFlags & PackageParser.PARSE_FORWARD_LOCK) != 0 && !isUpdatedPkgBetter) {
9003            if (ps != null && ps.resourcePathString != null) {
9004                resourcePath = ps.resourcePathString;
9005                baseResourcePath = ps.resourcePathString;
9006            } else {
9007                // Should not happen at all. Just log an error.
9008                Slog.e(TAG, "Resource path not set for package " + pkg.packageName);
9009            }
9010        } else {
9011            resourcePath = pkg.codePath;
9012            baseResourcePath = pkg.baseCodePath;
9013        }
9014
9015        // Set application objects path explicitly.
9016        pkg.setApplicationVolumeUuid(pkg.volumeUuid);
9017        pkg.setApplicationInfoCodePath(pkg.codePath);
9018        pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
9019        pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
9020        pkg.setApplicationInfoResourcePath(resourcePath);
9021        pkg.setApplicationInfoBaseResourcePath(baseResourcePath);
9022        pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
9023
9024        // throw an exception if we have an update to a system application, but, it's not more
9025        // recent than the package we've already scanned
9026        if (isUpdatedSystemPkg && !isUpdatedPkgBetter) {
9027            throw new PackageManagerException(Log.WARN, "Package " + ps.name + " at "
9028                    + scanFile + " ignored: updated version " + ps.versionCode
9029                    + " better than this " + pkg.mVersionCode);
9030        }
9031
9032        if (isUpdatedPkg) {
9033            // An updated system app will not have the PARSE_IS_SYSTEM flag set
9034            // initially
9035            policyFlags |= PackageParser.PARSE_IS_SYSTEM;
9036
9037            // An updated privileged app will not have the PARSE_IS_PRIVILEGED
9038            // flag set initially
9039            if ((updatedPkg.pkgPrivateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0) {
9040                policyFlags |= PackageParser.PARSE_IS_PRIVILEGED;
9041            }
9042        }
9043
9044        // Verify certificates against what was last scanned
9045        collectCertificatesLI(ps, pkg, scanFile, policyFlags);
9046
9047        /*
9048         * A new system app appeared, but we already had a non-system one of the
9049         * same name installed earlier.
9050         */
9051        boolean shouldHideSystemApp = false;
9052        if (!isUpdatedPkg && ps != null
9053                && (policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0 && !isSystemApp(ps)) {
9054            /*
9055             * Check to make sure the signatures match first. If they don't,
9056             * wipe the installed application and its data.
9057             */
9058            if (compareSignatures(ps.signatures.mSignatures, pkg.mSignatures)
9059                    != PackageManager.SIGNATURE_MATCH) {
9060                logCriticalInfo(Log.WARN, "Package " + ps.name + " appeared on system, but"
9061                        + " signatures don't match existing userdata copy; removing");
9062                try (PackageFreezer freezer = freezePackage(pkg.packageName,
9063                        "scanPackageInternalLI")) {
9064                    deletePackageLIF(pkg.packageName, null, true, null, 0, null, false, null);
9065                }
9066                ps = null;
9067            } else {
9068                /*
9069                 * If the newly-added system app is an older version than the
9070                 * already installed version, hide it. It will be scanned later
9071                 * and re-added like an update.
9072                 */
9073                if (pkg.mVersionCode <= ps.versionCode) {
9074                    shouldHideSystemApp = true;
9075                    logCriticalInfo(Log.INFO, "Package " + ps.name + " appeared at " + scanFile
9076                            + " but new version " + pkg.mVersionCode + " better than installed "
9077                            + ps.versionCode + "; hiding system");
9078                } else {
9079                    /*
9080                     * The newly found system app is a newer version that the
9081                     * one previously installed. Simply remove the
9082                     * already-installed application and replace it with our own
9083                     * while keeping the application data.
9084                     */
9085                    logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile
9086                            + " reverting from " + ps.codePathString + ": new version "
9087                            + pkg.mVersionCode + " better than installed " + ps.versionCode);
9088                    InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
9089                            ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
9090                    synchronized (mInstallLock) {
9091                        args.cleanUpResourcesLI();
9092                    }
9093                }
9094            }
9095        }
9096
9097        // The apk is forward locked (not public) if its code and resources
9098        // are kept in different files. (except for app in either system or
9099        // vendor path).
9100        // TODO grab this value from PackageSettings
9101        if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
9102            if (ps != null && !ps.codePath.equals(ps.resourcePath)) {
9103                policyFlags |= PackageParser.PARSE_FORWARD_LOCK;
9104            }
9105        }
9106
9107        final int userId = ((user == null) ? 0 : user.getIdentifier());
9108        if (ps != null && ps.getInstantApp(userId)) {
9109            scanFlags |= SCAN_AS_INSTANT_APP;
9110        }
9111
9112        // Note that we invoke the following method only if we are about to unpack an application
9113        PackageParser.Package scannedPkg = scanPackageLI(pkg, policyFlags, scanFlags
9114                | SCAN_UPDATE_SIGNATURE, currentTime, user);
9115
9116        /*
9117         * If the system app should be overridden by a previously installed
9118         * data, hide the system app now and let the /data/app scan pick it up
9119         * again.
9120         */
9121        if (shouldHideSystemApp) {
9122            synchronized (mPackages) {
9123                mSettings.disableSystemPackageLPw(pkg.packageName, true);
9124            }
9125        }
9126
9127        return scannedPkg;
9128    }
9129
9130    private void renameStaticSharedLibraryPackage(PackageParser.Package pkg) {
9131        // Derive the new package synthetic package name
9132        pkg.setPackageName(pkg.packageName + STATIC_SHARED_LIB_DELIMITER
9133                + pkg.staticSharedLibVersion);
9134    }
9135
9136    private static String fixProcessName(String defProcessName,
9137            String processName) {
9138        if (processName == null) {
9139            return defProcessName;
9140        }
9141        return processName;
9142    }
9143
9144    private void verifySignaturesLP(PackageSetting pkgSetting, PackageParser.Package pkg)
9145            throws PackageManagerException {
9146        if (pkgSetting.signatures.mSignatures != null) {
9147            // Already existing package. Make sure signatures match
9148            boolean match = compareSignatures(pkgSetting.signatures.mSignatures, pkg.mSignatures)
9149                    == PackageManager.SIGNATURE_MATCH;
9150            if (!match) {
9151                match = compareSignaturesCompat(pkgSetting.signatures, pkg)
9152                        == PackageManager.SIGNATURE_MATCH;
9153            }
9154            if (!match) {
9155                match = compareSignaturesRecover(pkgSetting.signatures, pkg)
9156                        == PackageManager.SIGNATURE_MATCH;
9157            }
9158            if (!match) {
9159                throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package "
9160                        + pkg.packageName + " signatures do not match the "
9161                        + "previously installed version; ignoring!");
9162            }
9163        }
9164
9165        // Check for shared user signatures
9166        if (pkgSetting.sharedUser != null && pkgSetting.sharedUser.signatures.mSignatures != null) {
9167            // Already existing package. Make sure signatures match
9168            boolean match = compareSignatures(pkgSetting.sharedUser.signatures.mSignatures,
9169                    pkg.mSignatures) == PackageManager.SIGNATURE_MATCH;
9170            if (!match) {
9171                match = compareSignaturesCompat(pkgSetting.sharedUser.signatures, pkg)
9172                        == PackageManager.SIGNATURE_MATCH;
9173            }
9174            if (!match) {
9175                match = compareSignaturesRecover(pkgSetting.sharedUser.signatures, pkg)
9176                        == PackageManager.SIGNATURE_MATCH;
9177            }
9178            if (!match) {
9179                throw new PackageManagerException(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE,
9180                        "Package " + pkg.packageName
9181                        + " has no signatures that match those in shared user "
9182                        + pkgSetting.sharedUser.name + "; ignoring!");
9183            }
9184        }
9185    }
9186
9187    /**
9188     * Enforces that only the system UID or root's UID can call a method exposed
9189     * via Binder.
9190     *
9191     * @param message used as message if SecurityException is thrown
9192     * @throws SecurityException if the caller is not system or root
9193     */
9194    private static final void enforceSystemOrRoot(String message) {
9195        final int uid = Binder.getCallingUid();
9196        if (uid != Process.SYSTEM_UID && uid != Process.ROOT_UID) {
9197            throw new SecurityException(message);
9198        }
9199    }
9200
9201    @Override
9202    public void performFstrimIfNeeded() {
9203        enforceSystemOrRoot("Only the system can request fstrim");
9204
9205        // Before everything else, see whether we need to fstrim.
9206        try {
9207            IStorageManager sm = PackageHelper.getStorageManager();
9208            if (sm != null) {
9209                boolean doTrim = false;
9210                final long interval = android.provider.Settings.Global.getLong(
9211                        mContext.getContentResolver(),
9212                        android.provider.Settings.Global.FSTRIM_MANDATORY_INTERVAL,
9213                        DEFAULT_MANDATORY_FSTRIM_INTERVAL);
9214                if (interval > 0) {
9215                    final long timeSinceLast = System.currentTimeMillis() - sm.lastMaintenance();
9216                    if (timeSinceLast > interval) {
9217                        doTrim = true;
9218                        Slog.w(TAG, "No disk maintenance in " + timeSinceLast
9219                                + "; running immediately");
9220                    }
9221                }
9222                if (doTrim) {
9223                    final boolean dexOptDialogShown;
9224                    synchronized (mPackages) {
9225                        dexOptDialogShown = mDexOptDialogShown;
9226                    }
9227                    if (!isFirstBoot() && dexOptDialogShown) {
9228                        try {
9229                            ActivityManager.getService().showBootMessage(
9230                                    mContext.getResources().getString(
9231                                            R.string.android_upgrading_fstrim), true);
9232                        } catch (RemoteException e) {
9233                        }
9234                    }
9235                    sm.runMaintenance();
9236                }
9237            } else {
9238                Slog.e(TAG, "storageManager service unavailable!");
9239            }
9240        } catch (RemoteException e) {
9241            // Can't happen; StorageManagerService is local
9242        }
9243    }
9244
9245    @Override
9246    public void updatePackagesIfNeeded() {
9247        enforceSystemOrRoot("Only the system can request package update");
9248
9249        // We need to re-extract after an OTA.
9250        boolean causeUpgrade = isUpgrade();
9251
9252        // First boot or factory reset.
9253        // Note: we also handle devices that are upgrading to N right now as if it is their
9254        //       first boot, as they do not have profile data.
9255        boolean causeFirstBoot = isFirstBoot() || mIsPreNUpgrade;
9256
9257        // We need to re-extract after a pruned cache, as AoT-ed files will be out of date.
9258        boolean causePrunedCache = VMRuntime.didPruneDalvikCache();
9259
9260        if (!causeUpgrade && !causeFirstBoot && !causePrunedCache) {
9261            return;
9262        }
9263
9264        List<PackageParser.Package> pkgs;
9265        synchronized (mPackages) {
9266            pkgs = PackageManagerServiceUtils.getPackagesForDexopt(mPackages.values(), this);
9267        }
9268
9269        final long startTime = System.nanoTime();
9270        final int[] stats = performDexOptUpgrade(pkgs, mIsPreNUpgrade /* showDialog */,
9271                    getCompilerFilterForReason(causeFirstBoot ? REASON_FIRST_BOOT : REASON_BOOT),
9272                    false /* bootComplete */);
9273
9274        final int elapsedTimeSeconds =
9275                (int) TimeUnit.NANOSECONDS.toSeconds(System.nanoTime() - startTime);
9276
9277        MetricsLogger.histogram(mContext, "opt_dialog_num_dexopted", stats[0]);
9278        MetricsLogger.histogram(mContext, "opt_dialog_num_skipped", stats[1]);
9279        MetricsLogger.histogram(mContext, "opt_dialog_num_failed", stats[2]);
9280        MetricsLogger.histogram(mContext, "opt_dialog_num_total", getOptimizablePackages().size());
9281        MetricsLogger.histogram(mContext, "opt_dialog_time_s", elapsedTimeSeconds);
9282    }
9283
9284    /*
9285     * Return the prebuilt profile path given a package base code path.
9286     */
9287    private static String getPrebuildProfilePath(PackageParser.Package pkg) {
9288        return pkg.baseCodePath + ".prof";
9289    }
9290
9291    /**
9292     * Performs dexopt on the set of packages in {@code packages} and returns an int array
9293     * containing statistics about the invocation. The array consists of three elements,
9294     * which are (in order) {@code numberOfPackagesOptimized}, {@code numberOfPackagesSkipped}
9295     * and {@code numberOfPackagesFailed}.
9296     */
9297    private int[] performDexOptUpgrade(List<PackageParser.Package> pkgs, boolean showDialog,
9298            String compilerFilter, boolean bootComplete) {
9299
9300        int numberOfPackagesVisited = 0;
9301        int numberOfPackagesOptimized = 0;
9302        int numberOfPackagesSkipped = 0;
9303        int numberOfPackagesFailed = 0;
9304        final int numberOfPackagesToDexopt = pkgs.size();
9305
9306        for (PackageParser.Package pkg : pkgs) {
9307            numberOfPackagesVisited++;
9308
9309            if ((isFirstBoot() || isUpgrade()) && isSystemApp(pkg)) {
9310                // Copy over initial preopt profiles since we won't get any JIT samples for methods
9311                // that are already compiled.
9312                File profileFile = new File(getPrebuildProfilePath(pkg));
9313                // Copy profile if it exists.
9314                if (profileFile.exists()) {
9315                    try {
9316                        // We could also do this lazily before calling dexopt in
9317                        // PackageDexOptimizer to prevent this happening on first boot. The issue
9318                        // is that we don't have a good way to say "do this only once".
9319                        if (!mInstaller.copySystemProfile(profileFile.getAbsolutePath(),
9320                                pkg.applicationInfo.uid, pkg.packageName)) {
9321                            Log.e(TAG, "Installer failed to copy system profile!");
9322                        }
9323                    } catch (Exception e) {
9324                        Log.e(TAG, "Failed to copy profile " + profileFile.getAbsolutePath() + " ",
9325                                e);
9326                    }
9327                }
9328            }
9329
9330            if (!PackageDexOptimizer.canOptimizePackage(pkg)) {
9331                if (DEBUG_DEXOPT) {
9332                    Log.i(TAG, "Skipping update of of non-optimizable app " + pkg.packageName);
9333                }
9334                numberOfPackagesSkipped++;
9335                continue;
9336            }
9337
9338            if (DEBUG_DEXOPT) {
9339                Log.i(TAG, "Updating app " + numberOfPackagesVisited + " of " +
9340                        numberOfPackagesToDexopt + ": " + pkg.packageName);
9341            }
9342
9343            if (showDialog) {
9344                try {
9345                    ActivityManager.getService().showBootMessage(
9346                            mContext.getResources().getString(R.string.android_upgrading_apk,
9347                                    numberOfPackagesVisited, numberOfPackagesToDexopt), true);
9348                } catch (RemoteException e) {
9349                }
9350                synchronized (mPackages) {
9351                    mDexOptDialogShown = true;
9352                }
9353            }
9354
9355            // If the OTA updates a system app which was previously preopted to a non-preopted state
9356            // the app might end up being verified at runtime. That's because by default the apps
9357            // are verify-profile but for preopted apps there's no profile.
9358            // Do a hacky check to ensure that if we have no profiles (a reasonable indication
9359            // that before the OTA the app was preopted) the app gets compiled with a non-profile
9360            // filter (by default 'quicken').
9361            // Note that at this stage unused apps are already filtered.
9362            if (isSystemApp(pkg) &&
9363                    DexFile.isProfileGuidedCompilerFilter(compilerFilter) &&
9364                    !Environment.getReferenceProfile(pkg.packageName).exists()) {
9365                compilerFilter = getNonProfileGuidedCompilerFilter(compilerFilter);
9366            }
9367
9368            // checkProfiles is false to avoid merging profiles during boot which
9369            // might interfere with background compilation (b/28612421).
9370            // Unfortunately this will also means that "pm.dexopt.boot=speed-profile" will
9371            // behave differently than "pm.dexopt.bg-dexopt=speed-profile" but that's a
9372            // trade-off worth doing to save boot time work.
9373            int dexoptFlags = bootComplete ? DexoptOptions.DEXOPT_BOOT_COMPLETE : 0;
9374            int primaryDexOptStaus = performDexOptTraced(new DexoptOptions(
9375                    pkg.packageName,
9376                    compilerFilter,
9377                    dexoptFlags));
9378
9379            if (pkg.isSystemApp()) {
9380                // Only dexopt shared secondary dex files belonging to system apps to not slow down
9381                // too much boot after an OTA.
9382                int secondaryDexoptFlags = dexoptFlags |
9383                        DexoptOptions.DEXOPT_ONLY_SECONDARY_DEX |
9384                        DexoptOptions.DEXOPT_ONLY_SHARED_DEX;
9385                mDexManager.dexoptSecondaryDex(new DexoptOptions(
9386                        pkg.packageName,
9387                        compilerFilter,
9388                        secondaryDexoptFlags));
9389            }
9390
9391            // TODO(shubhamajmera): Record secondary dexopt stats.
9392            switch (primaryDexOptStaus) {
9393                case PackageDexOptimizer.DEX_OPT_PERFORMED:
9394                    numberOfPackagesOptimized++;
9395                    break;
9396                case PackageDexOptimizer.DEX_OPT_SKIPPED:
9397                    numberOfPackagesSkipped++;
9398                    break;
9399                case PackageDexOptimizer.DEX_OPT_FAILED:
9400                    numberOfPackagesFailed++;
9401                    break;
9402                default:
9403                    Log.e(TAG, "Unexpected dexopt return code " + primaryDexOptStaus);
9404                    break;
9405            }
9406        }
9407
9408        return new int[] { numberOfPackagesOptimized, numberOfPackagesSkipped,
9409                numberOfPackagesFailed };
9410    }
9411
9412    @Override
9413    public void notifyPackageUse(String packageName, int reason) {
9414        synchronized (mPackages) {
9415            final int callingUid = Binder.getCallingUid();
9416            final int callingUserId = UserHandle.getUserId(callingUid);
9417            if (getInstantAppPackageName(callingUid) != null) {
9418                if (!isCallerSameApp(packageName, callingUid)) {
9419                    return;
9420                }
9421            } else {
9422                if (isInstantApp(packageName, callingUserId)) {
9423                    return;
9424                }
9425            }
9426            final PackageParser.Package p = mPackages.get(packageName);
9427            if (p == null) {
9428                return;
9429            }
9430            p.mLastPackageUsageTimeInMills[reason] = System.currentTimeMillis();
9431        }
9432    }
9433
9434    @Override
9435    public void notifyDexLoad(String loadingPackageName, List<String> dexPaths, String loaderIsa) {
9436        int userId = UserHandle.getCallingUserId();
9437        ApplicationInfo ai = getApplicationInfo(loadingPackageName, /*flags*/ 0, userId);
9438        if (ai == null) {
9439            Slog.w(TAG, "Loading a package that does not exist for the calling user. package="
9440                + loadingPackageName + ", user=" + userId);
9441            return;
9442        }
9443        mDexManager.notifyDexLoad(ai, dexPaths, loaderIsa, userId);
9444    }
9445
9446    @Override
9447    public void registerDexModule(String packageName, String dexModulePath, boolean isSharedModule,
9448            IDexModuleRegisterCallback callback) {
9449        int userId = UserHandle.getCallingUserId();
9450        ApplicationInfo ai = getApplicationInfo(packageName, /*flags*/ 0, userId);
9451        DexManager.RegisterDexModuleResult result;
9452        if (ai == null) {
9453            Slog.w(TAG, "Registering a dex module for a package that does not exist for the" +
9454                     " calling user. package=" + packageName + ", user=" + userId);
9455            result = new DexManager.RegisterDexModuleResult(false, "Package not installed");
9456        } else {
9457            result = mDexManager.registerDexModule(ai, dexModulePath, isSharedModule, userId);
9458        }
9459
9460        if (callback != null) {
9461            mHandler.post(() -> {
9462                try {
9463                    callback.onDexModuleRegistered(dexModulePath, result.success, result.message);
9464                } catch (RemoteException e) {
9465                    Slog.w(TAG, "Failed to callback after module registration " + dexModulePath, e);
9466                }
9467            });
9468        }
9469    }
9470
9471    /**
9472     * Ask the package manager to perform a dex-opt with the given compiler filter.
9473     *
9474     * Note: exposed only for the shell command to allow moving packages explicitly to a
9475     *       definite state.
9476     */
9477    @Override
9478    public boolean performDexOptMode(String packageName,
9479            boolean checkProfiles, String targetCompilerFilter, boolean force,
9480            boolean bootComplete, String splitName) {
9481        int flags = (checkProfiles ? DexoptOptions.DEXOPT_CHECK_FOR_PROFILES_UPDATES : 0) |
9482                (force ? DexoptOptions.DEXOPT_FORCE : 0) |
9483                (bootComplete ? DexoptOptions.DEXOPT_BOOT_COMPLETE : 0);
9484        return performDexOpt(new DexoptOptions(packageName, targetCompilerFilter,
9485                splitName, flags));
9486    }
9487
9488    /**
9489     * Ask the package manager to perform a dex-opt with the given compiler filter on the
9490     * secondary dex files belonging to the given package.
9491     *
9492     * Note: exposed only for the shell command to allow moving packages explicitly to a
9493     *       definite state.
9494     */
9495    @Override
9496    public boolean performDexOptSecondary(String packageName, String compilerFilter,
9497            boolean force) {
9498        int flags = DexoptOptions.DEXOPT_ONLY_SECONDARY_DEX |
9499                DexoptOptions.DEXOPT_CHECK_FOR_PROFILES_UPDATES |
9500                DexoptOptions.DEXOPT_BOOT_COMPLETE |
9501                (force ? DexoptOptions.DEXOPT_FORCE : 0);
9502        return performDexOpt(new DexoptOptions(packageName, compilerFilter, flags));
9503    }
9504
9505    /*package*/ boolean performDexOpt(DexoptOptions options) {
9506        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
9507            return false;
9508        } else if (isInstantApp(options.getPackageName(), UserHandle.getCallingUserId())) {
9509            return false;
9510        }
9511
9512        if (options.isDexoptOnlySecondaryDex()) {
9513            return mDexManager.dexoptSecondaryDex(options);
9514        } else {
9515            int dexoptStatus = performDexOptWithStatus(options);
9516            return dexoptStatus != PackageDexOptimizer.DEX_OPT_FAILED;
9517        }
9518    }
9519
9520    /**
9521     * Perform dexopt on the given package and return one of following result:
9522     *  {@link PackageDexOptimizer#DEX_OPT_SKIPPED}
9523     *  {@link PackageDexOptimizer#DEX_OPT_PERFORMED}
9524     *  {@link PackageDexOptimizer#DEX_OPT_FAILED}
9525     */
9526    /* package */ int performDexOptWithStatus(DexoptOptions options) {
9527        return performDexOptTraced(options);
9528    }
9529
9530    private int performDexOptTraced(DexoptOptions options) {
9531        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt");
9532        try {
9533            return performDexOptInternal(options);
9534        } finally {
9535            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
9536        }
9537    }
9538
9539    // Run dexopt on a given package. Returns true if dexopt did not fail, i.e.
9540    // if the package can now be considered up to date for the given filter.
9541    private int performDexOptInternal(DexoptOptions options) {
9542        PackageParser.Package p;
9543        synchronized (mPackages) {
9544            p = mPackages.get(options.getPackageName());
9545            if (p == null) {
9546                // Package could not be found. Report failure.
9547                return PackageDexOptimizer.DEX_OPT_FAILED;
9548            }
9549            mPackageUsage.maybeWriteAsync(mPackages);
9550            mCompilerStats.maybeWriteAsync();
9551        }
9552        long callingId = Binder.clearCallingIdentity();
9553        try {
9554            synchronized (mInstallLock) {
9555                return performDexOptInternalWithDependenciesLI(p, options);
9556            }
9557        } finally {
9558            Binder.restoreCallingIdentity(callingId);
9559        }
9560    }
9561
9562    public ArraySet<String> getOptimizablePackages() {
9563        ArraySet<String> pkgs = new ArraySet<String>();
9564        synchronized (mPackages) {
9565            for (PackageParser.Package p : mPackages.values()) {
9566                if (PackageDexOptimizer.canOptimizePackage(p)) {
9567                    pkgs.add(p.packageName);
9568                }
9569            }
9570        }
9571        return pkgs;
9572    }
9573
9574    private int performDexOptInternalWithDependenciesLI(PackageParser.Package p,
9575            DexoptOptions options) {
9576        // Select the dex optimizer based on the force parameter.
9577        // Note: The force option is rarely used (cmdline input for testing, mostly), so it's OK to
9578        //       allocate an object here.
9579        PackageDexOptimizer pdo = options.isForce()
9580                ? new PackageDexOptimizer.ForcedUpdatePackageDexOptimizer(mPackageDexOptimizer)
9581                : mPackageDexOptimizer;
9582
9583        // Dexopt all dependencies first. Note: we ignore the return value and march on
9584        // on errors.
9585        // Note that we are going to call performDexOpt on those libraries as many times as
9586        // they are referenced in packages. When we do a batch of performDexOpt (for example
9587        // at boot, or background job), the passed 'targetCompilerFilter' stays the same,
9588        // and the first package that uses the library will dexopt it. The
9589        // others will see that the compiled code for the library is up to date.
9590        Collection<PackageParser.Package> deps = findSharedNonSystemLibraries(p);
9591        final String[] instructionSets = getAppDexInstructionSets(p.applicationInfo);
9592        if (!deps.isEmpty()) {
9593            for (PackageParser.Package depPackage : deps) {
9594                // TODO: Analyze and investigate if we (should) profile libraries.
9595                pdo.performDexOpt(depPackage, null /* sharedLibraries */, instructionSets,
9596                        getOrCreateCompilerPackageStats(depPackage),
9597                        true /* isUsedByOtherApps */,
9598                        options);
9599            }
9600        }
9601        return pdo.performDexOpt(p, p.usesLibraryFiles, instructionSets,
9602                getOrCreateCompilerPackageStats(p),
9603                mDexManager.isUsedByOtherApps(p.packageName), options);
9604    }
9605
9606    /**
9607     * Reconcile the information we have about the secondary dex files belonging to
9608     * {@code packagName} and the actual dex files. For all dex files that were
9609     * deleted, update the internal records and delete the generated oat files.
9610     */
9611    @Override
9612    public void reconcileSecondaryDexFiles(String packageName) {
9613        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
9614            return;
9615        } else if (isInstantApp(packageName, UserHandle.getCallingUserId())) {
9616            return;
9617        }
9618        mDexManager.reconcileSecondaryDexFiles(packageName);
9619    }
9620
9621    // TODO(calin): this is only needed for BackgroundDexOptService. Find a cleaner way to inject
9622    // a reference there.
9623    /*package*/ DexManager getDexManager() {
9624        return mDexManager;
9625    }
9626
9627    /**
9628     * Execute the background dexopt job immediately.
9629     */
9630    @Override
9631    public boolean runBackgroundDexoptJob() {
9632        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
9633            return false;
9634        }
9635        return BackgroundDexOptService.runIdleOptimizationsNow(this, mContext);
9636    }
9637
9638    List<PackageParser.Package> findSharedNonSystemLibraries(PackageParser.Package p) {
9639        if (p.usesLibraries != null || p.usesOptionalLibraries != null
9640                || p.usesStaticLibraries != null) {
9641            ArrayList<PackageParser.Package> retValue = new ArrayList<>();
9642            Set<String> collectedNames = new HashSet<>();
9643            findSharedNonSystemLibrariesRecursive(p, retValue, collectedNames);
9644
9645            retValue.remove(p);
9646
9647            return retValue;
9648        } else {
9649            return Collections.emptyList();
9650        }
9651    }
9652
9653    private void findSharedNonSystemLibrariesRecursive(PackageParser.Package p,
9654            ArrayList<PackageParser.Package> collected, Set<String> collectedNames) {
9655        if (!collectedNames.contains(p.packageName)) {
9656            collectedNames.add(p.packageName);
9657            collected.add(p);
9658
9659            if (p.usesLibraries != null) {
9660                findSharedNonSystemLibrariesRecursive(p.usesLibraries,
9661                        null, collected, collectedNames);
9662            }
9663            if (p.usesOptionalLibraries != null) {
9664                findSharedNonSystemLibrariesRecursive(p.usesOptionalLibraries,
9665                        null, collected, collectedNames);
9666            }
9667            if (p.usesStaticLibraries != null) {
9668                findSharedNonSystemLibrariesRecursive(p.usesStaticLibraries,
9669                        p.usesStaticLibrariesVersions, collected, collectedNames);
9670            }
9671        }
9672    }
9673
9674    private void findSharedNonSystemLibrariesRecursive(ArrayList<String> libs, int[] versions,
9675            ArrayList<PackageParser.Package> collected, Set<String> collectedNames) {
9676        final int libNameCount = libs.size();
9677        for (int i = 0; i < libNameCount; i++) {
9678            String libName = libs.get(i);
9679            int version = (versions != null && versions.length == libNameCount)
9680                    ? versions[i] : PackageManager.VERSION_CODE_HIGHEST;
9681            PackageParser.Package libPkg = findSharedNonSystemLibrary(libName, version);
9682            if (libPkg != null) {
9683                findSharedNonSystemLibrariesRecursive(libPkg, collected, collectedNames);
9684            }
9685        }
9686    }
9687
9688    private PackageParser.Package findSharedNonSystemLibrary(String name, int version) {
9689        synchronized (mPackages) {
9690            SharedLibraryEntry libEntry = getSharedLibraryEntryLPr(name, version);
9691            if (libEntry != null) {
9692                return mPackages.get(libEntry.apk);
9693            }
9694            return null;
9695        }
9696    }
9697
9698    private SharedLibraryEntry getSharedLibraryEntryLPr(String name, int version) {
9699        SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(name);
9700        if (versionedLib == null) {
9701            return null;
9702        }
9703        return versionedLib.get(version);
9704    }
9705
9706    private SharedLibraryEntry getLatestSharedLibraVersionLPr(PackageParser.Package pkg) {
9707        SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(
9708                pkg.staticSharedLibName);
9709        if (versionedLib == null) {
9710            return null;
9711        }
9712        int previousLibVersion = -1;
9713        final int versionCount = versionedLib.size();
9714        for (int i = 0; i < versionCount; i++) {
9715            final int libVersion = versionedLib.keyAt(i);
9716            if (libVersion < pkg.staticSharedLibVersion) {
9717                previousLibVersion = Math.max(previousLibVersion, libVersion);
9718            }
9719        }
9720        if (previousLibVersion >= 0) {
9721            return versionedLib.get(previousLibVersion);
9722        }
9723        return null;
9724    }
9725
9726    public void shutdown() {
9727        mPackageUsage.writeNow(mPackages);
9728        mCompilerStats.writeNow();
9729    }
9730
9731    @Override
9732    public void dumpProfiles(String packageName) {
9733        PackageParser.Package pkg;
9734        synchronized (mPackages) {
9735            pkg = mPackages.get(packageName);
9736            if (pkg == null) {
9737                throw new IllegalArgumentException("Unknown package: " + packageName);
9738            }
9739        }
9740        /* Only the shell, root, or the app user should be able to dump profiles. */
9741        int callingUid = Binder.getCallingUid();
9742        if (callingUid != Process.SHELL_UID &&
9743            callingUid != Process.ROOT_UID &&
9744            callingUid != pkg.applicationInfo.uid) {
9745            throw new SecurityException("dumpProfiles");
9746        }
9747
9748        synchronized (mInstallLock) {
9749            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dump profiles");
9750            final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid);
9751            try {
9752                List<String> allCodePaths = pkg.getAllCodePathsExcludingResourceOnly();
9753                String codePaths = TextUtils.join(";", allCodePaths);
9754                mInstaller.dumpProfiles(sharedGid, packageName, codePaths);
9755            } catch (InstallerException e) {
9756                Slog.w(TAG, "Failed to dump profiles", e);
9757            }
9758            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
9759        }
9760    }
9761
9762    @Override
9763    public void forceDexOpt(String packageName) {
9764        enforceSystemOrRoot("forceDexOpt");
9765
9766        PackageParser.Package pkg;
9767        synchronized (mPackages) {
9768            pkg = mPackages.get(packageName);
9769            if (pkg == null) {
9770                throw new IllegalArgumentException("Unknown package: " + packageName);
9771            }
9772        }
9773
9774        synchronized (mInstallLock) {
9775            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt");
9776
9777            // Whoever is calling forceDexOpt wants a compiled package.
9778            // Don't use profiles since that may cause compilation to be skipped.
9779            final int res = performDexOptInternalWithDependenciesLI(
9780                    pkg,
9781                    new DexoptOptions(packageName,
9782                            getDefaultCompilerFilter(),
9783                            DexoptOptions.DEXOPT_FORCE | DexoptOptions.DEXOPT_BOOT_COMPLETE));
9784
9785            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
9786            if (res != PackageDexOptimizer.DEX_OPT_PERFORMED) {
9787                throw new IllegalStateException("Failed to dexopt: " + res);
9788            }
9789        }
9790    }
9791
9792    private boolean verifyPackageUpdateLPr(PackageSetting oldPkg, PackageParser.Package newPkg) {
9793        if ((oldPkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) {
9794            Slog.w(TAG, "Unable to update from " + oldPkg.name
9795                    + " to " + newPkg.packageName
9796                    + ": old package not in system partition");
9797            return false;
9798        } else if (mPackages.get(oldPkg.name) != null) {
9799            Slog.w(TAG, "Unable to update from " + oldPkg.name
9800                    + " to " + newPkg.packageName
9801                    + ": old package still exists");
9802            return false;
9803        }
9804        return true;
9805    }
9806
9807    void removeCodePathLI(File codePath) {
9808        if (codePath.isDirectory()) {
9809            try {
9810                mInstaller.rmPackageDir(codePath.getAbsolutePath());
9811            } catch (InstallerException e) {
9812                Slog.w(TAG, "Failed to remove code path", e);
9813            }
9814        } else {
9815            codePath.delete();
9816        }
9817    }
9818
9819    private int[] resolveUserIds(int userId) {
9820        return (userId == UserHandle.USER_ALL) ? sUserManager.getUserIds() : new int[] { userId };
9821    }
9822
9823    private void clearAppDataLIF(PackageParser.Package pkg, int userId, int flags) {
9824        if (pkg == null) {
9825            Slog.wtf(TAG, "Package was null!", new Throwable());
9826            return;
9827        }
9828        clearAppDataLeafLIF(pkg, userId, flags);
9829        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
9830        for (int i = 0; i < childCount; i++) {
9831            clearAppDataLeafLIF(pkg.childPackages.get(i), userId, flags);
9832        }
9833    }
9834
9835    private void clearAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) {
9836        final PackageSetting ps;
9837        synchronized (mPackages) {
9838            ps = mSettings.mPackages.get(pkg.packageName);
9839        }
9840        for (int realUserId : resolveUserIds(userId)) {
9841            final long ceDataInode = (ps != null) ? ps.getCeDataInode(realUserId) : 0;
9842            try {
9843                mInstaller.clearAppData(pkg.volumeUuid, pkg.packageName, realUserId, flags,
9844                        ceDataInode);
9845            } catch (InstallerException e) {
9846                Slog.w(TAG, String.valueOf(e));
9847            }
9848        }
9849    }
9850
9851    private void destroyAppDataLIF(PackageParser.Package pkg, int userId, int flags) {
9852        if (pkg == null) {
9853            Slog.wtf(TAG, "Package was null!", new Throwable());
9854            return;
9855        }
9856        destroyAppDataLeafLIF(pkg, userId, flags);
9857        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
9858        for (int i = 0; i < childCount; i++) {
9859            destroyAppDataLeafLIF(pkg.childPackages.get(i), userId, flags);
9860        }
9861    }
9862
9863    private void destroyAppDataLeafLIF(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.destroyAppData(pkg.volumeUuid, pkg.packageName, realUserId, flags,
9872                        ceDataInode);
9873            } catch (InstallerException e) {
9874                Slog.w(TAG, String.valueOf(e));
9875            }
9876            mDexManager.notifyPackageDataDestroyed(pkg.packageName, userId);
9877        }
9878    }
9879
9880    private void destroyAppProfilesLIF(PackageParser.Package pkg, int userId) {
9881        if (pkg == null) {
9882            Slog.wtf(TAG, "Package was null!", new Throwable());
9883            return;
9884        }
9885        destroyAppProfilesLeafLIF(pkg);
9886        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
9887        for (int i = 0; i < childCount; i++) {
9888            destroyAppProfilesLeafLIF(pkg.childPackages.get(i));
9889        }
9890    }
9891
9892    private void destroyAppProfilesLeafLIF(PackageParser.Package pkg) {
9893        try {
9894            mInstaller.destroyAppProfiles(pkg.packageName);
9895        } catch (InstallerException e) {
9896            Slog.w(TAG, String.valueOf(e));
9897        }
9898    }
9899
9900    private void clearAppProfilesLIF(PackageParser.Package pkg, int userId) {
9901        if (pkg == null) {
9902            Slog.wtf(TAG, "Package was null!", new Throwable());
9903            return;
9904        }
9905        clearAppProfilesLeafLIF(pkg);
9906        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
9907        for (int i = 0; i < childCount; i++) {
9908            clearAppProfilesLeafLIF(pkg.childPackages.get(i));
9909        }
9910    }
9911
9912    private void clearAppProfilesLeafLIF(PackageParser.Package pkg) {
9913        try {
9914            mInstaller.clearAppProfiles(pkg.packageName);
9915        } catch (InstallerException e) {
9916            Slog.w(TAG, String.valueOf(e));
9917        }
9918    }
9919
9920    private void setInstallAndUpdateTime(PackageParser.Package pkg, long firstInstallTime,
9921            long lastUpdateTime) {
9922        // Set parent install/update time
9923        PackageSetting ps = (PackageSetting) pkg.mExtras;
9924        if (ps != null) {
9925            ps.firstInstallTime = firstInstallTime;
9926            ps.lastUpdateTime = lastUpdateTime;
9927        }
9928        // Set children install/update time
9929        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
9930        for (int i = 0; i < childCount; i++) {
9931            PackageParser.Package childPkg = pkg.childPackages.get(i);
9932            ps = (PackageSetting) childPkg.mExtras;
9933            if (ps != null) {
9934                ps.firstInstallTime = firstInstallTime;
9935                ps.lastUpdateTime = lastUpdateTime;
9936            }
9937        }
9938    }
9939
9940    private void addSharedLibraryLPr(ArraySet<String> usesLibraryFiles, SharedLibraryEntry file,
9941            PackageParser.Package changingLib) {
9942        if (file.path != null) {
9943            usesLibraryFiles.add(file.path);
9944            return;
9945        }
9946        PackageParser.Package p = mPackages.get(file.apk);
9947        if (changingLib != null && changingLib.packageName.equals(file.apk)) {
9948            // If we are doing this while in the middle of updating a library apk,
9949            // then we need to make sure to use that new apk for determining the
9950            // dependencies here.  (We haven't yet finished committing the new apk
9951            // to the package manager state.)
9952            if (p == null || p.packageName.equals(changingLib.packageName)) {
9953                p = changingLib;
9954            }
9955        }
9956        if (p != null) {
9957            usesLibraryFiles.addAll(p.getAllCodePaths());
9958            if (p.usesLibraryFiles != null) {
9959                Collections.addAll(usesLibraryFiles, p.usesLibraryFiles);
9960            }
9961        }
9962    }
9963
9964    private void updateSharedLibrariesLPr(PackageParser.Package pkg,
9965            PackageParser.Package changingLib) throws PackageManagerException {
9966        if (pkg == null) {
9967            return;
9968        }
9969        ArraySet<String> usesLibraryFiles = null;
9970        if (pkg.usesLibraries != null) {
9971            usesLibraryFiles = addSharedLibrariesLPw(pkg.usesLibraries,
9972                    null, null, pkg.packageName, changingLib, true, null);
9973        }
9974        if (pkg.usesStaticLibraries != null) {
9975            usesLibraryFiles = addSharedLibrariesLPw(pkg.usesStaticLibraries,
9976                    pkg.usesStaticLibrariesVersions, pkg.usesStaticLibrariesCertDigests,
9977                    pkg.packageName, changingLib, true, usesLibraryFiles);
9978        }
9979        if (pkg.usesOptionalLibraries != null) {
9980            usesLibraryFiles = addSharedLibrariesLPw(pkg.usesOptionalLibraries,
9981                    null, null, pkg.packageName, changingLib, false, usesLibraryFiles);
9982        }
9983        if (!ArrayUtils.isEmpty(usesLibraryFiles)) {
9984            pkg.usesLibraryFiles = usesLibraryFiles.toArray(new String[usesLibraryFiles.size()]);
9985        } else {
9986            pkg.usesLibraryFiles = null;
9987        }
9988    }
9989
9990    private ArraySet<String> addSharedLibrariesLPw(@NonNull List<String> requestedLibraries,
9991            @Nullable int[] requiredVersions, @Nullable String[] requiredCertDigests,
9992            @NonNull String packageName, @Nullable PackageParser.Package changingLib,
9993            boolean required, @Nullable ArraySet<String> outUsedLibraries)
9994            throws PackageManagerException {
9995        final int libCount = requestedLibraries.size();
9996        for (int i = 0; i < libCount; i++) {
9997            final String libName = requestedLibraries.get(i);
9998            final int libVersion = requiredVersions != null ? requiredVersions[i]
9999                    : SharedLibraryInfo.VERSION_UNDEFINED;
10000            final SharedLibraryEntry libEntry = getSharedLibraryEntryLPr(libName, libVersion);
10001            if (libEntry == null) {
10002                if (required) {
10003                    throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY,
10004                            "Package " + packageName + " requires unavailable shared library "
10005                                    + libName + "; failing!");
10006                } else if (DEBUG_SHARED_LIBRARIES) {
10007                    Slog.i(TAG, "Package " + packageName
10008                            + " desires unavailable shared library "
10009                            + libName + "; ignoring!");
10010                }
10011            } else {
10012                if (requiredVersions != null && requiredCertDigests != null) {
10013                    if (libEntry.info.getVersion() != requiredVersions[i]) {
10014                        throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY,
10015                            "Package " + packageName + " requires unavailable static shared"
10016                                    + " library " + libName + " version "
10017                                    + libEntry.info.getVersion() + "; failing!");
10018                    }
10019
10020                    PackageParser.Package libPkg = mPackages.get(libEntry.apk);
10021                    if (libPkg == null) {
10022                        throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY,
10023                                "Package " + packageName + " requires unavailable static shared"
10024                                        + " library; failing!");
10025                    }
10026
10027                    String expectedCertDigest = requiredCertDigests[i];
10028                    String libCertDigest = PackageUtils.computeCertSha256Digest(
10029                                libPkg.mSignatures[0]);
10030                    if (!libCertDigest.equalsIgnoreCase(expectedCertDigest)) {
10031                        throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY,
10032                                "Package " + packageName + " requires differently signed" +
10033                                        " static shared library; failing!");
10034                    }
10035                }
10036
10037                if (outUsedLibraries == null) {
10038                    outUsedLibraries = new ArraySet<>();
10039                }
10040                addSharedLibraryLPr(outUsedLibraries, libEntry, changingLib);
10041            }
10042        }
10043        return outUsedLibraries;
10044    }
10045
10046    private static boolean hasString(List<String> list, List<String> which) {
10047        if (list == null) {
10048            return false;
10049        }
10050        for (int i=list.size()-1; i>=0; i--) {
10051            for (int j=which.size()-1; j>=0; j--) {
10052                if (which.get(j).equals(list.get(i))) {
10053                    return true;
10054                }
10055            }
10056        }
10057        return false;
10058    }
10059
10060    private ArrayList<PackageParser.Package> updateAllSharedLibrariesLPw(
10061            PackageParser.Package changingPkg) {
10062        ArrayList<PackageParser.Package> res = null;
10063        for (PackageParser.Package pkg : mPackages.values()) {
10064            if (changingPkg != null
10065                    && !hasString(pkg.usesLibraries, changingPkg.libraryNames)
10066                    && !hasString(pkg.usesOptionalLibraries, changingPkg.libraryNames)
10067                    && !ArrayUtils.contains(pkg.usesStaticLibraries,
10068                            changingPkg.staticSharedLibName)) {
10069                return null;
10070            }
10071            if (res == null) {
10072                res = new ArrayList<>();
10073            }
10074            res.add(pkg);
10075            try {
10076                updateSharedLibrariesLPr(pkg, changingPkg);
10077            } catch (PackageManagerException e) {
10078                // If a system app update or an app and a required lib missing we
10079                // delete the package and for updated system apps keep the data as
10080                // it is better for the user to reinstall than to be in an limbo
10081                // state. Also libs disappearing under an app should never happen
10082                // - just in case.
10083                if (!pkg.isSystemApp() || pkg.isUpdatedSystemApp()) {
10084                    final int flags = pkg.isUpdatedSystemApp()
10085                            ? PackageManager.DELETE_KEEP_DATA : 0;
10086                    deletePackageLIF(pkg.packageName, null, true, sUserManager.getUserIds(),
10087                            flags , null, true, null);
10088                }
10089                Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
10090            }
10091        }
10092        return res;
10093    }
10094
10095    /**
10096     * Derive the value of the {@code cpuAbiOverride} based on the provided
10097     * value and an optional stored value from the package settings.
10098     */
10099    private static String deriveAbiOverride(String abiOverride, PackageSetting settings) {
10100        String cpuAbiOverride = null;
10101
10102        if (NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(abiOverride)) {
10103            cpuAbiOverride = null;
10104        } else if (abiOverride != null) {
10105            cpuAbiOverride = abiOverride;
10106        } else if (settings != null) {
10107            cpuAbiOverride = settings.cpuAbiOverrideString;
10108        }
10109
10110        return cpuAbiOverride;
10111    }
10112
10113    private PackageParser.Package scanPackageTracedLI(PackageParser.Package pkg,
10114            final int policyFlags, int scanFlags, long currentTime, @Nullable UserHandle user)
10115                    throws PackageManagerException {
10116        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage");
10117        // If the package has children and this is the first dive in the function
10118        // we recursively scan the package with the SCAN_CHECK_ONLY flag set to see
10119        // whether all packages (parent and children) would be successfully scanned
10120        // before the actual scan since scanning mutates internal state and we want
10121        // to atomically install the package and its children.
10122        if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
10123            if (pkg.childPackages != null && pkg.childPackages.size() > 0) {
10124                scanFlags |= SCAN_CHECK_ONLY;
10125            }
10126        } else {
10127            scanFlags &= ~SCAN_CHECK_ONLY;
10128        }
10129
10130        final PackageParser.Package scannedPkg;
10131        try {
10132            // Scan the parent
10133            scannedPkg = scanPackageLI(pkg, policyFlags, scanFlags, currentTime, user);
10134            // Scan the children
10135            final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
10136            for (int i = 0; i < childCount; i++) {
10137                PackageParser.Package childPkg = pkg.childPackages.get(i);
10138                scanPackageLI(childPkg, policyFlags,
10139                        scanFlags, currentTime, user);
10140            }
10141        } finally {
10142            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
10143        }
10144
10145        if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
10146            return scanPackageTracedLI(pkg, policyFlags, scanFlags, currentTime, user);
10147        }
10148
10149        return scannedPkg;
10150    }
10151
10152    private PackageParser.Package scanPackageLI(PackageParser.Package pkg, final int policyFlags,
10153            int scanFlags, long currentTime, @Nullable UserHandle user)
10154                    throws PackageManagerException {
10155        boolean success = false;
10156        try {
10157            final PackageParser.Package res = scanPackageDirtyLI(pkg, policyFlags, scanFlags,
10158                    currentTime, user);
10159            success = true;
10160            return res;
10161        } finally {
10162            if (!success && (scanFlags & SCAN_DELETE_DATA_ON_FAILURES) != 0) {
10163                // DELETE_DATA_ON_FAILURES is only used by frozen paths
10164                destroyAppDataLIF(pkg, UserHandle.USER_ALL,
10165                        StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
10166                destroyAppProfilesLIF(pkg, UserHandle.USER_ALL);
10167            }
10168        }
10169    }
10170
10171    /**
10172     * Returns {@code true} if the given file contains code. Otherwise {@code false}.
10173     */
10174    private static boolean apkHasCode(String fileName) {
10175        StrictJarFile jarFile = null;
10176        try {
10177            jarFile = new StrictJarFile(fileName,
10178                    false /*verify*/, false /*signatureSchemeRollbackProtectionsEnforced*/);
10179            return jarFile.findEntry("classes.dex") != null;
10180        } catch (IOException ignore) {
10181        } finally {
10182            try {
10183                if (jarFile != null) {
10184                    jarFile.close();
10185                }
10186            } catch (IOException ignore) {}
10187        }
10188        return false;
10189    }
10190
10191    /**
10192     * Enforces code policy for the package. This ensures that if an APK has
10193     * declared hasCode="true" in its manifest that the APK actually contains
10194     * code.
10195     *
10196     * @throws PackageManagerException If bytecode could not be found when it should exist
10197     */
10198    private static void assertCodePolicy(PackageParser.Package pkg)
10199            throws PackageManagerException {
10200        final boolean shouldHaveCode =
10201                (pkg.applicationInfo.flags & ApplicationInfo.FLAG_HAS_CODE) != 0;
10202        if (shouldHaveCode && !apkHasCode(pkg.baseCodePath)) {
10203            throw new PackageManagerException(INSTALL_FAILED_INVALID_APK,
10204                    "Package " + pkg.baseCodePath + " code is missing");
10205        }
10206
10207        if (!ArrayUtils.isEmpty(pkg.splitCodePaths)) {
10208            for (int i = 0; i < pkg.splitCodePaths.length; i++) {
10209                final boolean splitShouldHaveCode =
10210                        (pkg.splitFlags[i] & ApplicationInfo.FLAG_HAS_CODE) != 0;
10211                if (splitShouldHaveCode && !apkHasCode(pkg.splitCodePaths[i])) {
10212                    throw new PackageManagerException(INSTALL_FAILED_INVALID_APK,
10213                            "Package " + pkg.splitCodePaths[i] + " code is missing");
10214                }
10215            }
10216        }
10217    }
10218
10219    private PackageParser.Package scanPackageDirtyLI(PackageParser.Package pkg,
10220            final int policyFlags, final int scanFlags, long currentTime, @Nullable UserHandle user)
10221                    throws PackageManagerException {
10222        if (DEBUG_PACKAGE_SCANNING) {
10223            if ((policyFlags & PackageParser.PARSE_CHATTY) != 0)
10224                Log.d(TAG, "Scanning package " + pkg.packageName);
10225        }
10226
10227        applyPolicy(pkg, policyFlags);
10228
10229        assertPackageIsValid(pkg, policyFlags, scanFlags);
10230
10231        // Initialize package source and resource directories
10232        final File scanFile = new File(pkg.codePath);
10233        final File destCodeFile = new File(pkg.applicationInfo.getCodePath());
10234        final File destResourceFile = new File(pkg.applicationInfo.getResourcePath());
10235
10236        SharedUserSetting suid = null;
10237        PackageSetting pkgSetting = null;
10238
10239        // Getting the package setting may have a side-effect, so if we
10240        // are only checking if scan would succeed, stash a copy of the
10241        // old setting to restore at the end.
10242        PackageSetting nonMutatedPs = null;
10243
10244        // We keep references to the derived CPU Abis from settings in oder to reuse
10245        // them in the case where we're not upgrading or booting for the first time.
10246        String primaryCpuAbiFromSettings = null;
10247        String secondaryCpuAbiFromSettings = null;
10248
10249        // writer
10250        synchronized (mPackages) {
10251            if (pkg.mSharedUserId != null) {
10252                // SIDE EFFECTS; may potentially allocate a new shared user
10253                suid = mSettings.getSharedUserLPw(
10254                        pkg.mSharedUserId, 0 /*pkgFlags*/, 0 /*pkgPrivateFlags*/, true /*create*/);
10255                if (DEBUG_PACKAGE_SCANNING) {
10256                    if ((policyFlags & PackageParser.PARSE_CHATTY) != 0)
10257                        Log.d(TAG, "Shared UserID " + pkg.mSharedUserId + " (uid=" + suid.userId
10258                                + "): packages=" + suid.packages);
10259                }
10260            }
10261
10262            // Check if we are renaming from an original package name.
10263            PackageSetting origPackage = null;
10264            String realName = null;
10265            if (pkg.mOriginalPackages != null) {
10266                // This package may need to be renamed to a previously
10267                // installed name.  Let's check on that...
10268                final String renamed = mSettings.getRenamedPackageLPr(pkg.mRealPackage);
10269                if (pkg.mOriginalPackages.contains(renamed)) {
10270                    // This package had originally been installed as the
10271                    // original name, and we have already taken care of
10272                    // transitioning to the new one.  Just update the new
10273                    // one to continue using the old name.
10274                    realName = pkg.mRealPackage;
10275                    if (!pkg.packageName.equals(renamed)) {
10276                        // Callers into this function may have already taken
10277                        // care of renaming the package; only do it here if
10278                        // it is not already done.
10279                        pkg.setPackageName(renamed);
10280                    }
10281                } else {
10282                    for (int i=pkg.mOriginalPackages.size()-1; i>=0; i--) {
10283                        if ((origPackage = mSettings.getPackageLPr(
10284                                pkg.mOriginalPackages.get(i))) != null) {
10285                            // We do have the package already installed under its
10286                            // original name...  should we use it?
10287                            if (!verifyPackageUpdateLPr(origPackage, pkg)) {
10288                                // New package is not compatible with original.
10289                                origPackage = null;
10290                                continue;
10291                            } else if (origPackage.sharedUser != null) {
10292                                // Make sure uid is compatible between packages.
10293                                if (!origPackage.sharedUser.name.equals(pkg.mSharedUserId)) {
10294                                    Slog.w(TAG, "Unable to migrate data from " + origPackage.name
10295                                            + " to " + pkg.packageName + ": old uid "
10296                                            + origPackage.sharedUser.name
10297                                            + " differs from " + pkg.mSharedUserId);
10298                                    origPackage = null;
10299                                    continue;
10300                                }
10301                                // TODO: Add case when shared user id is added [b/28144775]
10302                            } else {
10303                                if (DEBUG_UPGRADE) Log.v(TAG, "Renaming new package "
10304                                        + pkg.packageName + " to old name " + origPackage.name);
10305                            }
10306                            break;
10307                        }
10308                    }
10309                }
10310            }
10311
10312            if (mTransferedPackages.contains(pkg.packageName)) {
10313                Slog.w(TAG, "Package " + pkg.packageName
10314                        + " was transferred to another, but its .apk remains");
10315            }
10316
10317            // See comments in nonMutatedPs declaration
10318            if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
10319                PackageSetting foundPs = mSettings.getPackageLPr(pkg.packageName);
10320                if (foundPs != null) {
10321                    nonMutatedPs = new PackageSetting(foundPs);
10322                }
10323            }
10324
10325            if ((scanFlags & SCAN_FIRST_BOOT_OR_UPGRADE) == 0) {
10326                PackageSetting foundPs = mSettings.getPackageLPr(pkg.packageName);
10327                if (foundPs != null) {
10328                    primaryCpuAbiFromSettings = foundPs.primaryCpuAbiString;
10329                    secondaryCpuAbiFromSettings = foundPs.secondaryCpuAbiString;
10330                }
10331            }
10332
10333            pkgSetting = mSettings.getPackageLPr(pkg.packageName);
10334            if (pkgSetting != null && pkgSetting.sharedUser != suid) {
10335                PackageManagerService.reportSettingsProblem(Log.WARN,
10336                        "Package " + pkg.packageName + " shared user changed from "
10337                                + (pkgSetting.sharedUser != null
10338                                        ? pkgSetting.sharedUser.name : "<nothing>")
10339                                + " to "
10340                                + (suid != null ? suid.name : "<nothing>")
10341                                + "; replacing with new");
10342                pkgSetting = null;
10343            }
10344            final PackageSetting oldPkgSetting =
10345                    pkgSetting == null ? null : new PackageSetting(pkgSetting);
10346            final PackageSetting disabledPkgSetting =
10347                    mSettings.getDisabledSystemPkgLPr(pkg.packageName);
10348
10349            String[] usesStaticLibraries = null;
10350            if (pkg.usesStaticLibraries != null) {
10351                usesStaticLibraries = new String[pkg.usesStaticLibraries.size()];
10352                pkg.usesStaticLibraries.toArray(usesStaticLibraries);
10353            }
10354
10355            if (pkgSetting == null) {
10356                final String parentPackageName = (pkg.parentPackage != null)
10357                        ? pkg.parentPackage.packageName : null;
10358                final boolean instantApp = (scanFlags & SCAN_AS_INSTANT_APP) != 0;
10359                // REMOVE SharedUserSetting from method; update in a separate call
10360                pkgSetting = Settings.createNewSetting(pkg.packageName, origPackage,
10361                        disabledPkgSetting, realName, suid, destCodeFile, destResourceFile,
10362                        pkg.applicationInfo.nativeLibraryRootDir, pkg.applicationInfo.primaryCpuAbi,
10363                        pkg.applicationInfo.secondaryCpuAbi, pkg.mVersionCode,
10364                        pkg.applicationInfo.flags, pkg.applicationInfo.privateFlags, user,
10365                        true /*allowInstall*/, instantApp, parentPackageName,
10366                        pkg.getChildPackageNames(), UserManagerService.getInstance(),
10367                        usesStaticLibraries, pkg.usesStaticLibrariesVersions);
10368                // SIDE EFFECTS; updates system state; move elsewhere
10369                if (origPackage != null) {
10370                    mSettings.addRenamedPackageLPw(pkg.packageName, origPackage.name);
10371                }
10372                mSettings.addUserToSettingLPw(pkgSetting);
10373            } else {
10374                // REMOVE SharedUserSetting from method; update in a separate call.
10375                //
10376                // TODO(narayan): This update is bogus. nativeLibraryDir & primaryCpuAbi,
10377                // secondaryCpuAbi are not known at this point so we always update them
10378                // to null here, only to reset them at a later point.
10379                Settings.updatePackageSetting(pkgSetting, disabledPkgSetting, suid, destCodeFile,
10380                        pkg.applicationInfo.nativeLibraryDir, pkg.applicationInfo.primaryCpuAbi,
10381                        pkg.applicationInfo.secondaryCpuAbi, pkg.applicationInfo.flags,
10382                        pkg.applicationInfo.privateFlags, pkg.getChildPackageNames(),
10383                        UserManagerService.getInstance(), usesStaticLibraries,
10384                        pkg.usesStaticLibrariesVersions);
10385            }
10386            // SIDE EFFECTS; persists system state to files on disk; move elsewhere
10387            mSettings.writeUserRestrictionsLPw(pkgSetting, oldPkgSetting);
10388
10389            // SIDE EFFECTS; modifies system state; move elsewhere
10390            if (pkgSetting.origPackage != null) {
10391                // If we are first transitioning from an original package,
10392                // fix up the new package's name now.  We need to do this after
10393                // looking up the package under its new name, so getPackageLP
10394                // can take care of fiddling things correctly.
10395                pkg.setPackageName(origPackage.name);
10396
10397                // File a report about this.
10398                String msg = "New package " + pkgSetting.realName
10399                        + " renamed to replace old package " + pkgSetting.name;
10400                reportSettingsProblem(Log.WARN, msg);
10401
10402                // Make a note of it.
10403                if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
10404                    mTransferedPackages.add(origPackage.name);
10405                }
10406
10407                // No longer need to retain this.
10408                pkgSetting.origPackage = null;
10409            }
10410
10411            // SIDE EFFECTS; modifies system state; move elsewhere
10412            if ((scanFlags & SCAN_CHECK_ONLY) == 0 && realName != null) {
10413                // Make a note of it.
10414                mTransferedPackages.add(pkg.packageName);
10415            }
10416
10417            if (mSettings.isDisabledSystemPackageLPr(pkg.packageName)) {
10418                pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
10419            }
10420
10421            if ((scanFlags & SCAN_BOOTING) == 0
10422                    && (policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
10423                // Check all shared libraries and map to their actual file path.
10424                // We only do this here for apps not on a system dir, because those
10425                // are the only ones that can fail an install due to this.  We
10426                // will take care of the system apps by updating all of their
10427                // library paths after the scan is done. Also during the initial
10428                // scan don't update any libs as we do this wholesale after all
10429                // apps are scanned to avoid dependency based scanning.
10430                updateSharedLibrariesLPr(pkg, null);
10431            }
10432
10433            if (mFoundPolicyFile) {
10434                SELinuxMMAC.assignSeInfoValue(pkg);
10435            }
10436            pkg.applicationInfo.uid = pkgSetting.appId;
10437            pkg.mExtras = pkgSetting;
10438
10439
10440            // Static shared libs have same package with different versions where
10441            // we internally use a synthetic package name to allow multiple versions
10442            // of the same package, therefore we need to compare signatures against
10443            // the package setting for the latest library version.
10444            PackageSetting signatureCheckPs = pkgSetting;
10445            if (pkg.applicationInfo.isStaticSharedLibrary()) {
10446                SharedLibraryEntry libraryEntry = getLatestSharedLibraVersionLPr(pkg);
10447                if (libraryEntry != null) {
10448                    signatureCheckPs = mSettings.getPackageLPr(libraryEntry.apk);
10449                }
10450            }
10451
10452            if (shouldCheckUpgradeKeySetLP(signatureCheckPs, scanFlags)) {
10453                if (checkUpgradeKeySetLP(signatureCheckPs, pkg)) {
10454                    // We just determined the app is signed correctly, so bring
10455                    // over the latest parsed certs.
10456                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
10457                } else {
10458                    if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
10459                        throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
10460                                "Package " + pkg.packageName + " upgrade keys do not match the "
10461                                + "previously installed version");
10462                    } else {
10463                        pkgSetting.signatures.mSignatures = pkg.mSignatures;
10464                        String msg = "System package " + pkg.packageName
10465                                + " signature changed; retaining data.";
10466                        reportSettingsProblem(Log.WARN, msg);
10467                    }
10468                }
10469            } else {
10470                try {
10471                    // SIDE EFFECTS; compareSignaturesCompat() changes KeysetManagerService
10472                    verifySignaturesLP(signatureCheckPs, pkg);
10473                    // We just determined the app is signed correctly, so bring
10474                    // over the latest parsed certs.
10475                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
10476                } catch (PackageManagerException e) {
10477                    if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
10478                        throw e;
10479                    }
10480                    // The signature has changed, but this package is in the system
10481                    // image...  let's recover!
10482                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
10483                    // However...  if this package is part of a shared user, but it
10484                    // doesn't match the signature of the shared user, let's fail.
10485                    // What this means is that you can't change the signatures
10486                    // associated with an overall shared user, which doesn't seem all
10487                    // that unreasonable.
10488                    if (signatureCheckPs.sharedUser != null) {
10489                        if (compareSignatures(signatureCheckPs.sharedUser.signatures.mSignatures,
10490                                pkg.mSignatures) != PackageManager.SIGNATURE_MATCH) {
10491                            throw new PackageManagerException(
10492                                    INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES,
10493                                    "Signature mismatch for shared user: "
10494                                            + pkgSetting.sharedUser);
10495                        }
10496                    }
10497                    // File a report about this.
10498                    String msg = "System package " + pkg.packageName
10499                            + " signature changed; retaining data.";
10500                    reportSettingsProblem(Log.WARN, msg);
10501                }
10502            }
10503
10504            if ((scanFlags & SCAN_CHECK_ONLY) == 0 && pkg.mAdoptPermissions != null) {
10505                // This package wants to adopt ownership of permissions from
10506                // another package.
10507                for (int i = pkg.mAdoptPermissions.size() - 1; i >= 0; i--) {
10508                    final String origName = pkg.mAdoptPermissions.get(i);
10509                    final PackageSetting orig = mSettings.getPackageLPr(origName);
10510                    if (orig != null) {
10511                        if (verifyPackageUpdateLPr(orig, pkg)) {
10512                            Slog.i(TAG, "Adopting permissions from " + origName + " to "
10513                                    + pkg.packageName);
10514                            // SIDE EFFECTS; updates permissions system state; move elsewhere
10515                            mSettings.transferPermissionsLPw(origName, pkg.packageName);
10516                        }
10517                    }
10518                }
10519            }
10520        }
10521
10522        pkg.applicationInfo.processName = fixProcessName(
10523                pkg.applicationInfo.packageName,
10524                pkg.applicationInfo.processName);
10525
10526        if (pkg != mPlatformPackage) {
10527            // Get all of our default paths setup
10528            pkg.applicationInfo.initForUser(UserHandle.USER_SYSTEM);
10529        }
10530
10531        final String cpuAbiOverride = deriveAbiOverride(pkg.cpuAbiOverride, pkgSetting);
10532
10533        if ((scanFlags & SCAN_NEW_INSTALL) == 0) {
10534            if ((scanFlags & SCAN_FIRST_BOOT_OR_UPGRADE) != 0) {
10535                Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "derivePackageAbi");
10536                final boolean extractNativeLibs = !pkg.isLibrary();
10537                derivePackageAbi(pkg, scanFile, cpuAbiOverride, extractNativeLibs,
10538                        mAppLib32InstallDir);
10539                Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
10540
10541                // Some system apps still use directory structure for native libraries
10542                // in which case we might end up not detecting abi solely based on apk
10543                // structure. Try to detect abi based on directory structure.
10544                if (isSystemApp(pkg) && !pkg.isUpdatedSystemApp() &&
10545                        pkg.applicationInfo.primaryCpuAbi == null) {
10546                    setBundledAppAbisAndRoots(pkg, pkgSetting);
10547                    setNativeLibraryPaths(pkg, mAppLib32InstallDir);
10548                }
10549            } else {
10550                // This is not a first boot or an upgrade, don't bother deriving the
10551                // ABI during the scan. Instead, trust the value that was stored in the
10552                // package setting.
10553                pkg.applicationInfo.primaryCpuAbi = primaryCpuAbiFromSettings;
10554                pkg.applicationInfo.secondaryCpuAbi = secondaryCpuAbiFromSettings;
10555
10556                setNativeLibraryPaths(pkg, mAppLib32InstallDir);
10557
10558                if (DEBUG_ABI_SELECTION) {
10559                    Slog.i(TAG, "Using ABIS and native lib paths from settings : " +
10560                        pkg.packageName + " " + pkg.applicationInfo.primaryCpuAbi + ", " +
10561                        pkg.applicationInfo.secondaryCpuAbi);
10562                }
10563            }
10564        } else {
10565            if ((scanFlags & SCAN_MOVE) != 0) {
10566                // We haven't run dex-opt for this move (since we've moved the compiled output too)
10567                // but we already have this packages package info in the PackageSetting. We just
10568                // use that and derive the native library path based on the new codepath.
10569                pkg.applicationInfo.primaryCpuAbi = pkgSetting.primaryCpuAbiString;
10570                pkg.applicationInfo.secondaryCpuAbi = pkgSetting.secondaryCpuAbiString;
10571            }
10572
10573            // Set native library paths again. For moves, the path will be updated based on the
10574            // ABIs we've determined above. For non-moves, the path will be updated based on the
10575            // ABIs we determined during compilation, but the path will depend on the final
10576            // package path (after the rename away from the stage path).
10577            setNativeLibraryPaths(pkg, mAppLib32InstallDir);
10578        }
10579
10580        // This is a special case for the "system" package, where the ABI is
10581        // dictated by the zygote configuration (and init.rc). We should keep track
10582        // of this ABI so that we can deal with "normal" applications that run under
10583        // the same UID correctly.
10584        if (mPlatformPackage == pkg) {
10585            pkg.applicationInfo.primaryCpuAbi = VMRuntime.getRuntime().is64Bit() ?
10586                    Build.SUPPORTED_64_BIT_ABIS[0] : Build.SUPPORTED_32_BIT_ABIS[0];
10587        }
10588
10589        // If there's a mismatch between the abi-override in the package setting
10590        // and the abiOverride specified for the install. Warn about this because we
10591        // would've already compiled the app without taking the package setting into
10592        // account.
10593        if ((scanFlags & SCAN_NO_DEX) == 0 && (scanFlags & SCAN_NEW_INSTALL) != 0) {
10594            if (cpuAbiOverride == null && pkgSetting.cpuAbiOverrideString != null) {
10595                Slog.w(TAG, "Ignoring persisted ABI override " + cpuAbiOverride +
10596                        " for package " + pkg.packageName);
10597            }
10598        }
10599
10600        pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi;
10601        pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi;
10602        pkgSetting.cpuAbiOverrideString = cpuAbiOverride;
10603
10604        // Copy the derived override back to the parsed package, so that we can
10605        // update the package settings accordingly.
10606        pkg.cpuAbiOverride = cpuAbiOverride;
10607
10608        if (DEBUG_ABI_SELECTION) {
10609            Slog.d(TAG, "Resolved nativeLibraryRoot for " + pkg.applicationInfo.packageName
10610                    + " to root=" + pkg.applicationInfo.nativeLibraryRootDir + ", isa="
10611                    + pkg.applicationInfo.nativeLibraryRootRequiresIsa);
10612        }
10613
10614        // Push the derived path down into PackageSettings so we know what to
10615        // clean up at uninstall time.
10616        pkgSetting.legacyNativeLibraryPathString = pkg.applicationInfo.nativeLibraryRootDir;
10617
10618        if (DEBUG_ABI_SELECTION) {
10619            Log.d(TAG, "Abis for package[" + pkg.packageName + "] are" +
10620                    " primary=" + pkg.applicationInfo.primaryCpuAbi +
10621                    " secondary=" + pkg.applicationInfo.secondaryCpuAbi);
10622        }
10623
10624        // SIDE EFFECTS; removes DEX files from disk; move elsewhere
10625        if ((scanFlags & SCAN_BOOTING) == 0 && pkgSetting.sharedUser != null) {
10626            // We don't do this here during boot because we can do it all
10627            // at once after scanning all existing packages.
10628            //
10629            // We also do this *before* we perform dexopt on this package, so that
10630            // we can avoid redundant dexopts, and also to make sure we've got the
10631            // code and package path correct.
10632            adjustCpuAbisForSharedUserLPw(pkgSetting.sharedUser.packages, pkg);
10633        }
10634
10635        if (mFactoryTest && pkg.requestedPermissions.contains(
10636                android.Manifest.permission.FACTORY_TEST)) {
10637            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_FACTORY_TEST;
10638        }
10639
10640        if (isSystemApp(pkg)) {
10641            pkgSetting.isOrphaned = true;
10642        }
10643
10644        // Take care of first install / last update times.
10645        final long scanFileTime = getLastModifiedTime(pkg, scanFile);
10646        if (currentTime != 0) {
10647            if (pkgSetting.firstInstallTime == 0) {
10648                pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = currentTime;
10649            } else if ((scanFlags & SCAN_UPDATE_TIME) != 0) {
10650                pkgSetting.lastUpdateTime = currentTime;
10651            }
10652        } else if (pkgSetting.firstInstallTime == 0) {
10653            // We need *something*.  Take time time stamp of the file.
10654            pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = scanFileTime;
10655        } else if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0) {
10656            if (scanFileTime != pkgSetting.timeStamp) {
10657                // A package on the system image has changed; consider this
10658                // to be an update.
10659                pkgSetting.lastUpdateTime = scanFileTime;
10660            }
10661        }
10662        pkgSetting.setTimeStamp(scanFileTime);
10663
10664        if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
10665            if (nonMutatedPs != null) {
10666                synchronized (mPackages) {
10667                    mSettings.mPackages.put(nonMutatedPs.name, nonMutatedPs);
10668                }
10669            }
10670        } else {
10671            final int userId = user == null ? 0 : user.getIdentifier();
10672            // Modify state for the given package setting
10673            commitPackageSettings(pkg, pkgSetting, user, scanFlags,
10674                    (policyFlags & PackageParser.PARSE_CHATTY) != 0 /*chatty*/);
10675            if (pkgSetting.getInstantApp(userId)) {
10676                mInstantAppRegistry.addInstantAppLPw(userId, pkgSetting.appId);
10677            }
10678        }
10679        return pkg;
10680    }
10681
10682    /**
10683     * Applies policy to the parsed package based upon the given policy flags.
10684     * Ensures the package is in a good state.
10685     * <p>
10686     * Implementation detail: This method must NOT have any side effect. It would
10687     * ideally be static, but, it requires locks to read system state.
10688     */
10689    private void applyPolicy(PackageParser.Package pkg, int policyFlags) {
10690        if ((policyFlags&PackageParser.PARSE_IS_SYSTEM) != 0) {
10691            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_SYSTEM;
10692            if (pkg.applicationInfo.isDirectBootAware()) {
10693                // we're direct boot aware; set for all components
10694                for (PackageParser.Service s : pkg.services) {
10695                    s.info.encryptionAware = s.info.directBootAware = true;
10696                }
10697                for (PackageParser.Provider p : pkg.providers) {
10698                    p.info.encryptionAware = p.info.directBootAware = true;
10699                }
10700                for (PackageParser.Activity a : pkg.activities) {
10701                    a.info.encryptionAware = a.info.directBootAware = true;
10702                }
10703                for (PackageParser.Activity r : pkg.receivers) {
10704                    r.info.encryptionAware = r.info.directBootAware = true;
10705                }
10706            }
10707        } else {
10708            // Only allow system apps to be flagged as core apps.
10709            pkg.coreApp = false;
10710            // clear flags not applicable to regular apps
10711            pkg.applicationInfo.privateFlags &=
10712                    ~ApplicationInfo.PRIVATE_FLAG_DEFAULT_TO_DEVICE_PROTECTED_STORAGE;
10713            pkg.applicationInfo.privateFlags &=
10714                    ~ApplicationInfo.PRIVATE_FLAG_DIRECT_BOOT_AWARE;
10715        }
10716        pkg.mTrustedOverlay = (policyFlags&PackageParser.PARSE_TRUSTED_OVERLAY) != 0;
10717
10718        if ((policyFlags&PackageParser.PARSE_IS_PRIVILEGED) != 0) {
10719            pkg.applicationInfo.privateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
10720        }
10721
10722        if (!isSystemApp(pkg)) {
10723            // Only system apps can use these features.
10724            pkg.mOriginalPackages = null;
10725            pkg.mRealPackage = null;
10726            pkg.mAdoptPermissions = null;
10727        }
10728    }
10729
10730    /**
10731     * Asserts the parsed package is valid according to the given policy. If the
10732     * package is invalid, for whatever reason, throws {@link PackageManagerException}.
10733     * <p>
10734     * Implementation detail: This method must NOT have any side effects. It would
10735     * ideally be static, but, it requires locks to read system state.
10736     *
10737     * @throws PackageManagerException If the package fails any of the validation checks
10738     */
10739    private void assertPackageIsValid(PackageParser.Package pkg, int policyFlags, int scanFlags)
10740            throws PackageManagerException {
10741        if ((policyFlags & PackageParser.PARSE_ENFORCE_CODE) != 0) {
10742            assertCodePolicy(pkg);
10743        }
10744
10745        if (pkg.applicationInfo.getCodePath() == null ||
10746                pkg.applicationInfo.getResourcePath() == null) {
10747            // Bail out. The resource and code paths haven't been set.
10748            throw new PackageManagerException(INSTALL_FAILED_INVALID_APK,
10749                    "Code and resource paths haven't been set correctly");
10750        }
10751
10752        // Make sure we're not adding any bogus keyset info
10753        KeySetManagerService ksms = mSettings.mKeySetManagerService;
10754        ksms.assertScannedPackageValid(pkg);
10755
10756        synchronized (mPackages) {
10757            // The special "android" package can only be defined once
10758            if (pkg.packageName.equals("android")) {
10759                if (mAndroidApplication != null) {
10760                    Slog.w(TAG, "*************************************************");
10761                    Slog.w(TAG, "Core android package being redefined.  Skipping.");
10762                    Slog.w(TAG, " codePath=" + pkg.codePath);
10763                    Slog.w(TAG, "*************************************************");
10764                    throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE,
10765                            "Core android package being redefined.  Skipping.");
10766                }
10767            }
10768
10769            // A package name must be unique; don't allow duplicates
10770            if (mPackages.containsKey(pkg.packageName)) {
10771                throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE,
10772                        "Application package " + pkg.packageName
10773                        + " already installed.  Skipping duplicate.");
10774            }
10775
10776            if (pkg.applicationInfo.isStaticSharedLibrary()) {
10777                // Static libs have a synthetic package name containing the version
10778                // but we still want the base name to be unique.
10779                if (mPackages.containsKey(pkg.manifestPackageName)) {
10780                    throw new PackageManagerException(
10781                            "Duplicate static shared lib provider package");
10782                }
10783
10784                // Static shared libraries should have at least O target SDK
10785                if (pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.O) {
10786                    throw new PackageManagerException(
10787                            "Packages declaring static-shared libs must target O SDK or higher");
10788                }
10789
10790                // Package declaring static a shared lib cannot be instant apps
10791                if ((scanFlags & SCAN_AS_INSTANT_APP) != 0) {
10792                    throw new PackageManagerException(
10793                            "Packages declaring static-shared libs cannot be instant apps");
10794                }
10795
10796                // Package declaring static a shared lib cannot be renamed since the package
10797                // name is synthetic and apps can't code around package manager internals.
10798                if (!ArrayUtils.isEmpty(pkg.mOriginalPackages)) {
10799                    throw new PackageManagerException(
10800                            "Packages declaring static-shared libs cannot be renamed");
10801                }
10802
10803                // Package declaring static a shared lib cannot declare child packages
10804                if (!ArrayUtils.isEmpty(pkg.childPackages)) {
10805                    throw new PackageManagerException(
10806                            "Packages declaring static-shared libs cannot have child packages");
10807                }
10808
10809                // Package declaring static a shared lib cannot declare dynamic libs
10810                if (!ArrayUtils.isEmpty(pkg.libraryNames)) {
10811                    throw new PackageManagerException(
10812                            "Packages declaring static-shared libs cannot declare dynamic libs");
10813                }
10814
10815                // Package declaring static a shared lib cannot declare shared users
10816                if (pkg.mSharedUserId != null) {
10817                    throw new PackageManagerException(
10818                            "Packages declaring static-shared libs cannot declare shared users");
10819                }
10820
10821                // Static shared libs cannot declare activities
10822                if (!pkg.activities.isEmpty()) {
10823                    throw new PackageManagerException(
10824                            "Static shared libs cannot declare activities");
10825                }
10826
10827                // Static shared libs cannot declare services
10828                if (!pkg.services.isEmpty()) {
10829                    throw new PackageManagerException(
10830                            "Static shared libs cannot declare services");
10831                }
10832
10833                // Static shared libs cannot declare providers
10834                if (!pkg.providers.isEmpty()) {
10835                    throw new PackageManagerException(
10836                            "Static shared libs cannot declare content providers");
10837                }
10838
10839                // Static shared libs cannot declare receivers
10840                if (!pkg.receivers.isEmpty()) {
10841                    throw new PackageManagerException(
10842                            "Static shared libs cannot declare broadcast receivers");
10843                }
10844
10845                // Static shared libs cannot declare permission groups
10846                if (!pkg.permissionGroups.isEmpty()) {
10847                    throw new PackageManagerException(
10848                            "Static shared libs cannot declare permission groups");
10849                }
10850
10851                // Static shared libs cannot declare permissions
10852                if (!pkg.permissions.isEmpty()) {
10853                    throw new PackageManagerException(
10854                            "Static shared libs cannot declare permissions");
10855                }
10856
10857                // Static shared libs cannot declare protected broadcasts
10858                if (pkg.protectedBroadcasts != null) {
10859                    throw new PackageManagerException(
10860                            "Static shared libs cannot declare protected broadcasts");
10861                }
10862
10863                // Static shared libs cannot be overlay targets
10864                if (pkg.mOverlayTarget != null) {
10865                    throw new PackageManagerException(
10866                            "Static shared libs cannot be overlay targets");
10867                }
10868
10869                // The version codes must be ordered as lib versions
10870                int minVersionCode = Integer.MIN_VALUE;
10871                int maxVersionCode = Integer.MAX_VALUE;
10872
10873                SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(
10874                        pkg.staticSharedLibName);
10875                if (versionedLib != null) {
10876                    final int versionCount = versionedLib.size();
10877                    for (int i = 0; i < versionCount; i++) {
10878                        SharedLibraryInfo libInfo = versionedLib.valueAt(i).info;
10879                        final int libVersionCode = libInfo.getDeclaringPackage()
10880                                .getVersionCode();
10881                        if (libInfo.getVersion() <  pkg.staticSharedLibVersion) {
10882                            minVersionCode = Math.max(minVersionCode, libVersionCode + 1);
10883                        } else if (libInfo.getVersion() >  pkg.staticSharedLibVersion) {
10884                            maxVersionCode = Math.min(maxVersionCode, libVersionCode - 1);
10885                        } else {
10886                            minVersionCode = maxVersionCode = libVersionCode;
10887                            break;
10888                        }
10889                    }
10890                }
10891                if (pkg.mVersionCode < minVersionCode || pkg.mVersionCode > maxVersionCode) {
10892                    throw new PackageManagerException("Static shared"
10893                            + " lib version codes must be ordered as lib versions");
10894                }
10895            }
10896
10897            // Only privileged apps and updated privileged apps can add child packages.
10898            if (pkg.childPackages != null && !pkg.childPackages.isEmpty()) {
10899                if ((policyFlags & PARSE_IS_PRIVILEGED) == 0) {
10900                    throw new PackageManagerException("Only privileged apps can add child "
10901                            + "packages. Ignoring package " + pkg.packageName);
10902                }
10903                final int childCount = pkg.childPackages.size();
10904                for (int i = 0; i < childCount; i++) {
10905                    PackageParser.Package childPkg = pkg.childPackages.get(i);
10906                    if (mSettings.hasOtherDisabledSystemPkgWithChildLPr(pkg.packageName,
10907                            childPkg.packageName)) {
10908                        throw new PackageManagerException("Can't override child of "
10909                                + "another disabled app. Ignoring package " + pkg.packageName);
10910                    }
10911                }
10912            }
10913
10914            // If we're only installing presumed-existing packages, require that the
10915            // scanned APK is both already known and at the path previously established
10916            // for it.  Previously unknown packages we pick up normally, but if we have an
10917            // a priori expectation about this package's install presence, enforce it.
10918            // With a singular exception for new system packages. When an OTA contains
10919            // a new system package, we allow the codepath to change from a system location
10920            // to the user-installed location. If we don't allow this change, any newer,
10921            // user-installed version of the application will be ignored.
10922            if ((scanFlags & SCAN_REQUIRE_KNOWN) != 0) {
10923                if (mExpectingBetter.containsKey(pkg.packageName)) {
10924                    logCriticalInfo(Log.WARN,
10925                            "Relax SCAN_REQUIRE_KNOWN requirement for package " + pkg.packageName);
10926                } else {
10927                    PackageSetting known = mSettings.getPackageLPr(pkg.packageName);
10928                    if (known != null) {
10929                        if (DEBUG_PACKAGE_SCANNING) {
10930                            Log.d(TAG, "Examining " + pkg.codePath
10931                                    + " and requiring known paths " + known.codePathString
10932                                    + " & " + known.resourcePathString);
10933                        }
10934                        if (!pkg.applicationInfo.getCodePath().equals(known.codePathString)
10935                                || !pkg.applicationInfo.getResourcePath().equals(
10936                                        known.resourcePathString)) {
10937                            throw new PackageManagerException(INSTALL_FAILED_PACKAGE_CHANGED,
10938                                    "Application package " + pkg.packageName
10939                                    + " found at " + pkg.applicationInfo.getCodePath()
10940                                    + " but expected at " + known.codePathString
10941                                    + "; ignoring.");
10942                        }
10943                    }
10944                }
10945            }
10946
10947            // Verify that this new package doesn't have any content providers
10948            // that conflict with existing packages.  Only do this if the
10949            // package isn't already installed, since we don't want to break
10950            // things that are installed.
10951            if ((scanFlags & SCAN_NEW_INSTALL) != 0) {
10952                final int N = pkg.providers.size();
10953                int i;
10954                for (i=0; i<N; i++) {
10955                    PackageParser.Provider p = pkg.providers.get(i);
10956                    if (p.info.authority != null) {
10957                        String names[] = p.info.authority.split(";");
10958                        for (int j = 0; j < names.length; j++) {
10959                            if (mProvidersByAuthority.containsKey(names[j])) {
10960                                PackageParser.Provider other = mProvidersByAuthority.get(names[j]);
10961                                final String otherPackageName =
10962                                        ((other != null && other.getComponentName() != null) ?
10963                                                other.getComponentName().getPackageName() : "?");
10964                                throw new PackageManagerException(
10965                                        INSTALL_FAILED_CONFLICTING_PROVIDER,
10966                                        "Can't install because provider name " + names[j]
10967                                                + " (in package " + pkg.applicationInfo.packageName
10968                                                + ") is already used by " + otherPackageName);
10969                            }
10970                        }
10971                    }
10972                }
10973            }
10974        }
10975    }
10976
10977    private boolean addSharedLibraryLPw(String path, String apk, String name, int version,
10978            int type, String declaringPackageName, int declaringVersionCode) {
10979        SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(name);
10980        if (versionedLib == null) {
10981            versionedLib = new SparseArray<>();
10982            mSharedLibraries.put(name, versionedLib);
10983            if (type == SharedLibraryInfo.TYPE_STATIC) {
10984                mStaticLibsByDeclaringPackage.put(declaringPackageName, versionedLib);
10985            }
10986        } else if (versionedLib.indexOfKey(version) >= 0) {
10987            return false;
10988        }
10989        SharedLibraryEntry libEntry = new SharedLibraryEntry(path, apk, name,
10990                version, type, declaringPackageName, declaringVersionCode);
10991        versionedLib.put(version, libEntry);
10992        return true;
10993    }
10994
10995    private boolean removeSharedLibraryLPw(String name, int version) {
10996        SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(name);
10997        if (versionedLib == null) {
10998            return false;
10999        }
11000        final int libIdx = versionedLib.indexOfKey(version);
11001        if (libIdx < 0) {
11002            return false;
11003        }
11004        SharedLibraryEntry libEntry = versionedLib.valueAt(libIdx);
11005        versionedLib.remove(version);
11006        if (versionedLib.size() <= 0) {
11007            mSharedLibraries.remove(name);
11008            if (libEntry.info.getType() == SharedLibraryInfo.TYPE_STATIC) {
11009                mStaticLibsByDeclaringPackage.remove(libEntry.info.getDeclaringPackage()
11010                        .getPackageName());
11011            }
11012        }
11013        return true;
11014    }
11015
11016    /**
11017     * Adds a scanned package to the system. When this method is finished, the package will
11018     * be available for query, resolution, etc...
11019     */
11020    private void commitPackageSettings(PackageParser.Package pkg, PackageSetting pkgSetting,
11021            UserHandle user, int scanFlags, boolean chatty) throws PackageManagerException {
11022        final String pkgName = pkg.packageName;
11023        if (mCustomResolverComponentName != null &&
11024                mCustomResolverComponentName.getPackageName().equals(pkg.packageName)) {
11025            setUpCustomResolverActivity(pkg);
11026        }
11027
11028        if (pkg.packageName.equals("android")) {
11029            synchronized (mPackages) {
11030                if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
11031                    // Set up information for our fall-back user intent resolution activity.
11032                    mPlatformPackage = pkg;
11033                    pkg.mVersionCode = mSdkVersion;
11034                    mAndroidApplication = pkg.applicationInfo;
11035                    if (!mResolverReplaced) {
11036                        mResolveActivity.applicationInfo = mAndroidApplication;
11037                        mResolveActivity.name = ResolverActivity.class.getName();
11038                        mResolveActivity.packageName = mAndroidApplication.packageName;
11039                        mResolveActivity.processName = "system:ui";
11040                        mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
11041                        mResolveActivity.documentLaunchMode = ActivityInfo.DOCUMENT_LAUNCH_NEVER;
11042                        mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS;
11043                        mResolveActivity.theme = R.style.Theme_Material_Dialog_Alert;
11044                        mResolveActivity.exported = true;
11045                        mResolveActivity.enabled = true;
11046                        mResolveActivity.resizeMode = ActivityInfo.RESIZE_MODE_RESIZEABLE;
11047                        mResolveActivity.configChanges = ActivityInfo.CONFIG_SCREEN_SIZE
11048                                | ActivityInfo.CONFIG_SMALLEST_SCREEN_SIZE
11049                                | ActivityInfo.CONFIG_SCREEN_LAYOUT
11050                                | ActivityInfo.CONFIG_ORIENTATION
11051                                | ActivityInfo.CONFIG_KEYBOARD
11052                                | ActivityInfo.CONFIG_KEYBOARD_HIDDEN;
11053                        mResolveInfo.activityInfo = mResolveActivity;
11054                        mResolveInfo.priority = 0;
11055                        mResolveInfo.preferredOrder = 0;
11056                        mResolveInfo.match = 0;
11057                        mResolveComponentName = new ComponentName(
11058                                mAndroidApplication.packageName, mResolveActivity.name);
11059                    }
11060                }
11061            }
11062        }
11063
11064        ArrayList<PackageParser.Package> clientLibPkgs = null;
11065        // writer
11066        synchronized (mPackages) {
11067            boolean hasStaticSharedLibs = false;
11068
11069            // Any app can add new static shared libraries
11070            if (pkg.staticSharedLibName != null) {
11071                // Static shared libs don't allow renaming as they have synthetic package
11072                // names to allow install of multiple versions, so use name from manifest.
11073                if (addSharedLibraryLPw(null, pkg.packageName, pkg.staticSharedLibName,
11074                        pkg.staticSharedLibVersion, SharedLibraryInfo.TYPE_STATIC,
11075                        pkg.manifestPackageName, pkg.mVersionCode)) {
11076                    hasStaticSharedLibs = true;
11077                } else {
11078                    Slog.w(TAG, "Package " + pkg.packageName + " library "
11079                                + pkg.staticSharedLibName + " already exists; skipping");
11080                }
11081                // Static shared libs cannot be updated once installed since they
11082                // use synthetic package name which includes the version code, so
11083                // not need to update other packages's shared lib dependencies.
11084            }
11085
11086            if (!hasStaticSharedLibs
11087                    && (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
11088                // Only system apps can add new dynamic shared libraries.
11089                if (pkg.libraryNames != null) {
11090                    for (int i = 0; i < pkg.libraryNames.size(); i++) {
11091                        String name = pkg.libraryNames.get(i);
11092                        boolean allowed = false;
11093                        if (pkg.isUpdatedSystemApp()) {
11094                            // New library entries can only be added through the
11095                            // system image.  This is important to get rid of a lot
11096                            // of nasty edge cases: for example if we allowed a non-
11097                            // system update of the app to add a library, then uninstalling
11098                            // the update would make the library go away, and assumptions
11099                            // we made such as through app install filtering would now
11100                            // have allowed apps on the device which aren't compatible
11101                            // with it.  Better to just have the restriction here, be
11102                            // conservative, and create many fewer cases that can negatively
11103                            // impact the user experience.
11104                            final PackageSetting sysPs = mSettings
11105                                    .getDisabledSystemPkgLPr(pkg.packageName);
11106                            if (sysPs.pkg != null && sysPs.pkg.libraryNames != null) {
11107                                for (int j = 0; j < sysPs.pkg.libraryNames.size(); j++) {
11108                                    if (name.equals(sysPs.pkg.libraryNames.get(j))) {
11109                                        allowed = true;
11110                                        break;
11111                                    }
11112                                }
11113                            }
11114                        } else {
11115                            allowed = true;
11116                        }
11117                        if (allowed) {
11118                            if (!addSharedLibraryLPw(null, pkg.packageName, name,
11119                                    SharedLibraryInfo.VERSION_UNDEFINED,
11120                                    SharedLibraryInfo.TYPE_DYNAMIC,
11121                                    pkg.packageName, pkg.mVersionCode)) {
11122                                Slog.w(TAG, "Package " + pkg.packageName + " library "
11123                                        + name + " already exists; skipping");
11124                            }
11125                        } else {
11126                            Slog.w(TAG, "Package " + pkg.packageName + " declares lib "
11127                                    + name + " that is not declared on system image; skipping");
11128                        }
11129                    }
11130
11131                    if ((scanFlags & SCAN_BOOTING) == 0) {
11132                        // If we are not booting, we need to update any applications
11133                        // that are clients of our shared library.  If we are booting,
11134                        // this will all be done once the scan is complete.
11135                        clientLibPkgs = updateAllSharedLibrariesLPw(pkg);
11136                    }
11137                }
11138            }
11139        }
11140
11141        if ((scanFlags & SCAN_BOOTING) != 0) {
11142            // No apps can run during boot scan, so they don't need to be frozen
11143        } else if ((scanFlags & SCAN_DONT_KILL_APP) != 0) {
11144            // Caller asked to not kill app, so it's probably not frozen
11145        } else if ((scanFlags & SCAN_IGNORE_FROZEN) != 0) {
11146            // Caller asked us to ignore frozen check for some reason; they
11147            // probably didn't know the package name
11148        } else {
11149            // We're doing major surgery on this package, so it better be frozen
11150            // right now to keep it from launching
11151            checkPackageFrozen(pkgName);
11152        }
11153
11154        // Also need to kill any apps that are dependent on the library.
11155        if (clientLibPkgs != null) {
11156            for (int i=0; i<clientLibPkgs.size(); i++) {
11157                PackageParser.Package clientPkg = clientLibPkgs.get(i);
11158                killApplication(clientPkg.applicationInfo.packageName,
11159                        clientPkg.applicationInfo.uid, "update lib");
11160            }
11161        }
11162
11163        // writer
11164        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings");
11165
11166        synchronized (mPackages) {
11167            // We don't expect installation to fail beyond this point
11168
11169            // Add the new setting to mSettings
11170            mSettings.insertPackageSettingLPw(pkgSetting, pkg);
11171            // Add the new setting to mPackages
11172            mPackages.put(pkg.applicationInfo.packageName, pkg);
11173            // Make sure we don't accidentally delete its data.
11174            final Iterator<PackageCleanItem> iter = mSettings.mPackagesToBeCleaned.iterator();
11175            while (iter.hasNext()) {
11176                PackageCleanItem item = iter.next();
11177                if (pkgName.equals(item.packageName)) {
11178                    iter.remove();
11179                }
11180            }
11181
11182            // Add the package's KeySets to the global KeySetManagerService
11183            KeySetManagerService ksms = mSettings.mKeySetManagerService;
11184            ksms.addScannedPackageLPw(pkg);
11185
11186            int N = pkg.providers.size();
11187            StringBuilder r = null;
11188            int i;
11189            for (i=0; i<N; i++) {
11190                PackageParser.Provider p = pkg.providers.get(i);
11191                p.info.processName = fixProcessName(pkg.applicationInfo.processName,
11192                        p.info.processName);
11193                mProviders.addProvider(p);
11194                p.syncable = p.info.isSyncable;
11195                if (p.info.authority != null) {
11196                    String names[] = p.info.authority.split(";");
11197                    p.info.authority = null;
11198                    for (int j = 0; j < names.length; j++) {
11199                        if (j == 1 && p.syncable) {
11200                            // We only want the first authority for a provider to possibly be
11201                            // syncable, so if we already added this provider using a different
11202                            // authority clear the syncable flag. We copy the provider before
11203                            // changing it because the mProviders object contains a reference
11204                            // to a provider that we don't want to change.
11205                            // Only do this for the second authority since the resulting provider
11206                            // object can be the same for all future authorities for this provider.
11207                            p = new PackageParser.Provider(p);
11208                            p.syncable = false;
11209                        }
11210                        if (!mProvidersByAuthority.containsKey(names[j])) {
11211                            mProvidersByAuthority.put(names[j], p);
11212                            if (p.info.authority == null) {
11213                                p.info.authority = names[j];
11214                            } else {
11215                                p.info.authority = p.info.authority + ";" + names[j];
11216                            }
11217                            if (DEBUG_PACKAGE_SCANNING) {
11218                                if (chatty)
11219                                    Log.d(TAG, "Registered content provider: " + names[j]
11220                                            + ", className = " + p.info.name + ", isSyncable = "
11221                                            + p.info.isSyncable);
11222                            }
11223                        } else {
11224                            PackageParser.Provider other = mProvidersByAuthority.get(names[j]);
11225                            Slog.w(TAG, "Skipping provider name " + names[j] +
11226                                    " (in package " + pkg.applicationInfo.packageName +
11227                                    "): name already used by "
11228                                    + ((other != null && other.getComponentName() != null)
11229                                            ? other.getComponentName().getPackageName() : "?"));
11230                        }
11231                    }
11232                }
11233                if (chatty) {
11234                    if (r == null) {
11235                        r = new StringBuilder(256);
11236                    } else {
11237                        r.append(' ');
11238                    }
11239                    r.append(p.info.name);
11240                }
11241            }
11242            if (r != null) {
11243                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Providers: " + r);
11244            }
11245
11246            N = pkg.services.size();
11247            r = null;
11248            for (i=0; i<N; i++) {
11249                PackageParser.Service s = pkg.services.get(i);
11250                s.info.processName = fixProcessName(pkg.applicationInfo.processName,
11251                        s.info.processName);
11252                mServices.addService(s);
11253                if (chatty) {
11254                    if (r == null) {
11255                        r = new StringBuilder(256);
11256                    } else {
11257                        r.append(' ');
11258                    }
11259                    r.append(s.info.name);
11260                }
11261            }
11262            if (r != null) {
11263                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Services: " + r);
11264            }
11265
11266            N = pkg.receivers.size();
11267            r = null;
11268            for (i=0; i<N; i++) {
11269                PackageParser.Activity a = pkg.receivers.get(i);
11270                a.info.processName = fixProcessName(pkg.applicationInfo.processName,
11271                        a.info.processName);
11272                mReceivers.addActivity(a, "receiver");
11273                if (chatty) {
11274                    if (r == null) {
11275                        r = new StringBuilder(256);
11276                    } else {
11277                        r.append(' ');
11278                    }
11279                    r.append(a.info.name);
11280                }
11281            }
11282            if (r != null) {
11283                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Receivers: " + r);
11284            }
11285
11286            N = pkg.activities.size();
11287            r = null;
11288            for (i=0; i<N; i++) {
11289                PackageParser.Activity a = pkg.activities.get(i);
11290                a.info.processName = fixProcessName(pkg.applicationInfo.processName,
11291                        a.info.processName);
11292                mActivities.addActivity(a, "activity");
11293                if (chatty) {
11294                    if (r == null) {
11295                        r = new StringBuilder(256);
11296                    } else {
11297                        r.append(' ');
11298                    }
11299                    r.append(a.info.name);
11300                }
11301            }
11302            if (r != null) {
11303                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Activities: " + r);
11304            }
11305
11306            N = pkg.permissionGroups.size();
11307            r = null;
11308            for (i=0; i<N; i++) {
11309                PackageParser.PermissionGroup pg = pkg.permissionGroups.get(i);
11310                PackageParser.PermissionGroup cur = mPermissionGroups.get(pg.info.name);
11311                final String curPackageName = cur == null ? null : cur.info.packageName;
11312                // Dont allow ephemeral apps to define new permission groups.
11313                if ((scanFlags & SCAN_AS_INSTANT_APP) != 0) {
11314                    Slog.w(TAG, "Permission group " + pg.info.name + " from package "
11315                            + pg.info.packageName
11316                            + " ignored: instant apps cannot define new permission groups.");
11317                    continue;
11318                }
11319                final boolean isPackageUpdate = pg.info.packageName.equals(curPackageName);
11320                if (cur == null || isPackageUpdate) {
11321                    mPermissionGroups.put(pg.info.name, pg);
11322                    if (chatty) {
11323                        if (r == null) {
11324                            r = new StringBuilder(256);
11325                        } else {
11326                            r.append(' ');
11327                        }
11328                        if (isPackageUpdate) {
11329                            r.append("UPD:");
11330                        }
11331                        r.append(pg.info.name);
11332                    }
11333                } else {
11334                    Slog.w(TAG, "Permission group " + pg.info.name + " from package "
11335                            + pg.info.packageName + " ignored: original from "
11336                            + cur.info.packageName);
11337                    if (chatty) {
11338                        if (r == null) {
11339                            r = new StringBuilder(256);
11340                        } else {
11341                            r.append(' ');
11342                        }
11343                        r.append("DUP:");
11344                        r.append(pg.info.name);
11345                    }
11346                }
11347            }
11348            if (r != null) {
11349                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Permission Groups: " + r);
11350            }
11351
11352            N = pkg.permissions.size();
11353            r = null;
11354            for (i=0; i<N; i++) {
11355                PackageParser.Permission p = pkg.permissions.get(i);
11356
11357                // Dont allow ephemeral apps to define new permissions.
11358                if ((scanFlags & SCAN_AS_INSTANT_APP) != 0) {
11359                    Slog.w(TAG, "Permission " + p.info.name + " from package "
11360                            + p.info.packageName
11361                            + " ignored: instant apps cannot define new permissions.");
11362                    continue;
11363                }
11364
11365                // Assume by default that we did not install this permission into the system.
11366                p.info.flags &= ~PermissionInfo.FLAG_INSTALLED;
11367
11368                // Now that permission groups have a special meaning, we ignore permission
11369                // groups for legacy apps to prevent unexpected behavior. In particular,
11370                // permissions for one app being granted to someone just because they happen
11371                // to be in a group defined by another app (before this had no implications).
11372                if (pkg.applicationInfo.targetSdkVersion > Build.VERSION_CODES.LOLLIPOP_MR1) {
11373                    p.group = mPermissionGroups.get(p.info.group);
11374                    // Warn for a permission in an unknown group.
11375                    if (DEBUG_PERMISSIONS && p.info.group != null && p.group == null) {
11376                        Slog.i(TAG, "Permission " + p.info.name + " from package "
11377                                + p.info.packageName + " in an unknown group " + p.info.group);
11378                    }
11379                }
11380
11381                ArrayMap<String, BasePermission> permissionMap =
11382                        p.tree ? mSettings.mPermissionTrees
11383                                : mSettings.mPermissions;
11384                BasePermission bp = permissionMap.get(p.info.name);
11385
11386                // Allow system apps to redefine non-system permissions
11387                if (bp != null && !Objects.equals(bp.sourcePackage, p.info.packageName)) {
11388                    final boolean currentOwnerIsSystem = (bp.perm != null
11389                            && isSystemApp(bp.perm.owner));
11390                    if (isSystemApp(p.owner)) {
11391                        if (bp.type == BasePermission.TYPE_BUILTIN && bp.perm == null) {
11392                            // It's a built-in permission and no owner, take ownership now
11393                            bp.packageSetting = pkgSetting;
11394                            bp.perm = p;
11395                            bp.uid = pkg.applicationInfo.uid;
11396                            bp.sourcePackage = p.info.packageName;
11397                            p.info.flags |= PermissionInfo.FLAG_INSTALLED;
11398                        } else if (!currentOwnerIsSystem) {
11399                            String msg = "New decl " + p.owner + " of permission  "
11400                                    + p.info.name + " is system; overriding " + bp.sourcePackage;
11401                            reportSettingsProblem(Log.WARN, msg);
11402                            bp = null;
11403                        }
11404                    }
11405                }
11406
11407                if (bp == null) {
11408                    bp = new BasePermission(p.info.name, p.info.packageName,
11409                            BasePermission.TYPE_NORMAL);
11410                    permissionMap.put(p.info.name, bp);
11411                }
11412
11413                if (bp.perm == null) {
11414                    if (bp.sourcePackage == null
11415                            || bp.sourcePackage.equals(p.info.packageName)) {
11416                        BasePermission tree = findPermissionTreeLP(p.info.name);
11417                        if (tree == null
11418                                || tree.sourcePackage.equals(p.info.packageName)) {
11419                            bp.packageSetting = pkgSetting;
11420                            bp.perm = p;
11421                            bp.uid = pkg.applicationInfo.uid;
11422                            bp.sourcePackage = p.info.packageName;
11423                            p.info.flags |= PermissionInfo.FLAG_INSTALLED;
11424                            if (chatty) {
11425                                if (r == null) {
11426                                    r = new StringBuilder(256);
11427                                } else {
11428                                    r.append(' ');
11429                                }
11430                                r.append(p.info.name);
11431                            }
11432                        } else {
11433                            Slog.w(TAG, "Permission " + p.info.name + " from package "
11434                                    + p.info.packageName + " ignored: base tree "
11435                                    + tree.name + " is from package "
11436                                    + tree.sourcePackage);
11437                        }
11438                    } else {
11439                        Slog.w(TAG, "Permission " + p.info.name + " from package "
11440                                + p.info.packageName + " ignored: original from "
11441                                + bp.sourcePackage);
11442                    }
11443                } else if (chatty) {
11444                    if (r == null) {
11445                        r = new StringBuilder(256);
11446                    } else {
11447                        r.append(' ');
11448                    }
11449                    r.append("DUP:");
11450                    r.append(p.info.name);
11451                }
11452                if (bp.perm == p) {
11453                    bp.protectionLevel = p.info.protectionLevel;
11454                }
11455            }
11456
11457            if (r != null) {
11458                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Permissions: " + r);
11459            }
11460
11461            N = pkg.instrumentation.size();
11462            r = null;
11463            for (i=0; i<N; i++) {
11464                PackageParser.Instrumentation a = pkg.instrumentation.get(i);
11465                a.info.packageName = pkg.applicationInfo.packageName;
11466                a.info.sourceDir = pkg.applicationInfo.sourceDir;
11467                a.info.publicSourceDir = pkg.applicationInfo.publicSourceDir;
11468                a.info.splitNames = pkg.splitNames;
11469                a.info.splitSourceDirs = pkg.applicationInfo.splitSourceDirs;
11470                a.info.splitPublicSourceDirs = pkg.applicationInfo.splitPublicSourceDirs;
11471                a.info.splitDependencies = pkg.applicationInfo.splitDependencies;
11472                a.info.dataDir = pkg.applicationInfo.dataDir;
11473                a.info.deviceProtectedDataDir = pkg.applicationInfo.deviceProtectedDataDir;
11474                a.info.credentialProtectedDataDir = pkg.applicationInfo.credentialProtectedDataDir;
11475                a.info.nativeLibraryDir = pkg.applicationInfo.nativeLibraryDir;
11476                a.info.secondaryNativeLibraryDir = pkg.applicationInfo.secondaryNativeLibraryDir;
11477                mInstrumentation.put(a.getComponentName(), a);
11478                if (chatty) {
11479                    if (r == null) {
11480                        r = new StringBuilder(256);
11481                    } else {
11482                        r.append(' ');
11483                    }
11484                    r.append(a.info.name);
11485                }
11486            }
11487            if (r != null) {
11488                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Instrumentation: " + r);
11489            }
11490
11491            if (pkg.protectedBroadcasts != null) {
11492                N = pkg.protectedBroadcasts.size();
11493                synchronized (mProtectedBroadcasts) {
11494                    for (i = 0; i < N; i++) {
11495                        mProtectedBroadcasts.add(pkg.protectedBroadcasts.get(i));
11496                    }
11497                }
11498            }
11499        }
11500
11501        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
11502    }
11503
11504    /**
11505     * Derive the ABI of a non-system package located at {@code scanFile}. This information
11506     * is derived purely on the basis of the contents of {@code scanFile} and
11507     * {@code cpuAbiOverride}.
11508     *
11509     * If {@code extractLibs} is true, native libraries are extracted from the app if required.
11510     */
11511    private static void derivePackageAbi(PackageParser.Package pkg, File scanFile,
11512                                 String cpuAbiOverride, boolean extractLibs,
11513                                 File appLib32InstallDir)
11514            throws PackageManagerException {
11515        // Give ourselves some initial paths; we'll come back for another
11516        // pass once we've determined ABI below.
11517        setNativeLibraryPaths(pkg, appLib32InstallDir);
11518
11519        // We would never need to extract libs for forward-locked and external packages,
11520        // since the container service will do it for us. We shouldn't attempt to
11521        // extract libs from system app when it was not updated.
11522        if (pkg.isForwardLocked() || pkg.applicationInfo.isExternalAsec() ||
11523                (isSystemApp(pkg) && !pkg.isUpdatedSystemApp())) {
11524            extractLibs = false;
11525        }
11526
11527        final String nativeLibraryRootStr = pkg.applicationInfo.nativeLibraryRootDir;
11528        final boolean useIsaSpecificSubdirs = pkg.applicationInfo.nativeLibraryRootRequiresIsa;
11529
11530        NativeLibraryHelper.Handle handle = null;
11531        try {
11532            handle = NativeLibraryHelper.Handle.create(pkg);
11533            // TODO(multiArch): This can be null for apps that didn't go through the
11534            // usual installation process. We can calculate it again, like we
11535            // do during install time.
11536            //
11537            // TODO(multiArch): Why do we need to rescan ASEC apps again ? It seems totally
11538            // unnecessary.
11539            final File nativeLibraryRoot = new File(nativeLibraryRootStr);
11540
11541            // Null out the abis so that they can be recalculated.
11542            pkg.applicationInfo.primaryCpuAbi = null;
11543            pkg.applicationInfo.secondaryCpuAbi = null;
11544            if (isMultiArch(pkg.applicationInfo)) {
11545                // Warn if we've set an abiOverride for multi-lib packages..
11546                // By definition, we need to copy both 32 and 64 bit libraries for
11547                // such packages.
11548                if (pkg.cpuAbiOverride != null
11549                        && !NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(pkg.cpuAbiOverride)) {
11550                    Slog.w(TAG, "Ignoring abiOverride for multi arch application.");
11551                }
11552
11553                int abi32 = PackageManager.NO_NATIVE_LIBRARIES;
11554                int abi64 = PackageManager.NO_NATIVE_LIBRARIES;
11555                if (Build.SUPPORTED_32_BIT_ABIS.length > 0) {
11556                    if (extractLibs) {
11557                        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyNativeBinaries");
11558                        abi32 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
11559                                nativeLibraryRoot, Build.SUPPORTED_32_BIT_ABIS,
11560                                useIsaSpecificSubdirs);
11561                    } else {
11562                        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "findSupportedAbi");
11563                        abi32 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_32_BIT_ABIS);
11564                    }
11565                    Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
11566                }
11567
11568                // Shared library native code should be in the APK zip aligned
11569                if (abi32 >= 0 && pkg.isLibrary() && extractLibs) {
11570                    throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR,
11571                            "Shared library native lib extraction not supported");
11572                }
11573
11574                maybeThrowExceptionForMultiArchCopy(
11575                        "Error unpackaging 32 bit native libs for multiarch app.", abi32);
11576
11577                if (Build.SUPPORTED_64_BIT_ABIS.length > 0) {
11578                    if (extractLibs) {
11579                        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyNativeBinaries");
11580                        abi64 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
11581                                nativeLibraryRoot, Build.SUPPORTED_64_BIT_ABIS,
11582                                useIsaSpecificSubdirs);
11583                    } else {
11584                        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "findSupportedAbi");
11585                        abi64 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_64_BIT_ABIS);
11586                    }
11587                    Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
11588                }
11589
11590                maybeThrowExceptionForMultiArchCopy(
11591                        "Error unpackaging 64 bit native libs for multiarch app.", abi64);
11592
11593                if (abi64 >= 0) {
11594                    // Shared library native libs should be in the APK zip aligned
11595                    if (extractLibs && pkg.isLibrary()) {
11596                        throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR,
11597                                "Shared library native lib extraction not supported");
11598                    }
11599                    pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[abi64];
11600                }
11601
11602                if (abi32 >= 0) {
11603                    final String abi = Build.SUPPORTED_32_BIT_ABIS[abi32];
11604                    if (abi64 >= 0) {
11605                        if (pkg.use32bitAbi) {
11606                            pkg.applicationInfo.secondaryCpuAbi = pkg.applicationInfo.primaryCpuAbi;
11607                            pkg.applicationInfo.primaryCpuAbi = abi;
11608                        } else {
11609                            pkg.applicationInfo.secondaryCpuAbi = abi;
11610                        }
11611                    } else {
11612                        pkg.applicationInfo.primaryCpuAbi = abi;
11613                    }
11614                }
11615            } else {
11616                String[] abiList = (cpuAbiOverride != null) ?
11617                        new String[] { cpuAbiOverride } : Build.SUPPORTED_ABIS;
11618
11619                // Enable gross and lame hacks for apps that are built with old
11620                // SDK tools. We must scan their APKs for renderscript bitcode and
11621                // not launch them if it's present. Don't bother checking on devices
11622                // that don't have 64 bit support.
11623                boolean needsRenderScriptOverride = false;
11624                if (Build.SUPPORTED_64_BIT_ABIS.length > 0 && cpuAbiOverride == null &&
11625                        NativeLibraryHelper.hasRenderscriptBitcode(handle)) {
11626                    abiList = Build.SUPPORTED_32_BIT_ABIS;
11627                    needsRenderScriptOverride = true;
11628                }
11629
11630                final int copyRet;
11631                if (extractLibs) {
11632                    Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyNativeBinaries");
11633                    copyRet = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
11634                            nativeLibraryRoot, abiList, useIsaSpecificSubdirs);
11635                } else {
11636                    Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "findSupportedAbi");
11637                    copyRet = NativeLibraryHelper.findSupportedAbi(handle, abiList);
11638                }
11639                Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
11640
11641                if (copyRet < 0 && copyRet != PackageManager.NO_NATIVE_LIBRARIES) {
11642                    throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR,
11643                            "Error unpackaging native libs for app, errorCode=" + copyRet);
11644                }
11645
11646                if (copyRet >= 0) {
11647                    // Shared libraries that have native libs must be multi-architecture
11648                    if (pkg.isLibrary()) {
11649                        throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR,
11650                                "Shared library with native libs must be multiarch");
11651                    }
11652                    pkg.applicationInfo.primaryCpuAbi = abiList[copyRet];
11653                } else if (copyRet == PackageManager.NO_NATIVE_LIBRARIES && cpuAbiOverride != null) {
11654                    pkg.applicationInfo.primaryCpuAbi = cpuAbiOverride;
11655                } else if (needsRenderScriptOverride) {
11656                    pkg.applicationInfo.primaryCpuAbi = abiList[0];
11657                }
11658            }
11659        } catch (IOException ioe) {
11660            Slog.e(TAG, "Unable to get canonical file " + ioe.toString());
11661        } finally {
11662            IoUtils.closeQuietly(handle);
11663        }
11664
11665        // Now that we've calculated the ABIs and determined if it's an internal app,
11666        // we will go ahead and populate the nativeLibraryPath.
11667        setNativeLibraryPaths(pkg, appLib32InstallDir);
11668    }
11669
11670    /**
11671     * Adjusts ABIs for a set of packages belonging to a shared user so that they all match.
11672     * i.e, so that all packages can be run inside a single process if required.
11673     *
11674     * Optionally, callers can pass in a parsed package via {@code newPackage} in which case
11675     * this function will either try and make the ABI for all packages in {@code packagesForUser}
11676     * match {@code scannedPackage} or will update the ABI of {@code scannedPackage} to match
11677     * the ABI selected for {@code packagesForUser}. This variant is used when installing or
11678     * updating a package that belongs to a shared user.
11679     *
11680     * NOTE: We currently only match for the primary CPU abi string. Matching the secondary
11681     * adds unnecessary complexity.
11682     */
11683    private void adjustCpuAbisForSharedUserLPw(Set<PackageSetting> packagesForUser,
11684            PackageParser.Package scannedPackage) {
11685        String requiredInstructionSet = null;
11686        if (scannedPackage != null && scannedPackage.applicationInfo.primaryCpuAbi != null) {
11687            requiredInstructionSet = VMRuntime.getInstructionSet(
11688                     scannedPackage.applicationInfo.primaryCpuAbi);
11689        }
11690
11691        PackageSetting requirer = null;
11692        for (PackageSetting ps : packagesForUser) {
11693            // If packagesForUser contains scannedPackage, we skip it. This will happen
11694            // when scannedPackage is an update of an existing package. Without this check,
11695            // we will never be able to change the ABI of any package belonging to a shared
11696            // user, even if it's compatible with other packages.
11697            if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) {
11698                if (ps.primaryCpuAbiString == null) {
11699                    continue;
11700                }
11701
11702                final String instructionSet = VMRuntime.getInstructionSet(ps.primaryCpuAbiString);
11703                if (requiredInstructionSet != null && !instructionSet.equals(requiredInstructionSet)) {
11704                    // We have a mismatch between instruction sets (say arm vs arm64) warn about
11705                    // this but there's not much we can do.
11706                    String errorMessage = "Instruction set mismatch, "
11707                            + ((requirer == null) ? "[caller]" : requirer)
11708                            + " requires " + requiredInstructionSet + " whereas " + ps
11709                            + " requires " + instructionSet;
11710                    Slog.w(TAG, errorMessage);
11711                }
11712
11713                if (requiredInstructionSet == null) {
11714                    requiredInstructionSet = instructionSet;
11715                    requirer = ps;
11716                }
11717            }
11718        }
11719
11720        if (requiredInstructionSet != null) {
11721            String adjustedAbi;
11722            if (requirer != null) {
11723                // requirer != null implies that either scannedPackage was null or that scannedPackage
11724                // did not require an ABI, in which case we have to adjust scannedPackage to match
11725                // the ABI of the set (which is the same as requirer's ABI)
11726                adjustedAbi = requirer.primaryCpuAbiString;
11727                if (scannedPackage != null) {
11728                    scannedPackage.applicationInfo.primaryCpuAbi = adjustedAbi;
11729                }
11730            } else {
11731                // requirer == null implies that we're updating all ABIs in the set to
11732                // match scannedPackage.
11733                adjustedAbi =  scannedPackage.applicationInfo.primaryCpuAbi;
11734            }
11735
11736            for (PackageSetting ps : packagesForUser) {
11737                if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) {
11738                    if (ps.primaryCpuAbiString != null) {
11739                        continue;
11740                    }
11741
11742                    ps.primaryCpuAbiString = adjustedAbi;
11743                    if (ps.pkg != null && ps.pkg.applicationInfo != null &&
11744                            !TextUtils.equals(adjustedAbi, ps.pkg.applicationInfo.primaryCpuAbi)) {
11745                        ps.pkg.applicationInfo.primaryCpuAbi = adjustedAbi;
11746                        if (DEBUG_ABI_SELECTION) {
11747                            Slog.i(TAG, "Adjusting ABI for " + ps.name + " to " + adjustedAbi
11748                                    + " (requirer="
11749                                    + (requirer != null ? requirer.pkg : "null")
11750                                    + ", scannedPackage="
11751                                    + (scannedPackage != null ? scannedPackage : "null")
11752                                    + ")");
11753                        }
11754                        try {
11755                            mInstaller.rmdex(ps.codePathString,
11756                                    getDexCodeInstructionSet(getPreferredInstructionSet()));
11757                        } catch (InstallerException ignored) {
11758                        }
11759                    }
11760                }
11761            }
11762        }
11763    }
11764
11765    private void setUpCustomResolverActivity(PackageParser.Package pkg) {
11766        synchronized (mPackages) {
11767            mResolverReplaced = true;
11768            // Set up information for custom user intent resolution activity.
11769            mResolveActivity.applicationInfo = pkg.applicationInfo;
11770            mResolveActivity.name = mCustomResolverComponentName.getClassName();
11771            mResolveActivity.packageName = pkg.applicationInfo.packageName;
11772            mResolveActivity.processName = pkg.applicationInfo.packageName;
11773            mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
11774            mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS |
11775                    ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS;
11776            mResolveActivity.theme = 0;
11777            mResolveActivity.exported = true;
11778            mResolveActivity.enabled = true;
11779            mResolveInfo.activityInfo = mResolveActivity;
11780            mResolveInfo.priority = 0;
11781            mResolveInfo.preferredOrder = 0;
11782            mResolveInfo.match = 0;
11783            mResolveComponentName = mCustomResolverComponentName;
11784            Slog.i(TAG, "Replacing default ResolverActivity with custom activity: " +
11785                    mResolveComponentName);
11786        }
11787    }
11788
11789    private void setUpInstantAppInstallerActivityLP(ActivityInfo installerActivity) {
11790        if (installerActivity == null) {
11791            if (DEBUG_EPHEMERAL) {
11792                Slog.d(TAG, "Clear ephemeral installer activity");
11793            }
11794            mInstantAppInstallerActivity = null;
11795            return;
11796        }
11797
11798        if (DEBUG_EPHEMERAL) {
11799            Slog.d(TAG, "Set ephemeral installer activity: "
11800                    + installerActivity.getComponentName());
11801        }
11802        // Set up information for ephemeral installer activity
11803        mInstantAppInstallerActivity = installerActivity;
11804        mInstantAppInstallerActivity.flags |= ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS
11805                | ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS;
11806        mInstantAppInstallerActivity.exported = true;
11807        mInstantAppInstallerActivity.enabled = true;
11808        mInstantAppInstallerInfo.activityInfo = mInstantAppInstallerActivity;
11809        mInstantAppInstallerInfo.priority = 0;
11810        mInstantAppInstallerInfo.preferredOrder = 1;
11811        mInstantAppInstallerInfo.isDefault = true;
11812        mInstantAppInstallerInfo.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART
11813                | IntentFilter.MATCH_ADJUSTMENT_NORMAL;
11814    }
11815
11816    private static String calculateBundledApkRoot(final String codePathString) {
11817        final File codePath = new File(codePathString);
11818        final File codeRoot;
11819        if (FileUtils.contains(Environment.getRootDirectory(), codePath)) {
11820            codeRoot = Environment.getRootDirectory();
11821        } else if (FileUtils.contains(Environment.getOemDirectory(), codePath)) {
11822            codeRoot = Environment.getOemDirectory();
11823        } else if (FileUtils.contains(Environment.getVendorDirectory(), codePath)) {
11824            codeRoot = Environment.getVendorDirectory();
11825        } else {
11826            // Unrecognized code path; take its top real segment as the apk root:
11827            // e.g. /something/app/blah.apk => /something
11828            try {
11829                File f = codePath.getCanonicalFile();
11830                File parent = f.getParentFile();    // non-null because codePath is a file
11831                File tmp;
11832                while ((tmp = parent.getParentFile()) != null) {
11833                    f = parent;
11834                    parent = tmp;
11835                }
11836                codeRoot = f;
11837                Slog.w(TAG, "Unrecognized code path "
11838                        + codePath + " - using " + codeRoot);
11839            } catch (IOException e) {
11840                // Can't canonicalize the code path -- shenanigans?
11841                Slog.w(TAG, "Can't canonicalize code path " + codePath);
11842                return Environment.getRootDirectory().getPath();
11843            }
11844        }
11845        return codeRoot.getPath();
11846    }
11847
11848    /**
11849     * Derive and set the location of native libraries for the given package,
11850     * which varies depending on where and how the package was installed.
11851     */
11852    private static void setNativeLibraryPaths(PackageParser.Package pkg, File appLib32InstallDir) {
11853        final ApplicationInfo info = pkg.applicationInfo;
11854        final String codePath = pkg.codePath;
11855        final File codeFile = new File(codePath);
11856        final boolean bundledApp = info.isSystemApp() && !info.isUpdatedSystemApp();
11857        final boolean asecApp = info.isForwardLocked() || info.isExternalAsec();
11858
11859        info.nativeLibraryRootDir = null;
11860        info.nativeLibraryRootRequiresIsa = false;
11861        info.nativeLibraryDir = null;
11862        info.secondaryNativeLibraryDir = null;
11863
11864        if (isApkFile(codeFile)) {
11865            // Monolithic install
11866            if (bundledApp) {
11867                // If "/system/lib64/apkname" exists, assume that is the per-package
11868                // native library directory to use; otherwise use "/system/lib/apkname".
11869                final String apkRoot = calculateBundledApkRoot(info.sourceDir);
11870                final boolean is64Bit = VMRuntime.is64BitInstructionSet(
11871                        getPrimaryInstructionSet(info));
11872
11873                // This is a bundled system app so choose the path based on the ABI.
11874                // if it's a 64 bit abi, use lib64 otherwise use lib32. Note that this
11875                // is just the default path.
11876                final String apkName = deriveCodePathName(codePath);
11877                final String libDir = is64Bit ? LIB64_DIR_NAME : LIB_DIR_NAME;
11878                info.nativeLibraryRootDir = Environment.buildPath(new File(apkRoot), libDir,
11879                        apkName).getAbsolutePath();
11880
11881                if (info.secondaryCpuAbi != null) {
11882                    final String secondaryLibDir = is64Bit ? LIB_DIR_NAME : LIB64_DIR_NAME;
11883                    info.secondaryNativeLibraryDir = Environment.buildPath(new File(apkRoot),
11884                            secondaryLibDir, apkName).getAbsolutePath();
11885                }
11886            } else if (asecApp) {
11887                info.nativeLibraryRootDir = new File(codeFile.getParentFile(), LIB_DIR_NAME)
11888                        .getAbsolutePath();
11889            } else {
11890                final String apkName = deriveCodePathName(codePath);
11891                info.nativeLibraryRootDir = new File(appLib32InstallDir, apkName)
11892                        .getAbsolutePath();
11893            }
11894
11895            info.nativeLibraryRootRequiresIsa = false;
11896            info.nativeLibraryDir = info.nativeLibraryRootDir;
11897        } else {
11898            // Cluster install
11899            info.nativeLibraryRootDir = new File(codeFile, LIB_DIR_NAME).getAbsolutePath();
11900            info.nativeLibraryRootRequiresIsa = true;
11901
11902            info.nativeLibraryDir = new File(info.nativeLibraryRootDir,
11903                    getPrimaryInstructionSet(info)).getAbsolutePath();
11904
11905            if (info.secondaryCpuAbi != null) {
11906                info.secondaryNativeLibraryDir = new File(info.nativeLibraryRootDir,
11907                        VMRuntime.getInstructionSet(info.secondaryCpuAbi)).getAbsolutePath();
11908            }
11909        }
11910    }
11911
11912    /**
11913     * Calculate the abis and roots for a bundled app. These can uniquely
11914     * be determined from the contents of the system partition, i.e whether
11915     * it contains 64 or 32 bit shared libraries etc. We do not validate any
11916     * of this information, and instead assume that the system was built
11917     * sensibly.
11918     */
11919    private static void setBundledAppAbisAndRoots(PackageParser.Package pkg,
11920                                           PackageSetting pkgSetting) {
11921        final String apkName = deriveCodePathName(pkg.applicationInfo.getCodePath());
11922
11923        // If "/system/lib64/apkname" exists, assume that is the per-package
11924        // native library directory to use; otherwise use "/system/lib/apkname".
11925        final String apkRoot = calculateBundledApkRoot(pkg.applicationInfo.sourceDir);
11926        setBundledAppAbi(pkg, apkRoot, apkName);
11927        // pkgSetting might be null during rescan following uninstall of updates
11928        // to a bundled app, so accommodate that possibility.  The settings in
11929        // that case will be established later from the parsed package.
11930        //
11931        // If the settings aren't null, sync them up with what we've just derived.
11932        // note that apkRoot isn't stored in the package settings.
11933        if (pkgSetting != null) {
11934            pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi;
11935            pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi;
11936        }
11937    }
11938
11939    /**
11940     * Deduces the ABI of a bundled app and sets the relevant fields on the
11941     * parsed pkg object.
11942     *
11943     * @param apkRoot the root of the installed apk, something like {@code /system} or {@code /oem}
11944     *        under which system libraries are installed.
11945     * @param apkName the name of the installed package.
11946     */
11947    private static void setBundledAppAbi(PackageParser.Package pkg, String apkRoot, String apkName) {
11948        final File codeFile = new File(pkg.codePath);
11949
11950        final boolean has64BitLibs;
11951        final boolean has32BitLibs;
11952        if (isApkFile(codeFile)) {
11953            // Monolithic install
11954            has64BitLibs = (new File(apkRoot, new File(LIB64_DIR_NAME, apkName).getPath())).exists();
11955            has32BitLibs = (new File(apkRoot, new File(LIB_DIR_NAME, apkName).getPath())).exists();
11956        } else {
11957            // Cluster install
11958            final File rootDir = new File(codeFile, LIB_DIR_NAME);
11959            if (!ArrayUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS)
11960                    && !TextUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS[0])) {
11961                final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_64_BIT_ABIS[0]);
11962                has64BitLibs = (new File(rootDir, isa)).exists();
11963            } else {
11964                has64BitLibs = false;
11965            }
11966            if (!ArrayUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS)
11967                    && !TextUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS[0])) {
11968                final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_32_BIT_ABIS[0]);
11969                has32BitLibs = (new File(rootDir, isa)).exists();
11970            } else {
11971                has32BitLibs = false;
11972            }
11973        }
11974
11975        if (has64BitLibs && !has32BitLibs) {
11976            // The package has 64 bit libs, but not 32 bit libs. Its primary
11977            // ABI should be 64 bit. We can safely assume here that the bundled
11978            // native libraries correspond to the most preferred ABI in the list.
11979
11980            pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
11981            pkg.applicationInfo.secondaryCpuAbi = null;
11982        } else if (has32BitLibs && !has64BitLibs) {
11983            // The package has 32 bit libs but not 64 bit libs. Its primary
11984            // ABI should be 32 bit.
11985
11986            pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
11987            pkg.applicationInfo.secondaryCpuAbi = null;
11988        } else if (has32BitLibs && has64BitLibs) {
11989            // The application has both 64 and 32 bit bundled libraries. We check
11990            // here that the app declares multiArch support, and warn if it doesn't.
11991            //
11992            // We will be lenient here and record both ABIs. The primary will be the
11993            // ABI that's higher on the list, i.e, a device that's configured to prefer
11994            // 64 bit apps will see a 64 bit primary ABI,
11995
11996            if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_MULTIARCH) == 0) {
11997                Slog.e(TAG, "Package " + pkg + " has multiple bundled libs, but is not multiarch.");
11998            }
11999
12000            if (VMRuntime.is64BitInstructionSet(getPreferredInstructionSet())) {
12001                pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
12002                pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
12003            } else {
12004                pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
12005                pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
12006            }
12007        } else {
12008            pkg.applicationInfo.primaryCpuAbi = null;
12009            pkg.applicationInfo.secondaryCpuAbi = null;
12010        }
12011    }
12012
12013    private void killApplication(String pkgName, int appId, String reason) {
12014        killApplication(pkgName, appId, UserHandle.USER_ALL, reason);
12015    }
12016
12017    private void killApplication(String pkgName, int appId, int userId, String reason) {
12018        // Request the ActivityManager to kill the process(only for existing packages)
12019        // so that we do not end up in a confused state while the user is still using the older
12020        // version of the application while the new one gets installed.
12021        final long token = Binder.clearCallingIdentity();
12022        try {
12023            IActivityManager am = ActivityManager.getService();
12024            if (am != null) {
12025                try {
12026                    am.killApplication(pkgName, appId, userId, reason);
12027                } catch (RemoteException e) {
12028                }
12029            }
12030        } finally {
12031            Binder.restoreCallingIdentity(token);
12032        }
12033    }
12034
12035    private void removePackageLI(PackageParser.Package pkg, boolean chatty) {
12036        // Remove the parent package setting
12037        PackageSetting ps = (PackageSetting) pkg.mExtras;
12038        if (ps != null) {
12039            removePackageLI(ps, chatty);
12040        }
12041        // Remove the child package setting
12042        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
12043        for (int i = 0; i < childCount; i++) {
12044            PackageParser.Package childPkg = pkg.childPackages.get(i);
12045            ps = (PackageSetting) childPkg.mExtras;
12046            if (ps != null) {
12047                removePackageLI(ps, chatty);
12048            }
12049        }
12050    }
12051
12052    void removePackageLI(PackageSetting ps, boolean chatty) {
12053        if (DEBUG_INSTALL) {
12054            if (chatty)
12055                Log.d(TAG, "Removing package " + ps.name);
12056        }
12057
12058        // writer
12059        synchronized (mPackages) {
12060            mPackages.remove(ps.name);
12061            final PackageParser.Package pkg = ps.pkg;
12062            if (pkg != null) {
12063                cleanPackageDataStructuresLILPw(pkg, chatty);
12064            }
12065        }
12066    }
12067
12068    void removeInstalledPackageLI(PackageParser.Package pkg, boolean chatty) {
12069        if (DEBUG_INSTALL) {
12070            if (chatty)
12071                Log.d(TAG, "Removing package " + pkg.applicationInfo.packageName);
12072        }
12073
12074        // writer
12075        synchronized (mPackages) {
12076            // Remove the parent package
12077            mPackages.remove(pkg.applicationInfo.packageName);
12078            cleanPackageDataStructuresLILPw(pkg, chatty);
12079
12080            // Remove the child packages
12081            final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
12082            for (int i = 0; i < childCount; i++) {
12083                PackageParser.Package childPkg = pkg.childPackages.get(i);
12084                mPackages.remove(childPkg.applicationInfo.packageName);
12085                cleanPackageDataStructuresLILPw(childPkg, chatty);
12086            }
12087        }
12088    }
12089
12090    void cleanPackageDataStructuresLILPw(PackageParser.Package pkg, boolean chatty) {
12091        int N = pkg.providers.size();
12092        StringBuilder r = null;
12093        int i;
12094        for (i=0; i<N; i++) {
12095            PackageParser.Provider p = pkg.providers.get(i);
12096            mProviders.removeProvider(p);
12097            if (p.info.authority == null) {
12098
12099                /* There was another ContentProvider with this authority when
12100                 * this app was installed so this authority is null,
12101                 * Ignore it as we don't have to unregister the provider.
12102                 */
12103                continue;
12104            }
12105            String names[] = p.info.authority.split(";");
12106            for (int j = 0; j < names.length; j++) {
12107                if (mProvidersByAuthority.get(names[j]) == p) {
12108                    mProvidersByAuthority.remove(names[j]);
12109                    if (DEBUG_REMOVE) {
12110                        if (chatty)
12111                            Log.d(TAG, "Unregistered content provider: " + names[j]
12112                                    + ", className = " + p.info.name + ", isSyncable = "
12113                                    + p.info.isSyncable);
12114                    }
12115                }
12116            }
12117            if (DEBUG_REMOVE && chatty) {
12118                if (r == null) {
12119                    r = new StringBuilder(256);
12120                } else {
12121                    r.append(' ');
12122                }
12123                r.append(p.info.name);
12124            }
12125        }
12126        if (r != null) {
12127            if (DEBUG_REMOVE) Log.d(TAG, "  Providers: " + r);
12128        }
12129
12130        N = pkg.services.size();
12131        r = null;
12132        for (i=0; i<N; i++) {
12133            PackageParser.Service s = pkg.services.get(i);
12134            mServices.removeService(s);
12135            if (chatty) {
12136                if (r == null) {
12137                    r = new StringBuilder(256);
12138                } else {
12139                    r.append(' ');
12140                }
12141                r.append(s.info.name);
12142            }
12143        }
12144        if (r != null) {
12145            if (DEBUG_REMOVE) Log.d(TAG, "  Services: " + r);
12146        }
12147
12148        N = pkg.receivers.size();
12149        r = null;
12150        for (i=0; i<N; i++) {
12151            PackageParser.Activity a = pkg.receivers.get(i);
12152            mReceivers.removeActivity(a, "receiver");
12153            if (DEBUG_REMOVE && chatty) {
12154                if (r == null) {
12155                    r = new StringBuilder(256);
12156                } else {
12157                    r.append(' ');
12158                }
12159                r.append(a.info.name);
12160            }
12161        }
12162        if (r != null) {
12163            if (DEBUG_REMOVE) Log.d(TAG, "  Receivers: " + r);
12164        }
12165
12166        N = pkg.activities.size();
12167        r = null;
12168        for (i=0; i<N; i++) {
12169            PackageParser.Activity a = pkg.activities.get(i);
12170            mActivities.removeActivity(a, "activity");
12171            if (DEBUG_REMOVE && chatty) {
12172                if (r == null) {
12173                    r = new StringBuilder(256);
12174                } else {
12175                    r.append(' ');
12176                }
12177                r.append(a.info.name);
12178            }
12179        }
12180        if (r != null) {
12181            if (DEBUG_REMOVE) Log.d(TAG, "  Activities: " + r);
12182        }
12183
12184        N = pkg.permissions.size();
12185        r = null;
12186        for (i=0; i<N; i++) {
12187            PackageParser.Permission p = pkg.permissions.get(i);
12188            BasePermission bp = mSettings.mPermissions.get(p.info.name);
12189            if (bp == null) {
12190                bp = mSettings.mPermissionTrees.get(p.info.name);
12191            }
12192            if (bp != null && bp.perm == p) {
12193                bp.perm = null;
12194                if (DEBUG_REMOVE && chatty) {
12195                    if (r == null) {
12196                        r = new StringBuilder(256);
12197                    } else {
12198                        r.append(' ');
12199                    }
12200                    r.append(p.info.name);
12201                }
12202            }
12203            if ((p.info.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
12204                ArraySet<String> appOpPkgs = mAppOpPermissionPackages.get(p.info.name);
12205                if (appOpPkgs != null) {
12206                    appOpPkgs.remove(pkg.packageName);
12207                }
12208            }
12209        }
12210        if (r != null) {
12211            if (DEBUG_REMOVE) Log.d(TAG, "  Permissions: " + r);
12212        }
12213
12214        N = pkg.requestedPermissions.size();
12215        r = null;
12216        for (i=0; i<N; i++) {
12217            String perm = pkg.requestedPermissions.get(i);
12218            BasePermission bp = mSettings.mPermissions.get(perm);
12219            if (bp != null && (bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
12220                ArraySet<String> appOpPkgs = mAppOpPermissionPackages.get(perm);
12221                if (appOpPkgs != null) {
12222                    appOpPkgs.remove(pkg.packageName);
12223                    if (appOpPkgs.isEmpty()) {
12224                        mAppOpPermissionPackages.remove(perm);
12225                    }
12226                }
12227            }
12228        }
12229        if (r != null) {
12230            if (DEBUG_REMOVE) Log.d(TAG, "  Permissions: " + r);
12231        }
12232
12233        N = pkg.instrumentation.size();
12234        r = null;
12235        for (i=0; i<N; i++) {
12236            PackageParser.Instrumentation a = pkg.instrumentation.get(i);
12237            mInstrumentation.remove(a.getComponentName());
12238            if (DEBUG_REMOVE && chatty) {
12239                if (r == null) {
12240                    r = new StringBuilder(256);
12241                } else {
12242                    r.append(' ');
12243                }
12244                r.append(a.info.name);
12245            }
12246        }
12247        if (r != null) {
12248            if (DEBUG_REMOVE) Log.d(TAG, "  Instrumentation: " + r);
12249        }
12250
12251        r = null;
12252        if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) {
12253            // Only system apps can hold shared libraries.
12254            if (pkg.libraryNames != null) {
12255                for (i = 0; i < pkg.libraryNames.size(); i++) {
12256                    String name = pkg.libraryNames.get(i);
12257                    if (removeSharedLibraryLPw(name, 0)) {
12258                        if (DEBUG_REMOVE && chatty) {
12259                            if (r == null) {
12260                                r = new StringBuilder(256);
12261                            } else {
12262                                r.append(' ');
12263                            }
12264                            r.append(name);
12265                        }
12266                    }
12267                }
12268            }
12269        }
12270
12271        r = null;
12272
12273        // Any package can hold static shared libraries.
12274        if (pkg.staticSharedLibName != null) {
12275            if (removeSharedLibraryLPw(pkg.staticSharedLibName, pkg.staticSharedLibVersion)) {
12276                if (DEBUG_REMOVE && chatty) {
12277                    if (r == null) {
12278                        r = new StringBuilder(256);
12279                    } else {
12280                        r.append(' ');
12281                    }
12282                    r.append(pkg.staticSharedLibName);
12283                }
12284            }
12285        }
12286
12287        if (r != null) {
12288            if (DEBUG_REMOVE) Log.d(TAG, "  Libraries: " + r);
12289        }
12290    }
12291
12292    private static boolean hasPermission(PackageParser.Package pkgInfo, String perm) {
12293        for (int i=pkgInfo.permissions.size()-1; i>=0; i--) {
12294            if (pkgInfo.permissions.get(i).info.name.equals(perm)) {
12295                return true;
12296            }
12297        }
12298        return false;
12299    }
12300
12301    static final int UPDATE_PERMISSIONS_ALL = 1<<0;
12302    static final int UPDATE_PERMISSIONS_REPLACE_PKG = 1<<1;
12303    static final int UPDATE_PERMISSIONS_REPLACE_ALL = 1<<2;
12304
12305    private void updatePermissionsLPw(PackageParser.Package pkg, int flags) {
12306        // Update the parent permissions
12307        updatePermissionsLPw(pkg.packageName, pkg, flags);
12308        // Update the child permissions
12309        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
12310        for (int i = 0; i < childCount; i++) {
12311            PackageParser.Package childPkg = pkg.childPackages.get(i);
12312            updatePermissionsLPw(childPkg.packageName, childPkg, flags);
12313        }
12314    }
12315
12316    private void updatePermissionsLPw(String changingPkg, PackageParser.Package pkgInfo,
12317            int flags) {
12318        final String volumeUuid = (pkgInfo != null) ? getVolumeUuidForPackage(pkgInfo) : null;
12319        updatePermissionsLPw(changingPkg, pkgInfo, volumeUuid, flags);
12320    }
12321
12322    private void updatePermissionsLPw(String changingPkg,
12323            PackageParser.Package pkgInfo, String replaceVolumeUuid, int flags) {
12324        // Make sure there are no dangling permission trees.
12325        Iterator<BasePermission> it = mSettings.mPermissionTrees.values().iterator();
12326        while (it.hasNext()) {
12327            final BasePermission bp = it.next();
12328            if (bp.packageSetting == null) {
12329                // We may not yet have parsed the package, so just see if
12330                // we still know about its settings.
12331                bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage);
12332            }
12333            if (bp.packageSetting == null) {
12334                Slog.w(TAG, "Removing dangling permission tree: " + bp.name
12335                        + " from package " + bp.sourcePackage);
12336                it.remove();
12337            } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) {
12338                if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) {
12339                    Slog.i(TAG, "Removing old permission tree: " + bp.name
12340                            + " from package " + bp.sourcePackage);
12341                    flags |= UPDATE_PERMISSIONS_ALL;
12342                    it.remove();
12343                }
12344            }
12345        }
12346
12347        // Make sure all dynamic permissions have been assigned to a package,
12348        // and make sure there are no dangling permissions.
12349        it = mSettings.mPermissions.values().iterator();
12350        while (it.hasNext()) {
12351            final BasePermission bp = it.next();
12352            if (bp.type == BasePermission.TYPE_DYNAMIC) {
12353                if (DEBUG_SETTINGS) Log.v(TAG, "Dynamic permission: name="
12354                        + bp.name + " pkg=" + bp.sourcePackage
12355                        + " info=" + bp.pendingInfo);
12356                if (bp.packageSetting == null && bp.pendingInfo != null) {
12357                    final BasePermission tree = findPermissionTreeLP(bp.name);
12358                    if (tree != null && tree.perm != null) {
12359                        bp.packageSetting = tree.packageSetting;
12360                        bp.perm = new PackageParser.Permission(tree.perm.owner,
12361                                new PermissionInfo(bp.pendingInfo));
12362                        bp.perm.info.packageName = tree.perm.info.packageName;
12363                        bp.perm.info.name = bp.name;
12364                        bp.uid = tree.uid;
12365                    }
12366                }
12367            }
12368            if (bp.packageSetting == null) {
12369                // We may not yet have parsed the package, so just see if
12370                // we still know about its settings.
12371                bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage);
12372            }
12373            if (bp.packageSetting == null) {
12374                Slog.w(TAG, "Removing dangling permission: " + bp.name
12375                        + " from package " + bp.sourcePackage);
12376                it.remove();
12377            } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) {
12378                if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) {
12379                    Slog.i(TAG, "Removing old permission: " + bp.name
12380                            + " from package " + bp.sourcePackage);
12381                    flags |= UPDATE_PERMISSIONS_ALL;
12382                    it.remove();
12383                }
12384            }
12385        }
12386
12387        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "grantPermissions");
12388        // Now update the permissions for all packages, in particular
12389        // replace the granted permissions of the system packages.
12390        if ((flags&UPDATE_PERMISSIONS_ALL) != 0) {
12391            for (PackageParser.Package pkg : mPackages.values()) {
12392                if (pkg != pkgInfo) {
12393                    // Only replace for packages on requested volume
12394                    final String volumeUuid = getVolumeUuidForPackage(pkg);
12395                    final boolean replace = ((flags & UPDATE_PERMISSIONS_REPLACE_ALL) != 0)
12396                            && Objects.equals(replaceVolumeUuid, volumeUuid);
12397                    grantPermissionsLPw(pkg, replace, changingPkg);
12398                }
12399            }
12400        }
12401
12402        if (pkgInfo != null) {
12403            // Only replace for packages on requested volume
12404            final String volumeUuid = getVolumeUuidForPackage(pkgInfo);
12405            final boolean replace = ((flags & UPDATE_PERMISSIONS_REPLACE_PKG) != 0)
12406                    && Objects.equals(replaceVolumeUuid, volumeUuid);
12407            grantPermissionsLPw(pkgInfo, replace, changingPkg);
12408        }
12409        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
12410    }
12411
12412    private void grantPermissionsLPw(PackageParser.Package pkg, boolean replace,
12413            String packageOfInterest) {
12414        // IMPORTANT: There are two types of permissions: install and runtime.
12415        // Install time permissions are granted when the app is installed to
12416        // all device users and users added in the future. Runtime permissions
12417        // are granted at runtime explicitly to specific users. Normal and signature
12418        // protected permissions are install time permissions. Dangerous permissions
12419        // are install permissions if the app's target SDK is Lollipop MR1 or older,
12420        // otherwise they are runtime permissions. This function does not manage
12421        // runtime permissions except for the case an app targeting Lollipop MR1
12422        // being upgraded to target a newer SDK, in which case dangerous permissions
12423        // are transformed from install time to runtime ones.
12424
12425        final PackageSetting ps = (PackageSetting) pkg.mExtras;
12426        if (ps == null) {
12427            return;
12428        }
12429
12430        PermissionsState permissionsState = ps.getPermissionsState();
12431        PermissionsState origPermissions = permissionsState;
12432
12433        final int[] currentUserIds = UserManagerService.getInstance().getUserIds();
12434
12435        boolean runtimePermissionsRevoked = false;
12436        int[] changedRuntimePermissionUserIds = EMPTY_INT_ARRAY;
12437
12438        boolean changedInstallPermission = false;
12439
12440        if (replace) {
12441            ps.installPermissionsFixed = false;
12442            if (!ps.isSharedUser()) {
12443                origPermissions = new PermissionsState(permissionsState);
12444                permissionsState.reset();
12445            } else {
12446                // We need to know only about runtime permission changes since the
12447                // calling code always writes the install permissions state but
12448                // the runtime ones are written only if changed. The only cases of
12449                // changed runtime permissions here are promotion of an install to
12450                // runtime and revocation of a runtime from a shared user.
12451                changedRuntimePermissionUserIds = revokeUnusedSharedUserPermissionsLPw(
12452                        ps.sharedUser, UserManagerService.getInstance().getUserIds());
12453                if (!ArrayUtils.isEmpty(changedRuntimePermissionUserIds)) {
12454                    runtimePermissionsRevoked = true;
12455                }
12456            }
12457        }
12458
12459        permissionsState.setGlobalGids(mGlobalGids);
12460
12461        final int N = pkg.requestedPermissions.size();
12462        for (int i=0; i<N; i++) {
12463            final String name = pkg.requestedPermissions.get(i);
12464            final BasePermission bp = mSettings.mPermissions.get(name);
12465            final boolean appSupportsRuntimePermissions = pkg.applicationInfo.targetSdkVersion
12466                    >= Build.VERSION_CODES.M;
12467
12468            if (DEBUG_INSTALL) {
12469                Log.i(TAG, "Package " + pkg.packageName + " checking " + name + ": " + bp);
12470            }
12471
12472            if (bp == null || bp.packageSetting == null) {
12473                if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) {
12474                    if (DEBUG_PERMISSIONS) {
12475                        Slog.i(TAG, "Unknown permission " + name
12476                                + " in package " + pkg.packageName);
12477                    }
12478                }
12479                continue;
12480            }
12481
12482
12483            // Limit ephemeral apps to ephemeral allowed permissions.
12484            if (pkg.applicationInfo.isInstantApp() && !bp.isInstant()) {
12485                if (DEBUG_PERMISSIONS) {
12486                    Log.i(TAG, "Denying non-ephemeral permission " + bp.name + " for package "
12487                            + pkg.packageName);
12488                }
12489                continue;
12490            }
12491
12492            if (bp.isRuntimeOnly() && !appSupportsRuntimePermissions) {
12493                if (DEBUG_PERMISSIONS) {
12494                    Log.i(TAG, "Denying runtime-only permission " + bp.name + " for package "
12495                            + pkg.packageName);
12496                }
12497                continue;
12498            }
12499
12500            final String perm = bp.name;
12501            boolean allowedSig = false;
12502            int grant = GRANT_DENIED;
12503
12504            // Keep track of app op permissions.
12505            if ((bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
12506                ArraySet<String> pkgs = mAppOpPermissionPackages.get(bp.name);
12507                if (pkgs == null) {
12508                    pkgs = new ArraySet<>();
12509                    mAppOpPermissionPackages.put(bp.name, pkgs);
12510                }
12511                pkgs.add(pkg.packageName);
12512            }
12513
12514            final int level = bp.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE;
12515            switch (level) {
12516                case PermissionInfo.PROTECTION_NORMAL: {
12517                    // For all apps normal permissions are install time ones.
12518                    grant = GRANT_INSTALL;
12519                } break;
12520
12521                case PermissionInfo.PROTECTION_DANGEROUS: {
12522                    // If a permission review is required for legacy apps we represent
12523                    // their permissions as always granted runtime ones since we need
12524                    // to keep the review required permission flag per user while an
12525                    // install permission's state is shared across all users.
12526                    if (!appSupportsRuntimePermissions && !mPermissionReviewRequired) {
12527                        // For legacy apps dangerous permissions are install time ones.
12528                        grant = GRANT_INSTALL;
12529                    } else if (origPermissions.hasInstallPermission(bp.name)) {
12530                        // For legacy apps that became modern, install becomes runtime.
12531                        grant = GRANT_UPGRADE;
12532                    } else if (mPromoteSystemApps
12533                            && isSystemApp(ps)
12534                            && mExistingSystemPackages.contains(ps.name)) {
12535                        // For legacy system apps, install becomes runtime.
12536                        // We cannot check hasInstallPermission() for system apps since those
12537                        // permissions were granted implicitly and not persisted pre-M.
12538                        grant = GRANT_UPGRADE;
12539                    } else {
12540                        // For modern apps keep runtime permissions unchanged.
12541                        grant = GRANT_RUNTIME;
12542                    }
12543                } break;
12544
12545                case PermissionInfo.PROTECTION_SIGNATURE: {
12546                    // For all apps signature permissions are install time ones.
12547                    allowedSig = grantSignaturePermission(perm, pkg, bp, origPermissions);
12548                    if (allowedSig) {
12549                        grant = GRANT_INSTALL;
12550                    }
12551                } break;
12552            }
12553
12554            if (DEBUG_PERMISSIONS) {
12555                Slog.i(TAG, "Granting permission " + perm + " to package " + pkg.packageName);
12556            }
12557
12558            if (grant != GRANT_DENIED) {
12559                if (!isSystemApp(ps) && ps.installPermissionsFixed) {
12560                    // If this is an existing, non-system package, then
12561                    // we can't add any new permissions to it.
12562                    if (!allowedSig && !origPermissions.hasInstallPermission(perm)) {
12563                        // Except...  if this is a permission that was added
12564                        // to the platform (note: need to only do this when
12565                        // updating the platform).
12566                        if (!isNewPlatformPermissionForPackage(perm, pkg)) {
12567                            grant = GRANT_DENIED;
12568                        }
12569                    }
12570                }
12571
12572                switch (grant) {
12573                    case GRANT_INSTALL: {
12574                        // Revoke this as runtime permission to handle the case of
12575                        // a runtime permission being downgraded to an install one.
12576                        // Also in permission review mode we keep dangerous permissions
12577                        // for legacy apps
12578                        for (int userId : UserManagerService.getInstance().getUserIds()) {
12579                            if (origPermissions.getRuntimePermissionState(
12580                                    bp.name, userId) != null) {
12581                                // Revoke the runtime permission and clear the flags.
12582                                origPermissions.revokeRuntimePermission(bp, userId);
12583                                origPermissions.updatePermissionFlags(bp, userId,
12584                                      PackageManager.MASK_PERMISSION_FLAGS, 0);
12585                                // If we revoked a permission permission, we have to write.
12586                                changedRuntimePermissionUserIds = ArrayUtils.appendInt(
12587                                        changedRuntimePermissionUserIds, userId);
12588                            }
12589                        }
12590                        // Grant an install permission.
12591                        if (permissionsState.grantInstallPermission(bp) !=
12592                                PermissionsState.PERMISSION_OPERATION_FAILURE) {
12593                            changedInstallPermission = true;
12594                        }
12595                    } break;
12596
12597                    case GRANT_RUNTIME: {
12598                        // Grant previously granted runtime permissions.
12599                        for (int userId : UserManagerService.getInstance().getUserIds()) {
12600                            PermissionState permissionState = origPermissions
12601                                    .getRuntimePermissionState(bp.name, userId);
12602                            int flags = permissionState != null
12603                                    ? permissionState.getFlags() : 0;
12604                            if (origPermissions.hasRuntimePermission(bp.name, userId)) {
12605                                // Don't propagate the permission in a permission review mode if
12606                                // the former was revoked, i.e. marked to not propagate on upgrade.
12607                                // Note that in a permission review mode install permissions are
12608                                // represented as constantly granted runtime ones since we need to
12609                                // keep a per user state associated with the permission. Also the
12610                                // revoke on upgrade flag is no longer applicable and is reset.
12611                                final boolean revokeOnUpgrade = (flags & PackageManager
12612                                        .FLAG_PERMISSION_REVOKE_ON_UPGRADE) != 0;
12613                                if (revokeOnUpgrade) {
12614                                    flags &= ~PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE;
12615                                    // Since we changed the flags, we have to write.
12616                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
12617                                            changedRuntimePermissionUserIds, userId);
12618                                }
12619                                if (!mPermissionReviewRequired || !revokeOnUpgrade) {
12620                                    if (permissionsState.grantRuntimePermission(bp, userId) ==
12621                                            PermissionsState.PERMISSION_OPERATION_FAILURE) {
12622                                        // If we cannot put the permission as it was,
12623                                        // we have to write.
12624                                        changedRuntimePermissionUserIds = ArrayUtils.appendInt(
12625                                                changedRuntimePermissionUserIds, userId);
12626                                    }
12627                                }
12628
12629                                // If the app supports runtime permissions no need for a review.
12630                                if (mPermissionReviewRequired
12631                                        && appSupportsRuntimePermissions
12632                                        && (flags & PackageManager
12633                                                .FLAG_PERMISSION_REVIEW_REQUIRED) != 0) {
12634                                    flags &= ~PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED;
12635                                    // Since we changed the flags, we have to write.
12636                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
12637                                            changedRuntimePermissionUserIds, userId);
12638                                }
12639                            } else if (mPermissionReviewRequired
12640                                    && !appSupportsRuntimePermissions) {
12641                                // For legacy apps that need a permission review, every new
12642                                // runtime permission is granted but it is pending a review.
12643                                // We also need to review only platform defined runtime
12644                                // permissions as these are the only ones the platform knows
12645                                // how to disable the API to simulate revocation as legacy
12646                                // apps don't expect to run with revoked permissions.
12647                                if (PLATFORM_PACKAGE_NAME.equals(bp.sourcePackage)) {
12648                                    if ((flags & FLAG_PERMISSION_REVIEW_REQUIRED) == 0) {
12649                                        flags |= FLAG_PERMISSION_REVIEW_REQUIRED;
12650                                        // We changed the flags, hence have to write.
12651                                        changedRuntimePermissionUserIds = ArrayUtils.appendInt(
12652                                                changedRuntimePermissionUserIds, userId);
12653                                    }
12654                                }
12655                                if (permissionsState.grantRuntimePermission(bp, userId)
12656                                        != PermissionsState.PERMISSION_OPERATION_FAILURE) {
12657                                    // We changed the permission, hence have to write.
12658                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
12659                                            changedRuntimePermissionUserIds, userId);
12660                                }
12661                            }
12662                            // Propagate the permission flags.
12663                            permissionsState.updatePermissionFlags(bp, userId, flags, flags);
12664                        }
12665                    } break;
12666
12667                    case GRANT_UPGRADE: {
12668                        // Grant runtime permissions for a previously held install permission.
12669                        PermissionState permissionState = origPermissions
12670                                .getInstallPermissionState(bp.name);
12671                        final int flags = permissionState != null ? permissionState.getFlags() : 0;
12672
12673                        if (origPermissions.revokeInstallPermission(bp)
12674                                != PermissionsState.PERMISSION_OPERATION_FAILURE) {
12675                            // We will be transferring the permission flags, so clear them.
12676                            origPermissions.updatePermissionFlags(bp, UserHandle.USER_ALL,
12677                                    PackageManager.MASK_PERMISSION_FLAGS, 0);
12678                            changedInstallPermission = true;
12679                        }
12680
12681                        // If the permission is not to be promoted to runtime we ignore it and
12682                        // also its other flags as they are not applicable to install permissions.
12683                        if ((flags & PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE) == 0) {
12684                            for (int userId : currentUserIds) {
12685                                if (permissionsState.grantRuntimePermission(bp, userId) !=
12686                                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
12687                                    // Transfer the permission flags.
12688                                    permissionsState.updatePermissionFlags(bp, userId,
12689                                            flags, flags);
12690                                    // If we granted the permission, we have to write.
12691                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
12692                                            changedRuntimePermissionUserIds, userId);
12693                                }
12694                            }
12695                        }
12696                    } break;
12697
12698                    default: {
12699                        if (packageOfInterest == null
12700                                || packageOfInterest.equals(pkg.packageName)) {
12701                            if (DEBUG_PERMISSIONS) {
12702                                Slog.i(TAG, "Not granting permission " + perm
12703                                        + " to package " + pkg.packageName
12704                                        + " because it was previously installed without");
12705                            }
12706                        }
12707                    } break;
12708                }
12709            } else {
12710                if (permissionsState.revokeInstallPermission(bp) !=
12711                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
12712                    // Also drop the permission flags.
12713                    permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL,
12714                            PackageManager.MASK_PERMISSION_FLAGS, 0);
12715                    changedInstallPermission = true;
12716                    Slog.i(TAG, "Un-granting permission " + perm
12717                            + " from package " + pkg.packageName
12718                            + " (protectionLevel=" + bp.protectionLevel
12719                            + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
12720                            + ")");
12721                } else if ((bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) == 0) {
12722                    // Don't print warning for app op permissions, since it is fine for them
12723                    // not to be granted, there is a UI for the user to decide.
12724                    if (DEBUG_PERMISSIONS
12725                            && (packageOfInterest == null
12726                                    || packageOfInterest.equals(pkg.packageName))) {
12727                        Slog.i(TAG, "Not granting permission " + perm
12728                                + " to package " + pkg.packageName
12729                                + " (protectionLevel=" + bp.protectionLevel
12730                                + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
12731                                + ")");
12732                    }
12733                }
12734            }
12735        }
12736
12737        if ((changedInstallPermission || replace) && !ps.installPermissionsFixed &&
12738                !isSystemApp(ps) || isUpdatedSystemApp(ps)){
12739            // This is the first that we have heard about this package, so the
12740            // permissions we have now selected are fixed until explicitly
12741            // changed.
12742            ps.installPermissionsFixed = true;
12743        }
12744
12745        // Persist the runtime permissions state for users with changes. If permissions
12746        // were revoked because no app in the shared user declares them we have to
12747        // write synchronously to avoid losing runtime permissions state.
12748        for (int userId : changedRuntimePermissionUserIds) {
12749            mSettings.writeRuntimePermissionsForUserLPr(userId, runtimePermissionsRevoked);
12750        }
12751    }
12752
12753    private boolean isNewPlatformPermissionForPackage(String perm, PackageParser.Package pkg) {
12754        boolean allowed = false;
12755        final int NP = PackageParser.NEW_PERMISSIONS.length;
12756        for (int ip=0; ip<NP; ip++) {
12757            final PackageParser.NewPermissionInfo npi
12758                    = PackageParser.NEW_PERMISSIONS[ip];
12759            if (npi.name.equals(perm)
12760                    && pkg.applicationInfo.targetSdkVersion < npi.sdkVersion) {
12761                allowed = true;
12762                Log.i(TAG, "Auto-granting " + perm + " to old pkg "
12763                        + pkg.packageName);
12764                break;
12765            }
12766        }
12767        return allowed;
12768    }
12769
12770    private boolean grantSignaturePermission(String perm, PackageParser.Package pkg,
12771            BasePermission bp, PermissionsState origPermissions) {
12772        boolean privilegedPermission = (bp.protectionLevel
12773                & PermissionInfo.PROTECTION_FLAG_PRIVILEGED) != 0;
12774        boolean privappPermissionsDisable =
12775                RoSystemProperties.CONTROL_PRIVAPP_PERMISSIONS_DISABLE;
12776        boolean platformPermission = PLATFORM_PACKAGE_NAME.equals(bp.sourcePackage);
12777        boolean platformPackage = PLATFORM_PACKAGE_NAME.equals(pkg.packageName);
12778        if (!privappPermissionsDisable && privilegedPermission && pkg.isPrivilegedApp()
12779                && !platformPackage && platformPermission) {
12780            ArraySet<String> wlPermissions = SystemConfig.getInstance()
12781                    .getPrivAppPermissions(pkg.packageName);
12782            boolean whitelisted = wlPermissions != null && wlPermissions.contains(perm);
12783            if (!whitelisted) {
12784                Slog.w(TAG, "Privileged permission " + perm + " for package "
12785                        + pkg.packageName + " - not in privapp-permissions whitelist");
12786                // Only report violations for apps on system image
12787                if (!mSystemReady && !pkg.isUpdatedSystemApp()) {
12788                    if (mPrivappPermissionsViolations == null) {
12789                        mPrivappPermissionsViolations = new ArraySet<>();
12790                    }
12791                    mPrivappPermissionsViolations.add(pkg.packageName + ": " + perm);
12792                }
12793                if (RoSystemProperties.CONTROL_PRIVAPP_PERMISSIONS_ENFORCE) {
12794                    return false;
12795                }
12796            }
12797        }
12798        boolean allowed = (compareSignatures(
12799                bp.packageSetting.signatures.mSignatures, pkg.mSignatures)
12800                        == PackageManager.SIGNATURE_MATCH)
12801                || (compareSignatures(mPlatformPackage.mSignatures, pkg.mSignatures)
12802                        == PackageManager.SIGNATURE_MATCH);
12803        if (!allowed && privilegedPermission) {
12804            if (isSystemApp(pkg)) {
12805                // For updated system applications, a system permission
12806                // is granted only if it had been defined by the original application.
12807                if (pkg.isUpdatedSystemApp()) {
12808                    final PackageSetting sysPs = mSettings
12809                            .getDisabledSystemPkgLPr(pkg.packageName);
12810                    if (sysPs != null && sysPs.getPermissionsState().hasInstallPermission(perm)) {
12811                        // If the original was granted this permission, we take
12812                        // that grant decision as read and propagate it to the
12813                        // update.
12814                        if (sysPs.isPrivileged()) {
12815                            allowed = true;
12816                        }
12817                    } else {
12818                        // The system apk may have been updated with an older
12819                        // version of the one on the data partition, but which
12820                        // granted a new system permission that it didn't have
12821                        // before.  In this case we do want to allow the app to
12822                        // now get the new permission if the ancestral apk is
12823                        // privileged to get it.
12824                        if (sysPs != null && sysPs.pkg != null && sysPs.isPrivileged()) {
12825                            for (int j = 0; j < sysPs.pkg.requestedPermissions.size(); j++) {
12826                                if (perm.equals(sysPs.pkg.requestedPermissions.get(j))) {
12827                                    allowed = true;
12828                                    break;
12829                                }
12830                            }
12831                        }
12832                        // Also if a privileged parent package on the system image or any of
12833                        // its children requested a privileged permission, the updated child
12834                        // packages can also get the permission.
12835                        if (pkg.parentPackage != null) {
12836                            final PackageSetting disabledSysParentPs = mSettings
12837                                    .getDisabledSystemPkgLPr(pkg.parentPackage.packageName);
12838                            if (disabledSysParentPs != null && disabledSysParentPs.pkg != null
12839                                    && disabledSysParentPs.isPrivileged()) {
12840                                if (isPackageRequestingPermission(disabledSysParentPs.pkg, perm)) {
12841                                    allowed = true;
12842                                } else if (disabledSysParentPs.pkg.childPackages != null) {
12843                                    final int count = disabledSysParentPs.pkg.childPackages.size();
12844                                    for (int i = 0; i < count; i++) {
12845                                        PackageParser.Package disabledSysChildPkg =
12846                                                disabledSysParentPs.pkg.childPackages.get(i);
12847                                        if (isPackageRequestingPermission(disabledSysChildPkg,
12848                                                perm)) {
12849                                            allowed = true;
12850                                            break;
12851                                        }
12852                                    }
12853                                }
12854                            }
12855                        }
12856                    }
12857                } else {
12858                    allowed = isPrivilegedApp(pkg);
12859                }
12860            }
12861        }
12862        if (!allowed) {
12863            if (!allowed && (bp.protectionLevel
12864                    & PermissionInfo.PROTECTION_FLAG_PRE23) != 0
12865                    && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) {
12866                // If this was a previously normal/dangerous permission that got moved
12867                // to a system permission as part of the runtime permission redesign, then
12868                // we still want to blindly grant it to old apps.
12869                allowed = true;
12870            }
12871            if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_INSTALLER) != 0
12872                    && pkg.packageName.equals(mRequiredInstallerPackage)) {
12873                // If this permission is to be granted to the system installer and
12874                // this app is an installer, then it gets the permission.
12875                allowed = true;
12876            }
12877            if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_VERIFIER) != 0
12878                    && pkg.packageName.equals(mRequiredVerifierPackage)) {
12879                // If this permission is to be granted to the system verifier and
12880                // this app is a verifier, then it gets the permission.
12881                allowed = true;
12882            }
12883            if (!allowed && (bp.protectionLevel
12884                    & PermissionInfo.PROTECTION_FLAG_PREINSTALLED) != 0
12885                    && isSystemApp(pkg)) {
12886                // Any pre-installed system app is allowed to get this permission.
12887                allowed = true;
12888            }
12889            if (!allowed && (bp.protectionLevel
12890                    & PermissionInfo.PROTECTION_FLAG_DEVELOPMENT) != 0) {
12891                // For development permissions, a development permission
12892                // is granted only if it was already granted.
12893                allowed = origPermissions.hasInstallPermission(perm);
12894            }
12895            if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_SETUP) != 0
12896                    && pkg.packageName.equals(mSetupWizardPackage)) {
12897                // If this permission is to be granted to the system setup wizard and
12898                // this app is a setup wizard, then it gets the permission.
12899                allowed = true;
12900            }
12901        }
12902        return allowed;
12903    }
12904
12905    private boolean isPackageRequestingPermission(PackageParser.Package pkg, String permission) {
12906        final int permCount = pkg.requestedPermissions.size();
12907        for (int j = 0; j < permCount; j++) {
12908            String requestedPermission = pkg.requestedPermissions.get(j);
12909            if (permission.equals(requestedPermission)) {
12910                return true;
12911            }
12912        }
12913        return false;
12914    }
12915
12916    final class ActivityIntentResolver
12917            extends IntentResolver<PackageParser.ActivityIntentInfo, ResolveInfo> {
12918        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
12919                boolean defaultOnly, int userId) {
12920            if (!sUserManager.exists(userId)) return null;
12921            mFlags = (defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0);
12922            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
12923        }
12924
12925        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
12926                int userId) {
12927            if (!sUserManager.exists(userId)) return null;
12928            mFlags = flags;
12929            return super.queryIntent(intent, resolvedType,
12930                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0,
12931                    userId);
12932        }
12933
12934        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
12935                int flags, ArrayList<PackageParser.Activity> packageActivities, int userId) {
12936            if (!sUserManager.exists(userId)) return null;
12937            if (packageActivities == null) {
12938                return null;
12939            }
12940            mFlags = flags;
12941            final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0;
12942            final int N = packageActivities.size();
12943            ArrayList<PackageParser.ActivityIntentInfo[]> listCut =
12944                new ArrayList<PackageParser.ActivityIntentInfo[]>(N);
12945
12946            ArrayList<PackageParser.ActivityIntentInfo> intentFilters;
12947            for (int i = 0; i < N; ++i) {
12948                intentFilters = packageActivities.get(i).intents;
12949                if (intentFilters != null && intentFilters.size() > 0) {
12950                    PackageParser.ActivityIntentInfo[] array =
12951                            new PackageParser.ActivityIntentInfo[intentFilters.size()];
12952                    intentFilters.toArray(array);
12953                    listCut.add(array);
12954                }
12955            }
12956            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
12957        }
12958
12959        /**
12960         * Finds a privileged activity that matches the specified activity names.
12961         */
12962        private PackageParser.Activity findMatchingActivity(
12963                List<PackageParser.Activity> activityList, ActivityInfo activityInfo) {
12964            for (PackageParser.Activity sysActivity : activityList) {
12965                if (sysActivity.info.name.equals(activityInfo.name)) {
12966                    return sysActivity;
12967                }
12968                if (sysActivity.info.name.equals(activityInfo.targetActivity)) {
12969                    return sysActivity;
12970                }
12971                if (sysActivity.info.targetActivity != null) {
12972                    if (sysActivity.info.targetActivity.equals(activityInfo.name)) {
12973                        return sysActivity;
12974                    }
12975                    if (sysActivity.info.targetActivity.equals(activityInfo.targetActivity)) {
12976                        return sysActivity;
12977                    }
12978                }
12979            }
12980            return null;
12981        }
12982
12983        public class IterGenerator<E> {
12984            public Iterator<E> generate(ActivityIntentInfo info) {
12985                return null;
12986            }
12987        }
12988
12989        public class ActionIterGenerator extends IterGenerator<String> {
12990            @Override
12991            public Iterator<String> generate(ActivityIntentInfo info) {
12992                return info.actionsIterator();
12993            }
12994        }
12995
12996        public class CategoriesIterGenerator extends IterGenerator<String> {
12997            @Override
12998            public Iterator<String> generate(ActivityIntentInfo info) {
12999                return info.categoriesIterator();
13000            }
13001        }
13002
13003        public class SchemesIterGenerator extends IterGenerator<String> {
13004            @Override
13005            public Iterator<String> generate(ActivityIntentInfo info) {
13006                return info.schemesIterator();
13007            }
13008        }
13009
13010        public class AuthoritiesIterGenerator extends IterGenerator<IntentFilter.AuthorityEntry> {
13011            @Override
13012            public Iterator<IntentFilter.AuthorityEntry> generate(ActivityIntentInfo info) {
13013                return info.authoritiesIterator();
13014            }
13015        }
13016
13017        /**
13018         * <em>WARNING</em> for performance reasons, the passed in intentList WILL BE
13019         * MODIFIED. Do not pass in a list that should not be changed.
13020         */
13021        private <T> void getIntentListSubset(List<ActivityIntentInfo> intentList,
13022                IterGenerator<T> generator, Iterator<T> searchIterator) {
13023            // loop through the set of actions; every one must be found in the intent filter
13024            while (searchIterator.hasNext()) {
13025                // we must have at least one filter in the list to consider a match
13026                if (intentList.size() == 0) {
13027                    break;
13028                }
13029
13030                final T searchAction = searchIterator.next();
13031
13032                // loop through the set of intent filters
13033                final Iterator<ActivityIntentInfo> intentIter = intentList.iterator();
13034                while (intentIter.hasNext()) {
13035                    final ActivityIntentInfo intentInfo = intentIter.next();
13036                    boolean selectionFound = false;
13037
13038                    // loop through the intent filter's selection criteria; at least one
13039                    // of them must match the searched criteria
13040                    final Iterator<T> intentSelectionIter = generator.generate(intentInfo);
13041                    while (intentSelectionIter != null && intentSelectionIter.hasNext()) {
13042                        final T intentSelection = intentSelectionIter.next();
13043                        if (intentSelection != null && intentSelection.equals(searchAction)) {
13044                            selectionFound = true;
13045                            break;
13046                        }
13047                    }
13048
13049                    // the selection criteria wasn't found in this filter's set; this filter
13050                    // is not a potential match
13051                    if (!selectionFound) {
13052                        intentIter.remove();
13053                    }
13054                }
13055            }
13056        }
13057
13058        private boolean isProtectedAction(ActivityIntentInfo filter) {
13059            final Iterator<String> actionsIter = filter.actionsIterator();
13060            while (actionsIter != null && actionsIter.hasNext()) {
13061                final String filterAction = actionsIter.next();
13062                if (PROTECTED_ACTIONS.contains(filterAction)) {
13063                    return true;
13064                }
13065            }
13066            return false;
13067        }
13068
13069        /**
13070         * Adjusts the priority of the given intent filter according to policy.
13071         * <p>
13072         * <ul>
13073         * <li>The priority for non privileged applications is capped to '0'</li>
13074         * <li>The priority for protected actions on privileged applications is capped to '0'</li>
13075         * <li>The priority for unbundled updates to privileged applications is capped to the
13076         *      priority defined on the system partition</li>
13077         * </ul>
13078         * <p>
13079         * <em>NOTE:</em> There is one exception. For security reasons, the setup wizard is
13080         * allowed to obtain any priority on any action.
13081         */
13082        private void adjustPriority(
13083                List<PackageParser.Activity> systemActivities, ActivityIntentInfo intent) {
13084            // nothing to do; priority is fine as-is
13085            if (intent.getPriority() <= 0) {
13086                return;
13087            }
13088
13089            final ActivityInfo activityInfo = intent.activity.info;
13090            final ApplicationInfo applicationInfo = activityInfo.applicationInfo;
13091
13092            final boolean privilegedApp =
13093                    ((applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0);
13094            if (!privilegedApp) {
13095                // non-privileged applications can never define a priority >0
13096                if (DEBUG_FILTERS) {
13097                    Slog.i(TAG, "Non-privileged app; cap priority to 0;"
13098                            + " package: " + applicationInfo.packageName
13099                            + " activity: " + intent.activity.className
13100                            + " origPrio: " + intent.getPriority());
13101                }
13102                intent.setPriority(0);
13103                return;
13104            }
13105
13106            if (systemActivities == null) {
13107                // the system package is not disabled; we're parsing the system partition
13108                if (isProtectedAction(intent)) {
13109                    if (mDeferProtectedFilters) {
13110                        // We can't deal with these just yet. No component should ever obtain a
13111                        // >0 priority for a protected actions, with ONE exception -- the setup
13112                        // wizard. The setup wizard, however, cannot be known until we're able to
13113                        // query it for the category CATEGORY_SETUP_WIZARD. Which we can't do
13114                        // until all intent filters have been processed. Chicken, meet egg.
13115                        // Let the filter temporarily have a high priority and rectify the
13116                        // priorities after all system packages have been scanned.
13117                        mProtectedFilters.add(intent);
13118                        if (DEBUG_FILTERS) {
13119                            Slog.i(TAG, "Protected action; save for later;"
13120                                    + " package: " + applicationInfo.packageName
13121                                    + " activity: " + intent.activity.className
13122                                    + " origPrio: " + intent.getPriority());
13123                        }
13124                        return;
13125                    } else {
13126                        if (DEBUG_FILTERS && mSetupWizardPackage == null) {
13127                            Slog.i(TAG, "No setup wizard;"
13128                                + " All protected intents capped to priority 0");
13129                        }
13130                        if (intent.activity.info.packageName.equals(mSetupWizardPackage)) {
13131                            if (DEBUG_FILTERS) {
13132                                Slog.i(TAG, "Found setup wizard;"
13133                                    + " allow priority " + intent.getPriority() + ";"
13134                                    + " package: " + intent.activity.info.packageName
13135                                    + " activity: " + intent.activity.className
13136                                    + " priority: " + intent.getPriority());
13137                            }
13138                            // setup wizard gets whatever it wants
13139                            return;
13140                        }
13141                        if (DEBUG_FILTERS) {
13142                            Slog.i(TAG, "Protected action; cap priority to 0;"
13143                                    + " package: " + intent.activity.info.packageName
13144                                    + " activity: " + intent.activity.className
13145                                    + " origPrio: " + intent.getPriority());
13146                        }
13147                        intent.setPriority(0);
13148                        return;
13149                    }
13150                }
13151                // privileged apps on the system image get whatever priority they request
13152                return;
13153            }
13154
13155            // privileged app unbundled update ... try to find the same activity
13156            final PackageParser.Activity foundActivity =
13157                    findMatchingActivity(systemActivities, activityInfo);
13158            if (foundActivity == null) {
13159                // this is a new activity; it cannot obtain >0 priority
13160                if (DEBUG_FILTERS) {
13161                    Slog.i(TAG, "New activity; cap priority to 0;"
13162                            + " package: " + applicationInfo.packageName
13163                            + " activity: " + intent.activity.className
13164                            + " origPrio: " + intent.getPriority());
13165                }
13166                intent.setPriority(0);
13167                return;
13168            }
13169
13170            // found activity, now check for filter equivalence
13171
13172            // a shallow copy is enough; we modify the list, not its contents
13173            final List<ActivityIntentInfo> intentListCopy =
13174                    new ArrayList<>(foundActivity.intents);
13175            final List<ActivityIntentInfo> foundFilters = findFilters(intent);
13176
13177            // find matching action subsets
13178            final Iterator<String> actionsIterator = intent.actionsIterator();
13179            if (actionsIterator != null) {
13180                getIntentListSubset(
13181                        intentListCopy, new ActionIterGenerator(), actionsIterator);
13182                if (intentListCopy.size() == 0) {
13183                    // no more intents to match; we're not equivalent
13184                    if (DEBUG_FILTERS) {
13185                        Slog.i(TAG, "Mismatched action; cap priority to 0;"
13186                                + " package: " + applicationInfo.packageName
13187                                + " activity: " + intent.activity.className
13188                                + " origPrio: " + intent.getPriority());
13189                    }
13190                    intent.setPriority(0);
13191                    return;
13192                }
13193            }
13194
13195            // find matching category subsets
13196            final Iterator<String> categoriesIterator = intent.categoriesIterator();
13197            if (categoriesIterator != null) {
13198                getIntentListSubset(intentListCopy, new CategoriesIterGenerator(),
13199                        categoriesIterator);
13200                if (intentListCopy.size() == 0) {
13201                    // no more intents to match; we're not equivalent
13202                    if (DEBUG_FILTERS) {
13203                        Slog.i(TAG, "Mismatched category; cap priority to 0;"
13204                                + " package: " + applicationInfo.packageName
13205                                + " activity: " + intent.activity.className
13206                                + " origPrio: " + intent.getPriority());
13207                    }
13208                    intent.setPriority(0);
13209                    return;
13210                }
13211            }
13212
13213            // find matching schemes subsets
13214            final Iterator<String> schemesIterator = intent.schemesIterator();
13215            if (schemesIterator != null) {
13216                getIntentListSubset(intentListCopy, new SchemesIterGenerator(),
13217                        schemesIterator);
13218                if (intentListCopy.size() == 0) {
13219                    // no more intents to match; we're not equivalent
13220                    if (DEBUG_FILTERS) {
13221                        Slog.i(TAG, "Mismatched scheme; cap priority to 0;"
13222                                + " package: " + applicationInfo.packageName
13223                                + " activity: " + intent.activity.className
13224                                + " origPrio: " + intent.getPriority());
13225                    }
13226                    intent.setPriority(0);
13227                    return;
13228                }
13229            }
13230
13231            // find matching authorities subsets
13232            final Iterator<IntentFilter.AuthorityEntry>
13233                    authoritiesIterator = intent.authoritiesIterator();
13234            if (authoritiesIterator != null) {
13235                getIntentListSubset(intentListCopy,
13236                        new AuthoritiesIterGenerator(),
13237                        authoritiesIterator);
13238                if (intentListCopy.size() == 0) {
13239                    // no more intents to match; we're not equivalent
13240                    if (DEBUG_FILTERS) {
13241                        Slog.i(TAG, "Mismatched authority; 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            // we found matching filter(s); app gets the max priority of all intents
13252            int cappedPriority = 0;
13253            for (int i = intentListCopy.size() - 1; i >= 0; --i) {
13254                cappedPriority = Math.max(cappedPriority, intentListCopy.get(i).getPriority());
13255            }
13256            if (intent.getPriority() > cappedPriority) {
13257                if (DEBUG_FILTERS) {
13258                    Slog.i(TAG, "Found matching filter(s);"
13259                            + " cap priority to " + cappedPriority + ";"
13260                            + " package: " + applicationInfo.packageName
13261                            + " activity: " + intent.activity.className
13262                            + " origPrio: " + intent.getPriority());
13263                }
13264                intent.setPriority(cappedPriority);
13265                return;
13266            }
13267            // all this for nothing; the requested priority was <= what was on the system
13268        }
13269
13270        public final void addActivity(PackageParser.Activity a, String type) {
13271            mActivities.put(a.getComponentName(), a);
13272            if (DEBUG_SHOW_INFO)
13273                Log.v(
13274                TAG, "  " + type + " " +
13275                (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":");
13276            if (DEBUG_SHOW_INFO)
13277                Log.v(TAG, "    Class=" + a.info.name);
13278            final int NI = a.intents.size();
13279            for (int j=0; j<NI; j++) {
13280                PackageParser.ActivityIntentInfo intent = a.intents.get(j);
13281                if ("activity".equals(type)) {
13282                    final PackageSetting ps =
13283                            mSettings.getDisabledSystemPkgLPr(intent.activity.info.packageName);
13284                    final List<PackageParser.Activity> systemActivities =
13285                            ps != null && ps.pkg != null ? ps.pkg.activities : null;
13286                    adjustPriority(systemActivities, intent);
13287                }
13288                if (DEBUG_SHOW_INFO) {
13289                    Log.v(TAG, "    IntentFilter:");
13290                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
13291                }
13292                if (!intent.debugCheck()) {
13293                    Log.w(TAG, "==> For Activity " + a.info.name);
13294                }
13295                addFilter(intent);
13296            }
13297        }
13298
13299        public final void removeActivity(PackageParser.Activity a, String type) {
13300            mActivities.remove(a.getComponentName());
13301            if (DEBUG_SHOW_INFO) {
13302                Log.v(TAG, "  " + type + " "
13303                        + (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel
13304                                : a.info.name) + ":");
13305                Log.v(TAG, "    Class=" + a.info.name);
13306            }
13307            final int NI = a.intents.size();
13308            for (int j=0; j<NI; j++) {
13309                PackageParser.ActivityIntentInfo intent = a.intents.get(j);
13310                if (DEBUG_SHOW_INFO) {
13311                    Log.v(TAG, "    IntentFilter:");
13312                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
13313                }
13314                removeFilter(intent);
13315            }
13316        }
13317
13318        @Override
13319        protected boolean allowFilterResult(
13320                PackageParser.ActivityIntentInfo filter, List<ResolveInfo> dest) {
13321            ActivityInfo filterAi = filter.activity.info;
13322            for (int i=dest.size()-1; i>=0; i--) {
13323                ActivityInfo destAi = dest.get(i).activityInfo;
13324                if (destAi.name == filterAi.name
13325                        && destAi.packageName == filterAi.packageName) {
13326                    return false;
13327                }
13328            }
13329            return true;
13330        }
13331
13332        @Override
13333        protected ActivityIntentInfo[] newArray(int size) {
13334            return new ActivityIntentInfo[size];
13335        }
13336
13337        @Override
13338        protected boolean isFilterStopped(PackageParser.ActivityIntentInfo filter, int userId) {
13339            if (!sUserManager.exists(userId)) return true;
13340            PackageParser.Package p = filter.activity.owner;
13341            if (p != null) {
13342                PackageSetting ps = (PackageSetting)p.mExtras;
13343                if (ps != null) {
13344                    // System apps are never considered stopped for purposes of
13345                    // filtering, because there may be no way for the user to
13346                    // actually re-launch them.
13347                    return (ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0
13348                            && ps.getStopped(userId);
13349                }
13350            }
13351            return false;
13352        }
13353
13354        @Override
13355        protected boolean isPackageForFilter(String packageName,
13356                PackageParser.ActivityIntentInfo info) {
13357            return packageName.equals(info.activity.owner.packageName);
13358        }
13359
13360        @Override
13361        protected ResolveInfo newResult(PackageParser.ActivityIntentInfo info,
13362                int match, int userId) {
13363            if (!sUserManager.exists(userId)) return null;
13364            if (!mSettings.isEnabledAndMatchLPr(info.activity.info, mFlags, userId)) {
13365                return null;
13366            }
13367            final PackageParser.Activity activity = info.activity;
13368            PackageSetting ps = (PackageSetting) activity.owner.mExtras;
13369            if (ps == null) {
13370                return null;
13371            }
13372            final PackageUserState userState = ps.readUserState(userId);
13373            ActivityInfo ai =
13374                    PackageParser.generateActivityInfo(activity, mFlags, userState, userId);
13375            if (ai == null) {
13376                return null;
13377            }
13378            final boolean matchExplicitlyVisibleOnly =
13379                    (mFlags & PackageManager.MATCH_EXPLICITLY_VISIBLE_ONLY) != 0;
13380            final boolean matchVisibleToInstantApp =
13381                    (mFlags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
13382            final boolean componentVisible =
13383                    matchVisibleToInstantApp
13384                    && info.isVisibleToInstantApp()
13385                    && (!matchExplicitlyVisibleOnly || info.isExplicitlyVisibleToInstantApp());
13386            final boolean matchInstantApp = (mFlags & PackageManager.MATCH_INSTANT) != 0;
13387            // throw out filters that aren't visible to ephemeral apps
13388            if (matchVisibleToInstantApp && !(componentVisible || userState.instantApp)) {
13389                return null;
13390            }
13391            // throw out instant app filters if we're not explicitly requesting them
13392            if (!matchInstantApp && userState.instantApp) {
13393                return null;
13394            }
13395            // throw out instant app filters if updates are available; will trigger
13396            // instant app resolution
13397            if (userState.instantApp && ps.isUpdateAvailable()) {
13398                return null;
13399            }
13400            final ResolveInfo res = new ResolveInfo();
13401            res.activityInfo = ai;
13402            if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
13403                res.filter = info;
13404            }
13405            if (info != null) {
13406                res.handleAllWebDataURI = info.handleAllWebDataURI();
13407            }
13408            res.priority = info.getPriority();
13409            res.preferredOrder = activity.owner.mPreferredOrder;
13410            //System.out.println("Result: " + res.activityInfo.className +
13411            //                   " = " + res.priority);
13412            res.match = match;
13413            res.isDefault = info.hasDefault;
13414            res.labelRes = info.labelRes;
13415            res.nonLocalizedLabel = info.nonLocalizedLabel;
13416            if (userNeedsBadging(userId)) {
13417                res.noResourceId = true;
13418            } else {
13419                res.icon = info.icon;
13420            }
13421            res.iconResourceId = info.icon;
13422            res.system = res.activityInfo.applicationInfo.isSystemApp();
13423            res.isInstantAppAvailable = userState.instantApp;
13424            return res;
13425        }
13426
13427        @Override
13428        protected void sortResults(List<ResolveInfo> results) {
13429            Collections.sort(results, mResolvePrioritySorter);
13430        }
13431
13432        @Override
13433        protected void dumpFilter(PrintWriter out, String prefix,
13434                PackageParser.ActivityIntentInfo filter) {
13435            out.print(prefix); out.print(
13436                    Integer.toHexString(System.identityHashCode(filter.activity)));
13437                    out.print(' ');
13438                    filter.activity.printComponentShortName(out);
13439                    out.print(" filter ");
13440                    out.println(Integer.toHexString(System.identityHashCode(filter)));
13441        }
13442
13443        @Override
13444        protected Object filterToLabel(PackageParser.ActivityIntentInfo filter) {
13445            return filter.activity;
13446        }
13447
13448        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
13449            PackageParser.Activity activity = (PackageParser.Activity)label;
13450            out.print(prefix); out.print(
13451                    Integer.toHexString(System.identityHashCode(activity)));
13452                    out.print(' ');
13453                    activity.printComponentShortName(out);
13454            if (count > 1) {
13455                out.print(" ("); out.print(count); out.print(" filters)");
13456            }
13457            out.println();
13458        }
13459
13460        // Keys are String (activity class name), values are Activity.
13461        private final ArrayMap<ComponentName, PackageParser.Activity> mActivities
13462                = new ArrayMap<ComponentName, PackageParser.Activity>();
13463        private int mFlags;
13464    }
13465
13466    private final class ServiceIntentResolver
13467            extends IntentResolver<PackageParser.ServiceIntentInfo, ResolveInfo> {
13468        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
13469                boolean defaultOnly, int userId) {
13470            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
13471            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
13472        }
13473
13474        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
13475                int userId) {
13476            if (!sUserManager.exists(userId)) return null;
13477            mFlags = flags;
13478            return super.queryIntent(intent, resolvedType,
13479                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0,
13480                    userId);
13481        }
13482
13483        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
13484                int flags, ArrayList<PackageParser.Service> packageServices, int userId) {
13485            if (!sUserManager.exists(userId)) return null;
13486            if (packageServices == null) {
13487                return null;
13488            }
13489            mFlags = flags;
13490            final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0;
13491            final int N = packageServices.size();
13492            ArrayList<PackageParser.ServiceIntentInfo[]> listCut =
13493                new ArrayList<PackageParser.ServiceIntentInfo[]>(N);
13494
13495            ArrayList<PackageParser.ServiceIntentInfo> intentFilters;
13496            for (int i = 0; i < N; ++i) {
13497                intentFilters = packageServices.get(i).intents;
13498                if (intentFilters != null && intentFilters.size() > 0) {
13499                    PackageParser.ServiceIntentInfo[] array =
13500                            new PackageParser.ServiceIntentInfo[intentFilters.size()];
13501                    intentFilters.toArray(array);
13502                    listCut.add(array);
13503                }
13504            }
13505            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
13506        }
13507
13508        public final void addService(PackageParser.Service s) {
13509            mServices.put(s.getComponentName(), s);
13510            if (DEBUG_SHOW_INFO) {
13511                Log.v(TAG, "  "
13512                        + (s.info.nonLocalizedLabel != null
13513                        ? s.info.nonLocalizedLabel : s.info.name) + ":");
13514                Log.v(TAG, "    Class=" + s.info.name);
13515            }
13516            final int NI = s.intents.size();
13517            int j;
13518            for (j=0; j<NI; j++) {
13519                PackageParser.ServiceIntentInfo intent = s.intents.get(j);
13520                if (DEBUG_SHOW_INFO) {
13521                    Log.v(TAG, "    IntentFilter:");
13522                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
13523                }
13524                if (!intent.debugCheck()) {
13525                    Log.w(TAG, "==> For Service " + s.info.name);
13526                }
13527                addFilter(intent);
13528            }
13529        }
13530
13531        public final void removeService(PackageParser.Service s) {
13532            mServices.remove(s.getComponentName());
13533            if (DEBUG_SHOW_INFO) {
13534                Log.v(TAG, "  " + (s.info.nonLocalizedLabel != null
13535                        ? s.info.nonLocalizedLabel : s.info.name) + ":");
13536                Log.v(TAG, "    Class=" + s.info.name);
13537            }
13538            final int NI = s.intents.size();
13539            int j;
13540            for (j=0; j<NI; j++) {
13541                PackageParser.ServiceIntentInfo intent = s.intents.get(j);
13542                if (DEBUG_SHOW_INFO) {
13543                    Log.v(TAG, "    IntentFilter:");
13544                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
13545                }
13546                removeFilter(intent);
13547            }
13548        }
13549
13550        @Override
13551        protected boolean allowFilterResult(
13552                PackageParser.ServiceIntentInfo filter, List<ResolveInfo> dest) {
13553            ServiceInfo filterSi = filter.service.info;
13554            for (int i=dest.size()-1; i>=0; i--) {
13555                ServiceInfo destAi = dest.get(i).serviceInfo;
13556                if (destAi.name == filterSi.name
13557                        && destAi.packageName == filterSi.packageName) {
13558                    return false;
13559                }
13560            }
13561            return true;
13562        }
13563
13564        @Override
13565        protected PackageParser.ServiceIntentInfo[] newArray(int size) {
13566            return new PackageParser.ServiceIntentInfo[size];
13567        }
13568
13569        @Override
13570        protected boolean isFilterStopped(PackageParser.ServiceIntentInfo filter, int userId) {
13571            if (!sUserManager.exists(userId)) return true;
13572            PackageParser.Package p = filter.service.owner;
13573            if (p != null) {
13574                PackageSetting ps = (PackageSetting)p.mExtras;
13575                if (ps != null) {
13576                    // System apps are never considered stopped for purposes of
13577                    // filtering, because there may be no way for the user to
13578                    // actually re-launch them.
13579                    return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0
13580                            && ps.getStopped(userId);
13581                }
13582            }
13583            return false;
13584        }
13585
13586        @Override
13587        protected boolean isPackageForFilter(String packageName,
13588                PackageParser.ServiceIntentInfo info) {
13589            return packageName.equals(info.service.owner.packageName);
13590        }
13591
13592        @Override
13593        protected ResolveInfo newResult(PackageParser.ServiceIntentInfo filter,
13594                int match, int userId) {
13595            if (!sUserManager.exists(userId)) return null;
13596            final PackageParser.ServiceIntentInfo info = (PackageParser.ServiceIntentInfo)filter;
13597            if (!mSettings.isEnabledAndMatchLPr(info.service.info, mFlags, userId)) {
13598                return null;
13599            }
13600            final PackageParser.Service service = info.service;
13601            PackageSetting ps = (PackageSetting) service.owner.mExtras;
13602            if (ps == null) {
13603                return null;
13604            }
13605            final PackageUserState userState = ps.readUserState(userId);
13606            ServiceInfo si = PackageParser.generateServiceInfo(service, mFlags,
13607                    userState, userId);
13608            if (si == null) {
13609                return null;
13610            }
13611            final boolean matchVisibleToInstantApp =
13612                    (mFlags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
13613            final boolean isInstantApp = (mFlags & PackageManager.MATCH_INSTANT) != 0;
13614            // throw out filters that aren't visible to ephemeral apps
13615            if (matchVisibleToInstantApp
13616                    && !(info.isVisibleToInstantApp() || userState.instantApp)) {
13617                return null;
13618            }
13619            // throw out ephemeral filters if we're not explicitly requesting them
13620            if (!isInstantApp && userState.instantApp) {
13621                return null;
13622            }
13623            // throw out instant app filters if updates are available; will trigger
13624            // instant app resolution
13625            if (userState.instantApp && ps.isUpdateAvailable()) {
13626                return null;
13627            }
13628            final ResolveInfo res = new ResolveInfo();
13629            res.serviceInfo = si;
13630            if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
13631                res.filter = filter;
13632            }
13633            res.priority = info.getPriority();
13634            res.preferredOrder = service.owner.mPreferredOrder;
13635            res.match = match;
13636            res.isDefault = info.hasDefault;
13637            res.labelRes = info.labelRes;
13638            res.nonLocalizedLabel = info.nonLocalizedLabel;
13639            res.icon = info.icon;
13640            res.system = res.serviceInfo.applicationInfo.isSystemApp();
13641            return res;
13642        }
13643
13644        @Override
13645        protected void sortResults(List<ResolveInfo> results) {
13646            Collections.sort(results, mResolvePrioritySorter);
13647        }
13648
13649        @Override
13650        protected void dumpFilter(PrintWriter out, String prefix,
13651                PackageParser.ServiceIntentInfo filter) {
13652            out.print(prefix); out.print(
13653                    Integer.toHexString(System.identityHashCode(filter.service)));
13654                    out.print(' ');
13655                    filter.service.printComponentShortName(out);
13656                    out.print(" filter ");
13657                    out.println(Integer.toHexString(System.identityHashCode(filter)));
13658        }
13659
13660        @Override
13661        protected Object filterToLabel(PackageParser.ServiceIntentInfo filter) {
13662            return filter.service;
13663        }
13664
13665        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
13666            PackageParser.Service service = (PackageParser.Service)label;
13667            out.print(prefix); out.print(
13668                    Integer.toHexString(System.identityHashCode(service)));
13669                    out.print(' ');
13670                    service.printComponentShortName(out);
13671            if (count > 1) {
13672                out.print(" ("); out.print(count); out.print(" filters)");
13673            }
13674            out.println();
13675        }
13676
13677//        List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) {
13678//            final Iterator<ResolveInfo> i = resolveInfoList.iterator();
13679//            final List<ResolveInfo> retList = Lists.newArrayList();
13680//            while (i.hasNext()) {
13681//                final ResolveInfo resolveInfo = (ResolveInfo) i;
13682//                if (isEnabledLP(resolveInfo.serviceInfo)) {
13683//                    retList.add(resolveInfo);
13684//                }
13685//            }
13686//            return retList;
13687//        }
13688
13689        // Keys are String (activity class name), values are Activity.
13690        private final ArrayMap<ComponentName, PackageParser.Service> mServices
13691                = new ArrayMap<ComponentName, PackageParser.Service>();
13692        private int mFlags;
13693    }
13694
13695    private final class ProviderIntentResolver
13696            extends IntentResolver<PackageParser.ProviderIntentInfo, ResolveInfo> {
13697        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
13698                boolean defaultOnly, int userId) {
13699            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
13700            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
13701        }
13702
13703        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
13704                int userId) {
13705            if (!sUserManager.exists(userId))
13706                return null;
13707            mFlags = flags;
13708            return super.queryIntent(intent, resolvedType,
13709                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0,
13710                    userId);
13711        }
13712
13713        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
13714                int flags, ArrayList<PackageParser.Provider> packageProviders, int userId) {
13715            if (!sUserManager.exists(userId))
13716                return null;
13717            if (packageProviders == null) {
13718                return null;
13719            }
13720            mFlags = flags;
13721            final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0;
13722            final int N = packageProviders.size();
13723            ArrayList<PackageParser.ProviderIntentInfo[]> listCut =
13724                    new ArrayList<PackageParser.ProviderIntentInfo[]>(N);
13725
13726            ArrayList<PackageParser.ProviderIntentInfo> intentFilters;
13727            for (int i = 0; i < N; ++i) {
13728                intentFilters = packageProviders.get(i).intents;
13729                if (intentFilters != null && intentFilters.size() > 0) {
13730                    PackageParser.ProviderIntentInfo[] array =
13731                            new PackageParser.ProviderIntentInfo[intentFilters.size()];
13732                    intentFilters.toArray(array);
13733                    listCut.add(array);
13734                }
13735            }
13736            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
13737        }
13738
13739        public final void addProvider(PackageParser.Provider p) {
13740            if (mProviders.containsKey(p.getComponentName())) {
13741                Slog.w(TAG, "Provider " + p.getComponentName() + " already defined; ignoring");
13742                return;
13743            }
13744
13745            mProviders.put(p.getComponentName(), p);
13746            if (DEBUG_SHOW_INFO) {
13747                Log.v(TAG, "  "
13748                        + (p.info.nonLocalizedLabel != null
13749                                ? p.info.nonLocalizedLabel : p.info.name) + ":");
13750                Log.v(TAG, "    Class=" + p.info.name);
13751            }
13752            final int NI = p.intents.size();
13753            int j;
13754            for (j = 0; j < NI; j++) {
13755                PackageParser.ProviderIntentInfo intent = p.intents.get(j);
13756                if (DEBUG_SHOW_INFO) {
13757                    Log.v(TAG, "    IntentFilter:");
13758                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
13759                }
13760                if (!intent.debugCheck()) {
13761                    Log.w(TAG, "==> For Provider " + p.info.name);
13762                }
13763                addFilter(intent);
13764            }
13765        }
13766
13767        public final void removeProvider(PackageParser.Provider p) {
13768            mProviders.remove(p.getComponentName());
13769            if (DEBUG_SHOW_INFO) {
13770                Log.v(TAG, "  " + (p.info.nonLocalizedLabel != null
13771                        ? p.info.nonLocalizedLabel : p.info.name) + ":");
13772                Log.v(TAG, "    Class=" + p.info.name);
13773            }
13774            final int NI = p.intents.size();
13775            int j;
13776            for (j = 0; j < NI; j++) {
13777                PackageParser.ProviderIntentInfo intent = p.intents.get(j);
13778                if (DEBUG_SHOW_INFO) {
13779                    Log.v(TAG, "    IntentFilter:");
13780                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
13781                }
13782                removeFilter(intent);
13783            }
13784        }
13785
13786        @Override
13787        protected boolean allowFilterResult(
13788                PackageParser.ProviderIntentInfo filter, List<ResolveInfo> dest) {
13789            ProviderInfo filterPi = filter.provider.info;
13790            for (int i = dest.size() - 1; i >= 0; i--) {
13791                ProviderInfo destPi = dest.get(i).providerInfo;
13792                if (destPi.name == filterPi.name
13793                        && destPi.packageName == filterPi.packageName) {
13794                    return false;
13795                }
13796            }
13797            return true;
13798        }
13799
13800        @Override
13801        protected PackageParser.ProviderIntentInfo[] newArray(int size) {
13802            return new PackageParser.ProviderIntentInfo[size];
13803        }
13804
13805        @Override
13806        protected boolean isFilterStopped(PackageParser.ProviderIntentInfo filter, int userId) {
13807            if (!sUserManager.exists(userId))
13808                return true;
13809            PackageParser.Package p = filter.provider.owner;
13810            if (p != null) {
13811                PackageSetting ps = (PackageSetting) p.mExtras;
13812                if (ps != null) {
13813                    // System apps are never considered stopped for purposes of
13814                    // filtering, because there may be no way for the user to
13815                    // actually re-launch them.
13816                    return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0
13817                            && ps.getStopped(userId);
13818                }
13819            }
13820            return false;
13821        }
13822
13823        @Override
13824        protected boolean isPackageForFilter(String packageName,
13825                PackageParser.ProviderIntentInfo info) {
13826            return packageName.equals(info.provider.owner.packageName);
13827        }
13828
13829        @Override
13830        protected ResolveInfo newResult(PackageParser.ProviderIntentInfo filter,
13831                int match, int userId) {
13832            if (!sUserManager.exists(userId))
13833                return null;
13834            final PackageParser.ProviderIntentInfo info = filter;
13835            if (!mSettings.isEnabledAndMatchLPr(info.provider.info, mFlags, userId)) {
13836                return null;
13837            }
13838            final PackageParser.Provider provider = info.provider;
13839            PackageSetting ps = (PackageSetting) provider.owner.mExtras;
13840            if (ps == null) {
13841                return null;
13842            }
13843            final PackageUserState userState = ps.readUserState(userId);
13844            final boolean matchVisibleToInstantApp =
13845                    (mFlags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
13846            final boolean isInstantApp = (mFlags & PackageManager.MATCH_INSTANT) != 0;
13847            // throw out filters that aren't visible to instant applications
13848            if (matchVisibleToInstantApp
13849                    && !(info.isVisibleToInstantApp() || userState.instantApp)) {
13850                return null;
13851            }
13852            // throw out instant application filters if we're not explicitly requesting them
13853            if (!isInstantApp && userState.instantApp) {
13854                return null;
13855            }
13856            // throw out instant application filters if updates are available; will trigger
13857            // instant application resolution
13858            if (userState.instantApp && ps.isUpdateAvailable()) {
13859                return null;
13860            }
13861            ProviderInfo pi = PackageParser.generateProviderInfo(provider, mFlags,
13862                    userState, userId);
13863            if (pi == null) {
13864                return null;
13865            }
13866            final ResolveInfo res = new ResolveInfo();
13867            res.providerInfo = pi;
13868            if ((mFlags & PackageManager.GET_RESOLVED_FILTER) != 0) {
13869                res.filter = filter;
13870            }
13871            res.priority = info.getPriority();
13872            res.preferredOrder = provider.owner.mPreferredOrder;
13873            res.match = match;
13874            res.isDefault = info.hasDefault;
13875            res.labelRes = info.labelRes;
13876            res.nonLocalizedLabel = info.nonLocalizedLabel;
13877            res.icon = info.icon;
13878            res.system = res.providerInfo.applicationInfo.isSystemApp();
13879            return res;
13880        }
13881
13882        @Override
13883        protected void sortResults(List<ResolveInfo> results) {
13884            Collections.sort(results, mResolvePrioritySorter);
13885        }
13886
13887        @Override
13888        protected void dumpFilter(PrintWriter out, String prefix,
13889                PackageParser.ProviderIntentInfo filter) {
13890            out.print(prefix);
13891            out.print(
13892                    Integer.toHexString(System.identityHashCode(filter.provider)));
13893            out.print(' ');
13894            filter.provider.printComponentShortName(out);
13895            out.print(" filter ");
13896            out.println(Integer.toHexString(System.identityHashCode(filter)));
13897        }
13898
13899        @Override
13900        protected Object filterToLabel(PackageParser.ProviderIntentInfo filter) {
13901            return filter.provider;
13902        }
13903
13904        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
13905            PackageParser.Provider provider = (PackageParser.Provider)label;
13906            out.print(prefix); out.print(
13907                    Integer.toHexString(System.identityHashCode(provider)));
13908                    out.print(' ');
13909                    provider.printComponentShortName(out);
13910            if (count > 1) {
13911                out.print(" ("); out.print(count); out.print(" filters)");
13912            }
13913            out.println();
13914        }
13915
13916        private final ArrayMap<ComponentName, PackageParser.Provider> mProviders
13917                = new ArrayMap<ComponentName, PackageParser.Provider>();
13918        private int mFlags;
13919    }
13920
13921    static final class EphemeralIntentResolver
13922            extends IntentResolver<AuxiliaryResolveInfo, AuxiliaryResolveInfo> {
13923        /**
13924         * The result that has the highest defined order. Ordering applies on a
13925         * per-package basis. Mapping is from package name to Pair of order and
13926         * EphemeralResolveInfo.
13927         * <p>
13928         * NOTE: This is implemented as a field variable for convenience and efficiency.
13929         * By having a field variable, we're able to track filter ordering as soon as
13930         * a non-zero order is defined. Otherwise, multiple loops across the result set
13931         * would be needed to apply ordering. If the intent resolver becomes re-entrant,
13932         * this needs to be contained entirely within {@link #filterResults}.
13933         */
13934        final ArrayMap<String, Pair<Integer, InstantAppResolveInfo>> mOrderResult = new ArrayMap<>();
13935
13936        @Override
13937        protected AuxiliaryResolveInfo[] newArray(int size) {
13938            return new AuxiliaryResolveInfo[size];
13939        }
13940
13941        @Override
13942        protected boolean isPackageForFilter(String packageName, AuxiliaryResolveInfo responseObj) {
13943            return true;
13944        }
13945
13946        @Override
13947        protected AuxiliaryResolveInfo newResult(AuxiliaryResolveInfo responseObj, int match,
13948                int userId) {
13949            if (!sUserManager.exists(userId)) {
13950                return null;
13951            }
13952            final String packageName = responseObj.resolveInfo.getPackageName();
13953            final Integer order = responseObj.getOrder();
13954            final Pair<Integer, InstantAppResolveInfo> lastOrderResult =
13955                    mOrderResult.get(packageName);
13956            // ordering is enabled and this item's order isn't high enough
13957            if (lastOrderResult != null && lastOrderResult.first >= order) {
13958                return null;
13959            }
13960            final InstantAppResolveInfo res = responseObj.resolveInfo;
13961            if (order > 0) {
13962                // non-zero order, enable ordering
13963                mOrderResult.put(packageName, new Pair<>(order, res));
13964            }
13965            return responseObj;
13966        }
13967
13968        @Override
13969        protected void filterResults(List<AuxiliaryResolveInfo> results) {
13970            // only do work if ordering is enabled [most of the time it won't be]
13971            if (mOrderResult.size() == 0) {
13972                return;
13973            }
13974            int resultSize = results.size();
13975            for (int i = 0; i < resultSize; i++) {
13976                final InstantAppResolveInfo info = results.get(i).resolveInfo;
13977                final String packageName = info.getPackageName();
13978                final Pair<Integer, InstantAppResolveInfo> savedInfo = mOrderResult.get(packageName);
13979                if (savedInfo == null) {
13980                    // package doesn't having ordering
13981                    continue;
13982                }
13983                if (savedInfo.second == info) {
13984                    // circled back to the highest ordered item; remove from order list
13985                    mOrderResult.remove(savedInfo);
13986                    if (mOrderResult.size() == 0) {
13987                        // no more ordered items
13988                        break;
13989                    }
13990                    continue;
13991                }
13992                // item has a worse order, remove it from the result list
13993                results.remove(i);
13994                resultSize--;
13995                i--;
13996            }
13997        }
13998    }
13999
14000    private static final Comparator<ResolveInfo> mResolvePrioritySorter =
14001            new Comparator<ResolveInfo>() {
14002        public int compare(ResolveInfo r1, ResolveInfo r2) {
14003            int v1 = r1.priority;
14004            int v2 = r2.priority;
14005            //System.out.println("Comparing: q1=" + q1 + " q2=" + q2);
14006            if (v1 != v2) {
14007                return (v1 > v2) ? -1 : 1;
14008            }
14009            v1 = r1.preferredOrder;
14010            v2 = r2.preferredOrder;
14011            if (v1 != v2) {
14012                return (v1 > v2) ? -1 : 1;
14013            }
14014            if (r1.isDefault != r2.isDefault) {
14015                return r1.isDefault ? -1 : 1;
14016            }
14017            v1 = r1.match;
14018            v2 = r2.match;
14019            //System.out.println("Comparing: m1=" + m1 + " m2=" + m2);
14020            if (v1 != v2) {
14021                return (v1 > v2) ? -1 : 1;
14022            }
14023            if (r1.system != r2.system) {
14024                return r1.system ? -1 : 1;
14025            }
14026            if (r1.activityInfo != null) {
14027                return r1.activityInfo.packageName.compareTo(r2.activityInfo.packageName);
14028            }
14029            if (r1.serviceInfo != null) {
14030                return r1.serviceInfo.packageName.compareTo(r2.serviceInfo.packageName);
14031            }
14032            if (r1.providerInfo != null) {
14033                return r1.providerInfo.packageName.compareTo(r2.providerInfo.packageName);
14034            }
14035            return 0;
14036        }
14037    };
14038
14039    private static final Comparator<ProviderInfo> mProviderInitOrderSorter =
14040            new Comparator<ProviderInfo>() {
14041        public int compare(ProviderInfo p1, ProviderInfo p2) {
14042            final int v1 = p1.initOrder;
14043            final int v2 = p2.initOrder;
14044            return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0);
14045        }
14046    };
14047
14048    public void sendPackageBroadcast(final String action, final String pkg, final Bundle extras,
14049            final int flags, final String targetPkg, final IIntentReceiver finishedReceiver,
14050            final int[] userIds) {
14051        mHandler.post(new Runnable() {
14052            @Override
14053            public void run() {
14054                try {
14055                    final IActivityManager am = ActivityManager.getService();
14056                    if (am == null) return;
14057                    final int[] resolvedUserIds;
14058                    if (userIds == null) {
14059                        resolvedUserIds = am.getRunningUserIds();
14060                    } else {
14061                        resolvedUserIds = userIds;
14062                    }
14063                    for (int id : resolvedUserIds) {
14064                        final Intent intent = new Intent(action,
14065                                pkg != null ? Uri.fromParts(PACKAGE_SCHEME, pkg, null) : null);
14066                        if (extras != null) {
14067                            intent.putExtras(extras);
14068                        }
14069                        if (targetPkg != null) {
14070                            intent.setPackage(targetPkg);
14071                        }
14072                        // Modify the UID when posting to other users
14073                        int uid = intent.getIntExtra(Intent.EXTRA_UID, -1);
14074                        if (uid > 0 && UserHandle.getUserId(uid) != id) {
14075                            uid = UserHandle.getUid(id, UserHandle.getAppId(uid));
14076                            intent.putExtra(Intent.EXTRA_UID, uid);
14077                        }
14078                        intent.putExtra(Intent.EXTRA_USER_HANDLE, id);
14079                        intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT | flags);
14080                        if (DEBUG_BROADCASTS) {
14081                            RuntimeException here = new RuntimeException("here");
14082                            here.fillInStackTrace();
14083                            Slog.d(TAG, "Sending to user " + id + ": "
14084                                    + intent.toShortString(false, true, false, false)
14085                                    + " " + intent.getExtras(), here);
14086                        }
14087                        am.broadcastIntent(null, intent, null, finishedReceiver,
14088                                0, null, null, null, android.app.AppOpsManager.OP_NONE,
14089                                null, finishedReceiver != null, false, id);
14090                    }
14091                } catch (RemoteException ex) {
14092                }
14093            }
14094        });
14095    }
14096
14097    /**
14098     * Check if the external storage media is available. This is true if there
14099     * is a mounted external storage medium or if the external storage is
14100     * emulated.
14101     */
14102    private boolean isExternalMediaAvailable() {
14103        return mMediaMounted || Environment.isExternalStorageEmulated();
14104    }
14105
14106    @Override
14107    public PackageCleanItem nextPackageToClean(PackageCleanItem lastPackage) {
14108        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
14109            return null;
14110        }
14111        // writer
14112        synchronized (mPackages) {
14113            if (!isExternalMediaAvailable()) {
14114                // If the external storage is no longer mounted at this point,
14115                // the caller may not have been able to delete all of this
14116                // packages files and can not delete any more.  Bail.
14117                return null;
14118            }
14119            final ArrayList<PackageCleanItem> pkgs = mSettings.mPackagesToBeCleaned;
14120            if (lastPackage != null) {
14121                pkgs.remove(lastPackage);
14122            }
14123            if (pkgs.size() > 0) {
14124                return pkgs.get(0);
14125            }
14126        }
14127        return null;
14128    }
14129
14130    void schedulePackageCleaning(String packageName, int userId, boolean andCode) {
14131        final Message msg = mHandler.obtainMessage(START_CLEANING_PACKAGE,
14132                userId, andCode ? 1 : 0, packageName);
14133        if (mSystemReady) {
14134            msg.sendToTarget();
14135        } else {
14136            if (mPostSystemReadyMessages == null) {
14137                mPostSystemReadyMessages = new ArrayList<>();
14138            }
14139            mPostSystemReadyMessages.add(msg);
14140        }
14141    }
14142
14143    void startCleaningPackages() {
14144        // reader
14145        if (!isExternalMediaAvailable()) {
14146            return;
14147        }
14148        synchronized (mPackages) {
14149            if (mSettings.mPackagesToBeCleaned.isEmpty()) {
14150                return;
14151            }
14152        }
14153        Intent intent = new Intent(PackageManager.ACTION_CLEAN_EXTERNAL_STORAGE);
14154        intent.setComponent(DEFAULT_CONTAINER_COMPONENT);
14155        IActivityManager am = ActivityManager.getService();
14156        if (am != null) {
14157            int dcsUid = -1;
14158            synchronized (mPackages) {
14159                if (!mDefaultContainerWhitelisted) {
14160                    mDefaultContainerWhitelisted = true;
14161                    PackageSetting ps = mSettings.mPackages.get(DEFAULT_CONTAINER_PACKAGE);
14162                    dcsUid = UserHandle.getUid(UserHandle.USER_SYSTEM, ps.appId);
14163                }
14164            }
14165            try {
14166                if (dcsUid > 0) {
14167                    am.backgroundWhitelistUid(dcsUid);
14168                }
14169                am.startService(null, intent, null, false, mContext.getOpPackageName(),
14170                        UserHandle.USER_SYSTEM);
14171            } catch (RemoteException e) {
14172            }
14173        }
14174    }
14175
14176    @Override
14177    public void installPackageAsUser(String originPath, IPackageInstallObserver2 observer,
14178            int installFlags, String installerPackageName, int userId) {
14179        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, null);
14180
14181        final int callingUid = Binder.getCallingUid();
14182        enforceCrossUserPermission(callingUid, userId,
14183                true /* requireFullPermission */, true /* checkShell */, "installPackageAsUser");
14184
14185        if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) {
14186            try {
14187                if (observer != null) {
14188                    observer.onPackageInstalled("", INSTALL_FAILED_USER_RESTRICTED, null, null);
14189                }
14190            } catch (RemoteException re) {
14191            }
14192            return;
14193        }
14194
14195        if ((callingUid == Process.SHELL_UID) || (callingUid == Process.ROOT_UID)) {
14196            installFlags |= PackageManager.INSTALL_FROM_ADB;
14197
14198        } else {
14199            // Caller holds INSTALL_PACKAGES permission, so we're less strict
14200            // about installerPackageName.
14201
14202            installFlags &= ~PackageManager.INSTALL_FROM_ADB;
14203            installFlags &= ~PackageManager.INSTALL_ALL_USERS;
14204        }
14205
14206        UserHandle user;
14207        if ((installFlags & PackageManager.INSTALL_ALL_USERS) != 0) {
14208            user = UserHandle.ALL;
14209        } else {
14210            user = new UserHandle(userId);
14211        }
14212
14213        // Only system components can circumvent runtime permissions when installing.
14214        if ((installFlags & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0
14215                && mContext.checkCallingOrSelfPermission(Manifest.permission
14216                .INSTALL_GRANT_RUNTIME_PERMISSIONS) == PackageManager.PERMISSION_DENIED) {
14217            throw new SecurityException("You need the "
14218                    + "android.permission.INSTALL_GRANT_RUNTIME_PERMISSIONS permission "
14219                    + "to use the PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS flag");
14220        }
14221
14222        if ((installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0
14223                || (installFlags & PackageManager.INSTALL_EXTERNAL) != 0) {
14224            throw new IllegalArgumentException(
14225                    "New installs into ASEC containers no longer supported");
14226        }
14227
14228        final File originFile = new File(originPath);
14229        final OriginInfo origin = OriginInfo.fromUntrustedFile(originFile);
14230
14231        final Message msg = mHandler.obtainMessage(INIT_COPY);
14232        final VerificationInfo verificationInfo = new VerificationInfo(
14233                null /*originatingUri*/, null /*referrer*/, -1 /*originatingUid*/, callingUid);
14234        final InstallParams params = new InstallParams(origin, null /*moveInfo*/, observer,
14235                installFlags, installerPackageName, null /*volumeUuid*/, verificationInfo, user,
14236                null /*packageAbiOverride*/, null /*grantedPermissions*/,
14237                null /*certificates*/, PackageManager.INSTALL_REASON_UNKNOWN);
14238        params.setTraceMethod("installAsUser").setTraceCookie(System.identityHashCode(params));
14239        msg.obj = params;
14240
14241        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "installAsUser",
14242                System.identityHashCode(msg.obj));
14243        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
14244                System.identityHashCode(msg.obj));
14245
14246        mHandler.sendMessage(msg);
14247    }
14248
14249
14250    /**
14251     * Ensure that the install reason matches what we know about the package installer (e.g. whether
14252     * it is acting on behalf on an enterprise or the user).
14253     *
14254     * Note that the ordering of the conditionals in this method is important. The checks we perform
14255     * are as follows, in this order:
14256     *
14257     * 1) If the install is being performed by a system app, we can trust the app to have set the
14258     *    install reason correctly. Thus, we pass through the install reason unchanged, no matter
14259     *    what it is.
14260     * 2) If the install is being performed by a device or profile owner app, the install reason
14261     *    should be enterprise policy. However, we cannot be sure that the device or profile owner
14262     *    set the install reason correctly. If the app targets an older SDK version where install
14263     *    reasons did not exist yet, or if the app author simply forgot, the install reason may be
14264     *    unset or wrong. Thus, we force the install reason to be enterprise policy.
14265     * 3) In all other cases, the install is being performed by a regular app that is neither part
14266     *    of the system nor a device or profile owner. We have no reason to believe that this app is
14267     *    acting on behalf of the enterprise admin. Thus, we check whether the install reason was
14268     *    set to enterprise policy and if so, change it to unknown instead.
14269     */
14270    private int fixUpInstallReason(String installerPackageName, int installerUid,
14271            int installReason) {
14272        if (checkUidPermission(android.Manifest.permission.INSTALL_PACKAGES, installerUid)
14273                == PERMISSION_GRANTED) {
14274            // If the install is being performed by a system app, we trust that app to have set the
14275            // install reason correctly.
14276            return installReason;
14277        }
14278
14279        final IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface(
14280            ServiceManager.getService(Context.DEVICE_POLICY_SERVICE));
14281        if (dpm != null) {
14282            ComponentName owner = null;
14283            try {
14284                owner = dpm.getDeviceOwnerComponent(true /* callingUserOnly */);
14285                if (owner == null) {
14286                    owner = dpm.getProfileOwner(UserHandle.getUserId(installerUid));
14287                }
14288            } catch (RemoteException e) {
14289            }
14290            if (owner != null && owner.getPackageName().equals(installerPackageName)) {
14291                // If the install is being performed by a device or profile owner, the install
14292                // reason should be enterprise policy.
14293                return PackageManager.INSTALL_REASON_POLICY;
14294            }
14295        }
14296
14297        if (installReason == PackageManager.INSTALL_REASON_POLICY) {
14298            // If the install is being performed by a regular app (i.e. neither system app nor
14299            // device or profile owner), we have no reason to believe that the app is acting on
14300            // behalf of an enterprise. If the app set the install reason to enterprise policy,
14301            // change it to unknown instead.
14302            return PackageManager.INSTALL_REASON_UNKNOWN;
14303        }
14304
14305        // If the install is being performed by a regular app and the install reason was set to any
14306        // value but enterprise policy, leave the install reason unchanged.
14307        return installReason;
14308    }
14309
14310    void installStage(String packageName, File stagedDir, String stagedCid,
14311            IPackageInstallObserver2 observer, PackageInstaller.SessionParams sessionParams,
14312            String installerPackageName, int installerUid, UserHandle user,
14313            Certificate[][] certificates) {
14314        if (DEBUG_EPHEMERAL) {
14315            if ((sessionParams.installFlags & PackageManager.INSTALL_INSTANT_APP) != 0) {
14316                Slog.d(TAG, "Ephemeral install of " + packageName);
14317            }
14318        }
14319        final VerificationInfo verificationInfo = new VerificationInfo(
14320                sessionParams.originatingUri, sessionParams.referrerUri,
14321                sessionParams.originatingUid, installerUid);
14322
14323        final OriginInfo origin;
14324        if (stagedDir != null) {
14325            origin = OriginInfo.fromStagedFile(stagedDir);
14326        } else {
14327            origin = OriginInfo.fromStagedContainer(stagedCid);
14328        }
14329
14330        final Message msg = mHandler.obtainMessage(INIT_COPY);
14331        final int installReason = fixUpInstallReason(installerPackageName, installerUid,
14332                sessionParams.installReason);
14333        final InstallParams params = new InstallParams(origin, null, observer,
14334                sessionParams.installFlags, installerPackageName, sessionParams.volumeUuid,
14335                verificationInfo, user, sessionParams.abiOverride,
14336                sessionParams.grantedRuntimePermissions, certificates, installReason);
14337        params.setTraceMethod("installStage").setTraceCookie(System.identityHashCode(params));
14338        msg.obj = params;
14339
14340        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "installStage",
14341                System.identityHashCode(msg.obj));
14342        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
14343                System.identityHashCode(msg.obj));
14344
14345        mHandler.sendMessage(msg);
14346    }
14347
14348    private void sendPackageAddedForUser(String packageName, PackageSetting pkgSetting,
14349            int userId) {
14350        final boolean isSystem = isSystemApp(pkgSetting) || isUpdatedSystemApp(pkgSetting);
14351        sendPackageAddedForNewUsers(packageName, isSystem, pkgSetting.appId, userId);
14352
14353        // Send a session commit broadcast
14354        final PackageInstaller.SessionInfo info = new PackageInstaller.SessionInfo();
14355        info.installReason = pkgSetting.getInstallReason(userId);
14356        info.appPackageName = packageName;
14357        sendSessionCommitBroadcast(info, userId);
14358    }
14359
14360    public void sendPackageAddedForNewUsers(String packageName, boolean isSystem, int appId, int... userIds) {
14361        if (ArrayUtils.isEmpty(userIds)) {
14362            return;
14363        }
14364        Bundle extras = new Bundle(1);
14365        // Set to UID of the first user, EXTRA_UID is automatically updated in sendPackageBroadcast
14366        extras.putInt(Intent.EXTRA_UID, UserHandle.getUid(userIds[0], appId));
14367
14368        sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
14369                packageName, extras, 0, null, null, userIds);
14370        if (isSystem) {
14371            mHandler.post(() -> {
14372                        for (int userId : userIds) {
14373                            sendBootCompletedBroadcastToSystemApp(packageName, userId);
14374                        }
14375                    }
14376            );
14377        }
14378    }
14379
14380    /**
14381     * The just-installed/enabled app is bundled on the system, so presumed to be able to run
14382     * automatically without needing an explicit launch.
14383     * Send it a LOCKED_BOOT_COMPLETED/BOOT_COMPLETED if it would ordinarily have gotten ones.
14384     */
14385    private void sendBootCompletedBroadcastToSystemApp(String packageName, int userId) {
14386        // If user is not running, the app didn't miss any broadcast
14387        if (!mUserManagerInternal.isUserRunning(userId)) {
14388            return;
14389        }
14390        final IActivityManager am = ActivityManager.getService();
14391        try {
14392            // Deliver LOCKED_BOOT_COMPLETED first
14393            Intent lockedBcIntent = new Intent(Intent.ACTION_LOCKED_BOOT_COMPLETED)
14394                    .setPackage(packageName);
14395            final String[] requiredPermissions = {Manifest.permission.RECEIVE_BOOT_COMPLETED};
14396            am.broadcastIntent(null, lockedBcIntent, null, null, 0, null, null, requiredPermissions,
14397                    android.app.AppOpsManager.OP_NONE, null, false, false, userId);
14398
14399            // Deliver BOOT_COMPLETED only if user is unlocked
14400            if (mUserManagerInternal.isUserUnlockingOrUnlocked(userId)) {
14401                Intent bcIntent = new Intent(Intent.ACTION_BOOT_COMPLETED).setPackage(packageName);
14402                am.broadcastIntent(null, bcIntent, null, null, 0, null, null, requiredPermissions,
14403                        android.app.AppOpsManager.OP_NONE, null, false, false, userId);
14404            }
14405        } catch (RemoteException e) {
14406            throw e.rethrowFromSystemServer();
14407        }
14408    }
14409
14410    @Override
14411    public boolean setApplicationHiddenSettingAsUser(String packageName, boolean hidden,
14412            int userId) {
14413        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
14414        PackageSetting pkgSetting;
14415        final int callingUid = Binder.getCallingUid();
14416        enforceCrossUserPermission(callingUid, userId,
14417                true /* requireFullPermission */, true /* checkShell */,
14418                "setApplicationHiddenSetting for user " + userId);
14419
14420        if (hidden && isPackageDeviceAdmin(packageName, userId)) {
14421            Slog.w(TAG, "Not hiding package " + packageName + ": has active device admin");
14422            return false;
14423        }
14424
14425        long callingId = Binder.clearCallingIdentity();
14426        try {
14427            boolean sendAdded = false;
14428            boolean sendRemoved = false;
14429            // writer
14430            synchronized (mPackages) {
14431                pkgSetting = mSettings.mPackages.get(packageName);
14432                if (pkgSetting == null) {
14433                    return false;
14434                }
14435                if (filterAppAccessLPr(pkgSetting, callingUid, userId)) {
14436                    return false;
14437                }
14438                // Do not allow "android" is being disabled
14439                if ("android".equals(packageName)) {
14440                    Slog.w(TAG, "Cannot hide package: android");
14441                    return false;
14442                }
14443                // Cannot hide static shared libs as they are considered
14444                // a part of the using app (emulating static linking). Also
14445                // static libs are installed always on internal storage.
14446                PackageParser.Package pkg = mPackages.get(packageName);
14447                if (pkg != null && pkg.staticSharedLibName != null) {
14448                    Slog.w(TAG, "Cannot hide package: " + packageName
14449                            + " providing static shared library: "
14450                            + pkg.staticSharedLibName);
14451                    return false;
14452                }
14453                // Only allow protected packages to hide themselves.
14454                if (hidden && !UserHandle.isSameApp(callingUid, pkgSetting.appId)
14455                        && mProtectedPackages.isPackageStateProtected(userId, packageName)) {
14456                    Slog.w(TAG, "Not hiding protected package: " + packageName);
14457                    return false;
14458                }
14459
14460                if (pkgSetting.getHidden(userId) != hidden) {
14461                    pkgSetting.setHidden(hidden, userId);
14462                    mSettings.writePackageRestrictionsLPr(userId);
14463                    if (hidden) {
14464                        sendRemoved = true;
14465                    } else {
14466                        sendAdded = true;
14467                    }
14468                }
14469            }
14470            if (sendAdded) {
14471                sendPackageAddedForUser(packageName, pkgSetting, userId);
14472                return true;
14473            }
14474            if (sendRemoved) {
14475                killApplication(packageName, UserHandle.getUid(userId, pkgSetting.appId),
14476                        "hiding pkg");
14477                sendApplicationHiddenForUser(packageName, pkgSetting, userId);
14478                return true;
14479            }
14480        } finally {
14481            Binder.restoreCallingIdentity(callingId);
14482        }
14483        return false;
14484    }
14485
14486    private void sendApplicationHiddenForUser(String packageName, PackageSetting pkgSetting,
14487            int userId) {
14488        final PackageRemovedInfo info = new PackageRemovedInfo(this);
14489        info.removedPackage = packageName;
14490        info.installerPackageName = pkgSetting.installerPackageName;
14491        info.removedUsers = new int[] {userId};
14492        info.broadcastUsers = new int[] {userId};
14493        info.uid = UserHandle.getUid(userId, pkgSetting.appId);
14494        info.sendPackageRemovedBroadcasts(true /*killApp*/);
14495    }
14496
14497    private void sendPackagesSuspendedForUser(String[] pkgList, int userId, boolean suspended) {
14498        if (pkgList.length > 0) {
14499            Bundle extras = new Bundle(1);
14500            extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList);
14501
14502            sendPackageBroadcast(
14503                    suspended ? Intent.ACTION_PACKAGES_SUSPENDED
14504                            : Intent.ACTION_PACKAGES_UNSUSPENDED,
14505                    null, extras, Intent.FLAG_RECEIVER_REGISTERED_ONLY, null, null,
14506                    new int[] {userId});
14507        }
14508    }
14509
14510    /**
14511     * Returns true if application is not found or there was an error. Otherwise it returns
14512     * the hidden state of the package for the given user.
14513     */
14514    @Override
14515    public boolean getApplicationHiddenSettingAsUser(String packageName, int userId) {
14516        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
14517        final int callingUid = Binder.getCallingUid();
14518        enforceCrossUserPermission(callingUid, userId,
14519                true /* requireFullPermission */, false /* checkShell */,
14520                "getApplicationHidden for user " + userId);
14521        PackageSetting ps;
14522        long callingId = Binder.clearCallingIdentity();
14523        try {
14524            // writer
14525            synchronized (mPackages) {
14526                ps = mSettings.mPackages.get(packageName);
14527                if (ps == null) {
14528                    return true;
14529                }
14530                if (filterAppAccessLPr(ps, callingUid, userId)) {
14531                    return true;
14532                }
14533                return ps.getHidden(userId);
14534            }
14535        } finally {
14536            Binder.restoreCallingIdentity(callingId);
14537        }
14538    }
14539
14540    /**
14541     * @hide
14542     */
14543    @Override
14544    public int installExistingPackageAsUser(String packageName, int userId, int installFlags,
14545            int installReason) {
14546        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES,
14547                null);
14548        PackageSetting pkgSetting;
14549        final int callingUid = Binder.getCallingUid();
14550        enforceCrossUserPermission(callingUid, userId,
14551                true /* requireFullPermission */, true /* checkShell */,
14552                "installExistingPackage for user " + userId);
14553        if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) {
14554            return PackageManager.INSTALL_FAILED_USER_RESTRICTED;
14555        }
14556
14557        long callingId = Binder.clearCallingIdentity();
14558        try {
14559            boolean installed = false;
14560            final boolean instantApp =
14561                    (installFlags & PackageManager.INSTALL_INSTANT_APP) != 0;
14562            final boolean fullApp =
14563                    (installFlags & PackageManager.INSTALL_FULL_APP) != 0;
14564
14565            // writer
14566            synchronized (mPackages) {
14567                pkgSetting = mSettings.mPackages.get(packageName);
14568                if (pkgSetting == null) {
14569                    return PackageManager.INSTALL_FAILED_INVALID_URI;
14570                }
14571                if (!canViewInstantApps(callingUid, UserHandle.getUserId(callingUid))) {
14572                    // only allow the existing package to be used if it's installed as a full
14573                    // application for at least one user
14574                    boolean installAllowed = false;
14575                    for (int checkUserId : sUserManager.getUserIds()) {
14576                        installAllowed = !pkgSetting.getInstantApp(checkUserId);
14577                        if (installAllowed) {
14578                            break;
14579                        }
14580                    }
14581                    if (!installAllowed) {
14582                        return PackageManager.INSTALL_FAILED_INVALID_URI;
14583                    }
14584                }
14585                if (!pkgSetting.getInstalled(userId)) {
14586                    pkgSetting.setInstalled(true, userId);
14587                    pkgSetting.setHidden(false, userId);
14588                    pkgSetting.setInstallReason(installReason, userId);
14589                    mSettings.writePackageRestrictionsLPr(userId);
14590                    mSettings.writeKernelMappingLPr(pkgSetting);
14591                    installed = true;
14592                } else if (fullApp && pkgSetting.getInstantApp(userId)) {
14593                    // upgrade app from instant to full; we don't allow app downgrade
14594                    installed = true;
14595                }
14596                setInstantAppForUser(pkgSetting, userId, instantApp, fullApp);
14597            }
14598
14599            if (installed) {
14600                if (pkgSetting.pkg != null) {
14601                    synchronized (mInstallLock) {
14602                        // We don't need to freeze for a brand new install
14603                        prepareAppDataAfterInstallLIF(pkgSetting.pkg);
14604                    }
14605                }
14606                sendPackageAddedForUser(packageName, pkgSetting, userId);
14607                synchronized (mPackages) {
14608                    updateSequenceNumberLP(pkgSetting, new int[]{ userId });
14609                }
14610            }
14611        } finally {
14612            Binder.restoreCallingIdentity(callingId);
14613        }
14614
14615        return PackageManager.INSTALL_SUCCEEDED;
14616    }
14617
14618    void setInstantAppForUser(PackageSetting pkgSetting, int userId,
14619            boolean instantApp, boolean fullApp) {
14620        // no state specified; do nothing
14621        if (!instantApp && !fullApp) {
14622            return;
14623        }
14624        if (userId != UserHandle.USER_ALL) {
14625            if (instantApp && !pkgSetting.getInstantApp(userId)) {
14626                pkgSetting.setInstantApp(true /*instantApp*/, userId);
14627            } else if (fullApp && pkgSetting.getInstantApp(userId)) {
14628                pkgSetting.setInstantApp(false /*instantApp*/, userId);
14629            }
14630        } else {
14631            for (int currentUserId : sUserManager.getUserIds()) {
14632                if (instantApp && !pkgSetting.getInstantApp(currentUserId)) {
14633                    pkgSetting.setInstantApp(true /*instantApp*/, currentUserId);
14634                } else if (fullApp && pkgSetting.getInstantApp(currentUserId)) {
14635                    pkgSetting.setInstantApp(false /*instantApp*/, currentUserId);
14636                }
14637            }
14638        }
14639    }
14640
14641    boolean isUserRestricted(int userId, String restrictionKey) {
14642        Bundle restrictions = sUserManager.getUserRestrictions(userId);
14643        if (restrictions.getBoolean(restrictionKey, false)) {
14644            Log.w(TAG, "User is restricted: " + restrictionKey);
14645            return true;
14646        }
14647        return false;
14648    }
14649
14650    @Override
14651    public String[] setPackagesSuspendedAsUser(String[] packageNames, boolean suspended,
14652            int userId) {
14653        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
14654        final int callingUid = Binder.getCallingUid();
14655        enforceCrossUserPermission(callingUid, userId,
14656                true /* requireFullPermission */, true /* checkShell */,
14657                "setPackagesSuspended for user " + userId);
14658
14659        if (ArrayUtils.isEmpty(packageNames)) {
14660            return packageNames;
14661        }
14662
14663        // List of package names for whom the suspended state has changed.
14664        List<String> changedPackages = new ArrayList<>(packageNames.length);
14665        // List of package names for whom the suspended state is not set as requested in this
14666        // method.
14667        List<String> unactionedPackages = new ArrayList<>(packageNames.length);
14668        long callingId = Binder.clearCallingIdentity();
14669        try {
14670            for (int i = 0; i < packageNames.length; i++) {
14671                String packageName = packageNames[i];
14672                boolean changed = false;
14673                final int appId;
14674                synchronized (mPackages) {
14675                    final PackageSetting pkgSetting = mSettings.mPackages.get(packageName);
14676                    if (pkgSetting == null
14677                            || filterAppAccessLPr(pkgSetting, callingUid, userId)) {
14678                        Slog.w(TAG, "Could not find package setting for package \"" + packageName
14679                                + "\". Skipping suspending/un-suspending.");
14680                        unactionedPackages.add(packageName);
14681                        continue;
14682                    }
14683                    appId = pkgSetting.appId;
14684                    if (pkgSetting.getSuspended(userId) != suspended) {
14685                        if (!canSuspendPackageForUserLocked(packageName, userId)) {
14686                            unactionedPackages.add(packageName);
14687                            continue;
14688                        }
14689                        pkgSetting.setSuspended(suspended, userId);
14690                        mSettings.writePackageRestrictionsLPr(userId);
14691                        changed = true;
14692                        changedPackages.add(packageName);
14693                    }
14694                }
14695
14696                if (changed && suspended) {
14697                    killApplication(packageName, UserHandle.getUid(userId, appId),
14698                            "suspending package");
14699                }
14700            }
14701        } finally {
14702            Binder.restoreCallingIdentity(callingId);
14703        }
14704
14705        if (!changedPackages.isEmpty()) {
14706            sendPackagesSuspendedForUser(changedPackages.toArray(
14707                    new String[changedPackages.size()]), userId, suspended);
14708        }
14709
14710        return unactionedPackages.toArray(new String[unactionedPackages.size()]);
14711    }
14712
14713    @Override
14714    public boolean isPackageSuspendedForUser(String packageName, int userId) {
14715        final int callingUid = Binder.getCallingUid();
14716        enforceCrossUserPermission(callingUid, userId,
14717                true /* requireFullPermission */, false /* checkShell */,
14718                "isPackageSuspendedForUser for user " + userId);
14719        synchronized (mPackages) {
14720            final PackageSetting ps = mSettings.mPackages.get(packageName);
14721            if (ps == null || filterAppAccessLPr(ps, callingUid, userId)) {
14722                throw new IllegalArgumentException("Unknown target package: " + packageName);
14723            }
14724            return ps.getSuspended(userId);
14725        }
14726    }
14727
14728    private boolean canSuspendPackageForUserLocked(String packageName, int userId) {
14729        if (isPackageDeviceAdmin(packageName, userId)) {
14730            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
14731                    + "\": has an active device admin");
14732            return false;
14733        }
14734
14735        String activeLauncherPackageName = getActiveLauncherPackageName(userId);
14736        if (packageName.equals(activeLauncherPackageName)) {
14737            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
14738                    + "\": contains the active launcher");
14739            return false;
14740        }
14741
14742        if (packageName.equals(mRequiredInstallerPackage)) {
14743            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
14744                    + "\": required for package installation");
14745            return false;
14746        }
14747
14748        if (packageName.equals(mRequiredUninstallerPackage)) {
14749            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
14750                    + "\": required for package uninstallation");
14751            return false;
14752        }
14753
14754        if (packageName.equals(mRequiredVerifierPackage)) {
14755            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
14756                    + "\": required for package verification");
14757            return false;
14758        }
14759
14760        if (packageName.equals(getDefaultDialerPackageName(userId))) {
14761            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
14762                    + "\": is the default dialer");
14763            return false;
14764        }
14765
14766        if (mProtectedPackages.isPackageStateProtected(userId, packageName)) {
14767            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
14768                    + "\": protected package");
14769            return false;
14770        }
14771
14772        // Cannot suspend static shared libs as they are considered
14773        // a part of the using app (emulating static linking). Also
14774        // static libs are installed always on internal storage.
14775        PackageParser.Package pkg = mPackages.get(packageName);
14776        if (pkg != null && pkg.applicationInfo.isStaticSharedLibrary()) {
14777            Slog.w(TAG, "Cannot suspend package: " + packageName
14778                    + " providing static shared library: "
14779                    + pkg.staticSharedLibName);
14780            return false;
14781        }
14782
14783        return true;
14784    }
14785
14786    private String getActiveLauncherPackageName(int userId) {
14787        Intent intent = new Intent(Intent.ACTION_MAIN);
14788        intent.addCategory(Intent.CATEGORY_HOME);
14789        ResolveInfo resolveInfo = resolveIntent(
14790                intent,
14791                intent.resolveTypeIfNeeded(mContext.getContentResolver()),
14792                PackageManager.MATCH_DEFAULT_ONLY,
14793                userId);
14794
14795        return resolveInfo == null ? null : resolveInfo.activityInfo.packageName;
14796    }
14797
14798    private String getDefaultDialerPackageName(int userId) {
14799        synchronized (mPackages) {
14800            return mSettings.getDefaultDialerPackageNameLPw(userId);
14801        }
14802    }
14803
14804    @Override
14805    public void verifyPendingInstall(int id, int verificationCode) throws RemoteException {
14806        mContext.enforceCallingOrSelfPermission(
14807                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
14808                "Only package verification agents can verify applications");
14809
14810        final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED);
14811        final PackageVerificationResponse response = new PackageVerificationResponse(
14812                verificationCode, Binder.getCallingUid());
14813        msg.arg1 = id;
14814        msg.obj = response;
14815        mHandler.sendMessage(msg);
14816    }
14817
14818    @Override
14819    public void extendVerificationTimeout(int id, int verificationCodeAtTimeout,
14820            long millisecondsToDelay) {
14821        mContext.enforceCallingOrSelfPermission(
14822                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
14823                "Only package verification agents can extend verification timeouts");
14824
14825        final PackageVerificationState state = mPendingVerification.get(id);
14826        final PackageVerificationResponse response = new PackageVerificationResponse(
14827                verificationCodeAtTimeout, Binder.getCallingUid());
14828
14829        if (millisecondsToDelay > PackageManager.MAXIMUM_VERIFICATION_TIMEOUT) {
14830            millisecondsToDelay = PackageManager.MAXIMUM_VERIFICATION_TIMEOUT;
14831        }
14832        if (millisecondsToDelay < 0) {
14833            millisecondsToDelay = 0;
14834        }
14835        if ((verificationCodeAtTimeout != PackageManager.VERIFICATION_ALLOW)
14836                && (verificationCodeAtTimeout != PackageManager.VERIFICATION_REJECT)) {
14837            verificationCodeAtTimeout = PackageManager.VERIFICATION_REJECT;
14838        }
14839
14840        if ((state != null) && !state.timeoutExtended()) {
14841            state.extendTimeout();
14842
14843            final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED);
14844            msg.arg1 = id;
14845            msg.obj = response;
14846            mHandler.sendMessageDelayed(msg, millisecondsToDelay);
14847        }
14848    }
14849
14850    private void broadcastPackageVerified(int verificationId, Uri packageUri,
14851            int verificationCode, UserHandle user) {
14852        final Intent intent = new Intent(Intent.ACTION_PACKAGE_VERIFIED);
14853        intent.setDataAndType(packageUri, PACKAGE_MIME_TYPE);
14854        intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
14855        intent.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId);
14856        intent.putExtra(PackageManager.EXTRA_VERIFICATION_RESULT, verificationCode);
14857
14858        mContext.sendBroadcastAsUser(intent, user,
14859                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT);
14860    }
14861
14862    private ComponentName matchComponentForVerifier(String packageName,
14863            List<ResolveInfo> receivers) {
14864        ActivityInfo targetReceiver = null;
14865
14866        final int NR = receivers.size();
14867        for (int i = 0; i < NR; i++) {
14868            final ResolveInfo info = receivers.get(i);
14869            if (info.activityInfo == null) {
14870                continue;
14871            }
14872
14873            if (packageName.equals(info.activityInfo.packageName)) {
14874                targetReceiver = info.activityInfo;
14875                break;
14876            }
14877        }
14878
14879        if (targetReceiver == null) {
14880            return null;
14881        }
14882
14883        return new ComponentName(targetReceiver.packageName, targetReceiver.name);
14884    }
14885
14886    private List<ComponentName> matchVerifiers(PackageInfoLite pkgInfo,
14887            List<ResolveInfo> receivers, final PackageVerificationState verificationState) {
14888        if (pkgInfo.verifiers.length == 0) {
14889            return null;
14890        }
14891
14892        final int N = pkgInfo.verifiers.length;
14893        final List<ComponentName> sufficientVerifiers = new ArrayList<ComponentName>(N + 1);
14894        for (int i = 0; i < N; i++) {
14895            final VerifierInfo verifierInfo = pkgInfo.verifiers[i];
14896
14897            final ComponentName comp = matchComponentForVerifier(verifierInfo.packageName,
14898                    receivers);
14899            if (comp == null) {
14900                continue;
14901            }
14902
14903            final int verifierUid = getUidForVerifier(verifierInfo);
14904            if (verifierUid == -1) {
14905                continue;
14906            }
14907
14908            if (DEBUG_VERIFY) {
14909                Slog.d(TAG, "Added sufficient verifier " + verifierInfo.packageName
14910                        + " with the correct signature");
14911            }
14912            sufficientVerifiers.add(comp);
14913            verificationState.addSufficientVerifier(verifierUid);
14914        }
14915
14916        return sufficientVerifiers;
14917    }
14918
14919    private int getUidForVerifier(VerifierInfo verifierInfo) {
14920        synchronized (mPackages) {
14921            final PackageParser.Package pkg = mPackages.get(verifierInfo.packageName);
14922            if (pkg == null) {
14923                return -1;
14924            } else if (pkg.mSignatures.length != 1) {
14925                Slog.i(TAG, "Verifier package " + verifierInfo.packageName
14926                        + " has more than one signature; ignoring");
14927                return -1;
14928            }
14929
14930            /*
14931             * If the public key of the package's signature does not match
14932             * our expected public key, then this is a different package and
14933             * we should skip.
14934             */
14935
14936            final byte[] expectedPublicKey;
14937            try {
14938                final Signature verifierSig = pkg.mSignatures[0];
14939                final PublicKey publicKey = verifierSig.getPublicKey();
14940                expectedPublicKey = publicKey.getEncoded();
14941            } catch (CertificateException e) {
14942                return -1;
14943            }
14944
14945            final byte[] actualPublicKey = verifierInfo.publicKey.getEncoded();
14946
14947            if (!Arrays.equals(actualPublicKey, expectedPublicKey)) {
14948                Slog.i(TAG, "Verifier package " + verifierInfo.packageName
14949                        + " does not have the expected public key; ignoring");
14950                return -1;
14951            }
14952
14953            return pkg.applicationInfo.uid;
14954        }
14955    }
14956
14957    @Override
14958    public void finishPackageInstall(int token, boolean didLaunch) {
14959        enforceSystemOrRoot("Only the system is allowed to finish installs");
14960
14961        if (DEBUG_INSTALL) {
14962            Slog.v(TAG, "BM finishing package install for " + token);
14963        }
14964        Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "restore", token);
14965
14966        final Message msg = mHandler.obtainMessage(POST_INSTALL, token, didLaunch ? 1 : 0);
14967        mHandler.sendMessage(msg);
14968    }
14969
14970    /**
14971     * Get the verification agent timeout.  Used for both the APK verifier and the
14972     * intent filter verifier.
14973     *
14974     * @return verification timeout in milliseconds
14975     */
14976    private long getVerificationTimeout() {
14977        return android.provider.Settings.Global.getLong(mContext.getContentResolver(),
14978                android.provider.Settings.Global.PACKAGE_VERIFIER_TIMEOUT,
14979                DEFAULT_VERIFICATION_TIMEOUT);
14980    }
14981
14982    /**
14983     * Get the default verification agent response code.
14984     *
14985     * @return default verification response code
14986     */
14987    private int getDefaultVerificationResponse(UserHandle user) {
14988        if (sUserManager.hasUserRestriction(UserManager.ENSURE_VERIFY_APPS, user.getIdentifier())) {
14989            return PackageManager.VERIFICATION_REJECT;
14990        }
14991        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
14992                android.provider.Settings.Global.PACKAGE_VERIFIER_DEFAULT_RESPONSE,
14993                DEFAULT_VERIFICATION_RESPONSE);
14994    }
14995
14996    /**
14997     * Check whether or not package verification has been enabled.
14998     *
14999     * @return true if verification should be performed
15000     */
15001    private boolean isVerificationEnabled(int userId, int installFlags, int installerUid) {
15002        if (!DEFAULT_VERIFY_ENABLE) {
15003            return false;
15004        }
15005
15006        boolean ensureVerifyAppsEnabled = isUserRestricted(userId, UserManager.ENSURE_VERIFY_APPS);
15007
15008        // Check if installing from ADB
15009        if ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0) {
15010            // Do not run verification in a test harness environment
15011            if (ActivityManager.isRunningInTestHarness()) {
15012                return false;
15013            }
15014            if (ensureVerifyAppsEnabled) {
15015                return true;
15016            }
15017            // Check if the developer does not want package verification for ADB installs
15018            if (android.provider.Settings.Global.getInt(mContext.getContentResolver(),
15019                    android.provider.Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB, 1) == 0) {
15020                return false;
15021            }
15022        } else {
15023            // only when not installed from ADB, skip verification for instant apps when
15024            // the installer and verifier are the same.
15025            if ((installFlags & PackageManager.INSTALL_INSTANT_APP) != 0) {
15026                if (mInstantAppInstallerActivity != null
15027                        && mInstantAppInstallerActivity.packageName.equals(
15028                                mRequiredVerifierPackage)) {
15029                    try {
15030                        mContext.getSystemService(AppOpsManager.class)
15031                                .checkPackage(installerUid, mRequiredVerifierPackage);
15032                        if (DEBUG_VERIFY) {
15033                            Slog.i(TAG, "disable verification for instant app");
15034                        }
15035                        return false;
15036                    } catch (SecurityException ignore) { }
15037                }
15038            }
15039        }
15040
15041        if (ensureVerifyAppsEnabled) {
15042            return true;
15043        }
15044
15045        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
15046                android.provider.Settings.Global.PACKAGE_VERIFIER_ENABLE, 1) == 1;
15047    }
15048
15049    @Override
15050    public void verifyIntentFilter(int id, int verificationCode, List<String> failedDomains)
15051            throws RemoteException {
15052        mContext.enforceCallingOrSelfPermission(
15053                Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT,
15054                "Only intentfilter verification agents can verify applications");
15055
15056        final Message msg = mHandler.obtainMessage(INTENT_FILTER_VERIFIED);
15057        final IntentFilterVerificationResponse response = new IntentFilterVerificationResponse(
15058                Binder.getCallingUid(), verificationCode, failedDomains);
15059        msg.arg1 = id;
15060        msg.obj = response;
15061        mHandler.sendMessage(msg);
15062    }
15063
15064    @Override
15065    public int getIntentVerificationStatus(String packageName, int userId) {
15066        final int callingUid = Binder.getCallingUid();
15067        if (getInstantAppPackageName(callingUid) != null) {
15068            return INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED;
15069        }
15070        synchronized (mPackages) {
15071            final PackageSetting ps = mSettings.mPackages.get(packageName);
15072            if (ps == null
15073                    || filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
15074                return INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED;
15075            }
15076            return mSettings.getIntentFilterVerificationStatusLPr(packageName, userId);
15077        }
15078    }
15079
15080    @Override
15081    public boolean updateIntentVerificationStatus(String packageName, int status, int userId) {
15082        mContext.enforceCallingOrSelfPermission(
15083                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
15084
15085        boolean result = false;
15086        synchronized (mPackages) {
15087            final PackageSetting ps = mSettings.mPackages.get(packageName);
15088            if (filterAppAccessLPr(ps, Binder.getCallingUid(), UserHandle.getCallingUserId())) {
15089                return false;
15090            }
15091            result = mSettings.updateIntentFilterVerificationStatusLPw(packageName, status, userId);
15092        }
15093        if (result) {
15094            scheduleWritePackageRestrictionsLocked(userId);
15095        }
15096        return result;
15097    }
15098
15099    @Override
15100    public @NonNull ParceledListSlice<IntentFilterVerificationInfo> getIntentFilterVerifications(
15101            String packageName) {
15102        final int callingUid = Binder.getCallingUid();
15103        if (getInstantAppPackageName(callingUid) != null) {
15104            return ParceledListSlice.emptyList();
15105        }
15106        synchronized (mPackages) {
15107            final PackageSetting ps = mSettings.mPackages.get(packageName);
15108            if (filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
15109                return ParceledListSlice.emptyList();
15110            }
15111            return new ParceledListSlice<>(mSettings.getIntentFilterVerificationsLPr(packageName));
15112        }
15113    }
15114
15115    @Override
15116    public @NonNull ParceledListSlice<IntentFilter> getAllIntentFilters(String packageName) {
15117        if (TextUtils.isEmpty(packageName)) {
15118            return ParceledListSlice.emptyList();
15119        }
15120        final int callingUid = Binder.getCallingUid();
15121        final int callingUserId = UserHandle.getUserId(callingUid);
15122        synchronized (mPackages) {
15123            PackageParser.Package pkg = mPackages.get(packageName);
15124            if (pkg == null || pkg.activities == null) {
15125                return ParceledListSlice.emptyList();
15126            }
15127            if (pkg.mExtras == null) {
15128                return ParceledListSlice.emptyList();
15129            }
15130            final PackageSetting ps = (PackageSetting) pkg.mExtras;
15131            if (filterAppAccessLPr(ps, callingUid, callingUserId)) {
15132                return ParceledListSlice.emptyList();
15133            }
15134            final int count = pkg.activities.size();
15135            ArrayList<IntentFilter> result = new ArrayList<>();
15136            for (int n=0; n<count; n++) {
15137                PackageParser.Activity activity = pkg.activities.get(n);
15138                if (activity.intents != null && activity.intents.size() > 0) {
15139                    result.addAll(activity.intents);
15140                }
15141            }
15142            return new ParceledListSlice<>(result);
15143        }
15144    }
15145
15146    @Override
15147    public boolean setDefaultBrowserPackageName(String packageName, int userId) {
15148        mContext.enforceCallingOrSelfPermission(
15149                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
15150
15151        synchronized (mPackages) {
15152            boolean result = mSettings.setDefaultBrowserPackageNameLPw(packageName, userId);
15153            if (packageName != null) {
15154                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultBrowserLPr(
15155                        packageName, userId);
15156            }
15157            return result;
15158        }
15159    }
15160
15161    @Override
15162    public String getDefaultBrowserPackageName(int userId) {
15163        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
15164            return null;
15165        }
15166        synchronized (mPackages) {
15167            return mSettings.getDefaultBrowserPackageNameLPw(userId);
15168        }
15169    }
15170
15171    /**
15172     * Get the "allow unknown sources" setting.
15173     *
15174     * @return the current "allow unknown sources" setting
15175     */
15176    private int getUnknownSourcesSettings() {
15177        return android.provider.Settings.Secure.getInt(mContext.getContentResolver(),
15178                android.provider.Settings.Secure.INSTALL_NON_MARKET_APPS,
15179                -1);
15180    }
15181
15182    @Override
15183    public void setInstallerPackageName(String targetPackage, String installerPackageName) {
15184        final int callingUid = Binder.getCallingUid();
15185        if (getInstantAppPackageName(callingUid) != null) {
15186            return;
15187        }
15188        // writer
15189        synchronized (mPackages) {
15190            PackageSetting targetPackageSetting = mSettings.mPackages.get(targetPackage);
15191            if (targetPackageSetting == null
15192                    || filterAppAccessLPr(
15193                            targetPackageSetting, callingUid, UserHandle.getUserId(callingUid))) {
15194                throw new IllegalArgumentException("Unknown target package: " + targetPackage);
15195            }
15196
15197            PackageSetting installerPackageSetting;
15198            if (installerPackageName != null) {
15199                installerPackageSetting = mSettings.mPackages.get(installerPackageName);
15200                if (installerPackageSetting == null) {
15201                    throw new IllegalArgumentException("Unknown installer package: "
15202                            + installerPackageName);
15203                }
15204            } else {
15205                installerPackageSetting = null;
15206            }
15207
15208            Signature[] callerSignature;
15209            Object obj = mSettings.getUserIdLPr(callingUid);
15210            if (obj != null) {
15211                if (obj instanceof SharedUserSetting) {
15212                    callerSignature = ((SharedUserSetting)obj).signatures.mSignatures;
15213                } else if (obj instanceof PackageSetting) {
15214                    callerSignature = ((PackageSetting)obj).signatures.mSignatures;
15215                } else {
15216                    throw new SecurityException("Bad object " + obj + " for uid " + callingUid);
15217                }
15218            } else {
15219                throw new SecurityException("Unknown calling UID: " + callingUid);
15220            }
15221
15222            // Verify: can't set installerPackageName to a package that is
15223            // not signed with the same cert as the caller.
15224            if (installerPackageSetting != null) {
15225                if (compareSignatures(callerSignature,
15226                        installerPackageSetting.signatures.mSignatures)
15227                        != PackageManager.SIGNATURE_MATCH) {
15228                    throw new SecurityException(
15229                            "Caller does not have same cert as new installer package "
15230                            + installerPackageName);
15231                }
15232            }
15233
15234            // Verify: if target already has an installer package, it must
15235            // be signed with the same cert as the caller.
15236            if (targetPackageSetting.installerPackageName != null) {
15237                PackageSetting setting = mSettings.mPackages.get(
15238                        targetPackageSetting.installerPackageName);
15239                // If the currently set package isn't valid, then it's always
15240                // okay to change it.
15241                if (setting != null) {
15242                    if (compareSignatures(callerSignature,
15243                            setting.signatures.mSignatures)
15244                            != PackageManager.SIGNATURE_MATCH) {
15245                        throw new SecurityException(
15246                                "Caller does not have same cert as old installer package "
15247                                + targetPackageSetting.installerPackageName);
15248                    }
15249                }
15250            }
15251
15252            // Okay!
15253            targetPackageSetting.installerPackageName = installerPackageName;
15254            if (installerPackageName != null) {
15255                mSettings.mInstallerPackages.add(installerPackageName);
15256            }
15257            scheduleWriteSettingsLocked();
15258        }
15259    }
15260
15261    @Override
15262    public void setApplicationCategoryHint(String packageName, int categoryHint,
15263            String callerPackageName) {
15264        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
15265            throw new SecurityException("Instant applications don't have access to this method");
15266        }
15267        mContext.getSystemService(AppOpsManager.class).checkPackage(Binder.getCallingUid(),
15268                callerPackageName);
15269        synchronized (mPackages) {
15270            PackageSetting ps = mSettings.mPackages.get(packageName);
15271            if (ps == null) {
15272                throw new IllegalArgumentException("Unknown target package " + packageName);
15273            }
15274            if (filterAppAccessLPr(ps, Binder.getCallingUid(), UserHandle.getCallingUserId())) {
15275                throw new IllegalArgumentException("Unknown target package " + packageName);
15276            }
15277            if (!Objects.equals(callerPackageName, ps.installerPackageName)) {
15278                throw new IllegalArgumentException("Calling package " + callerPackageName
15279                        + " is not installer for " + packageName);
15280            }
15281
15282            if (ps.categoryHint != categoryHint) {
15283                ps.categoryHint = categoryHint;
15284                scheduleWriteSettingsLocked();
15285            }
15286        }
15287    }
15288
15289    private void processPendingInstall(final InstallArgs args, final int currentStatus) {
15290        // Queue up an async operation since the package installation may take a little while.
15291        mHandler.post(new Runnable() {
15292            public void run() {
15293                mHandler.removeCallbacks(this);
15294                 // Result object to be returned
15295                PackageInstalledInfo res = new PackageInstalledInfo();
15296                res.setReturnCode(currentStatus);
15297                res.uid = -1;
15298                res.pkg = null;
15299                res.removedInfo = null;
15300                if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
15301                    args.doPreInstall(res.returnCode);
15302                    synchronized (mInstallLock) {
15303                        installPackageTracedLI(args, res);
15304                    }
15305                    args.doPostInstall(res.returnCode, res.uid);
15306                }
15307
15308                // A restore should be performed at this point if (a) the install
15309                // succeeded, (b) the operation is not an update, and (c) the new
15310                // package has not opted out of backup participation.
15311                final boolean update = res.removedInfo != null
15312                        && res.removedInfo.removedPackage != null;
15313                final int flags = (res.pkg == null) ? 0 : res.pkg.applicationInfo.flags;
15314                boolean doRestore = !update
15315                        && ((flags & ApplicationInfo.FLAG_ALLOW_BACKUP) != 0);
15316
15317                // Set up the post-install work request bookkeeping.  This will be used
15318                // and cleaned up by the post-install event handling regardless of whether
15319                // there's a restore pass performed.  Token values are >= 1.
15320                int token;
15321                if (mNextInstallToken < 0) mNextInstallToken = 1;
15322                token = mNextInstallToken++;
15323
15324                PostInstallData data = new PostInstallData(args, res);
15325                mRunningInstalls.put(token, data);
15326                if (DEBUG_INSTALL) Log.v(TAG, "+ starting restore round-trip " + token);
15327
15328                if (res.returnCode == PackageManager.INSTALL_SUCCEEDED && doRestore) {
15329                    // Pass responsibility to the Backup Manager.  It will perform a
15330                    // restore if appropriate, then pass responsibility back to the
15331                    // Package Manager to run the post-install observer callbacks
15332                    // and broadcasts.
15333                    IBackupManager bm = IBackupManager.Stub.asInterface(
15334                            ServiceManager.getService(Context.BACKUP_SERVICE));
15335                    if (bm != null) {
15336                        if (DEBUG_INSTALL) Log.v(TAG, "token " + token
15337                                + " to BM for possible restore");
15338                        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "restore", token);
15339                        try {
15340                            // TODO: http://b/22388012
15341                            if (bm.isBackupServiceActive(UserHandle.USER_SYSTEM)) {
15342                                bm.restoreAtInstall(res.pkg.applicationInfo.packageName, token);
15343                            } else {
15344                                doRestore = false;
15345                            }
15346                        } catch (RemoteException e) {
15347                            // can't happen; the backup manager is local
15348                        } catch (Exception e) {
15349                            Slog.e(TAG, "Exception trying to enqueue restore", e);
15350                            doRestore = false;
15351                        }
15352                    } else {
15353                        Slog.e(TAG, "Backup Manager not found!");
15354                        doRestore = false;
15355                    }
15356                }
15357
15358                if (!doRestore) {
15359                    // No restore possible, or the Backup Manager was mysteriously not
15360                    // available -- just fire the post-install work request directly.
15361                    if (DEBUG_INSTALL) Log.v(TAG, "No restore - queue post-install for " + token);
15362
15363                    Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "postInstall", token);
15364
15365                    Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0);
15366                    mHandler.sendMessage(msg);
15367                }
15368            }
15369        });
15370    }
15371
15372    /**
15373     * Callback from PackageSettings whenever an app is first transitioned out of the
15374     * 'stopped' state.  Normally we just issue the broadcast, but we can't do that if
15375     * the app was "launched" for a restoreAtInstall operation.  Therefore we check
15376     * here whether the app is the target of an ongoing install, and only send the
15377     * broadcast immediately if it is not in that state.  If it *is* undergoing a restore,
15378     * the first-launch broadcast will be sent implicitly on that basis in POST_INSTALL
15379     * handling.
15380     */
15381    void notifyFirstLaunch(final String pkgName, final String installerPackage, final int userId) {
15382        // Serialize this with the rest of the install-process message chain.  In the
15383        // restore-at-install case, this Runnable will necessarily run before the
15384        // POST_INSTALL message is processed, so the contents of mRunningInstalls
15385        // are coherent.  In the non-restore case, the app has already completed install
15386        // and been launched through some other means, so it is not in a problematic
15387        // state for observers to see the FIRST_LAUNCH signal.
15388        mHandler.post(new Runnable() {
15389            @Override
15390            public void run() {
15391                for (int i = 0; i < mRunningInstalls.size(); i++) {
15392                    final PostInstallData data = mRunningInstalls.valueAt(i);
15393                    if (data.res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
15394                        continue;
15395                    }
15396                    if (pkgName.equals(data.res.pkg.applicationInfo.packageName)) {
15397                        // right package; but is it for the right user?
15398                        for (int uIndex = 0; uIndex < data.res.newUsers.length; uIndex++) {
15399                            if (userId == data.res.newUsers[uIndex]) {
15400                                if (DEBUG_BACKUP) {
15401                                    Slog.i(TAG, "Package " + pkgName
15402                                            + " being restored so deferring FIRST_LAUNCH");
15403                                }
15404                                return;
15405                            }
15406                        }
15407                    }
15408                }
15409                // didn't find it, so not being restored
15410                if (DEBUG_BACKUP) {
15411                    Slog.i(TAG, "Package " + pkgName + " sending normal FIRST_LAUNCH");
15412                }
15413                sendFirstLaunchBroadcast(pkgName, installerPackage, new int[] {userId});
15414            }
15415        });
15416    }
15417
15418    private void sendFirstLaunchBroadcast(String pkgName, String installerPkg, int[] userIds) {
15419        sendPackageBroadcast(Intent.ACTION_PACKAGE_FIRST_LAUNCH, pkgName, null, 0,
15420                installerPkg, null, userIds);
15421    }
15422
15423    private abstract class HandlerParams {
15424        private static final int MAX_RETRIES = 4;
15425
15426        /**
15427         * Number of times startCopy() has been attempted and had a non-fatal
15428         * error.
15429         */
15430        private int mRetries = 0;
15431
15432        /** User handle for the user requesting the information or installation. */
15433        private final UserHandle mUser;
15434        String traceMethod;
15435        int traceCookie;
15436
15437        HandlerParams(UserHandle user) {
15438            mUser = user;
15439        }
15440
15441        UserHandle getUser() {
15442            return mUser;
15443        }
15444
15445        HandlerParams setTraceMethod(String traceMethod) {
15446            this.traceMethod = traceMethod;
15447            return this;
15448        }
15449
15450        HandlerParams setTraceCookie(int traceCookie) {
15451            this.traceCookie = traceCookie;
15452            return this;
15453        }
15454
15455        final boolean startCopy() {
15456            boolean res;
15457            try {
15458                if (DEBUG_INSTALL) Slog.i(TAG, "startCopy " + mUser + ": " + this);
15459
15460                if (++mRetries > MAX_RETRIES) {
15461                    Slog.w(TAG, "Failed to invoke remote methods on default container service. Giving up");
15462                    mHandler.sendEmptyMessage(MCS_GIVE_UP);
15463                    handleServiceError();
15464                    return false;
15465                } else {
15466                    handleStartCopy();
15467                    res = true;
15468                }
15469            } catch (RemoteException e) {
15470                if (DEBUG_INSTALL) Slog.i(TAG, "Posting install MCS_RECONNECT");
15471                mHandler.sendEmptyMessage(MCS_RECONNECT);
15472                res = false;
15473            }
15474            handleReturnCode();
15475            return res;
15476        }
15477
15478        final void serviceError() {
15479            if (DEBUG_INSTALL) Slog.i(TAG, "serviceError");
15480            handleServiceError();
15481            handleReturnCode();
15482        }
15483
15484        abstract void handleStartCopy() throws RemoteException;
15485        abstract void handleServiceError();
15486        abstract void handleReturnCode();
15487    }
15488
15489    private static void clearDirectory(IMediaContainerService mcs, File[] paths) {
15490        for (File path : paths) {
15491            try {
15492                mcs.clearDirectory(path.getAbsolutePath());
15493            } catch (RemoteException e) {
15494            }
15495        }
15496    }
15497
15498    static class OriginInfo {
15499        /**
15500         * Location where install is coming from, before it has been
15501         * copied/renamed into place. This could be a single monolithic APK
15502         * file, or a cluster directory. This location may be untrusted.
15503         */
15504        final File file;
15505        final String cid;
15506
15507        /**
15508         * Flag indicating that {@link #file} or {@link #cid} has already been
15509         * staged, meaning downstream users don't need to defensively copy the
15510         * contents.
15511         */
15512        final boolean staged;
15513
15514        /**
15515         * Flag indicating that {@link #file} or {@link #cid} is an already
15516         * installed app that is being moved.
15517         */
15518        final boolean existing;
15519
15520        final String resolvedPath;
15521        final File resolvedFile;
15522
15523        static OriginInfo fromNothing() {
15524            return new OriginInfo(null, null, false, false);
15525        }
15526
15527        static OriginInfo fromUntrustedFile(File file) {
15528            return new OriginInfo(file, null, false, false);
15529        }
15530
15531        static OriginInfo fromExistingFile(File file) {
15532            return new OriginInfo(file, null, false, true);
15533        }
15534
15535        static OriginInfo fromStagedFile(File file) {
15536            return new OriginInfo(file, null, true, false);
15537        }
15538
15539        static OriginInfo fromStagedContainer(String cid) {
15540            return new OriginInfo(null, cid, true, false);
15541        }
15542
15543        private OriginInfo(File file, String cid, boolean staged, boolean existing) {
15544            this.file = file;
15545            this.cid = cid;
15546            this.staged = staged;
15547            this.existing = existing;
15548
15549            if (cid != null) {
15550                resolvedPath = PackageHelper.getSdDir(cid);
15551                resolvedFile = new File(resolvedPath);
15552            } else if (file != null) {
15553                resolvedPath = file.getAbsolutePath();
15554                resolvedFile = file;
15555            } else {
15556                resolvedPath = null;
15557                resolvedFile = null;
15558            }
15559        }
15560    }
15561
15562    static class MoveInfo {
15563        final int moveId;
15564        final String fromUuid;
15565        final String toUuid;
15566        final String packageName;
15567        final String dataAppName;
15568        final int appId;
15569        final String seinfo;
15570        final int targetSdkVersion;
15571
15572        public MoveInfo(int moveId, String fromUuid, String toUuid, String packageName,
15573                String dataAppName, int appId, String seinfo, int targetSdkVersion) {
15574            this.moveId = moveId;
15575            this.fromUuid = fromUuid;
15576            this.toUuid = toUuid;
15577            this.packageName = packageName;
15578            this.dataAppName = dataAppName;
15579            this.appId = appId;
15580            this.seinfo = seinfo;
15581            this.targetSdkVersion = targetSdkVersion;
15582        }
15583    }
15584
15585    static class VerificationInfo {
15586        /** A constant used to indicate that a uid value is not present. */
15587        public static final int NO_UID = -1;
15588
15589        /** URI referencing where the package was downloaded from. */
15590        final Uri originatingUri;
15591
15592        /** HTTP referrer URI associated with the originatingURI. */
15593        final Uri referrer;
15594
15595        /** UID of the application that the install request originated from. */
15596        final int originatingUid;
15597
15598        /** UID of application requesting the install */
15599        final int installerUid;
15600
15601        VerificationInfo(Uri originatingUri, Uri referrer, int originatingUid, int installerUid) {
15602            this.originatingUri = originatingUri;
15603            this.referrer = referrer;
15604            this.originatingUid = originatingUid;
15605            this.installerUid = installerUid;
15606        }
15607    }
15608
15609    class InstallParams extends HandlerParams {
15610        final OriginInfo origin;
15611        final MoveInfo move;
15612        final IPackageInstallObserver2 observer;
15613        int installFlags;
15614        final String installerPackageName;
15615        final String volumeUuid;
15616        private InstallArgs mArgs;
15617        private int mRet;
15618        final String packageAbiOverride;
15619        final String[] grantedRuntimePermissions;
15620        final VerificationInfo verificationInfo;
15621        final Certificate[][] certificates;
15622        final int installReason;
15623
15624        InstallParams(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer,
15625                int installFlags, String installerPackageName, String volumeUuid,
15626                VerificationInfo verificationInfo, UserHandle user, String packageAbiOverride,
15627                String[] grantedPermissions, Certificate[][] certificates, int installReason) {
15628            super(user);
15629            this.origin = origin;
15630            this.move = move;
15631            this.observer = observer;
15632            this.installFlags = installFlags;
15633            this.installerPackageName = installerPackageName;
15634            this.volumeUuid = volumeUuid;
15635            this.verificationInfo = verificationInfo;
15636            this.packageAbiOverride = packageAbiOverride;
15637            this.grantedRuntimePermissions = grantedPermissions;
15638            this.certificates = certificates;
15639            this.installReason = installReason;
15640        }
15641
15642        @Override
15643        public String toString() {
15644            return "InstallParams{" + Integer.toHexString(System.identityHashCode(this))
15645                    + " file=" + origin.file + " cid=" + origin.cid + "}";
15646        }
15647
15648        private int installLocationPolicy(PackageInfoLite pkgLite) {
15649            String packageName = pkgLite.packageName;
15650            int installLocation = pkgLite.installLocation;
15651            boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
15652            // reader
15653            synchronized (mPackages) {
15654                // Currently installed package which the new package is attempting to replace or
15655                // null if no such package is installed.
15656                PackageParser.Package installedPkg = mPackages.get(packageName);
15657                // Package which currently owns the data which the new package will own if installed.
15658                // If an app is unstalled while keeping data (e.g., adb uninstall -k), installedPkg
15659                // will be null whereas dataOwnerPkg will contain information about the package
15660                // which was uninstalled while keeping its data.
15661                PackageParser.Package dataOwnerPkg = installedPkg;
15662                if (dataOwnerPkg  == null) {
15663                    PackageSetting ps = mSettings.mPackages.get(packageName);
15664                    if (ps != null) {
15665                        dataOwnerPkg = ps.pkg;
15666                    }
15667                }
15668
15669                if (dataOwnerPkg != null) {
15670                    // If installed, the package will get access to data left on the device by its
15671                    // predecessor. As a security measure, this is permited only if this is not a
15672                    // version downgrade or if the predecessor package is marked as debuggable and
15673                    // a downgrade is explicitly requested.
15674                    //
15675                    // On debuggable platform builds, downgrades are permitted even for
15676                    // non-debuggable packages to make testing easier. Debuggable platform builds do
15677                    // not offer security guarantees and thus it's OK to disable some security
15678                    // mechanisms to make debugging/testing easier on those builds. However, even on
15679                    // debuggable builds downgrades of packages are permitted only if requested via
15680                    // installFlags. This is because we aim to keep the behavior of debuggable
15681                    // platform builds as close as possible to the behavior of non-debuggable
15682                    // platform builds.
15683                    final boolean downgradeRequested =
15684                            (installFlags & PackageManager.INSTALL_ALLOW_DOWNGRADE) != 0;
15685                    final boolean packageDebuggable =
15686                                (dataOwnerPkg.applicationInfo.flags
15687                                        & ApplicationInfo.FLAG_DEBUGGABLE) != 0;
15688                    final boolean downgradePermitted =
15689                            (downgradeRequested) && ((Build.IS_DEBUGGABLE) || (packageDebuggable));
15690                    if (!downgradePermitted) {
15691                        try {
15692                            checkDowngrade(dataOwnerPkg, pkgLite);
15693                        } catch (PackageManagerException e) {
15694                            Slog.w(TAG, "Downgrade detected: " + e.getMessage());
15695                            return PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE;
15696                        }
15697                    }
15698                }
15699
15700                if (installedPkg != null) {
15701                    if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
15702                        // Check for updated system application.
15703                        if ((installedPkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
15704                            if (onSd) {
15705                                Slog.w(TAG, "Cannot install update to system app on sdcard");
15706                                return PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION;
15707                            }
15708                            return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
15709                        } else {
15710                            if (onSd) {
15711                                // Install flag overrides everything.
15712                                return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
15713                            }
15714                            // If current upgrade specifies particular preference
15715                            if (installLocation == PackageInfo.INSTALL_LOCATION_INTERNAL_ONLY) {
15716                                // Application explicitly specified internal.
15717                                return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
15718                            } else if (installLocation == PackageInfo.INSTALL_LOCATION_PREFER_EXTERNAL) {
15719                                // App explictly prefers external. Let policy decide
15720                            } else {
15721                                // Prefer previous location
15722                                if (isExternal(installedPkg)) {
15723                                    return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
15724                                }
15725                                return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
15726                            }
15727                        }
15728                    } else {
15729                        // Invalid install. Return error code
15730                        return PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS;
15731                    }
15732                }
15733            }
15734            // All the special cases have been taken care of.
15735            // Return result based on recommended install location.
15736            if (onSd) {
15737                return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
15738            }
15739            return pkgLite.recommendedInstallLocation;
15740        }
15741
15742        /*
15743         * Invoke remote method to get package information and install
15744         * location values. Override install location based on default
15745         * policy if needed and then create install arguments based
15746         * on the install location.
15747         */
15748        public void handleStartCopy() throws RemoteException {
15749            int ret = PackageManager.INSTALL_SUCCEEDED;
15750
15751            // If we're already staged, we've firmly committed to an install location
15752            if (origin.staged) {
15753                if (origin.file != null) {
15754                    installFlags |= PackageManager.INSTALL_INTERNAL;
15755                    installFlags &= ~PackageManager.INSTALL_EXTERNAL;
15756                } else if (origin.cid != null) {
15757                    installFlags |= PackageManager.INSTALL_EXTERNAL;
15758                    installFlags &= ~PackageManager.INSTALL_INTERNAL;
15759                } else {
15760                    throw new IllegalStateException("Invalid stage location");
15761                }
15762            }
15763
15764            final boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
15765            final boolean onInt = (installFlags & PackageManager.INSTALL_INTERNAL) != 0;
15766            final boolean ephemeral = (installFlags & PackageManager.INSTALL_INSTANT_APP) != 0;
15767            PackageInfoLite pkgLite = null;
15768
15769            if (onInt && onSd) {
15770                // Check if both bits are set.
15771                Slog.w(TAG, "Conflicting flags specified for installing on both internal and external");
15772                ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
15773            } else if (onSd && ephemeral) {
15774                Slog.w(TAG,  "Conflicting flags specified for installing ephemeral on external");
15775                ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
15776            } else {
15777                pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, installFlags,
15778                        packageAbiOverride);
15779
15780                if (DEBUG_EPHEMERAL && ephemeral) {
15781                    Slog.v(TAG, "pkgLite for install: " + pkgLite);
15782                }
15783
15784                /*
15785                 * If we have too little free space, try to free cache
15786                 * before giving up.
15787                 */
15788                if (!origin.staged && pkgLite.recommendedInstallLocation
15789                        == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) {
15790                    // TODO: focus freeing disk space on the target device
15791                    final StorageManager storage = StorageManager.from(mContext);
15792                    final long lowThreshold = storage.getStorageLowBytes(
15793                            Environment.getDataDirectory());
15794
15795                    final long sizeBytes = mContainerService.calculateInstalledSize(
15796                            origin.resolvedPath, isForwardLocked(), packageAbiOverride);
15797
15798                    try {
15799                        mInstaller.freeCache(null, sizeBytes + lowThreshold, 0, 0);
15800                        pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath,
15801                                installFlags, packageAbiOverride);
15802                    } catch (InstallerException e) {
15803                        Slog.w(TAG, "Failed to free cache", e);
15804                    }
15805
15806                    /*
15807                     * The cache free must have deleted the file we
15808                     * downloaded to install.
15809                     *
15810                     * TODO: fix the "freeCache" call to not delete
15811                     *       the file we care about.
15812                     */
15813                    if (pkgLite.recommendedInstallLocation
15814                            == PackageHelper.RECOMMEND_FAILED_INVALID_URI) {
15815                        pkgLite.recommendedInstallLocation
15816                            = PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE;
15817                    }
15818                }
15819            }
15820
15821            if (ret == PackageManager.INSTALL_SUCCEEDED) {
15822                int loc = pkgLite.recommendedInstallLocation;
15823                if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION) {
15824                    ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
15825                } else if (loc == PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS) {
15826                    ret = PackageManager.INSTALL_FAILED_ALREADY_EXISTS;
15827                } else if (loc == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) {
15828                    ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
15829                } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_APK) {
15830                    ret = PackageManager.INSTALL_FAILED_INVALID_APK;
15831                } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_URI) {
15832                    ret = PackageManager.INSTALL_FAILED_INVALID_URI;
15833                } else if (loc == PackageHelper.RECOMMEND_MEDIA_UNAVAILABLE) {
15834                    ret = PackageManager.INSTALL_FAILED_MEDIA_UNAVAILABLE;
15835                } else {
15836                    // Override with defaults if needed.
15837                    loc = installLocationPolicy(pkgLite);
15838                    if (loc == PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE) {
15839                        ret = PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE;
15840                    } else if (!onSd && !onInt) {
15841                        // Override install location with flags
15842                        if (loc == PackageHelper.RECOMMEND_INSTALL_EXTERNAL) {
15843                            // Set the flag to install on external media.
15844                            installFlags |= PackageManager.INSTALL_EXTERNAL;
15845                            installFlags &= ~PackageManager.INSTALL_INTERNAL;
15846                        } else if (loc == PackageHelper.RECOMMEND_INSTALL_EPHEMERAL) {
15847                            if (DEBUG_EPHEMERAL) {
15848                                Slog.v(TAG, "...setting INSTALL_EPHEMERAL install flag");
15849                            }
15850                            installFlags |= PackageManager.INSTALL_INSTANT_APP;
15851                            installFlags &= ~(PackageManager.INSTALL_EXTERNAL
15852                                    |PackageManager.INSTALL_INTERNAL);
15853                        } else {
15854                            // Make sure the flag for installing on external
15855                            // media is unset
15856                            installFlags |= PackageManager.INSTALL_INTERNAL;
15857                            installFlags &= ~PackageManager.INSTALL_EXTERNAL;
15858                        }
15859                    }
15860                }
15861            }
15862
15863            final InstallArgs args = createInstallArgs(this);
15864            mArgs = args;
15865
15866            if (ret == PackageManager.INSTALL_SUCCEEDED) {
15867                // TODO: http://b/22976637
15868                // Apps installed for "all" users use the device owner to verify the app
15869                UserHandle verifierUser = getUser();
15870                if (verifierUser == UserHandle.ALL) {
15871                    verifierUser = UserHandle.SYSTEM;
15872                }
15873
15874                /*
15875                 * Determine if we have any installed package verifiers. If we
15876                 * do, then we'll defer to them to verify the packages.
15877                 */
15878                final int requiredUid = mRequiredVerifierPackage == null ? -1
15879                        : getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING,
15880                                verifierUser.getIdentifier());
15881                final int installerUid =
15882                        verificationInfo == null ? -1 : verificationInfo.installerUid;
15883                if (!origin.existing && requiredUid != -1
15884                        && isVerificationEnabled(
15885                                verifierUser.getIdentifier(), installFlags, installerUid)) {
15886                    final Intent verification = new Intent(
15887                            Intent.ACTION_PACKAGE_NEEDS_VERIFICATION);
15888                    verification.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
15889                    verification.setDataAndType(Uri.fromFile(new File(origin.resolvedPath)),
15890                            PACKAGE_MIME_TYPE);
15891                    verification.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
15892
15893                    // Query all live verifiers based on current user state
15894                    final List<ResolveInfo> receivers = queryIntentReceiversInternal(verification,
15895                            PACKAGE_MIME_TYPE, 0, verifierUser.getIdentifier());
15896
15897                    if (DEBUG_VERIFY) {
15898                        Slog.d(TAG, "Found " + receivers.size() + " verifiers for intent "
15899                                + verification.toString() + " with " + pkgLite.verifiers.length
15900                                + " optional verifiers");
15901                    }
15902
15903                    final int verificationId = mPendingVerificationToken++;
15904
15905                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId);
15906
15907                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_PACKAGE,
15908                            installerPackageName);
15909
15910                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALL_FLAGS,
15911                            installFlags);
15912
15913                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_PACKAGE_NAME,
15914                            pkgLite.packageName);
15915
15916                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_VERSION_CODE,
15917                            pkgLite.versionCode);
15918
15919                    if (verificationInfo != null) {
15920                        if (verificationInfo.originatingUri != null) {
15921                            verification.putExtra(Intent.EXTRA_ORIGINATING_URI,
15922                                    verificationInfo.originatingUri);
15923                        }
15924                        if (verificationInfo.referrer != null) {
15925                            verification.putExtra(Intent.EXTRA_REFERRER,
15926                                    verificationInfo.referrer);
15927                        }
15928                        if (verificationInfo.originatingUid >= 0) {
15929                            verification.putExtra(Intent.EXTRA_ORIGINATING_UID,
15930                                    verificationInfo.originatingUid);
15931                        }
15932                        if (verificationInfo.installerUid >= 0) {
15933                            verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_UID,
15934                                    verificationInfo.installerUid);
15935                        }
15936                    }
15937
15938                    final PackageVerificationState verificationState = new PackageVerificationState(
15939                            requiredUid, args);
15940
15941                    mPendingVerification.append(verificationId, verificationState);
15942
15943                    final List<ComponentName> sufficientVerifiers = matchVerifiers(pkgLite,
15944                            receivers, verificationState);
15945
15946                    DeviceIdleController.LocalService idleController = getDeviceIdleController();
15947                    final long idleDuration = getVerificationTimeout();
15948
15949                    /*
15950                     * If any sufficient verifiers were listed in the package
15951                     * manifest, attempt to ask them.
15952                     */
15953                    if (sufficientVerifiers != null) {
15954                        final int N = sufficientVerifiers.size();
15955                        if (N == 0) {
15956                            Slog.i(TAG, "Additional verifiers required, but none installed.");
15957                            ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
15958                        } else {
15959                            for (int i = 0; i < N; i++) {
15960                                final ComponentName verifierComponent = sufficientVerifiers.get(i);
15961                                idleController.addPowerSaveTempWhitelistApp(Process.myUid(),
15962                                        verifierComponent.getPackageName(), idleDuration,
15963                                        verifierUser.getIdentifier(), false, "package verifier");
15964
15965                                final Intent sufficientIntent = new Intent(verification);
15966                                sufficientIntent.setComponent(verifierComponent);
15967                                mContext.sendBroadcastAsUser(sufficientIntent, verifierUser);
15968                            }
15969                        }
15970                    }
15971
15972                    final ComponentName requiredVerifierComponent = matchComponentForVerifier(
15973                            mRequiredVerifierPackage, receivers);
15974                    if (ret == PackageManager.INSTALL_SUCCEEDED
15975                            && mRequiredVerifierPackage != null) {
15976                        Trace.asyncTraceBegin(
15977                                TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId);
15978                        /*
15979                         * Send the intent to the required verification agent,
15980                         * but only start the verification timeout after the
15981                         * target BroadcastReceivers have run.
15982                         */
15983                        verification.setComponent(requiredVerifierComponent);
15984                        idleController.addPowerSaveTempWhitelistApp(Process.myUid(),
15985                                mRequiredVerifierPackage, idleDuration,
15986                                verifierUser.getIdentifier(), false, "package verifier");
15987                        mContext.sendOrderedBroadcastAsUser(verification, verifierUser,
15988                                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
15989                                new BroadcastReceiver() {
15990                                    @Override
15991                                    public void onReceive(Context context, Intent intent) {
15992                                        final Message msg = mHandler
15993                                                .obtainMessage(CHECK_PENDING_VERIFICATION);
15994                                        msg.arg1 = verificationId;
15995                                        mHandler.sendMessageDelayed(msg, getVerificationTimeout());
15996                                    }
15997                                }, null, 0, null, null);
15998
15999                        /*
16000                         * We don't want the copy to proceed until verification
16001                         * succeeds, so null out this field.
16002                         */
16003                        mArgs = null;
16004                    }
16005                } else {
16006                    /*
16007                     * No package verification is enabled, so immediately start
16008                     * the remote call to initiate copy using temporary file.
16009                     */
16010                    ret = args.copyApk(mContainerService, true);
16011                }
16012            }
16013
16014            mRet = ret;
16015        }
16016
16017        @Override
16018        void handleReturnCode() {
16019            // If mArgs is null, then MCS couldn't be reached. When it
16020            // reconnects, it will try again to install. At that point, this
16021            // will succeed.
16022            if (mArgs != null) {
16023                processPendingInstall(mArgs, mRet);
16024            }
16025        }
16026
16027        @Override
16028        void handleServiceError() {
16029            mArgs = createInstallArgs(this);
16030            mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
16031        }
16032
16033        public boolean isForwardLocked() {
16034            return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
16035        }
16036    }
16037
16038    /**
16039     * Used during creation of InstallArgs
16040     *
16041     * @param installFlags package installation flags
16042     * @return true if should be installed on external storage
16043     */
16044    private static boolean installOnExternalAsec(int installFlags) {
16045        if ((installFlags & PackageManager.INSTALL_INTERNAL) != 0) {
16046            return false;
16047        }
16048        if ((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) {
16049            return true;
16050        }
16051        return false;
16052    }
16053
16054    /**
16055     * Used during creation of InstallArgs
16056     *
16057     * @param installFlags package installation flags
16058     * @return true if should be installed as forward locked
16059     */
16060    private static boolean installForwardLocked(int installFlags) {
16061        return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
16062    }
16063
16064    private InstallArgs createInstallArgs(InstallParams params) {
16065        if (params.move != null) {
16066            return new MoveInstallArgs(params);
16067        } else if (installOnExternalAsec(params.installFlags) || params.isForwardLocked()) {
16068            return new AsecInstallArgs(params);
16069        } else {
16070            return new FileInstallArgs(params);
16071        }
16072    }
16073
16074    /**
16075     * Create args that describe an existing installed package. Typically used
16076     * when cleaning up old installs, or used as a move source.
16077     */
16078    private InstallArgs createInstallArgsForExisting(int installFlags, String codePath,
16079            String resourcePath, String[] instructionSets) {
16080        final boolean isInAsec;
16081        if (installOnExternalAsec(installFlags)) {
16082            /* Apps on SD card are always in ASEC containers. */
16083            isInAsec = true;
16084        } else if (installForwardLocked(installFlags)
16085                && !codePath.startsWith(mDrmAppPrivateInstallDir.getAbsolutePath())) {
16086            /*
16087             * Forward-locked apps are only in ASEC containers if they're the
16088             * new style
16089             */
16090            isInAsec = true;
16091        } else {
16092            isInAsec = false;
16093        }
16094
16095        if (isInAsec) {
16096            return new AsecInstallArgs(codePath, instructionSets,
16097                    installOnExternalAsec(installFlags), installForwardLocked(installFlags));
16098        } else {
16099            return new FileInstallArgs(codePath, resourcePath, instructionSets);
16100        }
16101    }
16102
16103    static abstract class InstallArgs {
16104        /** @see InstallParams#origin */
16105        final OriginInfo origin;
16106        /** @see InstallParams#move */
16107        final MoveInfo move;
16108
16109        final IPackageInstallObserver2 observer;
16110        // Always refers to PackageManager flags only
16111        final int installFlags;
16112        final String installerPackageName;
16113        final String volumeUuid;
16114        final UserHandle user;
16115        final String abiOverride;
16116        final String[] installGrantPermissions;
16117        /** If non-null, drop an async trace when the install completes */
16118        final String traceMethod;
16119        final int traceCookie;
16120        final Certificate[][] certificates;
16121        final int installReason;
16122
16123        // The list of instruction sets supported by this app. This is currently
16124        // only used during the rmdex() phase to clean up resources. We can get rid of this
16125        // if we move dex files under the common app path.
16126        /* nullable */ String[] instructionSets;
16127
16128        InstallArgs(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer,
16129                int installFlags, String installerPackageName, String volumeUuid,
16130                UserHandle user, String[] instructionSets,
16131                String abiOverride, String[] installGrantPermissions,
16132                String traceMethod, int traceCookie, Certificate[][] certificates,
16133                int installReason) {
16134            this.origin = origin;
16135            this.move = move;
16136            this.installFlags = installFlags;
16137            this.observer = observer;
16138            this.installerPackageName = installerPackageName;
16139            this.volumeUuid = volumeUuid;
16140            this.user = user;
16141            this.instructionSets = instructionSets;
16142            this.abiOverride = abiOverride;
16143            this.installGrantPermissions = installGrantPermissions;
16144            this.traceMethod = traceMethod;
16145            this.traceCookie = traceCookie;
16146            this.certificates = certificates;
16147            this.installReason = installReason;
16148        }
16149
16150        abstract int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException;
16151        abstract int doPreInstall(int status);
16152
16153        /**
16154         * Rename package into final resting place. All paths on the given
16155         * scanned package should be updated to reflect the rename.
16156         */
16157        abstract boolean doRename(int status, PackageParser.Package pkg, String oldCodePath);
16158        abstract int doPostInstall(int status, int uid);
16159
16160        /** @see PackageSettingBase#codePathString */
16161        abstract String getCodePath();
16162        /** @see PackageSettingBase#resourcePathString */
16163        abstract String getResourcePath();
16164
16165        // Need installer lock especially for dex file removal.
16166        abstract void cleanUpResourcesLI();
16167        abstract boolean doPostDeleteLI(boolean delete);
16168
16169        /**
16170         * Called before the source arguments are copied. This is used mostly
16171         * for MoveParams when it needs to read the source file to put it in the
16172         * destination.
16173         */
16174        int doPreCopy() {
16175            return PackageManager.INSTALL_SUCCEEDED;
16176        }
16177
16178        /**
16179         * Called after the source arguments are copied. This is used mostly for
16180         * MoveParams when it needs to read the source file to put it in the
16181         * destination.
16182         */
16183        int doPostCopy(int uid) {
16184            return PackageManager.INSTALL_SUCCEEDED;
16185        }
16186
16187        protected boolean isFwdLocked() {
16188            return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
16189        }
16190
16191        protected boolean isExternalAsec() {
16192            return (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
16193        }
16194
16195        protected boolean isEphemeral() {
16196            return (installFlags & PackageManager.INSTALL_INSTANT_APP) != 0;
16197        }
16198
16199        UserHandle getUser() {
16200            return user;
16201        }
16202    }
16203
16204    void removeDexFiles(List<String> allCodePaths, String[] instructionSets) {
16205        if (!allCodePaths.isEmpty()) {
16206            if (instructionSets == null) {
16207                throw new IllegalStateException("instructionSet == null");
16208            }
16209            String[] dexCodeInstructionSets = getDexCodeInstructionSets(instructionSets);
16210            for (String codePath : allCodePaths) {
16211                for (String dexCodeInstructionSet : dexCodeInstructionSets) {
16212                    try {
16213                        mInstaller.rmdex(codePath, dexCodeInstructionSet);
16214                    } catch (InstallerException ignored) {
16215                    }
16216                }
16217            }
16218        }
16219    }
16220
16221    /**
16222     * Logic to handle installation of non-ASEC applications, including copying
16223     * and renaming logic.
16224     */
16225    class FileInstallArgs extends InstallArgs {
16226        private File codeFile;
16227        private File resourceFile;
16228
16229        // Example topology:
16230        // /data/app/com.example/base.apk
16231        // /data/app/com.example/split_foo.apk
16232        // /data/app/com.example/lib/arm/libfoo.so
16233        // /data/app/com.example/lib/arm64/libfoo.so
16234        // /data/app/com.example/dalvik/arm/base.apk@classes.dex
16235
16236        /** New install */
16237        FileInstallArgs(InstallParams params) {
16238            super(params.origin, params.move, params.observer, params.installFlags,
16239                    params.installerPackageName, params.volumeUuid,
16240                    params.getUser(), null /*instructionSets*/, params.packageAbiOverride,
16241                    params.grantedRuntimePermissions,
16242                    params.traceMethod, params.traceCookie, params.certificates,
16243                    params.installReason);
16244            if (isFwdLocked()) {
16245                throw new IllegalArgumentException("Forward locking only supported in ASEC");
16246            }
16247        }
16248
16249        /** Existing install */
16250        FileInstallArgs(String codePath, String resourcePath, String[] instructionSets) {
16251            super(OriginInfo.fromNothing(), null, null, 0, null, null, null, instructionSets,
16252                    null, null, null, 0, null /*certificates*/,
16253                    PackageManager.INSTALL_REASON_UNKNOWN);
16254            this.codeFile = (codePath != null) ? new File(codePath) : null;
16255            this.resourceFile = (resourcePath != null) ? new File(resourcePath) : null;
16256        }
16257
16258        int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
16259            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyApk");
16260            try {
16261                return doCopyApk(imcs, temp);
16262            } finally {
16263                Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
16264            }
16265        }
16266
16267        private int doCopyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
16268            if (origin.staged) {
16269                if (DEBUG_INSTALL) Slog.d(TAG, origin.file + " already staged; skipping copy");
16270                codeFile = origin.file;
16271                resourceFile = origin.file;
16272                return PackageManager.INSTALL_SUCCEEDED;
16273            }
16274
16275            try {
16276                final boolean isEphemeral = (installFlags & PackageManager.INSTALL_INSTANT_APP) != 0;
16277                final File tempDir =
16278                        mInstallerService.allocateStageDirLegacy(volumeUuid, isEphemeral);
16279                codeFile = tempDir;
16280                resourceFile = tempDir;
16281            } catch (IOException e) {
16282                Slog.w(TAG, "Failed to create copy file: " + e);
16283                return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
16284            }
16285
16286            final IParcelFileDescriptorFactory target = new IParcelFileDescriptorFactory.Stub() {
16287                @Override
16288                public ParcelFileDescriptor open(String name, int mode) throws RemoteException {
16289                    if (!FileUtils.isValidExtFilename(name)) {
16290                        throw new IllegalArgumentException("Invalid filename: " + name);
16291                    }
16292                    try {
16293                        final File file = new File(codeFile, name);
16294                        final FileDescriptor fd = Os.open(file.getAbsolutePath(),
16295                                O_RDWR | O_CREAT, 0644);
16296                        Os.chmod(file.getAbsolutePath(), 0644);
16297                        return new ParcelFileDescriptor(fd);
16298                    } catch (ErrnoException e) {
16299                        throw new RemoteException("Failed to open: " + e.getMessage());
16300                    }
16301                }
16302            };
16303
16304            int ret = PackageManager.INSTALL_SUCCEEDED;
16305            ret = imcs.copyPackage(origin.file.getAbsolutePath(), target);
16306            if (ret != PackageManager.INSTALL_SUCCEEDED) {
16307                Slog.e(TAG, "Failed to copy package");
16308                return ret;
16309            }
16310
16311            final File libraryRoot = new File(codeFile, LIB_DIR_NAME);
16312            NativeLibraryHelper.Handle handle = null;
16313            try {
16314                handle = NativeLibraryHelper.Handle.create(codeFile);
16315                ret = NativeLibraryHelper.copyNativeBinariesWithOverride(handle, libraryRoot,
16316                        abiOverride);
16317            } catch (IOException e) {
16318                Slog.e(TAG, "Copying native libraries failed", e);
16319                ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
16320            } finally {
16321                IoUtils.closeQuietly(handle);
16322            }
16323
16324            return ret;
16325        }
16326
16327        int doPreInstall(int status) {
16328            if (status != PackageManager.INSTALL_SUCCEEDED) {
16329                cleanUp();
16330            }
16331            return status;
16332        }
16333
16334        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
16335            if (status != PackageManager.INSTALL_SUCCEEDED) {
16336                cleanUp();
16337                return false;
16338            }
16339
16340            final File targetDir = codeFile.getParentFile();
16341            final File beforeCodeFile = codeFile;
16342            final File afterCodeFile = getNextCodePath(targetDir, pkg.packageName);
16343
16344            if (DEBUG_INSTALL) Slog.d(TAG, "Renaming " + beforeCodeFile + " to " + afterCodeFile);
16345            try {
16346                Os.rename(beforeCodeFile.getAbsolutePath(), afterCodeFile.getAbsolutePath());
16347            } catch (ErrnoException e) {
16348                Slog.w(TAG, "Failed to rename", e);
16349                return false;
16350            }
16351
16352            if (!SELinux.restoreconRecursive(afterCodeFile)) {
16353                Slog.w(TAG, "Failed to restorecon");
16354                return false;
16355            }
16356
16357            // Reflect the rename internally
16358            codeFile = afterCodeFile;
16359            resourceFile = afterCodeFile;
16360
16361            // Reflect the rename in scanned details
16362            pkg.setCodePath(afterCodeFile.getAbsolutePath());
16363            pkg.setBaseCodePath(FileUtils.rewriteAfterRename(beforeCodeFile,
16364                    afterCodeFile, pkg.baseCodePath));
16365            pkg.setSplitCodePaths(FileUtils.rewriteAfterRename(beforeCodeFile,
16366                    afterCodeFile, pkg.splitCodePaths));
16367
16368            // Reflect the rename in app info
16369            pkg.setApplicationVolumeUuid(pkg.volumeUuid);
16370            pkg.setApplicationInfoCodePath(pkg.codePath);
16371            pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
16372            pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
16373            pkg.setApplicationInfoResourcePath(pkg.codePath);
16374            pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath);
16375            pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
16376
16377            return true;
16378        }
16379
16380        int doPostInstall(int status, int uid) {
16381            if (status != PackageManager.INSTALL_SUCCEEDED) {
16382                cleanUp();
16383            }
16384            return status;
16385        }
16386
16387        @Override
16388        String getCodePath() {
16389            return (codeFile != null) ? codeFile.getAbsolutePath() : null;
16390        }
16391
16392        @Override
16393        String getResourcePath() {
16394            return (resourceFile != null) ? resourceFile.getAbsolutePath() : null;
16395        }
16396
16397        private boolean cleanUp() {
16398            if (codeFile == null || !codeFile.exists()) {
16399                return false;
16400            }
16401
16402            removeCodePathLI(codeFile);
16403
16404            if (resourceFile != null && !FileUtils.contains(codeFile, resourceFile)) {
16405                resourceFile.delete();
16406            }
16407
16408            return true;
16409        }
16410
16411        void cleanUpResourcesLI() {
16412            // Try enumerating all code paths before deleting
16413            List<String> allCodePaths = Collections.EMPTY_LIST;
16414            if (codeFile != null && codeFile.exists()) {
16415                try {
16416                    final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0);
16417                    allCodePaths = pkg.getAllCodePaths();
16418                } catch (PackageParserException e) {
16419                    // Ignored; we tried our best
16420                }
16421            }
16422
16423            cleanUp();
16424            removeDexFiles(allCodePaths, instructionSets);
16425        }
16426
16427        boolean doPostDeleteLI(boolean delete) {
16428            // XXX err, shouldn't we respect the delete flag?
16429            cleanUpResourcesLI();
16430            return true;
16431        }
16432    }
16433
16434    private boolean isAsecExternal(String cid) {
16435        final String asecPath = PackageHelper.getSdFilesystem(cid);
16436        return !asecPath.startsWith(mAsecInternalPath);
16437    }
16438
16439    private static void maybeThrowExceptionForMultiArchCopy(String message, int copyRet) throws
16440            PackageManagerException {
16441        if (copyRet < 0) {
16442            if (copyRet != PackageManager.NO_NATIVE_LIBRARIES &&
16443                    copyRet != PackageManager.INSTALL_FAILED_NO_MATCHING_ABIS) {
16444                throw new PackageManagerException(copyRet, message);
16445            }
16446        }
16447    }
16448
16449    /**
16450     * Extract the StorageManagerService "container ID" from the full code path of an
16451     * .apk.
16452     */
16453    static String cidFromCodePath(String fullCodePath) {
16454        int eidx = fullCodePath.lastIndexOf("/");
16455        String subStr1 = fullCodePath.substring(0, eidx);
16456        int sidx = subStr1.lastIndexOf("/");
16457        return subStr1.substring(sidx+1, eidx);
16458    }
16459
16460    /**
16461     * Logic to handle installation of ASEC applications, including copying and
16462     * renaming logic.
16463     */
16464    class AsecInstallArgs extends InstallArgs {
16465        static final String RES_FILE_NAME = "pkg.apk";
16466        static final String PUBLIC_RES_FILE_NAME = "res.zip";
16467
16468        String cid;
16469        String packagePath;
16470        String resourcePath;
16471
16472        /** New install */
16473        AsecInstallArgs(InstallParams params) {
16474            super(params.origin, params.move, params.observer, params.installFlags,
16475                    params.installerPackageName, params.volumeUuid,
16476                    params.getUser(), null /* instruction sets */, params.packageAbiOverride,
16477                    params.grantedRuntimePermissions,
16478                    params.traceMethod, params.traceCookie, params.certificates,
16479                    params.installReason);
16480        }
16481
16482        /** Existing install */
16483        AsecInstallArgs(String fullCodePath, String[] instructionSets,
16484                        boolean isExternal, boolean isForwardLocked) {
16485            super(OriginInfo.fromNothing(), null, null, (isExternal ? INSTALL_EXTERNAL : 0)
16486                    | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null,
16487                    instructionSets, null, null, null, 0, null /*certificates*/,
16488                    PackageManager.INSTALL_REASON_UNKNOWN);
16489            // Hackily pretend we're still looking at a full code path
16490            if (!fullCodePath.endsWith(RES_FILE_NAME)) {
16491                fullCodePath = new File(fullCodePath, RES_FILE_NAME).getAbsolutePath();
16492            }
16493
16494            // Extract cid from fullCodePath
16495            int eidx = fullCodePath.lastIndexOf("/");
16496            String subStr1 = fullCodePath.substring(0, eidx);
16497            int sidx = subStr1.lastIndexOf("/");
16498            cid = subStr1.substring(sidx+1, eidx);
16499            setMountPath(subStr1);
16500        }
16501
16502        AsecInstallArgs(String cid, String[] instructionSets, boolean isForwardLocked) {
16503            super(OriginInfo.fromNothing(), null, null, (isAsecExternal(cid) ? INSTALL_EXTERNAL : 0)
16504                    | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null,
16505                    instructionSets, null, null, null, 0, null /*certificates*/,
16506                    PackageManager.INSTALL_REASON_UNKNOWN);
16507            this.cid = cid;
16508            setMountPath(PackageHelper.getSdDir(cid));
16509        }
16510
16511        void createCopyFile() {
16512            cid = mInstallerService.allocateExternalStageCidLegacy();
16513        }
16514
16515        int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
16516            if (origin.staged && origin.cid != null) {
16517                if (DEBUG_INSTALL) Slog.d(TAG, origin.cid + " already staged; skipping copy");
16518                cid = origin.cid;
16519                setMountPath(PackageHelper.getSdDir(cid));
16520                return PackageManager.INSTALL_SUCCEEDED;
16521            }
16522
16523            if (temp) {
16524                createCopyFile();
16525            } else {
16526                /*
16527                 * Pre-emptively destroy the container since it's destroyed if
16528                 * copying fails due to it existing anyway.
16529                 */
16530                PackageHelper.destroySdDir(cid);
16531            }
16532
16533            final String newMountPath = imcs.copyPackageToContainer(
16534                    origin.file.getAbsolutePath(), cid, getEncryptKey(), isExternalAsec(),
16535                    isFwdLocked(), deriveAbiOverride(abiOverride, null /* settings */));
16536
16537            if (newMountPath != null) {
16538                setMountPath(newMountPath);
16539                return PackageManager.INSTALL_SUCCEEDED;
16540            } else {
16541                return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
16542            }
16543        }
16544
16545        @Override
16546        String getCodePath() {
16547            return packagePath;
16548        }
16549
16550        @Override
16551        String getResourcePath() {
16552            return resourcePath;
16553        }
16554
16555        int doPreInstall(int status) {
16556            if (status != PackageManager.INSTALL_SUCCEEDED) {
16557                // Destroy container
16558                PackageHelper.destroySdDir(cid);
16559            } else {
16560                boolean mounted = PackageHelper.isContainerMounted(cid);
16561                if (!mounted) {
16562                    String newMountPath = PackageHelper.mountSdDir(cid, getEncryptKey(),
16563                            Process.SYSTEM_UID);
16564                    if (newMountPath != null) {
16565                        setMountPath(newMountPath);
16566                    } else {
16567                        return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
16568                    }
16569                }
16570            }
16571            return status;
16572        }
16573
16574        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
16575            String newCacheId = getNextCodePath(oldCodePath, pkg.packageName, "/" + RES_FILE_NAME);
16576            String newMountPath = null;
16577            if (PackageHelper.isContainerMounted(cid)) {
16578                // Unmount the container
16579                if (!PackageHelper.unMountSdDir(cid)) {
16580                    Slog.i(TAG, "Failed to unmount " + cid + " before renaming");
16581                    return false;
16582                }
16583            }
16584            if (!PackageHelper.renameSdDir(cid, newCacheId)) {
16585                Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId +
16586                        " which might be stale. Will try to clean up.");
16587                // Clean up the stale container and proceed to recreate.
16588                if (!PackageHelper.destroySdDir(newCacheId)) {
16589                    Slog.e(TAG, "Very strange. Cannot clean up stale container " + newCacheId);
16590                    return false;
16591                }
16592                // Successfully cleaned up stale container. Try to rename again.
16593                if (!PackageHelper.renameSdDir(cid, newCacheId)) {
16594                    Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId
16595                            + " inspite of cleaning it up.");
16596                    return false;
16597                }
16598            }
16599            if (!PackageHelper.isContainerMounted(newCacheId)) {
16600                Slog.w(TAG, "Mounting container " + newCacheId);
16601                newMountPath = PackageHelper.mountSdDir(newCacheId,
16602                        getEncryptKey(), Process.SYSTEM_UID);
16603            } else {
16604                newMountPath = PackageHelper.getSdDir(newCacheId);
16605            }
16606            if (newMountPath == null) {
16607                Slog.w(TAG, "Failed to get cache path for  " + newCacheId);
16608                return false;
16609            }
16610            Log.i(TAG, "Succesfully renamed " + cid +
16611                    " to " + newCacheId +
16612                    " at new path: " + newMountPath);
16613            cid = newCacheId;
16614
16615            final File beforeCodeFile = new File(packagePath);
16616            setMountPath(newMountPath);
16617            final File afterCodeFile = new File(packagePath);
16618
16619            // Reflect the rename in scanned details
16620            pkg.setCodePath(afterCodeFile.getAbsolutePath());
16621            pkg.setBaseCodePath(FileUtils.rewriteAfterRename(beforeCodeFile,
16622                    afterCodeFile, pkg.baseCodePath));
16623            pkg.setSplitCodePaths(FileUtils.rewriteAfterRename(beforeCodeFile,
16624                    afterCodeFile, pkg.splitCodePaths));
16625
16626            // Reflect the rename in app info
16627            pkg.setApplicationVolumeUuid(pkg.volumeUuid);
16628            pkg.setApplicationInfoCodePath(pkg.codePath);
16629            pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
16630            pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
16631            pkg.setApplicationInfoResourcePath(pkg.codePath);
16632            pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath);
16633            pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
16634
16635            return true;
16636        }
16637
16638        private void setMountPath(String mountPath) {
16639            final File mountFile = new File(mountPath);
16640
16641            final File monolithicFile = new File(mountFile, RES_FILE_NAME);
16642            if (monolithicFile.exists()) {
16643                packagePath = monolithicFile.getAbsolutePath();
16644                if (isFwdLocked()) {
16645                    resourcePath = new File(mountFile, PUBLIC_RES_FILE_NAME).getAbsolutePath();
16646                } else {
16647                    resourcePath = packagePath;
16648                }
16649            } else {
16650                packagePath = mountFile.getAbsolutePath();
16651                resourcePath = packagePath;
16652            }
16653        }
16654
16655        int doPostInstall(int status, int uid) {
16656            if (status != PackageManager.INSTALL_SUCCEEDED) {
16657                cleanUp();
16658            } else {
16659                final int groupOwner;
16660                final String protectedFile;
16661                if (isFwdLocked()) {
16662                    groupOwner = UserHandle.getSharedAppGid(uid);
16663                    protectedFile = RES_FILE_NAME;
16664                } else {
16665                    groupOwner = -1;
16666                    protectedFile = null;
16667                }
16668
16669                if (uid < Process.FIRST_APPLICATION_UID
16670                        || !PackageHelper.fixSdPermissions(cid, groupOwner, protectedFile)) {
16671                    Slog.e(TAG, "Failed to finalize " + cid);
16672                    PackageHelper.destroySdDir(cid);
16673                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
16674                }
16675
16676                boolean mounted = PackageHelper.isContainerMounted(cid);
16677                if (!mounted) {
16678                    PackageHelper.mountSdDir(cid, getEncryptKey(), Process.myUid());
16679                }
16680            }
16681            return status;
16682        }
16683
16684        private void cleanUp() {
16685            if (DEBUG_SD_INSTALL) Slog.i(TAG, "cleanUp");
16686
16687            // Destroy secure container
16688            PackageHelper.destroySdDir(cid);
16689        }
16690
16691        private List<String> getAllCodePaths() {
16692            final File codeFile = new File(getCodePath());
16693            if (codeFile != null && codeFile.exists()) {
16694                try {
16695                    final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0);
16696                    return pkg.getAllCodePaths();
16697                } catch (PackageParserException e) {
16698                    // Ignored; we tried our best
16699                }
16700            }
16701            return Collections.EMPTY_LIST;
16702        }
16703
16704        void cleanUpResourcesLI() {
16705            // Enumerate all code paths before deleting
16706            cleanUpResourcesLI(getAllCodePaths());
16707        }
16708
16709        private void cleanUpResourcesLI(List<String> allCodePaths) {
16710            cleanUp();
16711            removeDexFiles(allCodePaths, instructionSets);
16712        }
16713
16714        String getPackageName() {
16715            return getAsecPackageName(cid);
16716        }
16717
16718        boolean doPostDeleteLI(boolean delete) {
16719            if (DEBUG_SD_INSTALL) Slog.i(TAG, "doPostDeleteLI() del=" + delete);
16720            final List<String> allCodePaths = getAllCodePaths();
16721            boolean mounted = PackageHelper.isContainerMounted(cid);
16722            if (mounted) {
16723                // Unmount first
16724                if (PackageHelper.unMountSdDir(cid)) {
16725                    mounted = false;
16726                }
16727            }
16728            if (!mounted && delete) {
16729                cleanUpResourcesLI(allCodePaths);
16730            }
16731            return !mounted;
16732        }
16733
16734        @Override
16735        int doPreCopy() {
16736            if (isFwdLocked()) {
16737                if (!PackageHelper.fixSdPermissions(cid, getPackageUid(DEFAULT_CONTAINER_PACKAGE,
16738                        MATCH_SYSTEM_ONLY, UserHandle.USER_SYSTEM), RES_FILE_NAME)) {
16739                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
16740                }
16741            }
16742
16743            return PackageManager.INSTALL_SUCCEEDED;
16744        }
16745
16746        @Override
16747        int doPostCopy(int uid) {
16748            if (isFwdLocked()) {
16749                if (uid < Process.FIRST_APPLICATION_UID
16750                        || !PackageHelper.fixSdPermissions(cid, UserHandle.getSharedAppGid(uid),
16751                                RES_FILE_NAME)) {
16752                    Slog.e(TAG, "Failed to finalize " + cid);
16753                    PackageHelper.destroySdDir(cid);
16754                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
16755                }
16756            }
16757
16758            return PackageManager.INSTALL_SUCCEEDED;
16759        }
16760    }
16761
16762    /**
16763     * Logic to handle movement of existing installed applications.
16764     */
16765    class MoveInstallArgs extends InstallArgs {
16766        private File codeFile;
16767        private File resourceFile;
16768
16769        /** New install */
16770        MoveInstallArgs(InstallParams params) {
16771            super(params.origin, params.move, params.observer, params.installFlags,
16772                    params.installerPackageName, params.volumeUuid,
16773                    params.getUser(), null /* instruction sets */, params.packageAbiOverride,
16774                    params.grantedRuntimePermissions,
16775                    params.traceMethod, params.traceCookie, params.certificates,
16776                    params.installReason);
16777        }
16778
16779        int copyApk(IMediaContainerService imcs, boolean temp) {
16780            if (DEBUG_INSTALL) Slog.d(TAG, "Moving " + move.packageName + " from "
16781                    + move.fromUuid + " to " + move.toUuid);
16782            synchronized (mInstaller) {
16783                try {
16784                    mInstaller.moveCompleteApp(move.fromUuid, move.toUuid, move.packageName,
16785                            move.dataAppName, move.appId, move.seinfo, move.targetSdkVersion);
16786                } catch (InstallerException e) {
16787                    Slog.w(TAG, "Failed to move app", e);
16788                    return PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
16789                }
16790            }
16791
16792            codeFile = new File(Environment.getDataAppDirectory(move.toUuid), move.dataAppName);
16793            resourceFile = codeFile;
16794            if (DEBUG_INSTALL) Slog.d(TAG, "codeFile after move is " + codeFile);
16795
16796            return PackageManager.INSTALL_SUCCEEDED;
16797        }
16798
16799        int doPreInstall(int status) {
16800            if (status != PackageManager.INSTALL_SUCCEEDED) {
16801                cleanUp(move.toUuid);
16802            }
16803            return status;
16804        }
16805
16806        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
16807            if (status != PackageManager.INSTALL_SUCCEEDED) {
16808                cleanUp(move.toUuid);
16809                return false;
16810            }
16811
16812            // Reflect the move in app info
16813            pkg.setApplicationVolumeUuid(pkg.volumeUuid);
16814            pkg.setApplicationInfoCodePath(pkg.codePath);
16815            pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
16816            pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
16817            pkg.setApplicationInfoResourcePath(pkg.codePath);
16818            pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath);
16819            pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
16820
16821            return true;
16822        }
16823
16824        int doPostInstall(int status, int uid) {
16825            if (status == PackageManager.INSTALL_SUCCEEDED) {
16826                cleanUp(move.fromUuid);
16827            } else {
16828                cleanUp(move.toUuid);
16829            }
16830            return status;
16831        }
16832
16833        @Override
16834        String getCodePath() {
16835            return (codeFile != null) ? codeFile.getAbsolutePath() : null;
16836        }
16837
16838        @Override
16839        String getResourcePath() {
16840            return (resourceFile != null) ? resourceFile.getAbsolutePath() : null;
16841        }
16842
16843        private boolean cleanUp(String volumeUuid) {
16844            final File codeFile = new File(Environment.getDataAppDirectory(volumeUuid),
16845                    move.dataAppName);
16846            Slog.d(TAG, "Cleaning up " + move.packageName + " on " + volumeUuid);
16847            final int[] userIds = sUserManager.getUserIds();
16848            synchronized (mInstallLock) {
16849                // Clean up both app data and code
16850                // All package moves are frozen until finished
16851                for (int userId : userIds) {
16852                    try {
16853                        mInstaller.destroyAppData(volumeUuid, move.packageName, userId,
16854                                StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE, 0);
16855                    } catch (InstallerException e) {
16856                        Slog.w(TAG, String.valueOf(e));
16857                    }
16858                }
16859                removeCodePathLI(codeFile);
16860            }
16861            return true;
16862        }
16863
16864        void cleanUpResourcesLI() {
16865            throw new UnsupportedOperationException();
16866        }
16867
16868        boolean doPostDeleteLI(boolean delete) {
16869            throw new UnsupportedOperationException();
16870        }
16871    }
16872
16873    static String getAsecPackageName(String packageCid) {
16874        int idx = packageCid.lastIndexOf("-");
16875        if (idx == -1) {
16876            return packageCid;
16877        }
16878        return packageCid.substring(0, idx);
16879    }
16880
16881    // Utility method used to create code paths based on package name and available index.
16882    private static String getNextCodePath(String oldCodePath, String prefix, String suffix) {
16883        String idxStr = "";
16884        int idx = 1;
16885        // Fall back to default value of idx=1 if prefix is not
16886        // part of oldCodePath
16887        if (oldCodePath != null) {
16888            String subStr = oldCodePath;
16889            // Drop the suffix right away
16890            if (suffix != null && subStr.endsWith(suffix)) {
16891                subStr = subStr.substring(0, subStr.length() - suffix.length());
16892            }
16893            // If oldCodePath already contains prefix find out the
16894            // ending index to either increment or decrement.
16895            int sidx = subStr.lastIndexOf(prefix);
16896            if (sidx != -1) {
16897                subStr = subStr.substring(sidx + prefix.length());
16898                if (subStr != null) {
16899                    if (subStr.startsWith(INSTALL_PACKAGE_SUFFIX)) {
16900                        subStr = subStr.substring(INSTALL_PACKAGE_SUFFIX.length());
16901                    }
16902                    try {
16903                        idx = Integer.parseInt(subStr);
16904                        if (idx <= 1) {
16905                            idx++;
16906                        } else {
16907                            idx--;
16908                        }
16909                    } catch(NumberFormatException e) {
16910                    }
16911                }
16912            }
16913        }
16914        idxStr = INSTALL_PACKAGE_SUFFIX + Integer.toString(idx);
16915        return prefix + idxStr;
16916    }
16917
16918    private File getNextCodePath(File targetDir, String packageName) {
16919        File result;
16920        SecureRandom random = new SecureRandom();
16921        byte[] bytes = new byte[16];
16922        do {
16923            random.nextBytes(bytes);
16924            String suffix = Base64.encodeToString(bytes, Base64.URL_SAFE | Base64.NO_WRAP);
16925            result = new File(targetDir, packageName + "-" + suffix);
16926        } while (result.exists());
16927        return result;
16928    }
16929
16930    // Utility method that returns the relative package path with respect
16931    // to the installation directory. Like say for /data/data/com.test-1.apk
16932    // string com.test-1 is returned.
16933    static String deriveCodePathName(String codePath) {
16934        if (codePath == null) {
16935            return null;
16936        }
16937        final File codeFile = new File(codePath);
16938        final String name = codeFile.getName();
16939        if (codeFile.isDirectory()) {
16940            return name;
16941        } else if (name.endsWith(".apk") || name.endsWith(".tmp")) {
16942            final int lastDot = name.lastIndexOf('.');
16943            return name.substring(0, lastDot);
16944        } else {
16945            Slog.w(TAG, "Odd, " + codePath + " doesn't look like an APK");
16946            return null;
16947        }
16948    }
16949
16950    static class PackageInstalledInfo {
16951        String name;
16952        int uid;
16953        // The set of users that originally had this package installed.
16954        int[] origUsers;
16955        // The set of users that now have this package installed.
16956        int[] newUsers;
16957        PackageParser.Package pkg;
16958        int returnCode;
16959        String returnMsg;
16960        PackageRemovedInfo removedInfo;
16961        ArrayMap<String, PackageInstalledInfo> addedChildPackages;
16962
16963        public void setError(int code, String msg) {
16964            setReturnCode(code);
16965            setReturnMessage(msg);
16966            Slog.w(TAG, msg);
16967        }
16968
16969        public void setError(String msg, PackageParserException e) {
16970            setReturnCode(e.error);
16971            setReturnMessage(ExceptionUtils.getCompleteMessage(msg, e));
16972            final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0;
16973            for (int i = 0; i < childCount; i++) {
16974                addedChildPackages.valueAt(i).setError(msg, e);
16975            }
16976            Slog.w(TAG, msg, e);
16977        }
16978
16979        public void setError(String msg, PackageManagerException e) {
16980            returnCode = e.error;
16981            setReturnMessage(ExceptionUtils.getCompleteMessage(msg, e));
16982            final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0;
16983            for (int i = 0; i < childCount; i++) {
16984                addedChildPackages.valueAt(i).setError(msg, e);
16985            }
16986            Slog.w(TAG, msg, e);
16987        }
16988
16989        public void setReturnCode(int returnCode) {
16990            this.returnCode = returnCode;
16991            final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0;
16992            for (int i = 0; i < childCount; i++) {
16993                addedChildPackages.valueAt(i).returnCode = returnCode;
16994            }
16995        }
16996
16997        private void setReturnMessage(String returnMsg) {
16998            this.returnMsg = returnMsg;
16999            final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0;
17000            for (int i = 0; i < childCount; i++) {
17001                addedChildPackages.valueAt(i).returnMsg = returnMsg;
17002            }
17003        }
17004
17005        // In some error cases we want to convey more info back to the observer
17006        String origPackage;
17007        String origPermission;
17008    }
17009
17010    /*
17011     * Install a non-existing package.
17012     */
17013    private void installNewPackageLIF(PackageParser.Package pkg, final int policyFlags,
17014            int scanFlags, UserHandle user, String installerPackageName, String volumeUuid,
17015            PackageInstalledInfo res, int installReason) {
17016        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installNewPackage");
17017
17018        // Remember this for later, in case we need to rollback this install
17019        String pkgName = pkg.packageName;
17020
17021        if (DEBUG_INSTALL) Slog.d(TAG, "installNewPackageLI: " + pkg);
17022
17023        synchronized(mPackages) {
17024            final String renamedPackage = mSettings.getRenamedPackageLPr(pkgName);
17025            if (renamedPackage != null) {
17026                // A package with the same name is already installed, though
17027                // it has been renamed to an older name.  The package we
17028                // are trying to install should be installed as an update to
17029                // the existing one, but that has not been requested, so bail.
17030                res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName
17031                        + " without first uninstalling package running as "
17032                        + renamedPackage);
17033                return;
17034            }
17035            if (mPackages.containsKey(pkgName)) {
17036                // Don't allow installation over an existing package with the same name.
17037                res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName
17038                        + " without first uninstalling.");
17039                return;
17040            }
17041        }
17042
17043        try {
17044            PackageParser.Package newPackage = scanPackageTracedLI(pkg, policyFlags, scanFlags,
17045                    System.currentTimeMillis(), user);
17046
17047            updateSettingsLI(newPackage, installerPackageName, null, res, user, installReason);
17048
17049            if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
17050                prepareAppDataAfterInstallLIF(newPackage);
17051
17052            } else {
17053                // Remove package from internal structures, but keep around any
17054                // data that might have already existed
17055                deletePackageLIF(pkgName, UserHandle.ALL, false, null,
17056                        PackageManager.DELETE_KEEP_DATA, res.removedInfo, true, null);
17057            }
17058        } catch (PackageManagerException e) {
17059            res.setError("Package couldn't be installed in " + pkg.codePath, e);
17060        }
17061
17062        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
17063    }
17064
17065    private boolean shouldCheckUpgradeKeySetLP(PackageSetting oldPs, int scanFlags) {
17066        // Can't rotate keys during boot or if sharedUser.
17067        if (oldPs == null || (scanFlags&SCAN_INITIAL) != 0 || oldPs.sharedUser != null
17068                || !oldPs.keySetData.isUsingUpgradeKeySets()) {
17069            return false;
17070        }
17071        // app is using upgradeKeySets; make sure all are valid
17072        KeySetManagerService ksms = mSettings.mKeySetManagerService;
17073        long[] upgradeKeySets = oldPs.keySetData.getUpgradeKeySets();
17074        for (int i = 0; i < upgradeKeySets.length; i++) {
17075            if (!ksms.isIdValidKeySetId(upgradeKeySets[i])) {
17076                Slog.wtf(TAG, "Package "
17077                         + (oldPs.name != null ? oldPs.name : "<null>")
17078                         + " contains upgrade-key-set reference to unknown key-set: "
17079                         + upgradeKeySets[i]
17080                         + " reverting to signatures check.");
17081                return false;
17082            }
17083        }
17084        return true;
17085    }
17086
17087    private boolean checkUpgradeKeySetLP(PackageSetting oldPS, PackageParser.Package newPkg) {
17088        // Upgrade keysets are being used.  Determine if new package has a superset of the
17089        // required keys.
17090        long[] upgradeKeySets = oldPS.keySetData.getUpgradeKeySets();
17091        KeySetManagerService ksms = mSettings.mKeySetManagerService;
17092        for (int i = 0; i < upgradeKeySets.length; i++) {
17093            Set<PublicKey> upgradeSet = ksms.getPublicKeysFromKeySetLPr(upgradeKeySets[i]);
17094            if (upgradeSet != null && newPkg.mSigningKeys.containsAll(upgradeSet)) {
17095                return true;
17096            }
17097        }
17098        return false;
17099    }
17100
17101    private static void updateDigest(MessageDigest digest, File file) throws IOException {
17102        try (DigestInputStream digestStream =
17103                new DigestInputStream(new FileInputStream(file), digest)) {
17104            while (digestStream.read() != -1) {} // nothing to do; just plow through the file
17105        }
17106    }
17107
17108    private void replacePackageLIF(PackageParser.Package pkg, final int policyFlags, int scanFlags,
17109            UserHandle user, String installerPackageName, PackageInstalledInfo res,
17110            int installReason) {
17111        final boolean isInstantApp = (scanFlags & SCAN_AS_INSTANT_APP) != 0;
17112
17113        final PackageParser.Package oldPackage;
17114        final PackageSetting ps;
17115        final String pkgName = pkg.packageName;
17116        final int[] allUsers;
17117        final int[] installedUsers;
17118
17119        synchronized(mPackages) {
17120            oldPackage = mPackages.get(pkgName);
17121            if (DEBUG_INSTALL) Slog.d(TAG, "replacePackageLI: new=" + pkg + ", old=" + oldPackage);
17122
17123            // don't allow upgrade to target a release SDK from a pre-release SDK
17124            final boolean oldTargetsPreRelease = oldPackage.applicationInfo.targetSdkVersion
17125                    == android.os.Build.VERSION_CODES.CUR_DEVELOPMENT;
17126            final boolean newTargetsPreRelease = pkg.applicationInfo.targetSdkVersion
17127                    == android.os.Build.VERSION_CODES.CUR_DEVELOPMENT;
17128            if (oldTargetsPreRelease
17129                    && !newTargetsPreRelease
17130                    && ((policyFlags & PackageParser.PARSE_FORCE_SDK) == 0)) {
17131                Slog.w(TAG, "Can't install package targeting released sdk");
17132                res.setReturnCode(PackageManager.INSTALL_FAILED_UPDATE_INCOMPATIBLE);
17133                return;
17134            }
17135
17136            ps = mSettings.mPackages.get(pkgName);
17137
17138            // verify signatures are valid
17139            if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) {
17140                if (!checkUpgradeKeySetLP(ps, pkg)) {
17141                    res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
17142                            "New package not signed by keys specified by upgrade-keysets: "
17143                                    + pkgName);
17144                    return;
17145                }
17146            } else {
17147                // default to original signature matching
17148                if (compareSignatures(oldPackage.mSignatures, pkg.mSignatures)
17149                        != PackageManager.SIGNATURE_MATCH) {
17150                    res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
17151                            "New package has a different signature: " + pkgName);
17152                    return;
17153                }
17154            }
17155
17156            // don't allow a system upgrade unless the upgrade hash matches
17157            if (oldPackage.restrictUpdateHash != null && oldPackage.isSystemApp()) {
17158                byte[] digestBytes = null;
17159                try {
17160                    final MessageDigest digest = MessageDigest.getInstance("SHA-512");
17161                    updateDigest(digest, new File(pkg.baseCodePath));
17162                    if (!ArrayUtils.isEmpty(pkg.splitCodePaths)) {
17163                        for (String path : pkg.splitCodePaths) {
17164                            updateDigest(digest, new File(path));
17165                        }
17166                    }
17167                    digestBytes = digest.digest();
17168                } catch (NoSuchAlgorithmException | IOException e) {
17169                    res.setError(INSTALL_FAILED_INVALID_APK,
17170                            "Could not compute hash: " + pkgName);
17171                    return;
17172                }
17173                if (!Arrays.equals(oldPackage.restrictUpdateHash, digestBytes)) {
17174                    res.setError(INSTALL_FAILED_INVALID_APK,
17175                            "New package fails restrict-update check: " + pkgName);
17176                    return;
17177                }
17178                // retain upgrade restriction
17179                pkg.restrictUpdateHash = oldPackage.restrictUpdateHash;
17180            }
17181
17182            // Check for shared user id changes
17183            String invalidPackageName =
17184                    getParentOrChildPackageChangedSharedUser(oldPackage, pkg);
17185            if (invalidPackageName != null) {
17186                res.setError(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE,
17187                        "Package " + invalidPackageName + " tried to change user "
17188                                + oldPackage.mSharedUserId);
17189                return;
17190            }
17191
17192            // In case of rollback, remember per-user/profile install state
17193            allUsers = sUserManager.getUserIds();
17194            installedUsers = ps.queryInstalledUsers(allUsers, true);
17195
17196            // don't allow an upgrade from full to ephemeral
17197            if (isInstantApp) {
17198                if (user == null || user.getIdentifier() == UserHandle.USER_ALL) {
17199                    for (int currentUser : allUsers) {
17200                        if (!ps.getInstantApp(currentUser)) {
17201                            // can't downgrade from full to instant
17202                            Slog.w(TAG, "Can't replace full app with instant app: " + pkgName
17203                                    + " for user: " + currentUser);
17204                            res.setReturnCode(PackageManager.INSTALL_FAILED_INSTANT_APP_INVALID);
17205                            return;
17206                        }
17207                    }
17208                } else if (!ps.getInstantApp(user.getIdentifier())) {
17209                    // can't downgrade from full to instant
17210                    Slog.w(TAG, "Can't replace full app with instant app: " + pkgName
17211                            + " for user: " + user.getIdentifier());
17212                    res.setReturnCode(PackageManager.INSTALL_FAILED_INSTANT_APP_INVALID);
17213                    return;
17214                }
17215            }
17216        }
17217
17218        // Update what is removed
17219        res.removedInfo = new PackageRemovedInfo(this);
17220        res.removedInfo.uid = oldPackage.applicationInfo.uid;
17221        res.removedInfo.removedPackage = oldPackage.packageName;
17222        res.removedInfo.installerPackageName = ps.installerPackageName;
17223        res.removedInfo.isStaticSharedLib = pkg.staticSharedLibName != null;
17224        res.removedInfo.isUpdate = true;
17225        res.removedInfo.origUsers = installedUsers;
17226        res.removedInfo.installReasons = new SparseArray<>(installedUsers.length);
17227        for (int i = 0; i < installedUsers.length; i++) {
17228            final int userId = installedUsers[i];
17229            res.removedInfo.installReasons.put(userId, ps.getInstallReason(userId));
17230        }
17231
17232        final int childCount = (oldPackage.childPackages != null)
17233                ? oldPackage.childPackages.size() : 0;
17234        for (int i = 0; i < childCount; i++) {
17235            boolean childPackageUpdated = false;
17236            PackageParser.Package childPkg = oldPackage.childPackages.get(i);
17237            final PackageSetting childPs = mSettings.getPackageLPr(childPkg.packageName);
17238            if (res.addedChildPackages != null) {
17239                PackageInstalledInfo childRes = res.addedChildPackages.get(childPkg.packageName);
17240                if (childRes != null) {
17241                    childRes.removedInfo.uid = childPkg.applicationInfo.uid;
17242                    childRes.removedInfo.removedPackage = childPkg.packageName;
17243                    if (childPs != null) {
17244                        childRes.removedInfo.installerPackageName = childPs.installerPackageName;
17245                    }
17246                    childRes.removedInfo.isUpdate = true;
17247                    childRes.removedInfo.installReasons = res.removedInfo.installReasons;
17248                    childPackageUpdated = true;
17249                }
17250            }
17251            if (!childPackageUpdated) {
17252                PackageRemovedInfo childRemovedRes = new PackageRemovedInfo(this);
17253                childRemovedRes.removedPackage = childPkg.packageName;
17254                if (childPs != null) {
17255                    childRemovedRes.installerPackageName = childPs.installerPackageName;
17256                }
17257                childRemovedRes.isUpdate = false;
17258                childRemovedRes.dataRemoved = true;
17259                synchronized (mPackages) {
17260                    if (childPs != null) {
17261                        childRemovedRes.origUsers = childPs.queryInstalledUsers(allUsers, true);
17262                    }
17263                }
17264                if (res.removedInfo.removedChildPackages == null) {
17265                    res.removedInfo.removedChildPackages = new ArrayMap<>();
17266                }
17267                res.removedInfo.removedChildPackages.put(childPkg.packageName, childRemovedRes);
17268            }
17269        }
17270
17271        boolean sysPkg = (isSystemApp(oldPackage));
17272        if (sysPkg) {
17273            // Set the system/privileged flags as needed
17274            final boolean privileged =
17275                    (oldPackage.applicationInfo.privateFlags
17276                            & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0;
17277            final int systemPolicyFlags = policyFlags
17278                    | PackageParser.PARSE_IS_SYSTEM
17279                    | (privileged ? PackageParser.PARSE_IS_PRIVILEGED : 0);
17280
17281            replaceSystemPackageLIF(oldPackage, pkg, systemPolicyFlags, scanFlags,
17282                    user, allUsers, installerPackageName, res, installReason);
17283        } else {
17284            replaceNonSystemPackageLIF(oldPackage, pkg, policyFlags, scanFlags,
17285                    user, allUsers, installerPackageName, res, installReason);
17286        }
17287    }
17288
17289    @Override
17290    public List<String> getPreviousCodePaths(String packageName) {
17291        final int callingUid = Binder.getCallingUid();
17292        final List<String> result = new ArrayList<>();
17293        if (getInstantAppPackageName(callingUid) != null) {
17294            return result;
17295        }
17296        final PackageSetting ps = mSettings.mPackages.get(packageName);
17297        if (ps != null
17298                && ps.oldCodePaths != null
17299                && !filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
17300            result.addAll(ps.oldCodePaths);
17301        }
17302        return result;
17303    }
17304
17305    private void replaceNonSystemPackageLIF(PackageParser.Package deletedPackage,
17306            PackageParser.Package pkg, final int policyFlags, int scanFlags, UserHandle user,
17307            int[] allUsers, String installerPackageName, PackageInstalledInfo res,
17308            int installReason) {
17309        if (DEBUG_INSTALL) Slog.d(TAG, "replaceNonSystemPackageLI: new=" + pkg + ", old="
17310                + deletedPackage);
17311
17312        String pkgName = deletedPackage.packageName;
17313        boolean deletedPkg = true;
17314        boolean addedPkg = false;
17315        boolean updatedSettings = false;
17316        final boolean killApp = (scanFlags & SCAN_DONT_KILL_APP) == 0;
17317        final int deleteFlags = PackageManager.DELETE_KEEP_DATA
17318                | (killApp ? 0 : PackageManager.DELETE_DONT_KILL_APP);
17319
17320        final long origUpdateTime = (pkg.mExtras != null)
17321                ? ((PackageSetting)pkg.mExtras).lastUpdateTime : 0;
17322
17323        // First delete the existing package while retaining the data directory
17324        if (!deletePackageLIF(pkgName, null, true, allUsers, deleteFlags,
17325                res.removedInfo, true, pkg)) {
17326            // If the existing package wasn't successfully deleted
17327            res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, "replaceNonSystemPackageLI");
17328            deletedPkg = false;
17329        } else {
17330            // Successfully deleted the old package; proceed with replace.
17331
17332            // If deleted package lived in a container, give users a chance to
17333            // relinquish resources before killing.
17334            if (deletedPackage.isForwardLocked() || isExternal(deletedPackage)) {
17335                if (DEBUG_INSTALL) {
17336                    Slog.i(TAG, "upgrading pkg " + deletedPackage + " is ASEC-hosted -> UNAVAILABLE");
17337                }
17338                final int[] uidArray = new int[] { deletedPackage.applicationInfo.uid };
17339                final ArrayList<String> pkgList = new ArrayList<String>(1);
17340                pkgList.add(deletedPackage.applicationInfo.packageName);
17341                sendResourcesChangedBroadcast(false, true, pkgList, uidArray, null);
17342            }
17343
17344            clearAppDataLIF(pkg, UserHandle.USER_ALL, StorageManager.FLAG_STORAGE_DE
17345                    | StorageManager.FLAG_STORAGE_CE | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
17346            clearAppProfilesLIF(deletedPackage, UserHandle.USER_ALL);
17347
17348            try {
17349                final PackageParser.Package newPackage = scanPackageTracedLI(pkg, policyFlags,
17350                        scanFlags | SCAN_UPDATE_TIME, System.currentTimeMillis(), user);
17351                updateSettingsLI(newPackage, installerPackageName, allUsers, res, user,
17352                        installReason);
17353
17354                // Update the in-memory copy of the previous code paths.
17355                PackageSetting ps = mSettings.mPackages.get(pkgName);
17356                if (!killApp) {
17357                    if (ps.oldCodePaths == null) {
17358                        ps.oldCodePaths = new ArraySet<>();
17359                    }
17360                    Collections.addAll(ps.oldCodePaths, deletedPackage.baseCodePath);
17361                    if (deletedPackage.splitCodePaths != null) {
17362                        Collections.addAll(ps.oldCodePaths, deletedPackage.splitCodePaths);
17363                    }
17364                } else {
17365                    ps.oldCodePaths = null;
17366                }
17367                if (ps.childPackageNames != null) {
17368                    for (int i = ps.childPackageNames.size() - 1; i >= 0; --i) {
17369                        final String childPkgName = ps.childPackageNames.get(i);
17370                        final PackageSetting childPs = mSettings.mPackages.get(childPkgName);
17371                        childPs.oldCodePaths = ps.oldCodePaths;
17372                    }
17373                }
17374                // set instant app status, but, only if it's explicitly specified
17375                final boolean instantApp = (scanFlags & SCAN_AS_INSTANT_APP) != 0;
17376                final boolean fullApp = (scanFlags & SCAN_AS_FULL_APP) != 0;
17377                setInstantAppForUser(ps, user.getIdentifier(), instantApp, fullApp);
17378                prepareAppDataAfterInstallLIF(newPackage);
17379                addedPkg = true;
17380                mDexManager.notifyPackageUpdated(newPackage.packageName,
17381                        newPackage.baseCodePath, newPackage.splitCodePaths);
17382            } catch (PackageManagerException e) {
17383                res.setError("Package couldn't be installed in " + pkg.codePath, e);
17384            }
17385        }
17386
17387        if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
17388            if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, rolling pack: " + pkgName);
17389
17390            // Revert all internal state mutations and added folders for the failed install
17391            if (addedPkg) {
17392                deletePackageLIF(pkgName, null, true, allUsers, deleteFlags,
17393                        res.removedInfo, true, null);
17394            }
17395
17396            // Restore the old package
17397            if (deletedPkg) {
17398                if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, reinstalling: " + deletedPackage);
17399                File restoreFile = new File(deletedPackage.codePath);
17400                // Parse old package
17401                boolean oldExternal = isExternal(deletedPackage);
17402                int oldParseFlags  = mDefParseFlags | PackageParser.PARSE_CHATTY |
17403                        (deletedPackage.isForwardLocked() ? PackageParser.PARSE_FORWARD_LOCK : 0) |
17404                        (oldExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0);
17405                int oldScanFlags = SCAN_UPDATE_SIGNATURE | SCAN_UPDATE_TIME;
17406                try {
17407                    scanPackageTracedLI(restoreFile, oldParseFlags, oldScanFlags, origUpdateTime,
17408                            null);
17409                } catch (PackageManagerException e) {
17410                    Slog.e(TAG, "Failed to restore package : " + pkgName + " after failed upgrade: "
17411                            + e.getMessage());
17412                    return;
17413                }
17414
17415                synchronized (mPackages) {
17416                    // Ensure the installer package name up to date
17417                    setInstallerPackageNameLPw(deletedPackage, installerPackageName);
17418
17419                    // Update permissions for restored package
17420                    updatePermissionsLPw(deletedPackage, UPDATE_PERMISSIONS_ALL);
17421
17422                    mSettings.writeLPr();
17423                }
17424
17425                Slog.i(TAG, "Successfully restored package : " + pkgName + " after failed upgrade");
17426            }
17427        } else {
17428            synchronized (mPackages) {
17429                PackageSetting ps = mSettings.getPackageLPr(pkg.packageName);
17430                if (ps != null) {
17431                    res.removedInfo.removedForAllUsers = mPackages.get(ps.name) == null;
17432                    if (res.removedInfo.removedChildPackages != null) {
17433                        final int childCount = res.removedInfo.removedChildPackages.size();
17434                        // Iterate in reverse as we may modify the collection
17435                        for (int i = childCount - 1; i >= 0; i--) {
17436                            String childPackageName = res.removedInfo.removedChildPackages.keyAt(i);
17437                            if (res.addedChildPackages.containsKey(childPackageName)) {
17438                                res.removedInfo.removedChildPackages.removeAt(i);
17439                            } else {
17440                                PackageRemovedInfo childInfo = res.removedInfo
17441                                        .removedChildPackages.valueAt(i);
17442                                childInfo.removedForAllUsers = mPackages.get(
17443                                        childInfo.removedPackage) == null;
17444                            }
17445                        }
17446                    }
17447                }
17448            }
17449        }
17450    }
17451
17452    private void replaceSystemPackageLIF(PackageParser.Package deletedPackage,
17453            PackageParser.Package pkg, final int policyFlags, int scanFlags, UserHandle user,
17454            int[] allUsers, String installerPackageName, PackageInstalledInfo res,
17455            int installReason) {
17456        if (DEBUG_INSTALL) Slog.d(TAG, "replaceSystemPackageLI: new=" + pkg
17457                + ", old=" + deletedPackage);
17458
17459        final boolean disabledSystem;
17460
17461        // Remove existing system package
17462        removePackageLI(deletedPackage, true);
17463
17464        synchronized (mPackages) {
17465            disabledSystem = disableSystemPackageLPw(deletedPackage, pkg);
17466        }
17467        if (!disabledSystem) {
17468            // We didn't need to disable the .apk as a current system package,
17469            // which means we are replacing another update that is already
17470            // installed.  We need to make sure to delete the older one's .apk.
17471            res.removedInfo.args = createInstallArgsForExisting(0,
17472                    deletedPackage.applicationInfo.getCodePath(),
17473                    deletedPackage.applicationInfo.getResourcePath(),
17474                    getAppDexInstructionSets(deletedPackage.applicationInfo));
17475        } else {
17476            res.removedInfo.args = null;
17477        }
17478
17479        // Successfully disabled the old package. Now proceed with re-installation
17480        clearAppDataLIF(pkg, UserHandle.USER_ALL, StorageManager.FLAG_STORAGE_DE
17481                | StorageManager.FLAG_STORAGE_CE | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
17482        clearAppProfilesLIF(deletedPackage, UserHandle.USER_ALL);
17483
17484        res.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
17485        pkg.setApplicationInfoFlags(ApplicationInfo.FLAG_UPDATED_SYSTEM_APP,
17486                ApplicationInfo.FLAG_UPDATED_SYSTEM_APP);
17487
17488        PackageParser.Package newPackage = null;
17489        try {
17490            // Add the package to the internal data structures
17491            newPackage = scanPackageTracedLI(pkg, policyFlags, scanFlags, 0, user);
17492
17493            // Set the update and install times
17494            PackageSetting deletedPkgSetting = (PackageSetting) deletedPackage.mExtras;
17495            setInstallAndUpdateTime(newPackage, deletedPkgSetting.firstInstallTime,
17496                    System.currentTimeMillis());
17497
17498            // Update the package dynamic state if succeeded
17499            if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
17500                // Now that the install succeeded make sure we remove data
17501                // directories for any child package the update removed.
17502                final int deletedChildCount = (deletedPackage.childPackages != null)
17503                        ? deletedPackage.childPackages.size() : 0;
17504                final int newChildCount = (newPackage.childPackages != null)
17505                        ? newPackage.childPackages.size() : 0;
17506                for (int i = 0; i < deletedChildCount; i++) {
17507                    PackageParser.Package deletedChildPkg = deletedPackage.childPackages.get(i);
17508                    boolean childPackageDeleted = true;
17509                    for (int j = 0; j < newChildCount; j++) {
17510                        PackageParser.Package newChildPkg = newPackage.childPackages.get(j);
17511                        if (deletedChildPkg.packageName.equals(newChildPkg.packageName)) {
17512                            childPackageDeleted = false;
17513                            break;
17514                        }
17515                    }
17516                    if (childPackageDeleted) {
17517                        PackageSetting ps = mSettings.getDisabledSystemPkgLPr(
17518                                deletedChildPkg.packageName);
17519                        if (ps != null && res.removedInfo.removedChildPackages != null) {
17520                            PackageRemovedInfo removedChildRes = res.removedInfo
17521                                    .removedChildPackages.get(deletedChildPkg.packageName);
17522                            removePackageDataLIF(ps, allUsers, removedChildRes, 0, false);
17523                            removedChildRes.removedForAllUsers = mPackages.get(ps.name) == null;
17524                        }
17525                    }
17526                }
17527
17528                updateSettingsLI(newPackage, installerPackageName, allUsers, res, user,
17529                        installReason);
17530                prepareAppDataAfterInstallLIF(newPackage);
17531
17532                mDexManager.notifyPackageUpdated(newPackage.packageName,
17533                            newPackage.baseCodePath, newPackage.splitCodePaths);
17534            }
17535        } catch (PackageManagerException e) {
17536            res.setReturnCode(INSTALL_FAILED_INTERNAL_ERROR);
17537            res.setError("Package couldn't be installed in " + pkg.codePath, e);
17538        }
17539
17540        if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
17541            // Re installation failed. Restore old information
17542            // Remove new pkg information
17543            if (newPackage != null) {
17544                removeInstalledPackageLI(newPackage, true);
17545            }
17546            // Add back the old system package
17547            try {
17548                scanPackageTracedLI(deletedPackage, policyFlags, SCAN_UPDATE_SIGNATURE, 0, user);
17549            } catch (PackageManagerException e) {
17550                Slog.e(TAG, "Failed to restore original package: " + e.getMessage());
17551            }
17552
17553            synchronized (mPackages) {
17554                if (disabledSystem) {
17555                    enableSystemPackageLPw(deletedPackage);
17556                }
17557
17558                // Ensure the installer package name up to date
17559                setInstallerPackageNameLPw(deletedPackage, installerPackageName);
17560
17561                // Update permissions for restored package
17562                updatePermissionsLPw(deletedPackage, UPDATE_PERMISSIONS_ALL);
17563
17564                mSettings.writeLPr();
17565            }
17566
17567            Slog.i(TAG, "Successfully restored package : " + deletedPackage.packageName
17568                    + " after failed upgrade");
17569        }
17570    }
17571
17572    /**
17573     * Checks whether the parent or any of the child packages have a change shared
17574     * user. For a package to be a valid update the shred users of the parent and
17575     * the children should match. We may later support changing child shared users.
17576     * @param oldPkg The updated package.
17577     * @param newPkg The update package.
17578     * @return The shared user that change between the versions.
17579     */
17580    private String getParentOrChildPackageChangedSharedUser(PackageParser.Package oldPkg,
17581            PackageParser.Package newPkg) {
17582        // Check parent shared user
17583        if (!Objects.equals(oldPkg.mSharedUserId, newPkg.mSharedUserId)) {
17584            return newPkg.packageName;
17585        }
17586        // Check child shared users
17587        final int oldChildCount = (oldPkg.childPackages != null) ? oldPkg.childPackages.size() : 0;
17588        final int newChildCount = (newPkg.childPackages != null) ? newPkg.childPackages.size() : 0;
17589        for (int i = 0; i < newChildCount; i++) {
17590            PackageParser.Package newChildPkg = newPkg.childPackages.get(i);
17591            // If this child was present, did it have the same shared user?
17592            for (int j = 0; j < oldChildCount; j++) {
17593                PackageParser.Package oldChildPkg = oldPkg.childPackages.get(j);
17594                if (newChildPkg.packageName.equals(oldChildPkg.packageName)
17595                        && !Objects.equals(newChildPkg.mSharedUserId, oldChildPkg.mSharedUserId)) {
17596                    return newChildPkg.packageName;
17597                }
17598            }
17599        }
17600        return null;
17601    }
17602
17603    private void removeNativeBinariesLI(PackageSetting ps) {
17604        // Remove the lib path for the parent package
17605        if (ps != null) {
17606            NativeLibraryHelper.removeNativeBinariesLI(ps.legacyNativeLibraryPathString);
17607            // Remove the lib path for the child packages
17608            final int childCount = (ps.childPackageNames != null) ? ps.childPackageNames.size() : 0;
17609            for (int i = 0; i < childCount; i++) {
17610                PackageSetting childPs = null;
17611                synchronized (mPackages) {
17612                    childPs = mSettings.getPackageLPr(ps.childPackageNames.get(i));
17613                }
17614                if (childPs != null) {
17615                    NativeLibraryHelper.removeNativeBinariesLI(childPs
17616                            .legacyNativeLibraryPathString);
17617                }
17618            }
17619        }
17620    }
17621
17622    private void enableSystemPackageLPw(PackageParser.Package pkg) {
17623        // Enable the parent package
17624        mSettings.enableSystemPackageLPw(pkg.packageName);
17625        // Enable the child packages
17626        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
17627        for (int i = 0; i < childCount; i++) {
17628            PackageParser.Package childPkg = pkg.childPackages.get(i);
17629            mSettings.enableSystemPackageLPw(childPkg.packageName);
17630        }
17631    }
17632
17633    private boolean disableSystemPackageLPw(PackageParser.Package oldPkg,
17634            PackageParser.Package newPkg) {
17635        // Disable the parent package (parent always replaced)
17636        boolean disabled = mSettings.disableSystemPackageLPw(oldPkg.packageName, true);
17637        // Disable the child packages
17638        final int childCount = (oldPkg.childPackages != null) ? oldPkg.childPackages.size() : 0;
17639        for (int i = 0; i < childCount; i++) {
17640            PackageParser.Package childPkg = oldPkg.childPackages.get(i);
17641            final boolean replace = newPkg.hasChildPackage(childPkg.packageName);
17642            disabled |= mSettings.disableSystemPackageLPw(childPkg.packageName, replace);
17643        }
17644        return disabled;
17645    }
17646
17647    private void setInstallerPackageNameLPw(PackageParser.Package pkg,
17648            String installerPackageName) {
17649        // Enable the parent package
17650        mSettings.setInstallerPackageName(pkg.packageName, installerPackageName);
17651        // Enable the child packages
17652        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
17653        for (int i = 0; i < childCount; i++) {
17654            PackageParser.Package childPkg = pkg.childPackages.get(i);
17655            mSettings.setInstallerPackageName(childPkg.packageName, installerPackageName);
17656        }
17657    }
17658
17659    private int[] revokeUnusedSharedUserPermissionsLPw(SharedUserSetting su, int[] allUserIds) {
17660        // Collect all used permissions in the UID
17661        ArraySet<String> usedPermissions = new ArraySet<>();
17662        final int packageCount = su.packages.size();
17663        for (int i = 0; i < packageCount; i++) {
17664            PackageSetting ps = su.packages.valueAt(i);
17665            if (ps.pkg == null) {
17666                continue;
17667            }
17668            final int requestedPermCount = ps.pkg.requestedPermissions.size();
17669            for (int j = 0; j < requestedPermCount; j++) {
17670                String permission = ps.pkg.requestedPermissions.get(j);
17671                BasePermission bp = mSettings.mPermissions.get(permission);
17672                if (bp != null) {
17673                    usedPermissions.add(permission);
17674                }
17675            }
17676        }
17677
17678        PermissionsState permissionsState = su.getPermissionsState();
17679        // Prune install permissions
17680        List<PermissionState> installPermStates = permissionsState.getInstallPermissionStates();
17681        final int installPermCount = installPermStates.size();
17682        for (int i = installPermCount - 1; i >= 0;  i--) {
17683            PermissionState permissionState = installPermStates.get(i);
17684            if (!usedPermissions.contains(permissionState.getName())) {
17685                BasePermission bp = mSettings.mPermissions.get(permissionState.getName());
17686                if (bp != null) {
17687                    permissionsState.revokeInstallPermission(bp);
17688                    permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL,
17689                            PackageManager.MASK_PERMISSION_FLAGS, 0);
17690                }
17691            }
17692        }
17693
17694        int[] runtimePermissionChangedUserIds = EmptyArray.INT;
17695
17696        // Prune runtime permissions
17697        for (int userId : allUserIds) {
17698            List<PermissionState> runtimePermStates = permissionsState
17699                    .getRuntimePermissionStates(userId);
17700            final int runtimePermCount = runtimePermStates.size();
17701            for (int i = runtimePermCount - 1; i >= 0; i--) {
17702                PermissionState permissionState = runtimePermStates.get(i);
17703                if (!usedPermissions.contains(permissionState.getName())) {
17704                    BasePermission bp = mSettings.mPermissions.get(permissionState.getName());
17705                    if (bp != null) {
17706                        permissionsState.revokeRuntimePermission(bp, userId);
17707                        permissionsState.updatePermissionFlags(bp, userId,
17708                                PackageManager.MASK_PERMISSION_FLAGS, 0);
17709                        runtimePermissionChangedUserIds = ArrayUtils.appendInt(
17710                                runtimePermissionChangedUserIds, userId);
17711                    }
17712                }
17713            }
17714        }
17715
17716        return runtimePermissionChangedUserIds;
17717    }
17718
17719    private void updateSettingsLI(PackageParser.Package newPackage, String installerPackageName,
17720            int[] allUsers, PackageInstalledInfo res, UserHandle user, int installReason) {
17721        // Update the parent package setting
17722        updateSettingsInternalLI(newPackage, installerPackageName, allUsers, res.origUsers,
17723                res, user, installReason);
17724        // Update the child packages setting
17725        final int childCount = (newPackage.childPackages != null)
17726                ? newPackage.childPackages.size() : 0;
17727        for (int i = 0; i < childCount; i++) {
17728            PackageParser.Package childPackage = newPackage.childPackages.get(i);
17729            PackageInstalledInfo childRes = res.addedChildPackages.get(childPackage.packageName);
17730            updateSettingsInternalLI(childPackage, installerPackageName, allUsers,
17731                    childRes.origUsers, childRes, user, installReason);
17732        }
17733    }
17734
17735    private void updateSettingsInternalLI(PackageParser.Package newPackage,
17736            String installerPackageName, int[] allUsers, int[] installedForUsers,
17737            PackageInstalledInfo res, UserHandle user, int installReason) {
17738        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings");
17739
17740        String pkgName = newPackage.packageName;
17741        synchronized (mPackages) {
17742            //write settings. the installStatus will be incomplete at this stage.
17743            //note that the new package setting would have already been
17744            //added to mPackages. It hasn't been persisted yet.
17745            mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_INCOMPLETE);
17746            // TODO: Remove this write? It's also written at the end of this method
17747            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings");
17748            mSettings.writeLPr();
17749            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
17750        }
17751
17752        if (DEBUG_INSTALL) Slog.d(TAG, "New package installed in " + newPackage.codePath);
17753        synchronized (mPackages) {
17754            updatePermissionsLPw(newPackage.packageName, newPackage,
17755                    UPDATE_PERMISSIONS_REPLACE_PKG | (newPackage.permissions.size() > 0
17756                            ? UPDATE_PERMISSIONS_ALL : 0));
17757            // For system-bundled packages, we assume that installing an upgraded version
17758            // of the package implies that the user actually wants to run that new code,
17759            // so we enable the package.
17760            PackageSetting ps = mSettings.mPackages.get(pkgName);
17761            final int userId = user.getIdentifier();
17762            if (ps != null) {
17763                if (isSystemApp(newPackage)) {
17764                    if (DEBUG_INSTALL) {
17765                        Slog.d(TAG, "Implicitly enabling system package on upgrade: " + pkgName);
17766                    }
17767                    // Enable system package for requested users
17768                    if (res.origUsers != null) {
17769                        for (int origUserId : res.origUsers) {
17770                            if (userId == UserHandle.USER_ALL || userId == origUserId) {
17771                                ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT,
17772                                        origUserId, installerPackageName);
17773                            }
17774                        }
17775                    }
17776                    // Also convey the prior install/uninstall state
17777                    if (allUsers != null && installedForUsers != null) {
17778                        for (int currentUserId : allUsers) {
17779                            final boolean installed = ArrayUtils.contains(
17780                                    installedForUsers, currentUserId);
17781                            if (DEBUG_INSTALL) {
17782                                Slog.d(TAG, "    user " + currentUserId + " => " + installed);
17783                            }
17784                            ps.setInstalled(installed, currentUserId);
17785                        }
17786                        // these install state changes will be persisted in the
17787                        // upcoming call to mSettings.writeLPr().
17788                    }
17789                }
17790                // It's implied that when a user requests installation, they want the app to be
17791                // installed and enabled.
17792                if (userId != UserHandle.USER_ALL) {
17793                    ps.setInstalled(true, userId);
17794                    ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, userId, installerPackageName);
17795                }
17796
17797                // When replacing an existing package, preserve the original install reason for all
17798                // users that had the package installed before.
17799                final Set<Integer> previousUserIds = new ArraySet<>();
17800                if (res.removedInfo != null && res.removedInfo.installReasons != null) {
17801                    final int installReasonCount = res.removedInfo.installReasons.size();
17802                    for (int i = 0; i < installReasonCount; i++) {
17803                        final int previousUserId = res.removedInfo.installReasons.keyAt(i);
17804                        final int previousInstallReason = res.removedInfo.installReasons.valueAt(i);
17805                        ps.setInstallReason(previousInstallReason, previousUserId);
17806                        previousUserIds.add(previousUserId);
17807                    }
17808                }
17809
17810                // Set install reason for users that are having the package newly installed.
17811                if (userId == UserHandle.USER_ALL) {
17812                    for (int currentUserId : sUserManager.getUserIds()) {
17813                        if (!previousUserIds.contains(currentUserId)) {
17814                            ps.setInstallReason(installReason, currentUserId);
17815                        }
17816                    }
17817                } else if (!previousUserIds.contains(userId)) {
17818                    ps.setInstallReason(installReason, userId);
17819                }
17820                mSettings.writeKernelMappingLPr(ps);
17821            }
17822            res.name = pkgName;
17823            res.uid = newPackage.applicationInfo.uid;
17824            res.pkg = newPackage;
17825            mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_COMPLETE);
17826            mSettings.setInstallerPackageName(pkgName, installerPackageName);
17827            res.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
17828            //to update install status
17829            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings");
17830            mSettings.writeLPr();
17831            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
17832        }
17833
17834        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
17835    }
17836
17837    private void installPackageTracedLI(InstallArgs args, PackageInstalledInfo res) {
17838        try {
17839            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installPackage");
17840            installPackageLI(args, res);
17841        } finally {
17842            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
17843        }
17844    }
17845
17846    private void installPackageLI(InstallArgs args, PackageInstalledInfo res) {
17847        final int installFlags = args.installFlags;
17848        final String installerPackageName = args.installerPackageName;
17849        final String volumeUuid = args.volumeUuid;
17850        final File tmpPackageFile = new File(args.getCodePath());
17851        final boolean forwardLocked = ((installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0);
17852        final boolean onExternal = (((installFlags & PackageManager.INSTALL_EXTERNAL) != 0)
17853                || (args.volumeUuid != null));
17854        final boolean instantApp = ((installFlags & PackageManager.INSTALL_INSTANT_APP) != 0);
17855        final boolean fullApp = ((installFlags & PackageManager.INSTALL_FULL_APP) != 0);
17856        final boolean forceSdk = ((installFlags & PackageManager.INSTALL_FORCE_SDK) != 0);
17857        boolean replace = false;
17858        int scanFlags = SCAN_NEW_INSTALL | SCAN_UPDATE_SIGNATURE;
17859        if (args.move != null) {
17860            // moving a complete application; perform an initial scan on the new install location
17861            scanFlags |= SCAN_INITIAL;
17862        }
17863        if ((installFlags & PackageManager.INSTALL_DONT_KILL_APP) != 0) {
17864            scanFlags |= SCAN_DONT_KILL_APP;
17865        }
17866        if (instantApp) {
17867            scanFlags |= SCAN_AS_INSTANT_APP;
17868        }
17869        if (fullApp) {
17870            scanFlags |= SCAN_AS_FULL_APP;
17871        }
17872
17873        // Result object to be returned
17874        res.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
17875
17876        if (DEBUG_INSTALL) Slog.d(TAG, "installPackageLI: path=" + tmpPackageFile);
17877
17878        // Sanity check
17879        if (instantApp && (forwardLocked || onExternal)) {
17880            Slog.i(TAG, "Incompatible ephemeral install; fwdLocked=" + forwardLocked
17881                    + " external=" + onExternal);
17882            res.setReturnCode(PackageManager.INSTALL_FAILED_INSTANT_APP_INVALID);
17883            return;
17884        }
17885
17886        // Retrieve PackageSettings and parse package
17887        final int parseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY
17888                | PackageParser.PARSE_ENFORCE_CODE
17889                | (forwardLocked ? PackageParser.PARSE_FORWARD_LOCK : 0)
17890                | (onExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0)
17891                | (instantApp ? PackageParser.PARSE_IS_EPHEMERAL : 0)
17892                | (forceSdk ? PackageParser.PARSE_FORCE_SDK : 0);
17893        PackageParser pp = new PackageParser();
17894        pp.setSeparateProcesses(mSeparateProcesses);
17895        pp.setDisplayMetrics(mMetrics);
17896        pp.setCallback(mPackageParserCallback);
17897
17898        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "parsePackage");
17899        final PackageParser.Package pkg;
17900        try {
17901            pkg = pp.parsePackage(tmpPackageFile, parseFlags);
17902        } catch (PackageParserException e) {
17903            res.setError("Failed parse during installPackageLI", e);
17904            return;
17905        } finally {
17906            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
17907        }
17908
17909        // Instant apps must have target SDK >= O and have targetSanboxVersion >= 2
17910        if (instantApp && pkg.applicationInfo.targetSdkVersion <= Build.VERSION_CODES.N_MR1) {
17911            Slog.w(TAG, "Instant app package " + pkg.packageName + " does not target O");
17912            res.setError(INSTALL_FAILED_SANDBOX_VERSION_DOWNGRADE,
17913                    "Instant app package must target O");
17914            return;
17915        }
17916        if (instantApp && pkg.applicationInfo.targetSandboxVersion != 2) {
17917            Slog.w(TAG, "Instant app package " + pkg.packageName
17918                    + " does not target targetSandboxVersion 2");
17919            res.setError(INSTALL_FAILED_SANDBOX_VERSION_DOWNGRADE,
17920                    "Instant app package must use targetSanboxVersion 2");
17921            return;
17922        }
17923
17924        if (pkg.applicationInfo.isStaticSharedLibrary()) {
17925            // Static shared libraries have synthetic package names
17926            renameStaticSharedLibraryPackage(pkg);
17927
17928            // No static shared libs on external storage
17929            if (onExternal) {
17930                Slog.i(TAG, "Static shared libs can only be installed on internal storage.");
17931                res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION,
17932                        "Packages declaring static-shared libs cannot be updated");
17933                return;
17934            }
17935        }
17936
17937        // If we are installing a clustered package add results for the children
17938        if (pkg.childPackages != null) {
17939            synchronized (mPackages) {
17940                final int childCount = pkg.childPackages.size();
17941                for (int i = 0; i < childCount; i++) {
17942                    PackageParser.Package childPkg = pkg.childPackages.get(i);
17943                    PackageInstalledInfo childRes = new PackageInstalledInfo();
17944                    childRes.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
17945                    childRes.pkg = childPkg;
17946                    childRes.name = childPkg.packageName;
17947                    PackageSetting childPs = mSettings.getPackageLPr(childPkg.packageName);
17948                    if (childPs != null) {
17949                        childRes.origUsers = childPs.queryInstalledUsers(
17950                                sUserManager.getUserIds(), true);
17951                    }
17952                    if ((mPackages.containsKey(childPkg.packageName))) {
17953                        childRes.removedInfo = new PackageRemovedInfo(this);
17954                        childRes.removedInfo.removedPackage = childPkg.packageName;
17955                        childRes.removedInfo.installerPackageName = childPs.installerPackageName;
17956                    }
17957                    if (res.addedChildPackages == null) {
17958                        res.addedChildPackages = new ArrayMap<>();
17959                    }
17960                    res.addedChildPackages.put(childPkg.packageName, childRes);
17961                }
17962            }
17963        }
17964
17965        // If package doesn't declare API override, mark that we have an install
17966        // time CPU ABI override.
17967        if (TextUtils.isEmpty(pkg.cpuAbiOverride)) {
17968            pkg.cpuAbiOverride = args.abiOverride;
17969        }
17970
17971        String pkgName = res.name = pkg.packageName;
17972        if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_TEST_ONLY) != 0) {
17973            if ((installFlags & PackageManager.INSTALL_ALLOW_TEST) == 0) {
17974                res.setError(INSTALL_FAILED_TEST_ONLY, "installPackageLI");
17975                return;
17976            }
17977        }
17978
17979        try {
17980            // either use what we've been given or parse directly from the APK
17981            if (args.certificates != null) {
17982                try {
17983                    PackageParser.populateCertificates(pkg, args.certificates);
17984                } catch (PackageParserException e) {
17985                    // there was something wrong with the certificates we were given;
17986                    // try to pull them from the APK
17987                    PackageParser.collectCertificates(pkg, parseFlags);
17988                }
17989            } else {
17990                PackageParser.collectCertificates(pkg, parseFlags);
17991            }
17992        } catch (PackageParserException e) {
17993            res.setError("Failed collect during installPackageLI", e);
17994            return;
17995        }
17996
17997        // Get rid of all references to package scan path via parser.
17998        pp = null;
17999        String oldCodePath = null;
18000        boolean systemApp = false;
18001        synchronized (mPackages) {
18002            // Check if installing already existing package
18003            if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
18004                String oldName = mSettings.getRenamedPackageLPr(pkgName);
18005                if (pkg.mOriginalPackages != null
18006                        && pkg.mOriginalPackages.contains(oldName)
18007                        && mPackages.containsKey(oldName)) {
18008                    // This package is derived from an original package,
18009                    // and this device has been updating from that original
18010                    // name.  We must continue using the original name, so
18011                    // rename the new package here.
18012                    pkg.setPackageName(oldName);
18013                    pkgName = pkg.packageName;
18014                    replace = true;
18015                    if (DEBUG_INSTALL) Slog.d(TAG, "Replacing existing renamed package: oldName="
18016                            + oldName + " pkgName=" + pkgName);
18017                } else if (mPackages.containsKey(pkgName)) {
18018                    // This package, under its official name, already exists
18019                    // on the device; we should replace it.
18020                    replace = true;
18021                    if (DEBUG_INSTALL) Slog.d(TAG, "Replace existing pacakge: " + pkgName);
18022                }
18023
18024                // Child packages are installed through the parent package
18025                if (pkg.parentPackage != null) {
18026                    res.setError(PackageManager.INSTALL_PARSE_FAILED_BAD_PACKAGE_NAME,
18027                            "Package " + pkg.packageName + " is child of package "
18028                                    + pkg.parentPackage.parentPackage + ". Child packages "
18029                                    + "can be updated only through the parent package.");
18030                    return;
18031                }
18032
18033                if (replace) {
18034                    // Prevent apps opting out from runtime permissions
18035                    PackageParser.Package oldPackage = mPackages.get(pkgName);
18036                    final int oldTargetSdk = oldPackage.applicationInfo.targetSdkVersion;
18037                    final int newTargetSdk = pkg.applicationInfo.targetSdkVersion;
18038                    if (oldTargetSdk > Build.VERSION_CODES.LOLLIPOP_MR1
18039                            && newTargetSdk <= Build.VERSION_CODES.LOLLIPOP_MR1) {
18040                        res.setError(PackageManager.INSTALL_FAILED_PERMISSION_MODEL_DOWNGRADE,
18041                                "Package " + pkg.packageName + " new target SDK " + newTargetSdk
18042                                        + " doesn't support runtime permissions but the old"
18043                                        + " target SDK " + oldTargetSdk + " does.");
18044                        return;
18045                    }
18046                    // Prevent apps from downgrading their targetSandbox.
18047                    final int oldTargetSandbox = oldPackage.applicationInfo.targetSandboxVersion;
18048                    final int newTargetSandbox = pkg.applicationInfo.targetSandboxVersion;
18049                    if (oldTargetSandbox == 2 && newTargetSandbox != 2) {
18050                        res.setError(PackageManager.INSTALL_FAILED_SANDBOX_VERSION_DOWNGRADE,
18051                                "Package " + pkg.packageName + " new target sandbox "
18052                                + newTargetSandbox + " is incompatible with the previous value of"
18053                                + oldTargetSandbox + ".");
18054                        return;
18055                    }
18056
18057                    // Prevent installing of child packages
18058                    if (oldPackage.parentPackage != null) {
18059                        res.setError(PackageManager.INSTALL_PARSE_FAILED_BAD_PACKAGE_NAME,
18060                                "Package " + pkg.packageName + " is child of package "
18061                                        + oldPackage.parentPackage + ". Child packages "
18062                                        + "can be updated only through the parent package.");
18063                        return;
18064                    }
18065                }
18066            }
18067
18068            PackageSetting ps = mSettings.mPackages.get(pkgName);
18069            if (ps != null) {
18070                if (DEBUG_INSTALL) Slog.d(TAG, "Existing package: " + ps);
18071
18072                // Static shared libs have same package with different versions where
18073                // we internally use a synthetic package name to allow multiple versions
18074                // of the same package, therefore we need to compare signatures against
18075                // the package setting for the latest library version.
18076                PackageSetting signatureCheckPs = ps;
18077                if (pkg.applicationInfo.isStaticSharedLibrary()) {
18078                    SharedLibraryEntry libraryEntry = getLatestSharedLibraVersionLPr(pkg);
18079                    if (libraryEntry != null) {
18080                        signatureCheckPs = mSettings.getPackageLPr(libraryEntry.apk);
18081                    }
18082                }
18083
18084                // Quick sanity check that we're signed correctly if updating;
18085                // we'll check this again later when scanning, but we want to
18086                // bail early here before tripping over redefined permissions.
18087                if (shouldCheckUpgradeKeySetLP(signatureCheckPs, scanFlags)) {
18088                    if (!checkUpgradeKeySetLP(signatureCheckPs, pkg)) {
18089                        res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package "
18090                                + pkg.packageName + " upgrade keys do not match the "
18091                                + "previously installed version");
18092                        return;
18093                    }
18094                } else {
18095                    try {
18096                        verifySignaturesLP(signatureCheckPs, pkg);
18097                    } catch (PackageManagerException e) {
18098                        res.setError(e.error, e.getMessage());
18099                        return;
18100                    }
18101                }
18102
18103                oldCodePath = mSettings.mPackages.get(pkgName).codePathString;
18104                if (ps.pkg != null && ps.pkg.applicationInfo != null) {
18105                    systemApp = (ps.pkg.applicationInfo.flags &
18106                            ApplicationInfo.FLAG_SYSTEM) != 0;
18107                }
18108                res.origUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
18109            }
18110
18111            int N = pkg.permissions.size();
18112            for (int i = N-1; i >= 0; i--) {
18113                PackageParser.Permission perm = pkg.permissions.get(i);
18114                BasePermission bp = mSettings.mPermissions.get(perm.info.name);
18115
18116                // Don't allow anyone but the system to define ephemeral permissions.
18117                if ((perm.info.protectionLevel & PermissionInfo.PROTECTION_FLAG_EPHEMERAL) != 0
18118                        && !systemApp) {
18119                    Slog.w(TAG, "Non-System package " + pkg.packageName
18120                            + " attempting to delcare ephemeral permission "
18121                            + perm.info.name + "; Removing ephemeral.");
18122                    perm.info.protectionLevel &= ~PermissionInfo.PROTECTION_FLAG_EPHEMERAL;
18123                }
18124                // Check whether the newly-scanned package wants to define an already-defined perm
18125                if (bp != null) {
18126                    // If the defining package is signed with our cert, it's okay.  This
18127                    // also includes the "updating the same package" case, of course.
18128                    // "updating same package" could also involve key-rotation.
18129                    final boolean sigsOk;
18130                    if (bp.sourcePackage.equals(pkg.packageName)
18131                            && (bp.packageSetting instanceof PackageSetting)
18132                            && (shouldCheckUpgradeKeySetLP((PackageSetting) bp.packageSetting,
18133                                    scanFlags))) {
18134                        sigsOk = checkUpgradeKeySetLP((PackageSetting) bp.packageSetting, pkg);
18135                    } else {
18136                        sigsOk = compareSignatures(bp.packageSetting.signatures.mSignatures,
18137                                pkg.mSignatures) == PackageManager.SIGNATURE_MATCH;
18138                    }
18139                    if (!sigsOk) {
18140                        // If the owning package is the system itself, we log but allow
18141                        // install to proceed; we fail the install on all other permission
18142                        // redefinitions.
18143                        if (!bp.sourcePackage.equals("android")) {
18144                            res.setError(INSTALL_FAILED_DUPLICATE_PERMISSION, "Package "
18145                                    + pkg.packageName + " attempting to redeclare permission "
18146                                    + perm.info.name + " already owned by " + bp.sourcePackage);
18147                            res.origPermission = perm.info.name;
18148                            res.origPackage = bp.sourcePackage;
18149                            return;
18150                        } else {
18151                            Slog.w(TAG, "Package " + pkg.packageName
18152                                    + " attempting to redeclare system permission "
18153                                    + perm.info.name + "; ignoring new declaration");
18154                            pkg.permissions.remove(i);
18155                        }
18156                    } else if (!PLATFORM_PACKAGE_NAME.equals(pkg.packageName)) {
18157                        // Prevent apps to change protection level to dangerous from any other
18158                        // type as this would allow a privilege escalation where an app adds a
18159                        // normal/signature permission in other app's group and later redefines
18160                        // it as dangerous leading to the group auto-grant.
18161                        if ((perm.info.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE)
18162                                == PermissionInfo.PROTECTION_DANGEROUS) {
18163                            if (bp != null && !bp.isRuntime()) {
18164                                Slog.w(TAG, "Package " + pkg.packageName + " trying to change a "
18165                                        + "non-runtime permission " + perm.info.name
18166                                        + " to runtime; keeping old protection level");
18167                                perm.info.protectionLevel = bp.protectionLevel;
18168                            }
18169                        }
18170                    }
18171                }
18172            }
18173        }
18174
18175        if (systemApp) {
18176            if (onExternal) {
18177                // Abort update; system app can't be replaced with app on sdcard
18178                res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION,
18179                        "Cannot install updates to system apps on sdcard");
18180                return;
18181            } else if (instantApp) {
18182                // Abort update; system app can't be replaced with an instant app
18183                res.setError(INSTALL_FAILED_INSTANT_APP_INVALID,
18184                        "Cannot update a system app with an instant app");
18185                return;
18186            }
18187        }
18188
18189        if (args.move != null) {
18190            // We did an in-place move, so dex is ready to roll
18191            scanFlags |= SCAN_NO_DEX;
18192            scanFlags |= SCAN_MOVE;
18193
18194            synchronized (mPackages) {
18195                final PackageSetting ps = mSettings.mPackages.get(pkgName);
18196                if (ps == null) {
18197                    res.setError(INSTALL_FAILED_INTERNAL_ERROR,
18198                            "Missing settings for moved package " + pkgName);
18199                }
18200
18201                // We moved the entire application as-is, so bring over the
18202                // previously derived ABI information.
18203                pkg.applicationInfo.primaryCpuAbi = ps.primaryCpuAbiString;
18204                pkg.applicationInfo.secondaryCpuAbi = ps.secondaryCpuAbiString;
18205            }
18206
18207        } else if (!forwardLocked && !pkg.applicationInfo.isExternalAsec()) {
18208            // Enable SCAN_NO_DEX flag to skip dexopt at a later stage
18209            scanFlags |= SCAN_NO_DEX;
18210
18211            try {
18212                String abiOverride = (TextUtils.isEmpty(pkg.cpuAbiOverride) ?
18213                    args.abiOverride : pkg.cpuAbiOverride);
18214                final boolean extractNativeLibs = !pkg.isLibrary();
18215                derivePackageAbi(pkg, new File(pkg.codePath), abiOverride,
18216                        extractNativeLibs, mAppLib32InstallDir);
18217            } catch (PackageManagerException pme) {
18218                Slog.e(TAG, "Error deriving application ABI", pme);
18219                res.setError(INSTALL_FAILED_INTERNAL_ERROR, "Error deriving application ABI");
18220                return;
18221            }
18222
18223            // Shared libraries for the package need to be updated.
18224            synchronized (mPackages) {
18225                try {
18226                    updateSharedLibrariesLPr(pkg, null);
18227                } catch (PackageManagerException e) {
18228                    Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
18229                }
18230            }
18231
18232            // dexopt can take some time to complete, so, for instant apps, we skip this
18233            // step during installation. Instead, we'll take extra time the first time the
18234            // instant app starts. It's preferred to do it this way to provide continuous
18235            // progress to the user instead of mysteriously blocking somewhere in the
18236            // middle of running an instant app. The default behaviour can be overridden
18237            // via gservices.
18238            if (!instantApp || Global.getInt(
18239                        mContext.getContentResolver(), Global.INSTANT_APP_DEXOPT_ENABLED, 0) != 0) {
18240                Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt");
18241                // Do not run PackageDexOptimizer through the local performDexOpt
18242                // method because `pkg` may not be in `mPackages` yet.
18243                //
18244                // Also, don't fail application installs if the dexopt step fails.
18245                DexoptOptions dexoptOptions = new DexoptOptions(pkg.packageName,
18246                        REASON_INSTALL,
18247                        DexoptOptions.DEXOPT_BOOT_COMPLETE);
18248                mPackageDexOptimizer.performDexOpt(pkg, pkg.usesLibraryFiles,
18249                        null /* instructionSets */,
18250                        getOrCreateCompilerPackageStats(pkg),
18251                        mDexManager.isUsedByOtherApps(pkg.packageName),
18252                        dexoptOptions);
18253                Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
18254            }
18255
18256            // Notify BackgroundDexOptService that the package has been changed.
18257            // If this is an update of a package which used to fail to compile,
18258            // BDOS will remove it from its blacklist.
18259            // TODO: Layering violation
18260            BackgroundDexOptService.notifyPackageChanged(pkg.packageName);
18261        }
18262
18263        if (!args.doRename(res.returnCode, pkg, oldCodePath)) {
18264            res.setError(INSTALL_FAILED_INSUFFICIENT_STORAGE, "Failed rename");
18265            return;
18266        }
18267
18268        startIntentFilterVerifications(args.user.getIdentifier(), replace, pkg);
18269
18270        try (PackageFreezer freezer = freezePackageForInstall(pkgName, installFlags,
18271                "installPackageLI")) {
18272            if (replace) {
18273                if (pkg.applicationInfo.isStaticSharedLibrary()) {
18274                    // Static libs have a synthetic package name containing the version
18275                    // and cannot be updated as an update would get a new package name,
18276                    // unless this is the exact same version code which is useful for
18277                    // development.
18278                    PackageParser.Package existingPkg = mPackages.get(pkg.packageName);
18279                    if (existingPkg != null && existingPkg.mVersionCode != pkg.mVersionCode) {
18280                        res.setError(INSTALL_FAILED_DUPLICATE_PACKAGE, "Packages declaring "
18281                                + "static-shared libs cannot be updated");
18282                        return;
18283                    }
18284                }
18285                replacePackageLIF(pkg, parseFlags, scanFlags | SCAN_REPLACING, args.user,
18286                        installerPackageName, res, args.installReason);
18287            } else {
18288                installNewPackageLIF(pkg, parseFlags, scanFlags | SCAN_DELETE_DATA_ON_FAILURES,
18289                        args.user, installerPackageName, volumeUuid, res, args.installReason);
18290            }
18291        }
18292
18293        synchronized (mPackages) {
18294            final PackageSetting ps = mSettings.mPackages.get(pkgName);
18295            if (ps != null) {
18296                res.newUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
18297                ps.setUpdateAvailable(false /*updateAvailable*/);
18298            }
18299
18300            final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
18301            for (int i = 0; i < childCount; i++) {
18302                PackageParser.Package childPkg = pkg.childPackages.get(i);
18303                PackageInstalledInfo childRes = res.addedChildPackages.get(childPkg.packageName);
18304                PackageSetting childPs = mSettings.getPackageLPr(childPkg.packageName);
18305                if (childPs != null) {
18306                    childRes.newUsers = childPs.queryInstalledUsers(
18307                            sUserManager.getUserIds(), true);
18308                }
18309            }
18310
18311            if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
18312                updateSequenceNumberLP(ps, res.newUsers);
18313                updateInstantAppInstallerLocked(pkgName);
18314            }
18315        }
18316    }
18317
18318    private void startIntentFilterVerifications(int userId, boolean replacing,
18319            PackageParser.Package pkg) {
18320        if (mIntentFilterVerifierComponent == null) {
18321            Slog.w(TAG, "No IntentFilter verification will not be done as "
18322                    + "there is no IntentFilterVerifier available!");
18323            return;
18324        }
18325
18326        final int verifierUid = getPackageUid(
18327                mIntentFilterVerifierComponent.getPackageName(),
18328                MATCH_DEBUG_TRIAGED_MISSING,
18329                (userId == UserHandle.USER_ALL) ? UserHandle.USER_SYSTEM : userId);
18330
18331        Message msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS);
18332        msg.obj = new IFVerificationParams(pkg, replacing, userId, verifierUid);
18333        mHandler.sendMessage(msg);
18334
18335        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
18336        for (int i = 0; i < childCount; i++) {
18337            PackageParser.Package childPkg = pkg.childPackages.get(i);
18338            msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS);
18339            msg.obj = new IFVerificationParams(childPkg, replacing, userId, verifierUid);
18340            mHandler.sendMessage(msg);
18341        }
18342    }
18343
18344    private void verifyIntentFiltersIfNeeded(int userId, int verifierUid, boolean replacing,
18345            PackageParser.Package pkg) {
18346        int size = pkg.activities.size();
18347        if (size == 0) {
18348            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
18349                    "No activity, so no need to verify any IntentFilter!");
18350            return;
18351        }
18352
18353        final boolean hasDomainURLs = hasDomainURLs(pkg);
18354        if (!hasDomainURLs) {
18355            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
18356                    "No domain URLs, so no need to verify any IntentFilter!");
18357            return;
18358        }
18359
18360        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Checking for userId:" + userId
18361                + " if any IntentFilter from the " + size
18362                + " Activities needs verification ...");
18363
18364        int count = 0;
18365        final String packageName = pkg.packageName;
18366
18367        synchronized (mPackages) {
18368            // If this is a new install and we see that we've already run verification for this
18369            // package, we have nothing to do: it means the state was restored from backup.
18370            if (!replacing) {
18371                IntentFilterVerificationInfo ivi =
18372                        mSettings.getIntentFilterVerificationLPr(packageName);
18373                if (ivi != null) {
18374                    if (DEBUG_DOMAIN_VERIFICATION) {
18375                        Slog.i(TAG, "Package " + packageName+ " already verified: status="
18376                                + ivi.getStatusString());
18377                    }
18378                    return;
18379                }
18380            }
18381
18382            // If any filters need to be verified, then all need to be.
18383            boolean needToVerify = false;
18384            for (PackageParser.Activity a : pkg.activities) {
18385                for (ActivityIntentInfo filter : a.intents) {
18386                    if (filter.needsVerification() && needsNetworkVerificationLPr(filter)) {
18387                        if (DEBUG_DOMAIN_VERIFICATION) {
18388                            Slog.d(TAG, "Intent filter needs verification, so processing all filters");
18389                        }
18390                        needToVerify = true;
18391                        break;
18392                    }
18393                }
18394            }
18395
18396            if (needToVerify) {
18397                final int verificationId = mIntentFilterVerificationToken++;
18398                for (PackageParser.Activity a : pkg.activities) {
18399                    for (ActivityIntentInfo filter : a.intents) {
18400                        if (filter.handlesWebUris(true) && needsNetworkVerificationLPr(filter)) {
18401                            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
18402                                    "Verification needed for IntentFilter:" + filter.toString());
18403                            mIntentFilterVerifier.addOneIntentFilterVerification(
18404                                    verifierUid, userId, verificationId, filter, packageName);
18405                            count++;
18406                        }
18407                    }
18408                }
18409            }
18410        }
18411
18412        if (count > 0) {
18413            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Starting " + count
18414                    + " IntentFilter verification" + (count > 1 ? "s" : "")
18415                    +  " for userId:" + userId);
18416            mIntentFilterVerifier.startVerifications(userId);
18417        } else {
18418            if (DEBUG_DOMAIN_VERIFICATION) {
18419                Slog.d(TAG, "No filters or not all autoVerify for " + packageName);
18420            }
18421        }
18422    }
18423
18424    private boolean needsNetworkVerificationLPr(ActivityIntentInfo filter) {
18425        final ComponentName cn  = filter.activity.getComponentName();
18426        final String packageName = cn.getPackageName();
18427
18428        IntentFilterVerificationInfo ivi = mSettings.getIntentFilterVerificationLPr(
18429                packageName);
18430        if (ivi == null) {
18431            return true;
18432        }
18433        int status = ivi.getStatus();
18434        switch (status) {
18435            case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED:
18436            case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK:
18437                return true;
18438
18439            default:
18440                // Nothing to do
18441                return false;
18442        }
18443    }
18444
18445    private static boolean isMultiArch(ApplicationInfo info) {
18446        return (info.flags & ApplicationInfo.FLAG_MULTIARCH) != 0;
18447    }
18448
18449    private static boolean isExternal(PackageParser.Package pkg) {
18450        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
18451    }
18452
18453    private static boolean isExternal(PackageSetting ps) {
18454        return (ps.pkgFlags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
18455    }
18456
18457    private static boolean isSystemApp(PackageParser.Package pkg) {
18458        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0;
18459    }
18460
18461    private static boolean isPrivilegedApp(PackageParser.Package pkg) {
18462        return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0;
18463    }
18464
18465    private static boolean hasDomainURLs(PackageParser.Package pkg) {
18466        return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_HAS_DOMAIN_URLS) != 0;
18467    }
18468
18469    private static boolean isSystemApp(PackageSetting ps) {
18470        return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0;
18471    }
18472
18473    private static boolean isUpdatedSystemApp(PackageSetting ps) {
18474        return (ps.pkgFlags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0;
18475    }
18476
18477    private int packageFlagsToInstallFlags(PackageSetting ps) {
18478        int installFlags = 0;
18479        if (isExternal(ps) && TextUtils.isEmpty(ps.volumeUuid)) {
18480            // This existing package was an external ASEC install when we have
18481            // the external flag without a UUID
18482            installFlags |= PackageManager.INSTALL_EXTERNAL;
18483        }
18484        if (ps.isForwardLocked()) {
18485            installFlags |= PackageManager.INSTALL_FORWARD_LOCK;
18486        }
18487        return installFlags;
18488    }
18489
18490    private String getVolumeUuidForPackage(PackageParser.Package pkg) {
18491        if (isExternal(pkg)) {
18492            if (TextUtils.isEmpty(pkg.volumeUuid)) {
18493                return StorageManager.UUID_PRIMARY_PHYSICAL;
18494            } else {
18495                return pkg.volumeUuid;
18496            }
18497        } else {
18498            return StorageManager.UUID_PRIVATE_INTERNAL;
18499        }
18500    }
18501
18502    private VersionInfo getSettingsVersionForPackage(PackageParser.Package pkg) {
18503        if (isExternal(pkg)) {
18504            if (TextUtils.isEmpty(pkg.volumeUuid)) {
18505                return mSettings.getExternalVersion();
18506            } else {
18507                return mSettings.findOrCreateVersion(pkg.volumeUuid);
18508            }
18509        } else {
18510            return mSettings.getInternalVersion();
18511        }
18512    }
18513
18514    private void deleteTempPackageFiles() {
18515        final FilenameFilter filter = new FilenameFilter() {
18516            public boolean accept(File dir, String name) {
18517                return name.startsWith("vmdl") && name.endsWith(".tmp");
18518            }
18519        };
18520        for (File file : mDrmAppPrivateInstallDir.listFiles(filter)) {
18521            file.delete();
18522        }
18523    }
18524
18525    @Override
18526    public void deletePackageAsUser(String packageName, int versionCode,
18527            IPackageDeleteObserver observer, int userId, int flags) {
18528        deletePackageVersioned(new VersionedPackage(packageName, versionCode),
18529                new LegacyPackageDeleteObserver(observer).getBinder(), userId, flags);
18530    }
18531
18532    @Override
18533    public void deletePackageVersioned(VersionedPackage versionedPackage,
18534            final IPackageDeleteObserver2 observer, final int userId, final int deleteFlags) {
18535        final int callingUid = Binder.getCallingUid();
18536        mContext.enforceCallingOrSelfPermission(
18537                android.Manifest.permission.DELETE_PACKAGES, null);
18538        final boolean canViewInstantApps = canViewInstantApps(callingUid, userId);
18539        Preconditions.checkNotNull(versionedPackage);
18540        Preconditions.checkNotNull(observer);
18541        Preconditions.checkArgumentInRange(versionedPackage.getVersionCode(),
18542                PackageManager.VERSION_CODE_HIGHEST,
18543                Integer.MAX_VALUE, "versionCode must be >= -1");
18544
18545        final String packageName = versionedPackage.getPackageName();
18546        final int versionCode = versionedPackage.getVersionCode();
18547        final String internalPackageName;
18548        synchronized (mPackages) {
18549            // Normalize package name to handle renamed packages and static libs
18550            internalPackageName = resolveInternalPackageNameLPr(versionedPackage.getPackageName(),
18551                    versionedPackage.getVersionCode());
18552        }
18553
18554        final int uid = Binder.getCallingUid();
18555        if (!isOrphaned(internalPackageName)
18556                && !isCallerAllowedToSilentlyUninstall(uid, internalPackageName)) {
18557            try {
18558                final Intent intent = new Intent(Intent.ACTION_UNINSTALL_PACKAGE);
18559                intent.setData(Uri.fromParts(PACKAGE_SCHEME, packageName, null));
18560                intent.putExtra(PackageInstaller.EXTRA_CALLBACK, observer.asBinder());
18561                observer.onUserActionRequired(intent);
18562            } catch (RemoteException re) {
18563            }
18564            return;
18565        }
18566        final boolean deleteAllUsers = (deleteFlags & PackageManager.DELETE_ALL_USERS) != 0;
18567        final int[] users = deleteAllUsers ? sUserManager.getUserIds() : new int[]{ userId };
18568        if (UserHandle.getUserId(uid) != userId || (deleteAllUsers && users.length > 1)) {
18569            mContext.enforceCallingOrSelfPermission(
18570                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
18571                    "deletePackage for user " + userId);
18572        }
18573
18574        if (isUserRestricted(userId, UserManager.DISALLOW_UNINSTALL_APPS)) {
18575            try {
18576                observer.onPackageDeleted(packageName,
18577                        PackageManager.DELETE_FAILED_USER_RESTRICTED, null);
18578            } catch (RemoteException re) {
18579            }
18580            return;
18581        }
18582
18583        if (!deleteAllUsers && getBlockUninstallForUser(internalPackageName, userId)) {
18584            try {
18585                observer.onPackageDeleted(packageName,
18586                        PackageManager.DELETE_FAILED_OWNER_BLOCKED, null);
18587            } catch (RemoteException re) {
18588            }
18589            return;
18590        }
18591
18592        if (DEBUG_REMOVE) {
18593            Slog.d(TAG, "deletePackageAsUser: pkg=" + internalPackageName + " user=" + userId
18594                    + " deleteAllUsers: " + deleteAllUsers + " version="
18595                    + (versionCode == PackageManager.VERSION_CODE_HIGHEST
18596                    ? "VERSION_CODE_HIGHEST" : versionCode));
18597        }
18598        // Queue up an async operation since the package deletion may take a little while.
18599        mHandler.post(new Runnable() {
18600            public void run() {
18601                mHandler.removeCallbacks(this);
18602                int returnCode;
18603                final PackageSetting ps = mSettings.mPackages.get(internalPackageName);
18604                boolean doDeletePackage = true;
18605                if (ps != null) {
18606                    final boolean targetIsInstantApp =
18607                            ps.getInstantApp(UserHandle.getUserId(callingUid));
18608                    doDeletePackage = !targetIsInstantApp
18609                            || canViewInstantApps;
18610                }
18611                if (doDeletePackage) {
18612                    if (!deleteAllUsers) {
18613                        returnCode = deletePackageX(internalPackageName, versionCode,
18614                                userId, deleteFlags);
18615                    } else {
18616                        int[] blockUninstallUserIds = getBlockUninstallForUsers(
18617                                internalPackageName, users);
18618                        // If nobody is blocking uninstall, proceed with delete for all users
18619                        if (ArrayUtils.isEmpty(blockUninstallUserIds)) {
18620                            returnCode = deletePackageX(internalPackageName, versionCode,
18621                                    userId, deleteFlags);
18622                        } else {
18623                            // Otherwise uninstall individually for users with blockUninstalls=false
18624                            final int userFlags = deleteFlags & ~PackageManager.DELETE_ALL_USERS;
18625                            for (int userId : users) {
18626                                if (!ArrayUtils.contains(blockUninstallUserIds, userId)) {
18627                                    returnCode = deletePackageX(internalPackageName, versionCode,
18628                                            userId, userFlags);
18629                                    if (returnCode != PackageManager.DELETE_SUCCEEDED) {
18630                                        Slog.w(TAG, "Package delete failed for user " + userId
18631                                                + ", returnCode " + returnCode);
18632                                    }
18633                                }
18634                            }
18635                            // The app has only been marked uninstalled for certain users.
18636                            // We still need to report that delete was blocked
18637                            returnCode = PackageManager.DELETE_FAILED_OWNER_BLOCKED;
18638                        }
18639                    }
18640                } else {
18641                    returnCode = PackageManager.DELETE_FAILED_INTERNAL_ERROR;
18642                }
18643                try {
18644                    observer.onPackageDeleted(packageName, returnCode, null);
18645                } catch (RemoteException e) {
18646                    Log.i(TAG, "Observer no longer exists.");
18647                } //end catch
18648            } //end run
18649        });
18650    }
18651
18652    private String resolveExternalPackageNameLPr(PackageParser.Package pkg) {
18653        if (pkg.staticSharedLibName != null) {
18654            return pkg.manifestPackageName;
18655        }
18656        return pkg.packageName;
18657    }
18658
18659    private String resolveInternalPackageNameLPr(String packageName, int versionCode) {
18660        // Handle renamed packages
18661        String normalizedPackageName = mSettings.getRenamedPackageLPr(packageName);
18662        packageName = normalizedPackageName != null ? normalizedPackageName : packageName;
18663
18664        // Is this a static library?
18665        SparseArray<SharedLibraryEntry> versionedLib =
18666                mStaticLibsByDeclaringPackage.get(packageName);
18667        if (versionedLib == null || versionedLib.size() <= 0) {
18668            return packageName;
18669        }
18670
18671        // Figure out which lib versions the caller can see
18672        SparseIntArray versionsCallerCanSee = null;
18673        final int callingAppId = UserHandle.getAppId(Binder.getCallingUid());
18674        if (callingAppId != Process.SYSTEM_UID && callingAppId != Process.SHELL_UID
18675                && callingAppId != Process.ROOT_UID) {
18676            versionsCallerCanSee = new SparseIntArray();
18677            String libName = versionedLib.valueAt(0).info.getName();
18678            String[] uidPackages = getPackagesForUid(Binder.getCallingUid());
18679            if (uidPackages != null) {
18680                for (String uidPackage : uidPackages) {
18681                    PackageSetting ps = mSettings.getPackageLPr(uidPackage);
18682                    final int libIdx = ArrayUtils.indexOf(ps.usesStaticLibraries, libName);
18683                    if (libIdx >= 0) {
18684                        final int libVersion = ps.usesStaticLibrariesVersions[libIdx];
18685                        versionsCallerCanSee.append(libVersion, libVersion);
18686                    }
18687                }
18688            }
18689        }
18690
18691        // Caller can see nothing - done
18692        if (versionsCallerCanSee != null && versionsCallerCanSee.size() <= 0) {
18693            return packageName;
18694        }
18695
18696        // Find the version the caller can see and the app version code
18697        SharedLibraryEntry highestVersion = null;
18698        final int versionCount = versionedLib.size();
18699        for (int i = 0; i < versionCount; i++) {
18700            SharedLibraryEntry libEntry = versionedLib.valueAt(i);
18701            if (versionsCallerCanSee != null && versionsCallerCanSee.indexOfKey(
18702                    libEntry.info.getVersion()) < 0) {
18703                continue;
18704            }
18705            final int libVersionCode = libEntry.info.getDeclaringPackage().getVersionCode();
18706            if (versionCode != PackageManager.VERSION_CODE_HIGHEST) {
18707                if (libVersionCode == versionCode) {
18708                    return libEntry.apk;
18709                }
18710            } else if (highestVersion == null) {
18711                highestVersion = libEntry;
18712            } else if (libVersionCode  > highestVersion.info
18713                    .getDeclaringPackage().getVersionCode()) {
18714                highestVersion = libEntry;
18715            }
18716        }
18717
18718        if (highestVersion != null) {
18719            return highestVersion.apk;
18720        }
18721
18722        return packageName;
18723    }
18724
18725    private boolean isCallerAllowedToSilentlyUninstall(int callingUid, String pkgName) {
18726        if (callingUid == Process.SHELL_UID || callingUid == Process.ROOT_UID
18727              || UserHandle.getAppId(callingUid) == Process.SYSTEM_UID) {
18728            return true;
18729        }
18730        final int callingUserId = UserHandle.getUserId(callingUid);
18731        // If the caller installed the pkgName, then allow it to silently uninstall.
18732        if (callingUid == getPackageUid(getInstallerPackageName(pkgName), 0, callingUserId)) {
18733            return true;
18734        }
18735
18736        // Allow package verifier to silently uninstall.
18737        if (mRequiredVerifierPackage != null &&
18738                callingUid == getPackageUid(mRequiredVerifierPackage, 0, callingUserId)) {
18739            return true;
18740        }
18741
18742        // Allow package uninstaller to silently uninstall.
18743        if (mRequiredUninstallerPackage != null &&
18744                callingUid == getPackageUid(mRequiredUninstallerPackage, 0, callingUserId)) {
18745            return true;
18746        }
18747
18748        // Allow storage manager to silently uninstall.
18749        if (mStorageManagerPackage != null &&
18750                callingUid == getPackageUid(mStorageManagerPackage, 0, callingUserId)) {
18751            return true;
18752        }
18753
18754        // Allow caller having MANAGE_PROFILE_AND_DEVICE_OWNERS permission to silently
18755        // uninstall for device owner provisioning.
18756        if (checkUidPermission(MANAGE_PROFILE_AND_DEVICE_OWNERS, callingUid)
18757                == PERMISSION_GRANTED) {
18758            return true;
18759        }
18760
18761        return false;
18762    }
18763
18764    private int[] getBlockUninstallForUsers(String packageName, int[] userIds) {
18765        int[] result = EMPTY_INT_ARRAY;
18766        for (int userId : userIds) {
18767            if (getBlockUninstallForUser(packageName, userId)) {
18768                result = ArrayUtils.appendInt(result, userId);
18769            }
18770        }
18771        return result;
18772    }
18773
18774    @Override
18775    public boolean isPackageDeviceAdminOnAnyUser(String packageName) {
18776        final int callingUid = Binder.getCallingUid();
18777        if (getInstantAppPackageName(callingUid) != null
18778                && !isCallerSameApp(packageName, callingUid)) {
18779            return false;
18780        }
18781        return isPackageDeviceAdmin(packageName, UserHandle.USER_ALL);
18782    }
18783
18784    private boolean isPackageDeviceAdmin(String packageName, int userId) {
18785        IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface(
18786                ServiceManager.getService(Context.DEVICE_POLICY_SERVICE));
18787        try {
18788            if (dpm != null) {
18789                final ComponentName deviceOwnerComponentName = dpm.getDeviceOwnerComponent(
18790                        /* callingUserOnly =*/ false);
18791                final String deviceOwnerPackageName = deviceOwnerComponentName == null ? null
18792                        : deviceOwnerComponentName.getPackageName();
18793                // Does the package contains the device owner?
18794                // TODO Do we have to do it even if userId != UserHandle.USER_ALL?  Otherwise,
18795                // this check is probably not needed, since DO should be registered as a device
18796                // admin on some user too. (Original bug for this: b/17657954)
18797                if (packageName.equals(deviceOwnerPackageName)) {
18798                    return true;
18799                }
18800                // Does it contain a device admin for any user?
18801                int[] users;
18802                if (userId == UserHandle.USER_ALL) {
18803                    users = sUserManager.getUserIds();
18804                } else {
18805                    users = new int[]{userId};
18806                }
18807                for (int i = 0; i < users.length; ++i) {
18808                    if (dpm.packageHasActiveAdmins(packageName, users[i])) {
18809                        return true;
18810                    }
18811                }
18812            }
18813        } catch (RemoteException e) {
18814        }
18815        return false;
18816    }
18817
18818    private boolean shouldKeepUninstalledPackageLPr(String packageName) {
18819        return mKeepUninstalledPackages != null && mKeepUninstalledPackages.contains(packageName);
18820    }
18821
18822    /**
18823     *  This method is an internal method that could be get invoked either
18824     *  to delete an installed package or to clean up a failed installation.
18825     *  After deleting an installed package, a broadcast is sent to notify any
18826     *  listeners that the package has been removed. For cleaning up a failed
18827     *  installation, the broadcast is not necessary since the package's
18828     *  installation wouldn't have sent the initial broadcast either
18829     *  The key steps in deleting a package are
18830     *  deleting the package information in internal structures like mPackages,
18831     *  deleting the packages base directories through installd
18832     *  updating mSettings to reflect current status
18833     *  persisting settings for later use
18834     *  sending a broadcast if necessary
18835     */
18836    int deletePackageX(String packageName, int versionCode, int userId, int deleteFlags) {
18837        final PackageRemovedInfo info = new PackageRemovedInfo(this);
18838        final boolean res;
18839
18840        final int removeUser = (deleteFlags & PackageManager.DELETE_ALL_USERS) != 0
18841                ? UserHandle.USER_ALL : userId;
18842
18843        if (isPackageDeviceAdmin(packageName, removeUser)) {
18844            Slog.w(TAG, "Not removing package " + packageName + ": has active device admin");
18845            return PackageManager.DELETE_FAILED_DEVICE_POLICY_MANAGER;
18846        }
18847
18848        PackageSetting uninstalledPs = null;
18849        PackageParser.Package pkg = null;
18850
18851        // for the uninstall-updates case and restricted profiles, remember the per-
18852        // user handle installed state
18853        int[] allUsers;
18854        synchronized (mPackages) {
18855            uninstalledPs = mSettings.mPackages.get(packageName);
18856            if (uninstalledPs == null) {
18857                Slog.w(TAG, "Not removing non-existent package " + packageName);
18858                return PackageManager.DELETE_FAILED_INTERNAL_ERROR;
18859            }
18860
18861            if (versionCode != PackageManager.VERSION_CODE_HIGHEST
18862                    && uninstalledPs.versionCode != versionCode) {
18863                Slog.w(TAG, "Not removing package " + packageName + " with versionCode "
18864                        + uninstalledPs.versionCode + " != " + versionCode);
18865                return PackageManager.DELETE_FAILED_INTERNAL_ERROR;
18866            }
18867
18868            // Static shared libs can be declared by any package, so let us not
18869            // allow removing a package if it provides a lib others depend on.
18870            pkg = mPackages.get(packageName);
18871
18872            allUsers = sUserManager.getUserIds();
18873
18874            if (pkg != null && pkg.staticSharedLibName != null) {
18875                SharedLibraryEntry libEntry = getSharedLibraryEntryLPr(pkg.staticSharedLibName,
18876                        pkg.staticSharedLibVersion);
18877                if (libEntry != null) {
18878                    for (int currUserId : allUsers) {
18879                        if (removeUser != UserHandle.USER_ALL && removeUser != currUserId) {
18880                            continue;
18881                        }
18882                        List<VersionedPackage> libClientPackages = getPackagesUsingSharedLibraryLPr(
18883                                libEntry.info, 0, currUserId);
18884                        if (!ArrayUtils.isEmpty(libClientPackages)) {
18885                            Slog.w(TAG, "Not removing package " + pkg.manifestPackageName
18886                                    + " hosting lib " + libEntry.info.getName() + " version "
18887                                    + libEntry.info.getVersion() + " used by " + libClientPackages
18888                                    + " for user " + currUserId);
18889                            return PackageManager.DELETE_FAILED_USED_SHARED_LIBRARY;
18890                        }
18891                    }
18892                }
18893            }
18894
18895            info.origUsers = uninstalledPs.queryInstalledUsers(allUsers, true);
18896        }
18897
18898        final int freezeUser;
18899        if (isUpdatedSystemApp(uninstalledPs)
18900                && ((deleteFlags & PackageManager.DELETE_SYSTEM_APP) == 0)) {
18901            // We're downgrading a system app, which will apply to all users, so
18902            // freeze them all during the downgrade
18903            freezeUser = UserHandle.USER_ALL;
18904        } else {
18905            freezeUser = removeUser;
18906        }
18907
18908        synchronized (mInstallLock) {
18909            if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageX: pkg=" + packageName + " user=" + userId);
18910            try (PackageFreezer freezer = freezePackageForDelete(packageName, freezeUser,
18911                    deleteFlags, "deletePackageX")) {
18912                res = deletePackageLIF(packageName, UserHandle.of(removeUser), true, allUsers,
18913                        deleteFlags | FLAGS_REMOVE_CHATTY, info, true, null);
18914            }
18915            synchronized (mPackages) {
18916                if (res) {
18917                    if (pkg != null) {
18918                        mInstantAppRegistry.onPackageUninstalledLPw(pkg, info.removedUsers);
18919                    }
18920                    updateSequenceNumberLP(uninstalledPs, info.removedUsers);
18921                    updateInstantAppInstallerLocked(packageName);
18922                }
18923            }
18924        }
18925
18926        if (res) {
18927            final boolean killApp = (deleteFlags & PackageManager.DELETE_DONT_KILL_APP) == 0;
18928            info.sendPackageRemovedBroadcasts(killApp);
18929            info.sendSystemPackageUpdatedBroadcasts();
18930            info.sendSystemPackageAppearedBroadcasts();
18931        }
18932        // Force a gc here.
18933        Runtime.getRuntime().gc();
18934        // Delete the resources here after sending the broadcast to let
18935        // other processes clean up before deleting resources.
18936        if (info.args != null) {
18937            synchronized (mInstallLock) {
18938                info.args.doPostDeleteLI(true);
18939            }
18940        }
18941
18942        return res ? PackageManager.DELETE_SUCCEEDED : PackageManager.DELETE_FAILED_INTERNAL_ERROR;
18943    }
18944
18945    static class PackageRemovedInfo {
18946        final PackageSender packageSender;
18947        String removedPackage;
18948        String installerPackageName;
18949        int uid = -1;
18950        int removedAppId = -1;
18951        int[] origUsers;
18952        int[] removedUsers = null;
18953        int[] broadcastUsers = null;
18954        SparseArray<Integer> installReasons;
18955        boolean isRemovedPackageSystemUpdate = false;
18956        boolean isUpdate;
18957        boolean dataRemoved;
18958        boolean removedForAllUsers;
18959        boolean isStaticSharedLib;
18960        // Clean up resources deleted packages.
18961        InstallArgs args = null;
18962        ArrayMap<String, PackageRemovedInfo> removedChildPackages;
18963        ArrayMap<String, PackageInstalledInfo> appearedChildPackages;
18964
18965        PackageRemovedInfo(PackageSender packageSender) {
18966            this.packageSender = packageSender;
18967        }
18968
18969        void sendPackageRemovedBroadcasts(boolean killApp) {
18970            sendPackageRemovedBroadcastInternal(killApp);
18971            final int childCount = removedChildPackages != null ? removedChildPackages.size() : 0;
18972            for (int i = 0; i < childCount; i++) {
18973                PackageRemovedInfo childInfo = removedChildPackages.valueAt(i);
18974                childInfo.sendPackageRemovedBroadcastInternal(killApp);
18975            }
18976        }
18977
18978        void sendSystemPackageUpdatedBroadcasts() {
18979            if (isRemovedPackageSystemUpdate) {
18980                sendSystemPackageUpdatedBroadcastsInternal();
18981                final int childCount = (removedChildPackages != null)
18982                        ? removedChildPackages.size() : 0;
18983                for (int i = 0; i < childCount; i++) {
18984                    PackageRemovedInfo childInfo = removedChildPackages.valueAt(i);
18985                    if (childInfo.isRemovedPackageSystemUpdate) {
18986                        childInfo.sendSystemPackageUpdatedBroadcastsInternal();
18987                    }
18988                }
18989            }
18990        }
18991
18992        void sendSystemPackageAppearedBroadcasts() {
18993            final int packageCount = (appearedChildPackages != null)
18994                    ? appearedChildPackages.size() : 0;
18995            for (int i = 0; i < packageCount; i++) {
18996                PackageInstalledInfo installedInfo = appearedChildPackages.valueAt(i);
18997                packageSender.sendPackageAddedForNewUsers(installedInfo.name,
18998                    true, UserHandle.getAppId(installedInfo.uid),
18999                    installedInfo.newUsers);
19000            }
19001        }
19002
19003        private void sendSystemPackageUpdatedBroadcastsInternal() {
19004            Bundle extras = new Bundle(2);
19005            extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid);
19006            extras.putBoolean(Intent.EXTRA_REPLACING, true);
19007            packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
19008                removedPackage, extras, 0, null /*targetPackage*/, null, null);
19009            packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED,
19010                removedPackage, extras, 0, null /*targetPackage*/, null, null);
19011            packageSender.sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED,
19012                null, null, 0, removedPackage, null, null);
19013            if (installerPackageName != null) {
19014                packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
19015                        removedPackage, extras, 0 /*flags*/,
19016                        installerPackageName, null, null);
19017                packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED,
19018                        removedPackage, extras, 0 /*flags*/,
19019                        installerPackageName, null, null);
19020            }
19021        }
19022
19023        private void sendPackageRemovedBroadcastInternal(boolean killApp) {
19024            // Don't send static shared library removal broadcasts as these
19025            // libs are visible only the the apps that depend on them an one
19026            // cannot remove the library if it has a dependency.
19027            if (isStaticSharedLib) {
19028                return;
19029            }
19030            Bundle extras = new Bundle(2);
19031            extras.putInt(Intent.EXTRA_UID, removedAppId >= 0  ? removedAppId : uid);
19032            extras.putBoolean(Intent.EXTRA_DATA_REMOVED, dataRemoved);
19033            extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, !killApp);
19034            if (isUpdate || isRemovedPackageSystemUpdate) {
19035                extras.putBoolean(Intent.EXTRA_REPLACING, true);
19036            }
19037            extras.putBoolean(Intent.EXTRA_REMOVED_FOR_ALL_USERS, removedForAllUsers);
19038            if (removedPackage != null) {
19039                packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED,
19040                    removedPackage, extras, 0, null /*targetPackage*/, null, broadcastUsers);
19041                if (installerPackageName != null) {
19042                    packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED,
19043                            removedPackage, extras, 0 /*flags*/,
19044                            installerPackageName, null, broadcastUsers);
19045                }
19046                if (dataRemoved && !isRemovedPackageSystemUpdate) {
19047                    packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_FULLY_REMOVED,
19048                        removedPackage, extras,
19049                        Intent.FLAG_RECEIVER_INCLUDE_BACKGROUND,
19050                        null, null, broadcastUsers);
19051                }
19052            }
19053            if (removedAppId >= 0) {
19054                packageSender.sendPackageBroadcast(Intent.ACTION_UID_REMOVED,
19055                    null, extras, Intent.FLAG_RECEIVER_INCLUDE_BACKGROUND,
19056                    null, null, broadcastUsers);
19057            }
19058        }
19059
19060        void populateUsers(int[] userIds, PackageSetting deletedPackageSetting) {
19061            removedUsers = userIds;
19062            if (removedUsers == null) {
19063                broadcastUsers = null;
19064                return;
19065            }
19066
19067            broadcastUsers = EMPTY_INT_ARRAY;
19068            for (int i = userIds.length - 1; i >= 0; --i) {
19069                final int userId = userIds[i];
19070                if (deletedPackageSetting.getInstantApp(userId)) {
19071                    continue;
19072                }
19073                broadcastUsers = ArrayUtils.appendInt(broadcastUsers, userId);
19074            }
19075        }
19076    }
19077
19078    /*
19079     * This method deletes the package from internal data structures. If the DONT_DELETE_DATA
19080     * flag is not set, the data directory is removed as well.
19081     * make sure this flag is set for partially installed apps. If not its meaningless to
19082     * delete a partially installed application.
19083     */
19084    private void removePackageDataLIF(PackageSetting ps, int[] allUserHandles,
19085            PackageRemovedInfo outInfo, int flags, boolean writeSettings) {
19086        String packageName = ps.name;
19087        if (DEBUG_REMOVE) Slog.d(TAG, "removePackageDataLI: " + ps);
19088        // Retrieve object to delete permissions for shared user later on
19089        final PackageParser.Package deletedPkg;
19090        final PackageSetting deletedPs;
19091        // reader
19092        synchronized (mPackages) {
19093            deletedPkg = mPackages.get(packageName);
19094            deletedPs = mSettings.mPackages.get(packageName);
19095            if (outInfo != null) {
19096                outInfo.removedPackage = packageName;
19097                outInfo.installerPackageName = ps.installerPackageName;
19098                outInfo.isStaticSharedLib = deletedPkg != null
19099                        && deletedPkg.staticSharedLibName != null;
19100                outInfo.populateUsers(deletedPs == null ? null
19101                        : deletedPs.queryInstalledUsers(sUserManager.getUserIds(), true), deletedPs);
19102            }
19103        }
19104
19105        removePackageLI(ps, (flags & FLAGS_REMOVE_CHATTY) != 0);
19106
19107        if ((flags & PackageManager.DELETE_KEEP_DATA) == 0) {
19108            final PackageParser.Package resolvedPkg;
19109            if (deletedPkg != null) {
19110                resolvedPkg = deletedPkg;
19111            } else {
19112                // We don't have a parsed package when it lives on an ejected
19113                // adopted storage device, so fake something together
19114                resolvedPkg = new PackageParser.Package(ps.name);
19115                resolvedPkg.setVolumeUuid(ps.volumeUuid);
19116            }
19117            destroyAppDataLIF(resolvedPkg, UserHandle.USER_ALL,
19118                    StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
19119            destroyAppProfilesLIF(resolvedPkg, UserHandle.USER_ALL);
19120            if (outInfo != null) {
19121                outInfo.dataRemoved = true;
19122            }
19123            schedulePackageCleaning(packageName, UserHandle.USER_ALL, true);
19124        }
19125
19126        int removedAppId = -1;
19127
19128        // writer
19129        synchronized (mPackages) {
19130            boolean installedStateChanged = false;
19131            if (deletedPs != null) {
19132                if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) {
19133                    clearIntentFilterVerificationsLPw(deletedPs.name, UserHandle.USER_ALL);
19134                    clearDefaultBrowserIfNeeded(packageName);
19135                    mSettings.mKeySetManagerService.removeAppKeySetDataLPw(packageName);
19136                    removedAppId = mSettings.removePackageLPw(packageName);
19137                    if (outInfo != null) {
19138                        outInfo.removedAppId = removedAppId;
19139                    }
19140                    updatePermissionsLPw(deletedPs.name, null, 0);
19141                    if (deletedPs.sharedUser != null) {
19142                        // Remove permissions associated with package. Since runtime
19143                        // permissions are per user we have to kill the removed package
19144                        // or packages running under the shared user of the removed
19145                        // package if revoking the permissions requested only by the removed
19146                        // package is successful and this causes a change in gids.
19147                        for (int userId : UserManagerService.getInstance().getUserIds()) {
19148                            final int userIdToKill = mSettings.updateSharedUserPermsLPw(deletedPs,
19149                                    userId);
19150                            if (userIdToKill == UserHandle.USER_ALL
19151                                    || userIdToKill >= UserHandle.USER_SYSTEM) {
19152                                // If gids changed for this user, kill all affected packages.
19153                                mHandler.post(new Runnable() {
19154                                    @Override
19155                                    public void run() {
19156                                        // This has to happen with no lock held.
19157                                        killApplication(deletedPs.name, deletedPs.appId,
19158                                                KILL_APP_REASON_GIDS_CHANGED);
19159                                    }
19160                                });
19161                                break;
19162                            }
19163                        }
19164                    }
19165                    clearPackagePreferredActivitiesLPw(deletedPs.name, UserHandle.USER_ALL);
19166                }
19167                // make sure to preserve per-user disabled state if this removal was just
19168                // a downgrade of a system app to the factory package
19169                if (allUserHandles != null && outInfo != null && outInfo.origUsers != null) {
19170                    if (DEBUG_REMOVE) {
19171                        Slog.d(TAG, "Propagating install state across downgrade");
19172                    }
19173                    for (int userId : allUserHandles) {
19174                        final boolean installed = ArrayUtils.contains(outInfo.origUsers, userId);
19175                        if (DEBUG_REMOVE) {
19176                            Slog.d(TAG, "    user " + userId + " => " + installed);
19177                        }
19178                        if (installed != ps.getInstalled(userId)) {
19179                            installedStateChanged = true;
19180                        }
19181                        ps.setInstalled(installed, userId);
19182                    }
19183                }
19184            }
19185            // can downgrade to reader
19186            if (writeSettings) {
19187                // Save settings now
19188                mSettings.writeLPr();
19189            }
19190            if (installedStateChanged) {
19191                mSettings.writeKernelMappingLPr(ps);
19192            }
19193        }
19194        if (removedAppId != -1) {
19195            // A user ID was deleted here. Go through all users and remove it
19196            // from KeyStore.
19197            removeKeystoreDataIfNeeded(UserHandle.USER_ALL, removedAppId);
19198        }
19199    }
19200
19201    static boolean locationIsPrivileged(File path) {
19202        try {
19203            final String privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app")
19204                    .getCanonicalPath();
19205            return path.getCanonicalPath().startsWith(privilegedAppDir);
19206        } catch (IOException e) {
19207            Slog.e(TAG, "Unable to access code path " + path);
19208        }
19209        return false;
19210    }
19211
19212    /*
19213     * Tries to delete system package.
19214     */
19215    private boolean deleteSystemPackageLIF(PackageParser.Package deletedPkg,
19216            PackageSetting deletedPs, int[] allUserHandles, int flags, PackageRemovedInfo outInfo,
19217            boolean writeSettings) {
19218        if (deletedPs.parentPackageName != null) {
19219            Slog.w(TAG, "Attempt to delete child system package " + deletedPkg.packageName);
19220            return false;
19221        }
19222
19223        final boolean applyUserRestrictions
19224                = (allUserHandles != null) && (outInfo.origUsers != null);
19225        final PackageSetting disabledPs;
19226        // Confirm if the system package has been updated
19227        // An updated system app can be deleted. This will also have to restore
19228        // the system pkg from system partition
19229        // reader
19230        synchronized (mPackages) {
19231            disabledPs = mSettings.getDisabledSystemPkgLPr(deletedPs.name);
19232        }
19233
19234        if (DEBUG_REMOVE) Slog.d(TAG, "deleteSystemPackageLI: newPs=" + deletedPkg.packageName
19235                + " disabledPs=" + disabledPs);
19236
19237        if (disabledPs == null) {
19238            Slog.w(TAG, "Attempt to delete unknown system package "+ deletedPkg.packageName);
19239            return false;
19240        } else if (DEBUG_REMOVE) {
19241            Slog.d(TAG, "Deleting system pkg from data partition");
19242        }
19243
19244        if (DEBUG_REMOVE) {
19245            if (applyUserRestrictions) {
19246                Slog.d(TAG, "Remembering install states:");
19247                for (int userId : allUserHandles) {
19248                    final boolean finstalled = ArrayUtils.contains(outInfo.origUsers, userId);
19249                    Slog.d(TAG, "   u=" + userId + " inst=" + finstalled);
19250                }
19251            }
19252        }
19253
19254        // Delete the updated package
19255        outInfo.isRemovedPackageSystemUpdate = true;
19256        if (outInfo.removedChildPackages != null) {
19257            final int childCount = (deletedPs.childPackageNames != null)
19258                    ? deletedPs.childPackageNames.size() : 0;
19259            for (int i = 0; i < childCount; i++) {
19260                String childPackageName = deletedPs.childPackageNames.get(i);
19261                if (disabledPs.childPackageNames != null && disabledPs.childPackageNames
19262                        .contains(childPackageName)) {
19263                    PackageRemovedInfo childInfo = outInfo.removedChildPackages.get(
19264                            childPackageName);
19265                    if (childInfo != null) {
19266                        childInfo.isRemovedPackageSystemUpdate = true;
19267                    }
19268                }
19269            }
19270        }
19271
19272        if (disabledPs.versionCode < deletedPs.versionCode) {
19273            // Delete data for downgrades
19274            flags &= ~PackageManager.DELETE_KEEP_DATA;
19275        } else {
19276            // Preserve data by setting flag
19277            flags |= PackageManager.DELETE_KEEP_DATA;
19278        }
19279
19280        boolean ret = deleteInstalledPackageLIF(deletedPs, true, flags, allUserHandles,
19281                outInfo, writeSettings, disabledPs.pkg);
19282        if (!ret) {
19283            return false;
19284        }
19285
19286        // writer
19287        synchronized (mPackages) {
19288            // Reinstate the old system package
19289            enableSystemPackageLPw(disabledPs.pkg);
19290            // Remove any native libraries from the upgraded package.
19291            removeNativeBinariesLI(deletedPs);
19292        }
19293
19294        // Install the system package
19295        if (DEBUG_REMOVE) Slog.d(TAG, "Re-installing system package: " + disabledPs);
19296        int parseFlags = mDefParseFlags
19297                | PackageParser.PARSE_MUST_BE_APK
19298                | PackageParser.PARSE_IS_SYSTEM
19299                | PackageParser.PARSE_IS_SYSTEM_DIR;
19300        if (locationIsPrivileged(disabledPs.codePath)) {
19301            parseFlags |= PackageParser.PARSE_IS_PRIVILEGED;
19302        }
19303
19304        final PackageParser.Package newPkg;
19305        try {
19306            newPkg = scanPackageTracedLI(disabledPs.codePath, parseFlags, 0 /* scanFlags */,
19307                0 /* currentTime */, null);
19308        } catch (PackageManagerException e) {
19309            Slog.w(TAG, "Failed to restore system package:" + deletedPkg.packageName + ": "
19310                    + e.getMessage());
19311            return false;
19312        }
19313
19314        try {
19315            // update shared libraries for the newly re-installed system package
19316            updateSharedLibrariesLPr(newPkg, null);
19317        } catch (PackageManagerException e) {
19318            Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
19319        }
19320
19321        prepareAppDataAfterInstallLIF(newPkg);
19322
19323        // writer
19324        synchronized (mPackages) {
19325            PackageSetting ps = mSettings.mPackages.get(newPkg.packageName);
19326
19327            // Propagate the permissions state as we do not want to drop on the floor
19328            // runtime permissions. The update permissions method below will take
19329            // care of removing obsolete permissions and grant install permissions.
19330            ps.getPermissionsState().copyFrom(deletedPs.getPermissionsState());
19331            updatePermissionsLPw(newPkg.packageName, newPkg,
19332                    UPDATE_PERMISSIONS_ALL | UPDATE_PERMISSIONS_REPLACE_PKG);
19333
19334            if (applyUserRestrictions) {
19335                boolean installedStateChanged = false;
19336                if (DEBUG_REMOVE) {
19337                    Slog.d(TAG, "Propagating install state across reinstall");
19338                }
19339                for (int userId : allUserHandles) {
19340                    final boolean installed = ArrayUtils.contains(outInfo.origUsers, userId);
19341                    if (DEBUG_REMOVE) {
19342                        Slog.d(TAG, "    user " + userId + " => " + installed);
19343                    }
19344                    if (installed != ps.getInstalled(userId)) {
19345                        installedStateChanged = true;
19346                    }
19347                    ps.setInstalled(installed, userId);
19348
19349                    mSettings.writeRuntimePermissionsForUserLPr(userId, false);
19350                }
19351                // Regardless of writeSettings we need to ensure that this restriction
19352                // state propagation is persisted
19353                mSettings.writeAllUsersPackageRestrictionsLPr();
19354                if (installedStateChanged) {
19355                    mSettings.writeKernelMappingLPr(ps);
19356                }
19357            }
19358            // can downgrade to reader here
19359            if (writeSettings) {
19360                mSettings.writeLPr();
19361            }
19362        }
19363        return true;
19364    }
19365
19366    private boolean deleteInstalledPackageLIF(PackageSetting ps,
19367            boolean deleteCodeAndResources, int flags, int[] allUserHandles,
19368            PackageRemovedInfo outInfo, boolean writeSettings,
19369            PackageParser.Package replacingPackage) {
19370        synchronized (mPackages) {
19371            if (outInfo != null) {
19372                outInfo.uid = ps.appId;
19373            }
19374
19375            if (outInfo != null && outInfo.removedChildPackages != null) {
19376                final int childCount = (ps.childPackageNames != null)
19377                        ? ps.childPackageNames.size() : 0;
19378                for (int i = 0; i < childCount; i++) {
19379                    String childPackageName = ps.childPackageNames.get(i);
19380                    PackageSetting childPs = mSettings.mPackages.get(childPackageName);
19381                    if (childPs == null) {
19382                        return false;
19383                    }
19384                    PackageRemovedInfo childInfo = outInfo.removedChildPackages.get(
19385                            childPackageName);
19386                    if (childInfo != null) {
19387                        childInfo.uid = childPs.appId;
19388                    }
19389                }
19390            }
19391        }
19392
19393        // Delete package data from internal structures and also remove data if flag is set
19394        removePackageDataLIF(ps, allUserHandles, outInfo, flags, writeSettings);
19395
19396        // Delete the child packages data
19397        final int childCount = (ps.childPackageNames != null) ? ps.childPackageNames.size() : 0;
19398        for (int i = 0; i < childCount; i++) {
19399            PackageSetting childPs;
19400            synchronized (mPackages) {
19401                childPs = mSettings.getPackageLPr(ps.childPackageNames.get(i));
19402            }
19403            if (childPs != null) {
19404                PackageRemovedInfo childOutInfo = (outInfo != null
19405                        && outInfo.removedChildPackages != null)
19406                        ? outInfo.removedChildPackages.get(childPs.name) : null;
19407                final int deleteFlags = (flags & DELETE_KEEP_DATA) != 0
19408                        && (replacingPackage != null
19409                        && !replacingPackage.hasChildPackage(childPs.name))
19410                        ? flags & ~DELETE_KEEP_DATA : flags;
19411                removePackageDataLIF(childPs, allUserHandles, childOutInfo,
19412                        deleteFlags, writeSettings);
19413            }
19414        }
19415
19416        // Delete application code and resources only for parent packages
19417        if (ps.parentPackageName == null) {
19418            if (deleteCodeAndResources && (outInfo != null)) {
19419                outInfo.args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
19420                        ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
19421                if (DEBUG_SD_INSTALL) Slog.i(TAG, "args=" + outInfo.args);
19422            }
19423        }
19424
19425        return true;
19426    }
19427
19428    @Override
19429    public boolean setBlockUninstallForUser(String packageName, boolean blockUninstall,
19430            int userId) {
19431        mContext.enforceCallingOrSelfPermission(
19432                android.Manifest.permission.DELETE_PACKAGES, null);
19433        synchronized (mPackages) {
19434            // Cannot block uninstall of static shared libs as they are
19435            // considered a part of the using app (emulating static linking).
19436            // Also static libs are installed always on internal storage.
19437            PackageParser.Package pkg = mPackages.get(packageName);
19438            if (pkg != null && pkg.staticSharedLibName != null) {
19439                Slog.w(TAG, "Cannot block uninstall of package: " + packageName
19440                        + " providing static shared library: " + pkg.staticSharedLibName);
19441                return false;
19442            }
19443            mSettings.setBlockUninstallLPw(userId, packageName, blockUninstall);
19444            mSettings.writePackageRestrictionsLPr(userId);
19445        }
19446        return true;
19447    }
19448
19449    @Override
19450    public boolean getBlockUninstallForUser(String packageName, int userId) {
19451        synchronized (mPackages) {
19452            final PackageSetting ps = mSettings.mPackages.get(packageName);
19453            if (ps == null || filterAppAccessLPr(ps, Binder.getCallingUid(), userId)) {
19454                return false;
19455            }
19456            return mSettings.getBlockUninstallLPr(userId, packageName);
19457        }
19458    }
19459
19460    @Override
19461    public boolean setRequiredForSystemUser(String packageName, boolean systemUserApp) {
19462        enforceSystemOrRoot("setRequiredForSystemUser can only be run by the system or root");
19463        synchronized (mPackages) {
19464            PackageSetting ps = mSettings.mPackages.get(packageName);
19465            if (ps == null) {
19466                Log.w(TAG, "Package doesn't exist: " + packageName);
19467                return false;
19468            }
19469            if (systemUserApp) {
19470                ps.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_REQUIRED_FOR_SYSTEM_USER;
19471            } else {
19472                ps.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_REQUIRED_FOR_SYSTEM_USER;
19473            }
19474            mSettings.writeLPr();
19475        }
19476        return true;
19477    }
19478
19479    /*
19480     * This method handles package deletion in general
19481     */
19482    private boolean deletePackageLIF(String packageName, UserHandle user,
19483            boolean deleteCodeAndResources, int[] allUserHandles, int flags,
19484            PackageRemovedInfo outInfo, boolean writeSettings,
19485            PackageParser.Package replacingPackage) {
19486        if (packageName == null) {
19487            Slog.w(TAG, "Attempt to delete null packageName.");
19488            return false;
19489        }
19490
19491        if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageLI: " + packageName + " user " + user);
19492
19493        PackageSetting ps;
19494        synchronized (mPackages) {
19495            ps = mSettings.mPackages.get(packageName);
19496            if (ps == null) {
19497                Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
19498                return false;
19499            }
19500
19501            if (ps.parentPackageName != null && (!isSystemApp(ps)
19502                    || (flags & PackageManager.DELETE_SYSTEM_APP) != 0)) {
19503                if (DEBUG_REMOVE) {
19504                    Slog.d(TAG, "Uninstalled child package:" + packageName + " for user:"
19505                            + ((user == null) ? UserHandle.USER_ALL : user));
19506                }
19507                final int removedUserId = (user != null) ? user.getIdentifier()
19508                        : UserHandle.USER_ALL;
19509                if (!clearPackageStateForUserLIF(ps, removedUserId, outInfo)) {
19510                    return false;
19511                }
19512                markPackageUninstalledForUserLPw(ps, user);
19513                scheduleWritePackageRestrictionsLocked(user);
19514                return true;
19515            }
19516        }
19517
19518        if (((!isSystemApp(ps) || (flags&PackageManager.DELETE_SYSTEM_APP) != 0) && user != null
19519                && user.getIdentifier() != UserHandle.USER_ALL)) {
19520            // The caller is asking that the package only be deleted for a single
19521            // user.  To do this, we just mark its uninstalled state and delete
19522            // its data. If this is a system app, we only allow this to happen if
19523            // they have set the special DELETE_SYSTEM_APP which requests different
19524            // semantics than normal for uninstalling system apps.
19525            markPackageUninstalledForUserLPw(ps, user);
19526
19527            if (!isSystemApp(ps)) {
19528                // Do not uninstall the APK if an app should be cached
19529                boolean keepUninstalledPackage = shouldKeepUninstalledPackageLPr(packageName);
19530                if (ps.isAnyInstalled(sUserManager.getUserIds()) || keepUninstalledPackage) {
19531                    // Other user still have this package installed, so all
19532                    // we need to do is clear this user's data and save that
19533                    // it is uninstalled.
19534                    if (DEBUG_REMOVE) Slog.d(TAG, "Still installed by other users");
19535                    if (!clearPackageStateForUserLIF(ps, user.getIdentifier(), outInfo)) {
19536                        return false;
19537                    }
19538                    scheduleWritePackageRestrictionsLocked(user);
19539                    return true;
19540                } else {
19541                    // We need to set it back to 'installed' so the uninstall
19542                    // broadcasts will be sent correctly.
19543                    if (DEBUG_REMOVE) Slog.d(TAG, "Not installed by other users, full delete");
19544                    ps.setInstalled(true, user.getIdentifier());
19545                    mSettings.writeKernelMappingLPr(ps);
19546                }
19547            } else {
19548                // This is a system app, so we assume that the
19549                // other users still have this package installed, so all
19550                // we need to do is clear this user's data and save that
19551                // it is uninstalled.
19552                if (DEBUG_REMOVE) Slog.d(TAG, "Deleting system app");
19553                if (!clearPackageStateForUserLIF(ps, user.getIdentifier(), outInfo)) {
19554                    return false;
19555                }
19556                scheduleWritePackageRestrictionsLocked(user);
19557                return true;
19558            }
19559        }
19560
19561        // If we are deleting a composite package for all users, keep track
19562        // of result for each child.
19563        if (ps.childPackageNames != null && outInfo != null) {
19564            synchronized (mPackages) {
19565                final int childCount = ps.childPackageNames.size();
19566                outInfo.removedChildPackages = new ArrayMap<>(childCount);
19567                for (int i = 0; i < childCount; i++) {
19568                    String childPackageName = ps.childPackageNames.get(i);
19569                    PackageRemovedInfo childInfo = new PackageRemovedInfo(this);
19570                    childInfo.removedPackage = childPackageName;
19571                    childInfo.installerPackageName = ps.installerPackageName;
19572                    outInfo.removedChildPackages.put(childPackageName, childInfo);
19573                    PackageSetting childPs = mSettings.getPackageLPr(childPackageName);
19574                    if (childPs != null) {
19575                        childInfo.origUsers = childPs.queryInstalledUsers(allUserHandles, true);
19576                    }
19577                }
19578            }
19579        }
19580
19581        boolean ret = false;
19582        if (isSystemApp(ps)) {
19583            if (DEBUG_REMOVE) Slog.d(TAG, "Removing system package: " + ps.name);
19584            // When an updated system application is deleted we delete the existing resources
19585            // as well and fall back to existing code in system partition
19586            ret = deleteSystemPackageLIF(ps.pkg, ps, allUserHandles, flags, outInfo, writeSettings);
19587        } else {
19588            if (DEBUG_REMOVE) Slog.d(TAG, "Removing non-system package: " + ps.name);
19589            ret = deleteInstalledPackageLIF(ps, deleteCodeAndResources, flags, allUserHandles,
19590                    outInfo, writeSettings, replacingPackage);
19591        }
19592
19593        // Take a note whether we deleted the package for all users
19594        if (outInfo != null) {
19595            outInfo.removedForAllUsers = mPackages.get(ps.name) == null;
19596            if (outInfo.removedChildPackages != null) {
19597                synchronized (mPackages) {
19598                    final int childCount = outInfo.removedChildPackages.size();
19599                    for (int i = 0; i < childCount; i++) {
19600                        PackageRemovedInfo childInfo = outInfo.removedChildPackages.valueAt(i);
19601                        if (childInfo != null) {
19602                            childInfo.removedForAllUsers = mPackages.get(
19603                                    childInfo.removedPackage) == null;
19604                        }
19605                    }
19606                }
19607            }
19608            // If we uninstalled an update to a system app there may be some
19609            // child packages that appeared as they are declared in the system
19610            // app but were not declared in the update.
19611            if (isSystemApp(ps)) {
19612                synchronized (mPackages) {
19613                    PackageSetting updatedPs = mSettings.getPackageLPr(ps.name);
19614                    final int childCount = (updatedPs.childPackageNames != null)
19615                            ? updatedPs.childPackageNames.size() : 0;
19616                    for (int i = 0; i < childCount; i++) {
19617                        String childPackageName = updatedPs.childPackageNames.get(i);
19618                        if (outInfo.removedChildPackages == null
19619                                || outInfo.removedChildPackages.indexOfKey(childPackageName) < 0) {
19620                            PackageSetting childPs = mSettings.getPackageLPr(childPackageName);
19621                            if (childPs == null) {
19622                                continue;
19623                            }
19624                            PackageInstalledInfo installRes = new PackageInstalledInfo();
19625                            installRes.name = childPackageName;
19626                            installRes.newUsers = childPs.queryInstalledUsers(allUserHandles, true);
19627                            installRes.pkg = mPackages.get(childPackageName);
19628                            installRes.uid = childPs.pkg.applicationInfo.uid;
19629                            if (outInfo.appearedChildPackages == null) {
19630                                outInfo.appearedChildPackages = new ArrayMap<>();
19631                            }
19632                            outInfo.appearedChildPackages.put(childPackageName, installRes);
19633                        }
19634                    }
19635                }
19636            }
19637        }
19638
19639        return ret;
19640    }
19641
19642    private void markPackageUninstalledForUserLPw(PackageSetting ps, UserHandle user) {
19643        final int[] userIds = (user == null || user.getIdentifier() == UserHandle.USER_ALL)
19644                ? sUserManager.getUserIds() : new int[] {user.getIdentifier()};
19645        for (int nextUserId : userIds) {
19646            if (DEBUG_REMOVE) {
19647                Slog.d(TAG, "Marking package:" + ps.name + " uninstalled for user:" + nextUserId);
19648            }
19649            ps.setUserState(nextUserId, 0, COMPONENT_ENABLED_STATE_DEFAULT,
19650                    false /*installed*/,
19651                    true /*stopped*/,
19652                    true /*notLaunched*/,
19653                    false /*hidden*/,
19654                    false /*suspended*/,
19655                    false /*instantApp*/,
19656                    null /*lastDisableAppCaller*/,
19657                    null /*enabledComponents*/,
19658                    null /*disabledComponents*/,
19659                    ps.readUserState(nextUserId).domainVerificationStatus,
19660                    0, PackageManager.INSTALL_REASON_UNKNOWN);
19661        }
19662        mSettings.writeKernelMappingLPr(ps);
19663    }
19664
19665    private boolean clearPackageStateForUserLIF(PackageSetting ps, int userId,
19666            PackageRemovedInfo outInfo) {
19667        final PackageParser.Package pkg;
19668        synchronized (mPackages) {
19669            pkg = mPackages.get(ps.name);
19670        }
19671
19672        final int[] userIds = (userId == UserHandle.USER_ALL) ? sUserManager.getUserIds()
19673                : new int[] {userId};
19674        for (int nextUserId : userIds) {
19675            if (DEBUG_REMOVE) {
19676                Slog.d(TAG, "Updating package:" + ps.name + " install state for user:"
19677                        + nextUserId);
19678            }
19679
19680            destroyAppDataLIF(pkg, userId,
19681                    StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
19682            destroyAppProfilesLIF(pkg, userId);
19683            clearDefaultBrowserIfNeededForUser(ps.name, userId);
19684            removeKeystoreDataIfNeeded(nextUserId, ps.appId);
19685            schedulePackageCleaning(ps.name, nextUserId, false);
19686            synchronized (mPackages) {
19687                if (clearPackagePreferredActivitiesLPw(ps.name, nextUserId)) {
19688                    scheduleWritePackageRestrictionsLocked(nextUserId);
19689                }
19690                resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, nextUserId);
19691            }
19692        }
19693
19694        if (outInfo != null) {
19695            outInfo.removedPackage = ps.name;
19696            outInfo.installerPackageName = ps.installerPackageName;
19697            outInfo.isStaticSharedLib = pkg != null && pkg.staticSharedLibName != null;
19698            outInfo.removedAppId = ps.appId;
19699            outInfo.removedUsers = userIds;
19700            outInfo.broadcastUsers = userIds;
19701        }
19702
19703        return true;
19704    }
19705
19706    private final class ClearStorageConnection implements ServiceConnection {
19707        IMediaContainerService mContainerService;
19708
19709        @Override
19710        public void onServiceConnected(ComponentName name, IBinder service) {
19711            synchronized (this) {
19712                mContainerService = IMediaContainerService.Stub
19713                        .asInterface(Binder.allowBlocking(service));
19714                notifyAll();
19715            }
19716        }
19717
19718        @Override
19719        public void onServiceDisconnected(ComponentName name) {
19720        }
19721    }
19722
19723    private void clearExternalStorageDataSync(String packageName, int userId, boolean allData) {
19724        if (DEFAULT_CONTAINER_PACKAGE.equals(packageName)) return;
19725
19726        final boolean mounted;
19727        if (Environment.isExternalStorageEmulated()) {
19728            mounted = true;
19729        } else {
19730            final String status = Environment.getExternalStorageState();
19731
19732            mounted = status.equals(Environment.MEDIA_MOUNTED)
19733                    || status.equals(Environment.MEDIA_MOUNTED_READ_ONLY);
19734        }
19735
19736        if (!mounted) {
19737            return;
19738        }
19739
19740        final Intent containerIntent = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
19741        int[] users;
19742        if (userId == UserHandle.USER_ALL) {
19743            users = sUserManager.getUserIds();
19744        } else {
19745            users = new int[] { userId };
19746        }
19747        final ClearStorageConnection conn = new ClearStorageConnection();
19748        if (mContext.bindServiceAsUser(
19749                containerIntent, conn, Context.BIND_AUTO_CREATE, UserHandle.SYSTEM)) {
19750            try {
19751                for (int curUser : users) {
19752                    long timeout = SystemClock.uptimeMillis() + 5000;
19753                    synchronized (conn) {
19754                        long now;
19755                        while (conn.mContainerService == null &&
19756                                (now = SystemClock.uptimeMillis()) < timeout) {
19757                            try {
19758                                conn.wait(timeout - now);
19759                            } catch (InterruptedException e) {
19760                            }
19761                        }
19762                    }
19763                    if (conn.mContainerService == null) {
19764                        return;
19765                    }
19766
19767                    final UserEnvironment userEnv = new UserEnvironment(curUser);
19768                    clearDirectory(conn.mContainerService,
19769                            userEnv.buildExternalStorageAppCacheDirs(packageName));
19770                    if (allData) {
19771                        clearDirectory(conn.mContainerService,
19772                                userEnv.buildExternalStorageAppDataDirs(packageName));
19773                        clearDirectory(conn.mContainerService,
19774                                userEnv.buildExternalStorageAppMediaDirs(packageName));
19775                    }
19776                }
19777            } finally {
19778                mContext.unbindService(conn);
19779            }
19780        }
19781    }
19782
19783    @Override
19784    public void clearApplicationProfileData(String packageName) {
19785        enforceSystemOrRoot("Only the system can clear all profile data");
19786
19787        final PackageParser.Package pkg;
19788        synchronized (mPackages) {
19789            pkg = mPackages.get(packageName);
19790        }
19791
19792        try (PackageFreezer freezer = freezePackage(packageName, "clearApplicationProfileData")) {
19793            synchronized (mInstallLock) {
19794                clearAppProfilesLIF(pkg, UserHandle.USER_ALL);
19795            }
19796        }
19797    }
19798
19799    @Override
19800    public void clearApplicationUserData(final String packageName,
19801            final IPackageDataObserver observer, final int userId) {
19802        mContext.enforceCallingOrSelfPermission(
19803                android.Manifest.permission.CLEAR_APP_USER_DATA, null);
19804
19805        final int callingUid = Binder.getCallingUid();
19806        enforceCrossUserPermission(callingUid, userId,
19807                true /* requireFullPermission */, false /* checkShell */, "clear application data");
19808
19809        final PackageSetting ps = mSettings.getPackageLPr(packageName);
19810        if (ps != null && filterAppAccessLPr(ps, callingUid, userId)) {
19811            return;
19812        }
19813        if (mProtectedPackages.isPackageDataProtected(userId, packageName)) {
19814            throw new SecurityException("Cannot clear data for a protected package: "
19815                    + packageName);
19816        }
19817        // Queue up an async operation since the package deletion may take a little while.
19818        mHandler.post(new Runnable() {
19819            public void run() {
19820                mHandler.removeCallbacks(this);
19821                final boolean succeeded;
19822                try (PackageFreezer freezer = freezePackage(packageName,
19823                        "clearApplicationUserData")) {
19824                    synchronized (mInstallLock) {
19825                        succeeded = clearApplicationUserDataLIF(packageName, userId);
19826                    }
19827                    clearExternalStorageDataSync(packageName, userId, true);
19828                    synchronized (mPackages) {
19829                        mInstantAppRegistry.deleteInstantApplicationMetadataLPw(
19830                                packageName, userId);
19831                    }
19832                }
19833                if (succeeded) {
19834                    // invoke DeviceStorageMonitor's update method to clear any notifications
19835                    DeviceStorageMonitorInternal dsm = LocalServices
19836                            .getService(DeviceStorageMonitorInternal.class);
19837                    if (dsm != null) {
19838                        dsm.checkMemory();
19839                    }
19840                }
19841                if(observer != null) {
19842                    try {
19843                        observer.onRemoveCompleted(packageName, succeeded);
19844                    } catch (RemoteException e) {
19845                        Log.i(TAG, "Observer no longer exists.");
19846                    }
19847                } //end if observer
19848            } //end run
19849        });
19850    }
19851
19852    private boolean clearApplicationUserDataLIF(String packageName, int userId) {
19853        if (packageName == null) {
19854            Slog.w(TAG, "Attempt to delete null packageName.");
19855            return false;
19856        }
19857
19858        // Try finding details about the requested package
19859        PackageParser.Package pkg;
19860        synchronized (mPackages) {
19861            pkg = mPackages.get(packageName);
19862            if (pkg == null) {
19863                final PackageSetting ps = mSettings.mPackages.get(packageName);
19864                if (ps != null) {
19865                    pkg = ps.pkg;
19866                }
19867            }
19868
19869            if (pkg == null) {
19870                Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
19871                return false;
19872            }
19873
19874            PackageSetting ps = (PackageSetting) pkg.mExtras;
19875            resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
19876        }
19877
19878        clearAppDataLIF(pkg, userId,
19879                StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
19880
19881        final int appId = UserHandle.getAppId(pkg.applicationInfo.uid);
19882        removeKeystoreDataIfNeeded(userId, appId);
19883
19884        UserManagerInternal umInternal = getUserManagerInternal();
19885        final int flags;
19886        if (umInternal.isUserUnlockingOrUnlocked(userId)) {
19887            flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
19888        } else if (umInternal.isUserRunning(userId)) {
19889            flags = StorageManager.FLAG_STORAGE_DE;
19890        } else {
19891            flags = 0;
19892        }
19893        prepareAppDataContentsLIF(pkg, userId, flags);
19894
19895        return true;
19896    }
19897
19898    /**
19899     * Reverts user permission state changes (permissions and flags) in
19900     * all packages for a given user.
19901     *
19902     * @param userId The device user for which to do a reset.
19903     */
19904    private void resetUserChangesToRuntimePermissionsAndFlagsLPw(int userId) {
19905        final int packageCount = mPackages.size();
19906        for (int i = 0; i < packageCount; i++) {
19907            PackageParser.Package pkg = mPackages.valueAt(i);
19908            PackageSetting ps = (PackageSetting) pkg.mExtras;
19909            resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
19910        }
19911    }
19912
19913    private void resetNetworkPolicies(int userId) {
19914        LocalServices.getService(NetworkPolicyManagerInternal.class).resetUserState(userId);
19915    }
19916
19917    /**
19918     * Reverts user permission state changes (permissions and flags).
19919     *
19920     * @param ps The package for which to reset.
19921     * @param userId The device user for which to do a reset.
19922     */
19923    private void resetUserChangesToRuntimePermissionsAndFlagsLPw(
19924            final PackageSetting ps, final int userId) {
19925        if (ps.pkg == null) {
19926            return;
19927        }
19928
19929        // These are flags that can change base on user actions.
19930        final int userSettableMask = FLAG_PERMISSION_USER_SET
19931                | FLAG_PERMISSION_USER_FIXED
19932                | FLAG_PERMISSION_REVOKE_ON_UPGRADE
19933                | FLAG_PERMISSION_REVIEW_REQUIRED;
19934
19935        final int policyOrSystemFlags = FLAG_PERMISSION_SYSTEM_FIXED
19936                | FLAG_PERMISSION_POLICY_FIXED;
19937
19938        boolean writeInstallPermissions = false;
19939        boolean writeRuntimePermissions = false;
19940
19941        final int permissionCount = ps.pkg.requestedPermissions.size();
19942        for (int i = 0; i < permissionCount; i++) {
19943            String permission = ps.pkg.requestedPermissions.get(i);
19944
19945            BasePermission bp = mSettings.mPermissions.get(permission);
19946            if (bp == null) {
19947                continue;
19948            }
19949
19950            // If shared user we just reset the state to which only this app contributed.
19951            if (ps.sharedUser != null) {
19952                boolean used = false;
19953                final int packageCount = ps.sharedUser.packages.size();
19954                for (int j = 0; j < packageCount; j++) {
19955                    PackageSetting pkg = ps.sharedUser.packages.valueAt(j);
19956                    if (pkg.pkg != null && !pkg.pkg.packageName.equals(ps.pkg.packageName)
19957                            && pkg.pkg.requestedPermissions.contains(permission)) {
19958                        used = true;
19959                        break;
19960                    }
19961                }
19962                if (used) {
19963                    continue;
19964                }
19965            }
19966
19967            PermissionsState permissionsState = ps.getPermissionsState();
19968
19969            final int oldFlags = permissionsState.getPermissionFlags(bp.name, userId);
19970
19971            // Always clear the user settable flags.
19972            final boolean hasInstallState = permissionsState.getInstallPermissionState(
19973                    bp.name) != null;
19974            // If permission review is enabled and this is a legacy app, mark the
19975            // permission as requiring a review as this is the initial state.
19976            int flags = 0;
19977            if (mPermissionReviewRequired
19978                    && ps.pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) {
19979                flags |= FLAG_PERMISSION_REVIEW_REQUIRED;
19980            }
19981            if (permissionsState.updatePermissionFlags(bp, userId, userSettableMask, flags)) {
19982                if (hasInstallState) {
19983                    writeInstallPermissions = true;
19984                } else {
19985                    writeRuntimePermissions = true;
19986                }
19987            }
19988
19989            // Below is only runtime permission handling.
19990            if (!bp.isRuntime()) {
19991                continue;
19992            }
19993
19994            // Never clobber system or policy.
19995            if ((oldFlags & policyOrSystemFlags) != 0) {
19996                continue;
19997            }
19998
19999            // If this permission was granted by default, make sure it is.
20000            if ((oldFlags & FLAG_PERMISSION_GRANTED_BY_DEFAULT) != 0) {
20001                if (permissionsState.grantRuntimePermission(bp, userId)
20002                        != PERMISSION_OPERATION_FAILURE) {
20003                    writeRuntimePermissions = true;
20004                }
20005            // If permission review is enabled the permissions for a legacy apps
20006            // are represented as constantly granted runtime ones, so don't revoke.
20007            } else if ((flags & FLAG_PERMISSION_REVIEW_REQUIRED) == 0) {
20008                // Otherwise, reset the permission.
20009                final int revokeResult = permissionsState.revokeRuntimePermission(bp, userId);
20010                switch (revokeResult) {
20011                    case PERMISSION_OPERATION_SUCCESS:
20012                    case PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: {
20013                        writeRuntimePermissions = true;
20014                        final int appId = ps.appId;
20015                        mHandler.post(new Runnable() {
20016                            @Override
20017                            public void run() {
20018                                killUid(appId, userId, KILL_APP_REASON_PERMISSIONS_REVOKED);
20019                            }
20020                        });
20021                    } break;
20022                }
20023            }
20024        }
20025
20026        // Synchronously write as we are taking permissions away.
20027        if (writeRuntimePermissions) {
20028            mSettings.writeRuntimePermissionsForUserLPr(userId, true);
20029        }
20030
20031        // Synchronously write as we are taking permissions away.
20032        if (writeInstallPermissions) {
20033            mSettings.writeLPr();
20034        }
20035    }
20036
20037    /**
20038     * Remove entries from the keystore daemon. Will only remove it if the
20039     * {@code appId} is valid.
20040     */
20041    private static void removeKeystoreDataIfNeeded(int userId, int appId) {
20042        if (appId < 0) {
20043            return;
20044        }
20045
20046        final KeyStore keyStore = KeyStore.getInstance();
20047        if (keyStore != null) {
20048            if (userId == UserHandle.USER_ALL) {
20049                for (final int individual : sUserManager.getUserIds()) {
20050                    keyStore.clearUid(UserHandle.getUid(individual, appId));
20051                }
20052            } else {
20053                keyStore.clearUid(UserHandle.getUid(userId, appId));
20054            }
20055        } else {
20056            Slog.w(TAG, "Could not contact keystore to clear entries for app id " + appId);
20057        }
20058    }
20059
20060    @Override
20061    public void deleteApplicationCacheFiles(final String packageName,
20062            final IPackageDataObserver observer) {
20063        final int userId = UserHandle.getCallingUserId();
20064        deleteApplicationCacheFilesAsUser(packageName, userId, observer);
20065    }
20066
20067    @Override
20068    public void deleteApplicationCacheFilesAsUser(final String packageName, final int userId,
20069            final IPackageDataObserver observer) {
20070        final int callingUid = Binder.getCallingUid();
20071        mContext.enforceCallingOrSelfPermission(
20072                android.Manifest.permission.DELETE_CACHE_FILES, null);
20073        enforceCrossUserPermission(callingUid, userId,
20074                /* requireFullPermission= */ true, /* checkShell= */ false,
20075                "delete application cache files");
20076        final int hasAccessInstantApps = mContext.checkCallingOrSelfPermission(
20077                android.Manifest.permission.ACCESS_INSTANT_APPS);
20078
20079        final PackageParser.Package pkg;
20080        synchronized (mPackages) {
20081            pkg = mPackages.get(packageName);
20082        }
20083
20084        // Queue up an async operation since the package deletion may take a little while.
20085        mHandler.post(new Runnable() {
20086            public void run() {
20087                final PackageSetting ps = pkg == null ? null : (PackageSetting) pkg.mExtras;
20088                boolean doClearData = true;
20089                if (ps != null) {
20090                    final boolean targetIsInstantApp =
20091                            ps.getInstantApp(UserHandle.getUserId(callingUid));
20092                    doClearData = !targetIsInstantApp
20093                            || hasAccessInstantApps == PackageManager.PERMISSION_GRANTED;
20094                }
20095                if (doClearData) {
20096                    synchronized (mInstallLock) {
20097                        final int flags = StorageManager.FLAG_STORAGE_DE
20098                                | StorageManager.FLAG_STORAGE_CE;
20099                        // We're only clearing cache files, so we don't care if the
20100                        // app is unfrozen and still able to run
20101                        clearAppDataLIF(pkg, userId, flags | Installer.FLAG_CLEAR_CACHE_ONLY);
20102                        clearAppDataLIF(pkg, userId, flags | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
20103                    }
20104                    clearExternalStorageDataSync(packageName, userId, false);
20105                }
20106                if (observer != null) {
20107                    try {
20108                        observer.onRemoveCompleted(packageName, true);
20109                    } catch (RemoteException e) {
20110                        Log.i(TAG, "Observer no longer exists.");
20111                    }
20112                }
20113            }
20114        });
20115    }
20116
20117    @Override
20118    public void getPackageSizeInfo(final String packageName, int userHandle,
20119            final IPackageStatsObserver observer) {
20120        throw new UnsupportedOperationException(
20121                "Shame on you for calling the hidden API getPackageSizeInfo(). Shame!");
20122    }
20123
20124    private boolean getPackageSizeInfoLI(String packageName, int userId, PackageStats stats) {
20125        final PackageSetting ps;
20126        synchronized (mPackages) {
20127            ps = mSettings.mPackages.get(packageName);
20128            if (ps == null) {
20129                Slog.w(TAG, "Failed to find settings for " + packageName);
20130                return false;
20131            }
20132        }
20133
20134        final String[] packageNames = { packageName };
20135        final long[] ceDataInodes = { ps.getCeDataInode(userId) };
20136        final String[] codePaths = { ps.codePathString };
20137
20138        try {
20139            mInstaller.getAppSize(ps.volumeUuid, packageNames, userId, 0,
20140                    ps.appId, ceDataInodes, codePaths, stats);
20141
20142            // For now, ignore code size of packages on system partition
20143            if (isSystemApp(ps) && !isUpdatedSystemApp(ps)) {
20144                stats.codeSize = 0;
20145            }
20146
20147            // External clients expect these to be tracked separately
20148            stats.dataSize -= stats.cacheSize;
20149
20150        } catch (InstallerException e) {
20151            Slog.w(TAG, String.valueOf(e));
20152            return false;
20153        }
20154
20155        return true;
20156    }
20157
20158    private int getUidTargetSdkVersionLockedLPr(int uid) {
20159        Object obj = mSettings.getUserIdLPr(uid);
20160        if (obj instanceof SharedUserSetting) {
20161            final SharedUserSetting sus = (SharedUserSetting) obj;
20162            int vers = Build.VERSION_CODES.CUR_DEVELOPMENT;
20163            final Iterator<PackageSetting> it = sus.packages.iterator();
20164            while (it.hasNext()) {
20165                final PackageSetting ps = it.next();
20166                if (ps.pkg != null) {
20167                    int v = ps.pkg.applicationInfo.targetSdkVersion;
20168                    if (v < vers) vers = v;
20169                }
20170            }
20171            return vers;
20172        } else if (obj instanceof PackageSetting) {
20173            final PackageSetting ps = (PackageSetting) obj;
20174            if (ps.pkg != null) {
20175                return ps.pkg.applicationInfo.targetSdkVersion;
20176            }
20177        }
20178        return Build.VERSION_CODES.CUR_DEVELOPMENT;
20179    }
20180
20181    @Override
20182    public void addPreferredActivity(IntentFilter filter, int match,
20183            ComponentName[] set, ComponentName activity, int userId) {
20184        addPreferredActivityInternal(filter, match, set, activity, true, userId,
20185                "Adding preferred");
20186    }
20187
20188    private void addPreferredActivityInternal(IntentFilter filter, int match,
20189            ComponentName[] set, ComponentName activity, boolean always, int userId,
20190            String opname) {
20191        // writer
20192        int callingUid = Binder.getCallingUid();
20193        enforceCrossUserPermission(callingUid, userId,
20194                true /* requireFullPermission */, false /* checkShell */, "add preferred activity");
20195        if (filter.countActions() == 0) {
20196            Slog.w(TAG, "Cannot set a preferred activity with no filter actions");
20197            return;
20198        }
20199        synchronized (mPackages) {
20200            if (mContext.checkCallingOrSelfPermission(
20201                    android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
20202                    != PackageManager.PERMISSION_GRANTED) {
20203                if (getUidTargetSdkVersionLockedLPr(callingUid)
20204                        < Build.VERSION_CODES.FROYO) {
20205                    Slog.w(TAG, "Ignoring addPreferredActivity() from uid "
20206                            + callingUid);
20207                    return;
20208                }
20209                mContext.enforceCallingOrSelfPermission(
20210                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
20211            }
20212
20213            PreferredIntentResolver pir = mSettings.editPreferredActivitiesLPw(userId);
20214            Slog.i(TAG, opname + " activity " + activity.flattenToShortString() + " for user "
20215                    + userId + ":");
20216            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
20217            pir.addFilter(new PreferredActivity(filter, match, set, activity, always));
20218            scheduleWritePackageRestrictionsLocked(userId);
20219            postPreferredActivityChangedBroadcast(userId);
20220        }
20221    }
20222
20223    private void postPreferredActivityChangedBroadcast(int userId) {
20224        mHandler.post(() -> {
20225            final IActivityManager am = ActivityManager.getService();
20226            if (am == null) {
20227                return;
20228            }
20229
20230            final Intent intent = new Intent(Intent.ACTION_PREFERRED_ACTIVITY_CHANGED);
20231            intent.putExtra(Intent.EXTRA_USER_HANDLE, userId);
20232            try {
20233                am.broadcastIntent(null, intent, null, null,
20234                        0, null, null, null, android.app.AppOpsManager.OP_NONE,
20235                        null, false, false, userId);
20236            } catch (RemoteException e) {
20237            }
20238        });
20239    }
20240
20241    @Override
20242    public void replacePreferredActivity(IntentFilter filter, int match,
20243            ComponentName[] set, ComponentName activity, int userId) {
20244        if (filter.countActions() != 1) {
20245            throw new IllegalArgumentException(
20246                    "replacePreferredActivity expects filter to have only 1 action.");
20247        }
20248        if (filter.countDataAuthorities() != 0
20249                || filter.countDataPaths() != 0
20250                || filter.countDataSchemes() > 1
20251                || filter.countDataTypes() != 0) {
20252            throw new IllegalArgumentException(
20253                    "replacePreferredActivity expects filter to have no data authorities, " +
20254                    "paths, or types; and at most one scheme.");
20255        }
20256
20257        final int callingUid = Binder.getCallingUid();
20258        enforceCrossUserPermission(callingUid, userId,
20259                true /* requireFullPermission */, false /* checkShell */,
20260                "replace preferred activity");
20261        synchronized (mPackages) {
20262            if (mContext.checkCallingOrSelfPermission(
20263                    android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
20264                    != PackageManager.PERMISSION_GRANTED) {
20265                if (getUidTargetSdkVersionLockedLPr(callingUid)
20266                        < Build.VERSION_CODES.FROYO) {
20267                    Slog.w(TAG, "Ignoring replacePreferredActivity() from uid "
20268                            + Binder.getCallingUid());
20269                    return;
20270                }
20271                mContext.enforceCallingOrSelfPermission(
20272                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
20273            }
20274
20275            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
20276            if (pir != null) {
20277                // Get all of the existing entries that exactly match this filter.
20278                ArrayList<PreferredActivity> existing = pir.findFilters(filter);
20279                if (existing != null && existing.size() == 1) {
20280                    PreferredActivity cur = existing.get(0);
20281                    if (DEBUG_PREFERRED) {
20282                        Slog.i(TAG, "Checking replace of preferred:");
20283                        filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
20284                        if (!cur.mPref.mAlways) {
20285                            Slog.i(TAG, "  -- CUR; not mAlways!");
20286                        } else {
20287                            Slog.i(TAG, "  -- CUR: mMatch=" + cur.mPref.mMatch);
20288                            Slog.i(TAG, "  -- CUR: mSet="
20289                                    + Arrays.toString(cur.mPref.mSetComponents));
20290                            Slog.i(TAG, "  -- CUR: mComponent=" + cur.mPref.mShortComponent);
20291                            Slog.i(TAG, "  -- NEW: mMatch="
20292                                    + (match&IntentFilter.MATCH_CATEGORY_MASK));
20293                            Slog.i(TAG, "  -- CUR: mSet=" + Arrays.toString(set));
20294                            Slog.i(TAG, "  -- CUR: mComponent=" + activity.flattenToShortString());
20295                        }
20296                    }
20297                    if (cur.mPref.mAlways && cur.mPref.mComponent.equals(activity)
20298                            && cur.mPref.mMatch == (match&IntentFilter.MATCH_CATEGORY_MASK)
20299                            && cur.mPref.sameSet(set)) {
20300                        // Setting the preferred activity to what it happens to be already
20301                        if (DEBUG_PREFERRED) {
20302                            Slog.i(TAG, "Replacing with same preferred activity "
20303                                    + cur.mPref.mShortComponent + " for user "
20304                                    + userId + ":");
20305                            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
20306                        }
20307                        return;
20308                    }
20309                }
20310
20311                if (existing != null) {
20312                    if (DEBUG_PREFERRED) {
20313                        Slog.i(TAG, existing.size() + " existing preferred matches for:");
20314                        filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
20315                    }
20316                    for (int i = 0; i < existing.size(); i++) {
20317                        PreferredActivity pa = existing.get(i);
20318                        if (DEBUG_PREFERRED) {
20319                            Slog.i(TAG, "Removing existing preferred activity "
20320                                    + pa.mPref.mComponent + ":");
20321                            pa.dump(new LogPrinter(Log.INFO, TAG), "  ");
20322                        }
20323                        pir.removeFilter(pa);
20324                    }
20325                }
20326            }
20327            addPreferredActivityInternal(filter, match, set, activity, true, userId,
20328                    "Replacing preferred");
20329        }
20330    }
20331
20332    @Override
20333    public void clearPackagePreferredActivities(String packageName) {
20334        final int callingUid = Binder.getCallingUid();
20335        if (getInstantAppPackageName(callingUid) != null) {
20336            return;
20337        }
20338        // writer
20339        synchronized (mPackages) {
20340            PackageParser.Package pkg = mPackages.get(packageName);
20341            if (pkg == null || pkg.applicationInfo.uid != callingUid) {
20342                if (mContext.checkCallingOrSelfPermission(
20343                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
20344                        != PackageManager.PERMISSION_GRANTED) {
20345                    if (getUidTargetSdkVersionLockedLPr(callingUid)
20346                            < Build.VERSION_CODES.FROYO) {
20347                        Slog.w(TAG, "Ignoring clearPackagePreferredActivities() from uid "
20348                                + callingUid);
20349                        return;
20350                    }
20351                    mContext.enforceCallingOrSelfPermission(
20352                            android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
20353                }
20354            }
20355            final PackageSetting ps = mSettings.getPackageLPr(packageName);
20356            if (ps != null
20357                    && filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
20358                return;
20359            }
20360            int user = UserHandle.getCallingUserId();
20361            if (clearPackagePreferredActivitiesLPw(packageName, user)) {
20362                scheduleWritePackageRestrictionsLocked(user);
20363            }
20364        }
20365    }
20366
20367    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
20368    boolean clearPackagePreferredActivitiesLPw(String packageName, int userId) {
20369        ArrayList<PreferredActivity> removed = null;
20370        boolean changed = false;
20371        for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
20372            final int thisUserId = mSettings.mPreferredActivities.keyAt(i);
20373            PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
20374            if (userId != UserHandle.USER_ALL && userId != thisUserId) {
20375                continue;
20376            }
20377            Iterator<PreferredActivity> it = pir.filterIterator();
20378            while (it.hasNext()) {
20379                PreferredActivity pa = it.next();
20380                // Mark entry for removal only if it matches the package name
20381                // and the entry is of type "always".
20382                if (packageName == null ||
20383                        (pa.mPref.mComponent.getPackageName().equals(packageName)
20384                                && pa.mPref.mAlways)) {
20385                    if (removed == null) {
20386                        removed = new ArrayList<PreferredActivity>();
20387                    }
20388                    removed.add(pa);
20389                }
20390            }
20391            if (removed != null) {
20392                for (int j=0; j<removed.size(); j++) {
20393                    PreferredActivity pa = removed.get(j);
20394                    pir.removeFilter(pa);
20395                }
20396                changed = true;
20397            }
20398        }
20399        if (changed) {
20400            postPreferredActivityChangedBroadcast(userId);
20401        }
20402        return changed;
20403    }
20404
20405    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
20406    private void clearIntentFilterVerificationsLPw(int userId) {
20407        final int packageCount = mPackages.size();
20408        for (int i = 0; i < packageCount; i++) {
20409            PackageParser.Package pkg = mPackages.valueAt(i);
20410            clearIntentFilterVerificationsLPw(pkg.packageName, userId);
20411        }
20412    }
20413
20414    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
20415    void clearIntentFilterVerificationsLPw(String packageName, int userId) {
20416        if (userId == UserHandle.USER_ALL) {
20417            if (mSettings.removeIntentFilterVerificationLPw(packageName,
20418                    sUserManager.getUserIds())) {
20419                for (int oneUserId : sUserManager.getUserIds()) {
20420                    scheduleWritePackageRestrictionsLocked(oneUserId);
20421                }
20422            }
20423        } else {
20424            if (mSettings.removeIntentFilterVerificationLPw(packageName, userId)) {
20425                scheduleWritePackageRestrictionsLocked(userId);
20426            }
20427        }
20428    }
20429
20430    /** Clears state for all users, and touches intent filter verification policy */
20431    void clearDefaultBrowserIfNeeded(String packageName) {
20432        for (int oneUserId : sUserManager.getUserIds()) {
20433            clearDefaultBrowserIfNeededForUser(packageName, oneUserId);
20434        }
20435    }
20436
20437    private void clearDefaultBrowserIfNeededForUser(String packageName, int userId) {
20438        final String defaultBrowserPackageName = getDefaultBrowserPackageName(userId);
20439        if (!TextUtils.isEmpty(defaultBrowserPackageName)) {
20440            if (packageName.equals(defaultBrowserPackageName)) {
20441                setDefaultBrowserPackageName(null, userId);
20442            }
20443        }
20444    }
20445
20446    @Override
20447    public void resetApplicationPreferences(int userId) {
20448        mContext.enforceCallingOrSelfPermission(
20449                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
20450        final long identity = Binder.clearCallingIdentity();
20451        // writer
20452        try {
20453            synchronized (mPackages) {
20454                clearPackagePreferredActivitiesLPw(null, userId);
20455                mSettings.applyDefaultPreferredAppsLPw(this, userId);
20456                // TODO: We have to reset the default SMS and Phone. This requires
20457                // significant refactoring to keep all default apps in the package
20458                // manager (cleaner but more work) or have the services provide
20459                // callbacks to the package manager to request a default app reset.
20460                applyFactoryDefaultBrowserLPw(userId);
20461                clearIntentFilterVerificationsLPw(userId);
20462                primeDomainVerificationsLPw(userId);
20463                resetUserChangesToRuntimePermissionsAndFlagsLPw(userId);
20464                scheduleWritePackageRestrictionsLocked(userId);
20465            }
20466            resetNetworkPolicies(userId);
20467        } finally {
20468            Binder.restoreCallingIdentity(identity);
20469        }
20470    }
20471
20472    @Override
20473    public int getPreferredActivities(List<IntentFilter> outFilters,
20474            List<ComponentName> outActivities, String packageName) {
20475        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
20476            return 0;
20477        }
20478        int num = 0;
20479        final int userId = UserHandle.getCallingUserId();
20480        // reader
20481        synchronized (mPackages) {
20482            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
20483            if (pir != null) {
20484                final Iterator<PreferredActivity> it = pir.filterIterator();
20485                while (it.hasNext()) {
20486                    final PreferredActivity pa = it.next();
20487                    if (packageName == null
20488                            || (pa.mPref.mComponent.getPackageName().equals(packageName)
20489                                    && pa.mPref.mAlways)) {
20490                        if (outFilters != null) {
20491                            outFilters.add(new IntentFilter(pa));
20492                        }
20493                        if (outActivities != null) {
20494                            outActivities.add(pa.mPref.mComponent);
20495                        }
20496                    }
20497                }
20498            }
20499        }
20500
20501        return num;
20502    }
20503
20504    @Override
20505    public void addPersistentPreferredActivity(IntentFilter filter, ComponentName activity,
20506            int userId) {
20507        int callingUid = Binder.getCallingUid();
20508        if (callingUid != Process.SYSTEM_UID) {
20509            throw new SecurityException(
20510                    "addPersistentPreferredActivity can only be run by the system");
20511        }
20512        if (filter.countActions() == 0) {
20513            Slog.w(TAG, "Cannot set a preferred activity with no filter actions");
20514            return;
20515        }
20516        synchronized (mPackages) {
20517            Slog.i(TAG, "Adding persistent preferred activity " + activity + " for user " + userId +
20518                    ":");
20519            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
20520            mSettings.editPersistentPreferredActivitiesLPw(userId).addFilter(
20521                    new PersistentPreferredActivity(filter, activity));
20522            scheduleWritePackageRestrictionsLocked(userId);
20523            postPreferredActivityChangedBroadcast(userId);
20524        }
20525    }
20526
20527    @Override
20528    public void clearPackagePersistentPreferredActivities(String packageName, int userId) {
20529        int callingUid = Binder.getCallingUid();
20530        if (callingUid != Process.SYSTEM_UID) {
20531            throw new SecurityException(
20532                    "clearPackagePersistentPreferredActivities can only be run by the system");
20533        }
20534        ArrayList<PersistentPreferredActivity> removed = null;
20535        boolean changed = false;
20536        synchronized (mPackages) {
20537            for (int i=0; i<mSettings.mPersistentPreferredActivities.size(); i++) {
20538                final int thisUserId = mSettings.mPersistentPreferredActivities.keyAt(i);
20539                PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities
20540                        .valueAt(i);
20541                if (userId != thisUserId) {
20542                    continue;
20543                }
20544                Iterator<PersistentPreferredActivity> it = ppir.filterIterator();
20545                while (it.hasNext()) {
20546                    PersistentPreferredActivity ppa = it.next();
20547                    // Mark entry for removal only if it matches the package name.
20548                    if (ppa.mComponent.getPackageName().equals(packageName)) {
20549                        if (removed == null) {
20550                            removed = new ArrayList<PersistentPreferredActivity>();
20551                        }
20552                        removed.add(ppa);
20553                    }
20554                }
20555                if (removed != null) {
20556                    for (int j=0; j<removed.size(); j++) {
20557                        PersistentPreferredActivity ppa = removed.get(j);
20558                        ppir.removeFilter(ppa);
20559                    }
20560                    changed = true;
20561                }
20562            }
20563
20564            if (changed) {
20565                scheduleWritePackageRestrictionsLocked(userId);
20566                postPreferredActivityChangedBroadcast(userId);
20567            }
20568        }
20569    }
20570
20571    /**
20572     * Common machinery for picking apart a restored XML blob and passing
20573     * it to a caller-supplied functor to be applied to the running system.
20574     */
20575    private void restoreFromXml(XmlPullParser parser, int userId,
20576            String expectedStartTag, BlobXmlRestorer functor)
20577            throws IOException, XmlPullParserException {
20578        int type;
20579        while ((type = parser.next()) != XmlPullParser.START_TAG
20580                && type != XmlPullParser.END_DOCUMENT) {
20581        }
20582        if (type != XmlPullParser.START_TAG) {
20583            // oops didn't find a start tag?!
20584            if (DEBUG_BACKUP) {
20585                Slog.e(TAG, "Didn't find start tag during restore");
20586            }
20587            return;
20588        }
20589Slog.v(TAG, ":: restoreFromXml() : got to tag " + parser.getName());
20590        // this is supposed to be TAG_PREFERRED_BACKUP
20591        if (!expectedStartTag.equals(parser.getName())) {
20592            if (DEBUG_BACKUP) {
20593                Slog.e(TAG, "Found unexpected tag " + parser.getName());
20594            }
20595            return;
20596        }
20597
20598        // skip interfering stuff, then we're aligned with the backing implementation
20599        while ((type = parser.next()) == XmlPullParser.TEXT) { }
20600Slog.v(TAG, ":: stepped forward, applying functor at tag " + parser.getName());
20601        functor.apply(parser, userId);
20602    }
20603
20604    private interface BlobXmlRestorer {
20605        public void apply(XmlPullParser parser, int userId) throws IOException, XmlPullParserException;
20606    }
20607
20608    /**
20609     * Non-Binder method, support for the backup/restore mechanism: write the
20610     * full set of preferred activities in its canonical XML format.  Returns the
20611     * XML output as a byte array, or null if there is none.
20612     */
20613    @Override
20614    public byte[] getPreferredActivityBackup(int userId) {
20615        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
20616            throw new SecurityException("Only the system may call getPreferredActivityBackup()");
20617        }
20618
20619        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
20620        try {
20621            final XmlSerializer serializer = new FastXmlSerializer();
20622            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
20623            serializer.startDocument(null, true);
20624            serializer.startTag(null, TAG_PREFERRED_BACKUP);
20625
20626            synchronized (mPackages) {
20627                mSettings.writePreferredActivitiesLPr(serializer, userId, true);
20628            }
20629
20630            serializer.endTag(null, TAG_PREFERRED_BACKUP);
20631            serializer.endDocument();
20632            serializer.flush();
20633        } catch (Exception e) {
20634            if (DEBUG_BACKUP) {
20635                Slog.e(TAG, "Unable to write preferred activities for backup", e);
20636            }
20637            return null;
20638        }
20639
20640        return dataStream.toByteArray();
20641    }
20642
20643    @Override
20644    public void restorePreferredActivities(byte[] backup, int userId) {
20645        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
20646            throw new SecurityException("Only the system may call restorePreferredActivities()");
20647        }
20648
20649        try {
20650            final XmlPullParser parser = Xml.newPullParser();
20651            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
20652            restoreFromXml(parser, userId, TAG_PREFERRED_BACKUP,
20653                    new BlobXmlRestorer() {
20654                        @Override
20655                        public void apply(XmlPullParser parser, int userId)
20656                                throws XmlPullParserException, IOException {
20657                            synchronized (mPackages) {
20658                                mSettings.readPreferredActivitiesLPw(parser, userId);
20659                            }
20660                        }
20661                    } );
20662        } catch (Exception e) {
20663            if (DEBUG_BACKUP) {
20664                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
20665            }
20666        }
20667    }
20668
20669    /**
20670     * Non-Binder method, support for the backup/restore mechanism: write the
20671     * default browser (etc) settings in its canonical XML format.  Returns the default
20672     * browser XML representation as a byte array, or null if there is none.
20673     */
20674    @Override
20675    public byte[] getDefaultAppsBackup(int userId) {
20676        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
20677            throw new SecurityException("Only the system may call getDefaultAppsBackup()");
20678        }
20679
20680        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
20681        try {
20682            final XmlSerializer serializer = new FastXmlSerializer();
20683            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
20684            serializer.startDocument(null, true);
20685            serializer.startTag(null, TAG_DEFAULT_APPS);
20686
20687            synchronized (mPackages) {
20688                mSettings.writeDefaultAppsLPr(serializer, userId);
20689            }
20690
20691            serializer.endTag(null, TAG_DEFAULT_APPS);
20692            serializer.endDocument();
20693            serializer.flush();
20694        } catch (Exception e) {
20695            if (DEBUG_BACKUP) {
20696                Slog.e(TAG, "Unable to write default apps for backup", e);
20697            }
20698            return null;
20699        }
20700
20701        return dataStream.toByteArray();
20702    }
20703
20704    @Override
20705    public void restoreDefaultApps(byte[] backup, int userId) {
20706        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
20707            throw new SecurityException("Only the system may call restoreDefaultApps()");
20708        }
20709
20710        try {
20711            final XmlPullParser parser = Xml.newPullParser();
20712            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
20713            restoreFromXml(parser, userId, TAG_DEFAULT_APPS,
20714                    new BlobXmlRestorer() {
20715                        @Override
20716                        public void apply(XmlPullParser parser, int userId)
20717                                throws XmlPullParserException, IOException {
20718                            synchronized (mPackages) {
20719                                mSettings.readDefaultAppsLPw(parser, userId);
20720                            }
20721                        }
20722                    } );
20723        } catch (Exception e) {
20724            if (DEBUG_BACKUP) {
20725                Slog.e(TAG, "Exception restoring default apps: " + e.getMessage());
20726            }
20727        }
20728    }
20729
20730    @Override
20731    public byte[] getIntentFilterVerificationBackup(int userId) {
20732        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
20733            throw new SecurityException("Only the system may call getIntentFilterVerificationBackup()");
20734        }
20735
20736        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
20737        try {
20738            final XmlSerializer serializer = new FastXmlSerializer();
20739            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
20740            serializer.startDocument(null, true);
20741            serializer.startTag(null, TAG_INTENT_FILTER_VERIFICATION);
20742
20743            synchronized (mPackages) {
20744                mSettings.writeAllDomainVerificationsLPr(serializer, userId);
20745            }
20746
20747            serializer.endTag(null, TAG_INTENT_FILTER_VERIFICATION);
20748            serializer.endDocument();
20749            serializer.flush();
20750        } catch (Exception e) {
20751            if (DEBUG_BACKUP) {
20752                Slog.e(TAG, "Unable to write default apps for backup", e);
20753            }
20754            return null;
20755        }
20756
20757        return dataStream.toByteArray();
20758    }
20759
20760    @Override
20761    public void restoreIntentFilterVerification(byte[] backup, int userId) {
20762        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
20763            throw new SecurityException("Only the system may call restorePreferredActivities()");
20764        }
20765
20766        try {
20767            final XmlPullParser parser = Xml.newPullParser();
20768            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
20769            restoreFromXml(parser, userId, TAG_INTENT_FILTER_VERIFICATION,
20770                    new BlobXmlRestorer() {
20771                        @Override
20772                        public void apply(XmlPullParser parser, int userId)
20773                                throws XmlPullParserException, IOException {
20774                            synchronized (mPackages) {
20775                                mSettings.readAllDomainVerificationsLPr(parser, userId);
20776                                mSettings.writeLPr();
20777                            }
20778                        }
20779                    } );
20780        } catch (Exception e) {
20781            if (DEBUG_BACKUP) {
20782                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
20783            }
20784        }
20785    }
20786
20787    @Override
20788    public byte[] getPermissionGrantBackup(int userId) {
20789        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
20790            throw new SecurityException("Only the system may call getPermissionGrantBackup()");
20791        }
20792
20793        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
20794        try {
20795            final XmlSerializer serializer = new FastXmlSerializer();
20796            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
20797            serializer.startDocument(null, true);
20798            serializer.startTag(null, TAG_PERMISSION_BACKUP);
20799
20800            synchronized (mPackages) {
20801                serializeRuntimePermissionGrantsLPr(serializer, userId);
20802            }
20803
20804            serializer.endTag(null, TAG_PERMISSION_BACKUP);
20805            serializer.endDocument();
20806            serializer.flush();
20807        } catch (Exception e) {
20808            if (DEBUG_BACKUP) {
20809                Slog.e(TAG, "Unable to write default apps for backup", e);
20810            }
20811            return null;
20812        }
20813
20814        return dataStream.toByteArray();
20815    }
20816
20817    @Override
20818    public void restorePermissionGrants(byte[] backup, int userId) {
20819        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
20820            throw new SecurityException("Only the system may call restorePermissionGrants()");
20821        }
20822
20823        try {
20824            final XmlPullParser parser = Xml.newPullParser();
20825            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
20826            restoreFromXml(parser, userId, TAG_PERMISSION_BACKUP,
20827                    new BlobXmlRestorer() {
20828                        @Override
20829                        public void apply(XmlPullParser parser, int userId)
20830                                throws XmlPullParserException, IOException {
20831                            synchronized (mPackages) {
20832                                processRestoredPermissionGrantsLPr(parser, userId);
20833                            }
20834                        }
20835                    } );
20836        } catch (Exception e) {
20837            if (DEBUG_BACKUP) {
20838                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
20839            }
20840        }
20841    }
20842
20843    private void serializeRuntimePermissionGrantsLPr(XmlSerializer serializer, final int userId)
20844            throws IOException {
20845        serializer.startTag(null, TAG_ALL_GRANTS);
20846
20847        final int N = mSettings.mPackages.size();
20848        for (int i = 0; i < N; i++) {
20849            final PackageSetting ps = mSettings.mPackages.valueAt(i);
20850            boolean pkgGrantsKnown = false;
20851
20852            PermissionsState packagePerms = ps.getPermissionsState();
20853
20854            for (PermissionState state : packagePerms.getRuntimePermissionStates(userId)) {
20855                final int grantFlags = state.getFlags();
20856                // only look at grants that are not system/policy fixed
20857                if ((grantFlags & SYSTEM_RUNTIME_GRANT_MASK) == 0) {
20858                    final boolean isGranted = state.isGranted();
20859                    // And only back up the user-twiddled state bits
20860                    if (isGranted || (grantFlags & USER_RUNTIME_GRANT_MASK) != 0) {
20861                        final String packageName = mSettings.mPackages.keyAt(i);
20862                        if (!pkgGrantsKnown) {
20863                            serializer.startTag(null, TAG_GRANT);
20864                            serializer.attribute(null, ATTR_PACKAGE_NAME, packageName);
20865                            pkgGrantsKnown = true;
20866                        }
20867
20868                        final boolean userSet =
20869                                (grantFlags & FLAG_PERMISSION_USER_SET) != 0;
20870                        final boolean userFixed =
20871                                (grantFlags & FLAG_PERMISSION_USER_FIXED) != 0;
20872                        final boolean revoke =
20873                                (grantFlags & FLAG_PERMISSION_REVOKE_ON_UPGRADE) != 0;
20874
20875                        serializer.startTag(null, TAG_PERMISSION);
20876                        serializer.attribute(null, ATTR_PERMISSION_NAME, state.getName());
20877                        if (isGranted) {
20878                            serializer.attribute(null, ATTR_IS_GRANTED, "true");
20879                        }
20880                        if (userSet) {
20881                            serializer.attribute(null, ATTR_USER_SET, "true");
20882                        }
20883                        if (userFixed) {
20884                            serializer.attribute(null, ATTR_USER_FIXED, "true");
20885                        }
20886                        if (revoke) {
20887                            serializer.attribute(null, ATTR_REVOKE_ON_UPGRADE, "true");
20888                        }
20889                        serializer.endTag(null, TAG_PERMISSION);
20890                    }
20891                }
20892            }
20893
20894            if (pkgGrantsKnown) {
20895                serializer.endTag(null, TAG_GRANT);
20896            }
20897        }
20898
20899        serializer.endTag(null, TAG_ALL_GRANTS);
20900    }
20901
20902    private void processRestoredPermissionGrantsLPr(XmlPullParser parser, int userId)
20903            throws XmlPullParserException, IOException {
20904        String pkgName = null;
20905        int outerDepth = parser.getDepth();
20906        int type;
20907        while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
20908                && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) {
20909            if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) {
20910                continue;
20911            }
20912
20913            final String tagName = parser.getName();
20914            if (tagName.equals(TAG_GRANT)) {
20915                pkgName = parser.getAttributeValue(null, ATTR_PACKAGE_NAME);
20916                if (DEBUG_BACKUP) {
20917                    Slog.v(TAG, "+++ Restoring grants for package " + pkgName);
20918                }
20919            } else if (tagName.equals(TAG_PERMISSION)) {
20920
20921                final boolean isGranted = "true".equals(parser.getAttributeValue(null, ATTR_IS_GRANTED));
20922                final String permName = parser.getAttributeValue(null, ATTR_PERMISSION_NAME);
20923
20924                int newFlagSet = 0;
20925                if ("true".equals(parser.getAttributeValue(null, ATTR_USER_SET))) {
20926                    newFlagSet |= FLAG_PERMISSION_USER_SET;
20927                }
20928                if ("true".equals(parser.getAttributeValue(null, ATTR_USER_FIXED))) {
20929                    newFlagSet |= FLAG_PERMISSION_USER_FIXED;
20930                }
20931                if ("true".equals(parser.getAttributeValue(null, ATTR_REVOKE_ON_UPGRADE))) {
20932                    newFlagSet |= FLAG_PERMISSION_REVOKE_ON_UPGRADE;
20933                }
20934                if (DEBUG_BACKUP) {
20935                    Slog.v(TAG, "  + Restoring grant: pkg=" + pkgName + " perm=" + permName
20936                            + " granted=" + isGranted + " bits=0x" + Integer.toHexString(newFlagSet));
20937                }
20938                final PackageSetting ps = mSettings.mPackages.get(pkgName);
20939                if (ps != null) {
20940                    // Already installed so we apply the grant immediately
20941                    if (DEBUG_BACKUP) {
20942                        Slog.v(TAG, "        + already installed; applying");
20943                    }
20944                    PermissionsState perms = ps.getPermissionsState();
20945                    BasePermission bp = mSettings.mPermissions.get(permName);
20946                    if (bp != null) {
20947                        if (isGranted) {
20948                            perms.grantRuntimePermission(bp, userId);
20949                        }
20950                        if (newFlagSet != 0) {
20951                            perms.updatePermissionFlags(bp, userId, USER_RUNTIME_GRANT_MASK, newFlagSet);
20952                        }
20953                    }
20954                } else {
20955                    // Need to wait for post-restore install to apply the grant
20956                    if (DEBUG_BACKUP) {
20957                        Slog.v(TAG, "        - not yet installed; saving for later");
20958                    }
20959                    mSettings.processRestoredPermissionGrantLPr(pkgName, permName,
20960                            isGranted, newFlagSet, userId);
20961                }
20962            } else {
20963                PackageManagerService.reportSettingsProblem(Log.WARN,
20964                        "Unknown element under <" + TAG_PERMISSION_BACKUP + ">: " + tagName);
20965                XmlUtils.skipCurrentTag(parser);
20966            }
20967        }
20968
20969        scheduleWriteSettingsLocked();
20970        mSettings.writeRuntimePermissionsForUserLPr(userId, false);
20971    }
20972
20973    @Override
20974    public void addCrossProfileIntentFilter(IntentFilter intentFilter, String ownerPackage,
20975            int sourceUserId, int targetUserId, int flags) {
20976        mContext.enforceCallingOrSelfPermission(
20977                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
20978        int callingUid = Binder.getCallingUid();
20979        enforceOwnerRights(ownerPackage, callingUid);
20980        enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId);
20981        if (intentFilter.countActions() == 0) {
20982            Slog.w(TAG, "Cannot set a crossProfile intent filter with no filter actions");
20983            return;
20984        }
20985        synchronized (mPackages) {
20986            CrossProfileIntentFilter newFilter = new CrossProfileIntentFilter(intentFilter,
20987                    ownerPackage, targetUserId, flags);
20988            CrossProfileIntentResolver resolver =
20989                    mSettings.editCrossProfileIntentResolverLPw(sourceUserId);
20990            ArrayList<CrossProfileIntentFilter> existing = resolver.findFilters(intentFilter);
20991            // We have all those whose filter is equal. Now checking if the rest is equal as well.
20992            if (existing != null) {
20993                int size = existing.size();
20994                for (int i = 0; i < size; i++) {
20995                    if (newFilter.equalsIgnoreFilter(existing.get(i))) {
20996                        return;
20997                    }
20998                }
20999            }
21000            resolver.addFilter(newFilter);
21001            scheduleWritePackageRestrictionsLocked(sourceUserId);
21002        }
21003    }
21004
21005    @Override
21006    public void clearCrossProfileIntentFilters(int sourceUserId, String ownerPackage) {
21007        mContext.enforceCallingOrSelfPermission(
21008                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
21009        final int callingUid = Binder.getCallingUid();
21010        enforceOwnerRights(ownerPackage, callingUid);
21011        enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId);
21012        synchronized (mPackages) {
21013            CrossProfileIntentResolver resolver =
21014                    mSettings.editCrossProfileIntentResolverLPw(sourceUserId);
21015            ArraySet<CrossProfileIntentFilter> set =
21016                    new ArraySet<CrossProfileIntentFilter>(resolver.filterSet());
21017            for (CrossProfileIntentFilter filter : set) {
21018                if (filter.getOwnerPackage().equals(ownerPackage)) {
21019                    resolver.removeFilter(filter);
21020                }
21021            }
21022            scheduleWritePackageRestrictionsLocked(sourceUserId);
21023        }
21024    }
21025
21026    // Enforcing that callingUid is owning pkg on userId
21027    private void enforceOwnerRights(String pkg, int callingUid) {
21028        // The system owns everything.
21029        if (UserHandle.getAppId(callingUid) == Process.SYSTEM_UID) {
21030            return;
21031        }
21032        final int callingUserId = UserHandle.getUserId(callingUid);
21033        PackageInfo pi = getPackageInfo(pkg, 0, callingUserId);
21034        if (pi == null) {
21035            throw new IllegalArgumentException("Unknown package " + pkg + " on user "
21036                    + callingUserId);
21037        }
21038        if (!UserHandle.isSameApp(pi.applicationInfo.uid, callingUid)) {
21039            throw new SecurityException("Calling uid " + callingUid
21040                    + " does not own package " + pkg);
21041        }
21042    }
21043
21044    @Override
21045    public ComponentName getHomeActivities(List<ResolveInfo> allHomeCandidates) {
21046        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
21047            return null;
21048        }
21049        return getHomeActivitiesAsUser(allHomeCandidates, UserHandle.getCallingUserId());
21050    }
21051
21052    public void sendSessionCommitBroadcast(PackageInstaller.SessionInfo sessionInfo, int userId) {
21053        UserManagerService ums = UserManagerService.getInstance();
21054        if (ums != null) {
21055            final UserInfo parent = ums.getProfileParent(userId);
21056            final int launcherUid = (parent != null) ? parent.id : userId;
21057            final ComponentName launcherComponent = getDefaultHomeActivity(launcherUid);
21058            if (launcherComponent != null) {
21059                Intent launcherIntent = new Intent(PackageInstaller.ACTION_SESSION_COMMITTED)
21060                        .putExtra(PackageInstaller.EXTRA_SESSION, sessionInfo)
21061                        .putExtra(Intent.EXTRA_USER, UserHandle.of(userId))
21062                        .setPackage(launcherComponent.getPackageName());
21063                mContext.sendBroadcastAsUser(launcherIntent, UserHandle.of(launcherUid));
21064            }
21065        }
21066    }
21067
21068    /**
21069     * Report the 'Home' activity which is currently set as "always use this one". If non is set
21070     * then reports the most likely home activity or null if there are more than one.
21071     */
21072    private ComponentName getDefaultHomeActivity(int userId) {
21073        List<ResolveInfo> allHomeCandidates = new ArrayList<>();
21074        ComponentName cn = getHomeActivitiesAsUser(allHomeCandidates, userId);
21075        if (cn != null) {
21076            return cn;
21077        }
21078
21079        // Find the launcher with the highest priority and return that component if there are no
21080        // other home activity with the same priority.
21081        int lastPriority = Integer.MIN_VALUE;
21082        ComponentName lastComponent = null;
21083        final int size = allHomeCandidates.size();
21084        for (int i = 0; i < size; i++) {
21085            final ResolveInfo ri = allHomeCandidates.get(i);
21086            if (ri.priority > lastPriority) {
21087                lastComponent = ri.activityInfo.getComponentName();
21088                lastPriority = ri.priority;
21089            } else if (ri.priority == lastPriority) {
21090                // Two components found with same priority.
21091                lastComponent = null;
21092            }
21093        }
21094        return lastComponent;
21095    }
21096
21097    private Intent getHomeIntent() {
21098        Intent intent = new Intent(Intent.ACTION_MAIN);
21099        intent.addCategory(Intent.CATEGORY_HOME);
21100        intent.addCategory(Intent.CATEGORY_DEFAULT);
21101        return intent;
21102    }
21103
21104    private IntentFilter getHomeFilter() {
21105        IntentFilter filter = new IntentFilter(Intent.ACTION_MAIN);
21106        filter.addCategory(Intent.CATEGORY_HOME);
21107        filter.addCategory(Intent.CATEGORY_DEFAULT);
21108        return filter;
21109    }
21110
21111    ComponentName getHomeActivitiesAsUser(List<ResolveInfo> allHomeCandidates,
21112            int userId) {
21113        Intent intent  = getHomeIntent();
21114        List<ResolveInfo> list = queryIntentActivitiesInternal(intent, null,
21115                PackageManager.GET_META_DATA, userId);
21116        ResolveInfo preferred = findPreferredActivity(intent, null, 0, list, 0,
21117                true, false, false, userId);
21118
21119        allHomeCandidates.clear();
21120        if (list != null) {
21121            for (ResolveInfo ri : list) {
21122                allHomeCandidates.add(ri);
21123            }
21124        }
21125        return (preferred == null || preferred.activityInfo == null)
21126                ? null
21127                : new ComponentName(preferred.activityInfo.packageName,
21128                        preferred.activityInfo.name);
21129    }
21130
21131    @Override
21132    public void setHomeActivity(ComponentName comp, int userId) {
21133        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
21134            return;
21135        }
21136        ArrayList<ResolveInfo> homeActivities = new ArrayList<>();
21137        getHomeActivitiesAsUser(homeActivities, userId);
21138
21139        boolean found = false;
21140
21141        final int size = homeActivities.size();
21142        final ComponentName[] set = new ComponentName[size];
21143        for (int i = 0; i < size; i++) {
21144            final ResolveInfo candidate = homeActivities.get(i);
21145            final ActivityInfo info = candidate.activityInfo;
21146            final ComponentName activityName = new ComponentName(info.packageName, info.name);
21147            set[i] = activityName;
21148            if (!found && activityName.equals(comp)) {
21149                found = true;
21150            }
21151        }
21152        if (!found) {
21153            throw new IllegalArgumentException("Component " + comp + " cannot be home on user "
21154                    + userId);
21155        }
21156        replacePreferredActivity(getHomeFilter(), IntentFilter.MATCH_CATEGORY_EMPTY,
21157                set, comp, userId);
21158    }
21159
21160    private @Nullable String getSetupWizardPackageName() {
21161        final Intent intent = new Intent(Intent.ACTION_MAIN);
21162        intent.addCategory(Intent.CATEGORY_SETUP_WIZARD);
21163
21164        final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, null,
21165                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE
21166                        | MATCH_DISABLED_COMPONENTS,
21167                UserHandle.myUserId());
21168        if (matches.size() == 1) {
21169            return matches.get(0).getComponentInfo().packageName;
21170        } else {
21171            Slog.e(TAG, "There should probably be exactly one setup wizard; found " + matches.size()
21172                    + ": matches=" + matches);
21173            return null;
21174        }
21175    }
21176
21177    private @Nullable String getStorageManagerPackageName() {
21178        final Intent intent = new Intent(StorageManager.ACTION_MANAGE_STORAGE);
21179
21180        final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, null,
21181                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE
21182                        | MATCH_DISABLED_COMPONENTS,
21183                UserHandle.myUserId());
21184        if (matches.size() == 1) {
21185            return matches.get(0).getComponentInfo().packageName;
21186        } else {
21187            Slog.e(TAG, "There should probably be exactly one storage manager; found "
21188                    + matches.size() + ": matches=" + matches);
21189            return null;
21190        }
21191    }
21192
21193    @Override
21194    public void setApplicationEnabledSetting(String appPackageName,
21195            int newState, int flags, int userId, String callingPackage) {
21196        if (!sUserManager.exists(userId)) return;
21197        if (callingPackage == null) {
21198            callingPackage = Integer.toString(Binder.getCallingUid());
21199        }
21200        setEnabledSetting(appPackageName, null, newState, flags, userId, callingPackage);
21201    }
21202
21203    @Override
21204    public void setUpdateAvailable(String packageName, boolean updateAvailable) {
21205        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, null);
21206        synchronized (mPackages) {
21207            final PackageSetting pkgSetting = mSettings.mPackages.get(packageName);
21208            if (pkgSetting != null) {
21209                pkgSetting.setUpdateAvailable(updateAvailable);
21210            }
21211        }
21212    }
21213
21214    @Override
21215    public void setComponentEnabledSetting(ComponentName componentName,
21216            int newState, int flags, int userId) {
21217        if (!sUserManager.exists(userId)) return;
21218        setEnabledSetting(componentName.getPackageName(),
21219                componentName.getClassName(), newState, flags, userId, null);
21220    }
21221
21222    private void setEnabledSetting(final String packageName, String className, int newState,
21223            final int flags, int userId, String callingPackage) {
21224        if (!(newState == COMPONENT_ENABLED_STATE_DEFAULT
21225              || newState == COMPONENT_ENABLED_STATE_ENABLED
21226              || newState == COMPONENT_ENABLED_STATE_DISABLED
21227              || newState == COMPONENT_ENABLED_STATE_DISABLED_USER
21228              || newState == COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED)) {
21229            throw new IllegalArgumentException("Invalid new component state: "
21230                    + newState);
21231        }
21232        PackageSetting pkgSetting;
21233        final int callingUid = Binder.getCallingUid();
21234        final int permission;
21235        if (callingUid == Process.SYSTEM_UID) {
21236            permission = PackageManager.PERMISSION_GRANTED;
21237        } else {
21238            permission = mContext.checkCallingOrSelfPermission(
21239                    android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
21240        }
21241        enforceCrossUserPermission(callingUid, userId,
21242                false /* requireFullPermission */, true /* checkShell */, "set enabled");
21243        final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
21244        boolean sendNow = false;
21245        boolean isApp = (className == null);
21246        final boolean isCallerInstantApp = (getInstantAppPackageName(callingUid) != null);
21247        String componentName = isApp ? packageName : className;
21248        int packageUid = -1;
21249        ArrayList<String> components;
21250
21251        // reader
21252        synchronized (mPackages) {
21253            pkgSetting = mSettings.mPackages.get(packageName);
21254            if (pkgSetting == null) {
21255                if (!isCallerInstantApp) {
21256                    if (className == null) {
21257                        throw new IllegalArgumentException("Unknown package: " + packageName);
21258                    }
21259                    throw new IllegalArgumentException(
21260                            "Unknown component: " + packageName + "/" + className);
21261                } else {
21262                    // throw SecurityException to prevent leaking package information
21263                    throw new SecurityException(
21264                            "Attempt to change component state; "
21265                            + "pid=" + Binder.getCallingPid()
21266                            + ", uid=" + callingUid
21267                            + (className == null
21268                                    ? ", package=" + packageName
21269                                    : ", component=" + packageName + "/" + className));
21270                }
21271            }
21272        }
21273
21274        // Limit who can change which apps
21275        if (!UserHandle.isSameApp(callingUid, pkgSetting.appId)) {
21276            // Don't allow apps that don't have permission to modify other apps
21277            if (!allowedByPermission
21278                    || filterAppAccessLPr(pkgSetting, callingUid, userId)) {
21279                throw new SecurityException(
21280                        "Attempt to change component state; "
21281                        + "pid=" + Binder.getCallingPid()
21282                        + ", uid=" + callingUid
21283                        + (className == null
21284                                ? ", package=" + packageName
21285                                : ", component=" + packageName + "/" + className));
21286            }
21287            // Don't allow changing protected packages.
21288            if (mProtectedPackages.isPackageStateProtected(userId, packageName)) {
21289                throw new SecurityException("Cannot disable a protected package: " + packageName);
21290            }
21291        }
21292
21293        synchronized (mPackages) {
21294            if (callingUid == Process.SHELL_UID
21295                    && (pkgSetting.pkgFlags & ApplicationInfo.FLAG_TEST_ONLY) == 0) {
21296                // Shell can only change whole packages between ENABLED and DISABLED_USER states
21297                // unless it is a test package.
21298                int oldState = pkgSetting.getEnabled(userId);
21299                if (className == null
21300                    &&
21301                    (oldState == COMPONENT_ENABLED_STATE_DISABLED_USER
21302                     || oldState == COMPONENT_ENABLED_STATE_DEFAULT
21303                     || oldState == COMPONENT_ENABLED_STATE_ENABLED)
21304                    &&
21305                    (newState == COMPONENT_ENABLED_STATE_DISABLED_USER
21306                     || newState == COMPONENT_ENABLED_STATE_DEFAULT
21307                     || newState == COMPONENT_ENABLED_STATE_ENABLED)) {
21308                    // ok
21309                } else {
21310                    throw new SecurityException(
21311                            "Shell cannot change component state for " + packageName + "/"
21312                            + className + " to " + newState);
21313                }
21314            }
21315            if (className == null) {
21316                // We're dealing with an application/package level state change
21317                if (pkgSetting.getEnabled(userId) == newState) {
21318                    // Nothing to do
21319                    return;
21320                }
21321                if (newState == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT
21322                    || newState == PackageManager.COMPONENT_ENABLED_STATE_ENABLED) {
21323                    // Don't care about who enables an app.
21324                    callingPackage = null;
21325                }
21326                pkgSetting.setEnabled(newState, userId, callingPackage);
21327                // pkgSetting.pkg.mSetEnabled = newState;
21328            } else {
21329                // We're dealing with a component level state change
21330                // First, verify that this is a valid class name.
21331                PackageParser.Package pkg = pkgSetting.pkg;
21332                if (pkg == null || !pkg.hasComponentClassName(className)) {
21333                    if (pkg != null &&
21334                            pkg.applicationInfo.targetSdkVersion >=
21335                                    Build.VERSION_CODES.JELLY_BEAN) {
21336                        throw new IllegalArgumentException("Component class " + className
21337                                + " does not exist in " + packageName);
21338                    } else {
21339                        Slog.w(TAG, "Failed setComponentEnabledSetting: component class "
21340                                + className + " does not exist in " + packageName);
21341                    }
21342                }
21343                switch (newState) {
21344                case COMPONENT_ENABLED_STATE_ENABLED:
21345                    if (!pkgSetting.enableComponentLPw(className, userId)) {
21346                        return;
21347                    }
21348                    break;
21349                case COMPONENT_ENABLED_STATE_DISABLED:
21350                    if (!pkgSetting.disableComponentLPw(className, userId)) {
21351                        return;
21352                    }
21353                    break;
21354                case COMPONENT_ENABLED_STATE_DEFAULT:
21355                    if (!pkgSetting.restoreComponentLPw(className, userId)) {
21356                        return;
21357                    }
21358                    break;
21359                default:
21360                    Slog.e(TAG, "Invalid new component state: " + newState);
21361                    return;
21362                }
21363            }
21364            scheduleWritePackageRestrictionsLocked(userId);
21365            updateSequenceNumberLP(pkgSetting, new int[] { userId });
21366            final long callingId = Binder.clearCallingIdentity();
21367            try {
21368                updateInstantAppInstallerLocked(packageName);
21369            } finally {
21370                Binder.restoreCallingIdentity(callingId);
21371            }
21372            components = mPendingBroadcasts.get(userId, packageName);
21373            final boolean newPackage = components == null;
21374            if (newPackage) {
21375                components = new ArrayList<String>();
21376            }
21377            if (!components.contains(componentName)) {
21378                components.add(componentName);
21379            }
21380            if ((flags&PackageManager.DONT_KILL_APP) == 0) {
21381                sendNow = true;
21382                // Purge entry from pending broadcast list if another one exists already
21383                // since we are sending one right away.
21384                mPendingBroadcasts.remove(userId, packageName);
21385            } else {
21386                if (newPackage) {
21387                    mPendingBroadcasts.put(userId, packageName, components);
21388                }
21389                if (!mHandler.hasMessages(SEND_PENDING_BROADCAST)) {
21390                    // Schedule a message
21391                    mHandler.sendEmptyMessageDelayed(SEND_PENDING_BROADCAST, BROADCAST_DELAY);
21392                }
21393            }
21394        }
21395
21396        long callingId = Binder.clearCallingIdentity();
21397        try {
21398            if (sendNow) {
21399                packageUid = UserHandle.getUid(userId, pkgSetting.appId);
21400                sendPackageChangedBroadcast(packageName,
21401                        (flags&PackageManager.DONT_KILL_APP) != 0, components, packageUid);
21402            }
21403        } finally {
21404            Binder.restoreCallingIdentity(callingId);
21405        }
21406    }
21407
21408    @Override
21409    public void flushPackageRestrictionsAsUser(int userId) {
21410        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
21411            return;
21412        }
21413        if (!sUserManager.exists(userId)) {
21414            return;
21415        }
21416        enforceCrossUserPermission(Binder.getCallingUid(), userId, false /* requireFullPermission*/,
21417                false /* checkShell */, "flushPackageRestrictions");
21418        synchronized (mPackages) {
21419            mSettings.writePackageRestrictionsLPr(userId);
21420            mDirtyUsers.remove(userId);
21421            if (mDirtyUsers.isEmpty()) {
21422                mHandler.removeMessages(WRITE_PACKAGE_RESTRICTIONS);
21423            }
21424        }
21425    }
21426
21427    private void sendPackageChangedBroadcast(String packageName,
21428            boolean killFlag, ArrayList<String> componentNames, int packageUid) {
21429        if (DEBUG_INSTALL)
21430            Log.v(TAG, "Sending package changed: package=" + packageName + " components="
21431                    + componentNames);
21432        Bundle extras = new Bundle(4);
21433        extras.putString(Intent.EXTRA_CHANGED_COMPONENT_NAME, componentNames.get(0));
21434        String nameList[] = new String[componentNames.size()];
21435        componentNames.toArray(nameList);
21436        extras.putStringArray(Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST, nameList);
21437        extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, killFlag);
21438        extras.putInt(Intent.EXTRA_UID, packageUid);
21439        // If this is not reporting a change of the overall package, then only send it
21440        // to registered receivers.  We don't want to launch a swath of apps for every
21441        // little component state change.
21442        final int flags = !componentNames.contains(packageName)
21443                ? Intent.FLAG_RECEIVER_REGISTERED_ONLY : 0;
21444        sendPackageBroadcast(Intent.ACTION_PACKAGE_CHANGED,  packageName, extras, flags, null, null,
21445                new int[] {UserHandle.getUserId(packageUid)});
21446    }
21447
21448    @Override
21449    public void setPackageStoppedState(String packageName, boolean stopped, int userId) {
21450        if (!sUserManager.exists(userId)) return;
21451        final int callingUid = Binder.getCallingUid();
21452        if (getInstantAppPackageName(callingUid) != null) {
21453            return;
21454        }
21455        final int permission = mContext.checkCallingOrSelfPermission(
21456                android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
21457        final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
21458        enforceCrossUserPermission(callingUid, userId,
21459                true /* requireFullPermission */, true /* checkShell */, "stop package");
21460        // writer
21461        synchronized (mPackages) {
21462            final PackageSetting ps = mSettings.mPackages.get(packageName);
21463            if (!filterAppAccessLPr(ps, callingUid, userId)
21464                    && mSettings.setPackageStoppedStateLPw(this, packageName, stopped,
21465                            allowedByPermission, callingUid, userId)) {
21466                scheduleWritePackageRestrictionsLocked(userId);
21467            }
21468        }
21469    }
21470
21471    @Override
21472    public String getInstallerPackageName(String packageName) {
21473        final int callingUid = Binder.getCallingUid();
21474        if (getInstantAppPackageName(callingUid) != null) {
21475            return null;
21476        }
21477        // reader
21478        synchronized (mPackages) {
21479            final PackageSetting ps = mSettings.mPackages.get(packageName);
21480            if (filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
21481                return null;
21482            }
21483            return mSettings.getInstallerPackageNameLPr(packageName);
21484        }
21485    }
21486
21487    public boolean isOrphaned(String packageName) {
21488        // reader
21489        synchronized (mPackages) {
21490            return mSettings.isOrphaned(packageName);
21491        }
21492    }
21493
21494    @Override
21495    public int getApplicationEnabledSetting(String packageName, int userId) {
21496        if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
21497        int callingUid = Binder.getCallingUid();
21498        enforceCrossUserPermission(callingUid, userId,
21499                false /* requireFullPermission */, false /* checkShell */, "get enabled");
21500        // reader
21501        synchronized (mPackages) {
21502            if (filterAppAccessLPr(mSettings.getPackageLPr(packageName), callingUid, userId)) {
21503                return COMPONENT_ENABLED_STATE_DISABLED;
21504            }
21505            return mSettings.getApplicationEnabledSettingLPr(packageName, userId);
21506        }
21507    }
21508
21509    @Override
21510    public int getComponentEnabledSetting(ComponentName component, int userId) {
21511        if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
21512        int callingUid = Binder.getCallingUid();
21513        enforceCrossUserPermission(callingUid, userId,
21514                false /*requireFullPermission*/, false /*checkShell*/, "getComponentEnabled");
21515        synchronized (mPackages) {
21516            if (filterAppAccessLPr(mSettings.getPackageLPr(component.getPackageName()), callingUid,
21517                    component, TYPE_UNKNOWN, userId)) {
21518                return COMPONENT_ENABLED_STATE_DISABLED;
21519            }
21520            return mSettings.getComponentEnabledSettingLPr(component, userId);
21521        }
21522    }
21523
21524    @Override
21525    public void enterSafeMode() {
21526        enforceSystemOrRoot("Only the system can request entering safe mode");
21527
21528        if (!mSystemReady) {
21529            mSafeMode = true;
21530        }
21531    }
21532
21533    @Override
21534    public void systemReady() {
21535        enforceSystemOrRoot("Only the system can claim the system is ready");
21536
21537        mSystemReady = true;
21538        final ContentResolver resolver = mContext.getContentResolver();
21539        ContentObserver co = new ContentObserver(mHandler) {
21540            @Override
21541            public void onChange(boolean selfChange) {
21542                mEphemeralAppsDisabled =
21543                        (Global.getInt(resolver, Global.ENABLE_EPHEMERAL_FEATURE, 1) == 0) ||
21544                                (Secure.getInt(resolver, Secure.INSTANT_APPS_ENABLED, 1) == 0);
21545            }
21546        };
21547        mContext.getContentResolver().registerContentObserver(android.provider.Settings.Global
21548                        .getUriFor(Global.ENABLE_EPHEMERAL_FEATURE),
21549                false, co, UserHandle.USER_SYSTEM);
21550        mContext.getContentResolver().registerContentObserver(android.provider.Settings.Global
21551                        .getUriFor(Secure.INSTANT_APPS_ENABLED), false, co, UserHandle.USER_SYSTEM);
21552        co.onChange(true);
21553
21554        // Disable any carrier apps. We do this very early in boot to prevent the apps from being
21555        // disabled after already being started.
21556        CarrierAppUtils.disableCarrierAppsUntilPrivileged(mContext.getOpPackageName(), this,
21557                mContext.getContentResolver(), UserHandle.USER_SYSTEM);
21558
21559        // Read the compatibilty setting when the system is ready.
21560        boolean compatibilityModeEnabled = android.provider.Settings.Global.getInt(
21561                mContext.getContentResolver(),
21562                android.provider.Settings.Global.COMPATIBILITY_MODE, 1) == 1;
21563        PackageParser.setCompatibilityModeEnabled(compatibilityModeEnabled);
21564        if (DEBUG_SETTINGS) {
21565            Log.d(TAG, "compatibility mode:" + compatibilityModeEnabled);
21566        }
21567
21568        int[] grantPermissionsUserIds = EMPTY_INT_ARRAY;
21569
21570        synchronized (mPackages) {
21571            // Verify that all of the preferred activity components actually
21572            // exist.  It is possible for applications to be updated and at
21573            // that point remove a previously declared activity component that
21574            // had been set as a preferred activity.  We try to clean this up
21575            // the next time we encounter that preferred activity, but it is
21576            // possible for the user flow to never be able to return to that
21577            // situation so here we do a sanity check to make sure we haven't
21578            // left any junk around.
21579            ArrayList<PreferredActivity> removed = new ArrayList<PreferredActivity>();
21580            for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
21581                PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
21582                removed.clear();
21583                for (PreferredActivity pa : pir.filterSet()) {
21584                    if (mActivities.mActivities.get(pa.mPref.mComponent) == null) {
21585                        removed.add(pa);
21586                    }
21587                }
21588                if (removed.size() > 0) {
21589                    for (int r=0; r<removed.size(); r++) {
21590                        PreferredActivity pa = removed.get(r);
21591                        Slog.w(TAG, "Removing dangling preferred activity: "
21592                                + pa.mPref.mComponent);
21593                        pir.removeFilter(pa);
21594                    }
21595                    mSettings.writePackageRestrictionsLPr(
21596                            mSettings.mPreferredActivities.keyAt(i));
21597                }
21598            }
21599
21600            for (int userId : UserManagerService.getInstance().getUserIds()) {
21601                if (!mSettings.areDefaultRuntimePermissionsGrantedLPr(userId)) {
21602                    grantPermissionsUserIds = ArrayUtils.appendInt(
21603                            grantPermissionsUserIds, userId);
21604                }
21605            }
21606        }
21607        sUserManager.systemReady();
21608
21609        // If we upgraded grant all default permissions before kicking off.
21610        for (int userId : grantPermissionsUserIds) {
21611            mDefaultPermissionPolicy.grantDefaultPermissions(userId);
21612        }
21613
21614        // If we did not grant default permissions, we preload from this the
21615        // default permission exceptions lazily to ensure we don't hit the
21616        // disk on a new user creation.
21617        if (grantPermissionsUserIds == EMPTY_INT_ARRAY) {
21618            mDefaultPermissionPolicy.scheduleReadDefaultPermissionExceptions();
21619        }
21620
21621        // Kick off any messages waiting for system ready
21622        if (mPostSystemReadyMessages != null) {
21623            for (Message msg : mPostSystemReadyMessages) {
21624                msg.sendToTarget();
21625            }
21626            mPostSystemReadyMessages = null;
21627        }
21628
21629        // Watch for external volumes that come and go over time
21630        final StorageManager storage = mContext.getSystemService(StorageManager.class);
21631        storage.registerListener(mStorageListener);
21632
21633        mInstallerService.systemReady();
21634        mPackageDexOptimizer.systemReady();
21635
21636        StorageManagerInternal StorageManagerInternal = LocalServices.getService(
21637                StorageManagerInternal.class);
21638        StorageManagerInternal.addExternalStoragePolicy(
21639                new StorageManagerInternal.ExternalStorageMountPolicy() {
21640            @Override
21641            public int getMountMode(int uid, String packageName) {
21642                if (Process.isIsolated(uid)) {
21643                    return Zygote.MOUNT_EXTERNAL_NONE;
21644                }
21645                if (checkUidPermission(WRITE_MEDIA_STORAGE, uid) == PERMISSION_GRANTED) {
21646                    return Zygote.MOUNT_EXTERNAL_DEFAULT;
21647                }
21648                if (checkUidPermission(READ_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) {
21649                    return Zygote.MOUNT_EXTERNAL_DEFAULT;
21650                }
21651                if (checkUidPermission(WRITE_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) {
21652                    return Zygote.MOUNT_EXTERNAL_READ;
21653                }
21654                return Zygote.MOUNT_EXTERNAL_WRITE;
21655            }
21656
21657            @Override
21658            public boolean hasExternalStorage(int uid, String packageName) {
21659                return true;
21660            }
21661        });
21662
21663        // Now that we're mostly running, clean up stale users and apps
21664        sUserManager.reconcileUsers(StorageManager.UUID_PRIVATE_INTERNAL);
21665        reconcileApps(StorageManager.UUID_PRIVATE_INTERNAL);
21666
21667        if (mPrivappPermissionsViolations != null) {
21668            Slog.wtf(TAG,"Signature|privileged permissions not in "
21669                    + "privapp-permissions whitelist: " + mPrivappPermissionsViolations);
21670            mPrivappPermissionsViolations = null;
21671        }
21672    }
21673
21674    public void waitForAppDataPrepared() {
21675        if (mPrepareAppDataFuture == null) {
21676            return;
21677        }
21678        ConcurrentUtils.waitForFutureNoInterrupt(mPrepareAppDataFuture, "wait for prepareAppData");
21679        mPrepareAppDataFuture = null;
21680    }
21681
21682    @Override
21683    public boolean isSafeMode() {
21684        // allow instant applications
21685        return mSafeMode;
21686    }
21687
21688    @Override
21689    public boolean hasSystemUidErrors() {
21690        // allow instant applications
21691        return mHasSystemUidErrors;
21692    }
21693
21694    static String arrayToString(int[] array) {
21695        StringBuffer buf = new StringBuffer(128);
21696        buf.append('[');
21697        if (array != null) {
21698            for (int i=0; i<array.length; i++) {
21699                if (i > 0) buf.append(", ");
21700                buf.append(array[i]);
21701            }
21702        }
21703        buf.append(']');
21704        return buf.toString();
21705    }
21706
21707    static class DumpState {
21708        public static final int DUMP_LIBS = 1 << 0;
21709        public static final int DUMP_FEATURES = 1 << 1;
21710        public static final int DUMP_ACTIVITY_RESOLVERS = 1 << 2;
21711        public static final int DUMP_SERVICE_RESOLVERS = 1 << 3;
21712        public static final int DUMP_RECEIVER_RESOLVERS = 1 << 4;
21713        public static final int DUMP_CONTENT_RESOLVERS = 1 << 5;
21714        public static final int DUMP_PERMISSIONS = 1 << 6;
21715        public static final int DUMP_PACKAGES = 1 << 7;
21716        public static final int DUMP_SHARED_USERS = 1 << 8;
21717        public static final int DUMP_MESSAGES = 1 << 9;
21718        public static final int DUMP_PROVIDERS = 1 << 10;
21719        public static final int DUMP_VERIFIERS = 1 << 11;
21720        public static final int DUMP_PREFERRED = 1 << 12;
21721        public static final int DUMP_PREFERRED_XML = 1 << 13;
21722        public static final int DUMP_KEYSETS = 1 << 14;
21723        public static final int DUMP_VERSION = 1 << 15;
21724        public static final int DUMP_INSTALLS = 1 << 16;
21725        public static final int DUMP_INTENT_FILTER_VERIFIERS = 1 << 17;
21726        public static final int DUMP_DOMAIN_PREFERRED = 1 << 18;
21727        public static final int DUMP_FROZEN = 1 << 19;
21728        public static final int DUMP_DEXOPT = 1 << 20;
21729        public static final int DUMP_COMPILER_STATS = 1 << 21;
21730        public static final int DUMP_CHANGES = 1 << 22;
21731        public static final int DUMP_VOLUMES = 1 << 23;
21732
21733        public static final int OPTION_SHOW_FILTERS = 1 << 0;
21734
21735        private int mTypes;
21736
21737        private int mOptions;
21738
21739        private boolean mTitlePrinted;
21740
21741        private SharedUserSetting mSharedUser;
21742
21743        public boolean isDumping(int type) {
21744            if (mTypes == 0 && type != DUMP_PREFERRED_XML) {
21745                return true;
21746            }
21747
21748            return (mTypes & type) != 0;
21749        }
21750
21751        public void setDump(int type) {
21752            mTypes |= type;
21753        }
21754
21755        public boolean isOptionEnabled(int option) {
21756            return (mOptions & option) != 0;
21757        }
21758
21759        public void setOptionEnabled(int option) {
21760            mOptions |= option;
21761        }
21762
21763        public boolean onTitlePrinted() {
21764            final boolean printed = mTitlePrinted;
21765            mTitlePrinted = true;
21766            return printed;
21767        }
21768
21769        public boolean getTitlePrinted() {
21770            return mTitlePrinted;
21771        }
21772
21773        public void setTitlePrinted(boolean enabled) {
21774            mTitlePrinted = enabled;
21775        }
21776
21777        public SharedUserSetting getSharedUser() {
21778            return mSharedUser;
21779        }
21780
21781        public void setSharedUser(SharedUserSetting user) {
21782            mSharedUser = user;
21783        }
21784    }
21785
21786    @Override
21787    public void onShellCommand(FileDescriptor in, FileDescriptor out,
21788            FileDescriptor err, String[] args, ShellCallback callback,
21789            ResultReceiver resultReceiver) {
21790        (new PackageManagerShellCommand(this)).exec(
21791                this, in, out, err, args, callback, resultReceiver);
21792    }
21793
21794    @Override
21795    protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
21796        if (!DumpUtils.checkDumpAndUsageStatsPermission(mContext, TAG, pw)) return;
21797
21798        DumpState dumpState = new DumpState();
21799        boolean fullPreferred = false;
21800        boolean checkin = false;
21801
21802        String packageName = null;
21803        ArraySet<String> permissionNames = null;
21804
21805        int opti = 0;
21806        while (opti < args.length) {
21807            String opt = args[opti];
21808            if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') {
21809                break;
21810            }
21811            opti++;
21812
21813            if ("-a".equals(opt)) {
21814                // Right now we only know how to print all.
21815            } else if ("-h".equals(opt)) {
21816                pw.println("Package manager dump options:");
21817                pw.println("  [-h] [-f] [--checkin] [cmd] ...");
21818                pw.println("    --checkin: dump for a checkin");
21819                pw.println("    -f: print details of intent filters");
21820                pw.println("    -h: print this help");
21821                pw.println("  cmd may be one of:");
21822                pw.println("    l[ibraries]: list known shared libraries");
21823                pw.println("    f[eatures]: list device features");
21824                pw.println("    k[eysets]: print known keysets");
21825                pw.println("    r[esolvers] [activity|service|receiver|content]: dump intent resolvers");
21826                pw.println("    perm[issions]: dump permissions");
21827                pw.println("    permission [name ...]: dump declaration and use of given permission");
21828                pw.println("    pref[erred]: print preferred package settings");
21829                pw.println("    preferred-xml [--full]: print preferred package settings as xml");
21830                pw.println("    prov[iders]: dump content providers");
21831                pw.println("    p[ackages]: dump installed packages");
21832                pw.println("    s[hared-users]: dump shared user IDs");
21833                pw.println("    m[essages]: print collected runtime messages");
21834                pw.println("    v[erifiers]: print package verifier info");
21835                pw.println("    d[omain-preferred-apps]: print domains preferred apps");
21836                pw.println("    i[ntent-filter-verifiers]|ifv: print intent filter verifier info");
21837                pw.println("    version: print database version info");
21838                pw.println("    write: write current settings now");
21839                pw.println("    installs: details about install sessions");
21840                pw.println("    check-permission <permission> <package> [<user>]: does pkg hold perm?");
21841                pw.println("    dexopt: dump dexopt state");
21842                pw.println("    compiler-stats: dump compiler statistics");
21843                pw.println("    enabled-overlays: dump list of enabled overlay packages");
21844                pw.println("    <package.name>: info about given package");
21845                return;
21846            } else if ("--checkin".equals(opt)) {
21847                checkin = true;
21848            } else if ("-f".equals(opt)) {
21849                dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS);
21850            } else if ("--proto".equals(opt)) {
21851                dumpProto(fd);
21852                return;
21853            } else {
21854                pw.println("Unknown argument: " + opt + "; use -h for help");
21855            }
21856        }
21857
21858        // Is the caller requesting to dump a particular piece of data?
21859        if (opti < args.length) {
21860            String cmd = args[opti];
21861            opti++;
21862            // Is this a package name?
21863            if ("android".equals(cmd) || cmd.contains(".")) {
21864                packageName = cmd;
21865                // When dumping a single package, we always dump all of its
21866                // filter information since the amount of data will be reasonable.
21867                dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS);
21868            } else if ("check-permission".equals(cmd)) {
21869                if (opti >= args.length) {
21870                    pw.println("Error: check-permission missing permission argument");
21871                    return;
21872                }
21873                String perm = args[opti];
21874                opti++;
21875                if (opti >= args.length) {
21876                    pw.println("Error: check-permission missing package argument");
21877                    return;
21878                }
21879
21880                String pkg = args[opti];
21881                opti++;
21882                int user = UserHandle.getUserId(Binder.getCallingUid());
21883                if (opti < args.length) {
21884                    try {
21885                        user = Integer.parseInt(args[opti]);
21886                    } catch (NumberFormatException e) {
21887                        pw.println("Error: check-permission user argument is not a number: "
21888                                + args[opti]);
21889                        return;
21890                    }
21891                }
21892
21893                // Normalize package name to handle renamed packages and static libs
21894                pkg = resolveInternalPackageNameLPr(pkg, PackageManager.VERSION_CODE_HIGHEST);
21895
21896                pw.println(checkPermission(perm, pkg, user));
21897                return;
21898            } else if ("l".equals(cmd) || "libraries".equals(cmd)) {
21899                dumpState.setDump(DumpState.DUMP_LIBS);
21900            } else if ("f".equals(cmd) || "features".equals(cmd)) {
21901                dumpState.setDump(DumpState.DUMP_FEATURES);
21902            } else if ("r".equals(cmd) || "resolvers".equals(cmd)) {
21903                if (opti >= args.length) {
21904                    dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS
21905                            | DumpState.DUMP_SERVICE_RESOLVERS
21906                            | DumpState.DUMP_RECEIVER_RESOLVERS
21907                            | DumpState.DUMP_CONTENT_RESOLVERS);
21908                } else {
21909                    while (opti < args.length) {
21910                        String name = args[opti];
21911                        if ("a".equals(name) || "activity".equals(name)) {
21912                            dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS);
21913                        } else if ("s".equals(name) || "service".equals(name)) {
21914                            dumpState.setDump(DumpState.DUMP_SERVICE_RESOLVERS);
21915                        } else if ("r".equals(name) || "receiver".equals(name)) {
21916                            dumpState.setDump(DumpState.DUMP_RECEIVER_RESOLVERS);
21917                        } else if ("c".equals(name) || "content".equals(name)) {
21918                            dumpState.setDump(DumpState.DUMP_CONTENT_RESOLVERS);
21919                        } else {
21920                            pw.println("Error: unknown resolver table type: " + name);
21921                            return;
21922                        }
21923                        opti++;
21924                    }
21925                }
21926            } else if ("perm".equals(cmd) || "permissions".equals(cmd)) {
21927                dumpState.setDump(DumpState.DUMP_PERMISSIONS);
21928            } else if ("permission".equals(cmd)) {
21929                if (opti >= args.length) {
21930                    pw.println("Error: permission requires permission name");
21931                    return;
21932                }
21933                permissionNames = new ArraySet<>();
21934                while (opti < args.length) {
21935                    permissionNames.add(args[opti]);
21936                    opti++;
21937                }
21938                dumpState.setDump(DumpState.DUMP_PERMISSIONS
21939                        | DumpState.DUMP_PACKAGES | DumpState.DUMP_SHARED_USERS);
21940            } else if ("pref".equals(cmd) || "preferred".equals(cmd)) {
21941                dumpState.setDump(DumpState.DUMP_PREFERRED);
21942            } else if ("preferred-xml".equals(cmd)) {
21943                dumpState.setDump(DumpState.DUMP_PREFERRED_XML);
21944                if (opti < args.length && "--full".equals(args[opti])) {
21945                    fullPreferred = true;
21946                    opti++;
21947                }
21948            } else if ("d".equals(cmd) || "domain-preferred-apps".equals(cmd)) {
21949                dumpState.setDump(DumpState.DUMP_DOMAIN_PREFERRED);
21950            } else if ("p".equals(cmd) || "packages".equals(cmd)) {
21951                dumpState.setDump(DumpState.DUMP_PACKAGES);
21952            } else if ("s".equals(cmd) || "shared-users".equals(cmd)) {
21953                dumpState.setDump(DumpState.DUMP_SHARED_USERS);
21954            } else if ("prov".equals(cmd) || "providers".equals(cmd)) {
21955                dumpState.setDump(DumpState.DUMP_PROVIDERS);
21956            } else if ("m".equals(cmd) || "messages".equals(cmd)) {
21957                dumpState.setDump(DumpState.DUMP_MESSAGES);
21958            } else if ("v".equals(cmd) || "verifiers".equals(cmd)) {
21959                dumpState.setDump(DumpState.DUMP_VERIFIERS);
21960            } else if ("i".equals(cmd) || "ifv".equals(cmd)
21961                    || "intent-filter-verifiers".equals(cmd)) {
21962                dumpState.setDump(DumpState.DUMP_INTENT_FILTER_VERIFIERS);
21963            } else if ("version".equals(cmd)) {
21964                dumpState.setDump(DumpState.DUMP_VERSION);
21965            } else if ("k".equals(cmd) || "keysets".equals(cmd)) {
21966                dumpState.setDump(DumpState.DUMP_KEYSETS);
21967            } else if ("installs".equals(cmd)) {
21968                dumpState.setDump(DumpState.DUMP_INSTALLS);
21969            } else if ("frozen".equals(cmd)) {
21970                dumpState.setDump(DumpState.DUMP_FROZEN);
21971            } else if ("volumes".equals(cmd)) {
21972                dumpState.setDump(DumpState.DUMP_VOLUMES);
21973            } else if ("dexopt".equals(cmd)) {
21974                dumpState.setDump(DumpState.DUMP_DEXOPT);
21975            } else if ("compiler-stats".equals(cmd)) {
21976                dumpState.setDump(DumpState.DUMP_COMPILER_STATS);
21977            } else if ("changes".equals(cmd)) {
21978                dumpState.setDump(DumpState.DUMP_CHANGES);
21979            } else if ("write".equals(cmd)) {
21980                synchronized (mPackages) {
21981                    mSettings.writeLPr();
21982                    pw.println("Settings written.");
21983                    return;
21984                }
21985            }
21986        }
21987
21988        if (checkin) {
21989            pw.println("vers,1");
21990        }
21991
21992        // reader
21993        synchronized (mPackages) {
21994            if (dumpState.isDumping(DumpState.DUMP_VERSION) && packageName == null) {
21995                if (!checkin) {
21996                    if (dumpState.onTitlePrinted())
21997                        pw.println();
21998                    pw.println("Database versions:");
21999                    mSettings.dumpVersionLPr(new IndentingPrintWriter(pw, "  "));
22000                }
22001            }
22002
22003            if (dumpState.isDumping(DumpState.DUMP_VERIFIERS) && packageName == null) {
22004                if (!checkin) {
22005                    if (dumpState.onTitlePrinted())
22006                        pw.println();
22007                    pw.println("Verifiers:");
22008                    pw.print("  Required: ");
22009                    pw.print(mRequiredVerifierPackage);
22010                    pw.print(" (uid=");
22011                    pw.print(getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING,
22012                            UserHandle.USER_SYSTEM));
22013                    pw.println(")");
22014                } else if (mRequiredVerifierPackage != null) {
22015                    pw.print("vrfy,"); pw.print(mRequiredVerifierPackage);
22016                    pw.print(",");
22017                    pw.println(getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING,
22018                            UserHandle.USER_SYSTEM));
22019                }
22020            }
22021
22022            if (dumpState.isDumping(DumpState.DUMP_INTENT_FILTER_VERIFIERS) &&
22023                    packageName == null) {
22024                if (mIntentFilterVerifierComponent != null) {
22025                    String verifierPackageName = mIntentFilterVerifierComponent.getPackageName();
22026                    if (!checkin) {
22027                        if (dumpState.onTitlePrinted())
22028                            pw.println();
22029                        pw.println("Intent Filter Verifier:");
22030                        pw.print("  Using: ");
22031                        pw.print(verifierPackageName);
22032                        pw.print(" (uid=");
22033                        pw.print(getPackageUid(verifierPackageName, MATCH_DEBUG_TRIAGED_MISSING,
22034                                UserHandle.USER_SYSTEM));
22035                        pw.println(")");
22036                    } else if (verifierPackageName != null) {
22037                        pw.print("ifv,"); pw.print(verifierPackageName);
22038                        pw.print(",");
22039                        pw.println(getPackageUid(verifierPackageName, MATCH_DEBUG_TRIAGED_MISSING,
22040                                UserHandle.USER_SYSTEM));
22041                    }
22042                } else {
22043                    pw.println();
22044                    pw.println("No Intent Filter Verifier available!");
22045                }
22046            }
22047
22048            if (dumpState.isDumping(DumpState.DUMP_LIBS) && packageName == null) {
22049                boolean printedHeader = false;
22050                final Iterator<String> it = mSharedLibraries.keySet().iterator();
22051                while (it.hasNext()) {
22052                    String libName = it.next();
22053                    SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(libName);
22054                    if (versionedLib == null) {
22055                        continue;
22056                    }
22057                    final int versionCount = versionedLib.size();
22058                    for (int i = 0; i < versionCount; i++) {
22059                        SharedLibraryEntry libEntry = versionedLib.valueAt(i);
22060                        if (!checkin) {
22061                            if (!printedHeader) {
22062                                if (dumpState.onTitlePrinted())
22063                                    pw.println();
22064                                pw.println("Libraries:");
22065                                printedHeader = true;
22066                            }
22067                            pw.print("  ");
22068                        } else {
22069                            pw.print("lib,");
22070                        }
22071                        pw.print(libEntry.info.getName());
22072                        if (libEntry.info.isStatic()) {
22073                            pw.print(" version=" + libEntry.info.getVersion());
22074                        }
22075                        if (!checkin) {
22076                            pw.print(" -> ");
22077                        }
22078                        if (libEntry.path != null) {
22079                            pw.print(" (jar) ");
22080                            pw.print(libEntry.path);
22081                        } else {
22082                            pw.print(" (apk) ");
22083                            pw.print(libEntry.apk);
22084                        }
22085                        pw.println();
22086                    }
22087                }
22088            }
22089
22090            if (dumpState.isDumping(DumpState.DUMP_FEATURES) && packageName == null) {
22091                if (dumpState.onTitlePrinted())
22092                    pw.println();
22093                if (!checkin) {
22094                    pw.println("Features:");
22095                }
22096
22097                synchronized (mAvailableFeatures) {
22098                    for (FeatureInfo feat : mAvailableFeatures.values()) {
22099                        if (checkin) {
22100                            pw.print("feat,");
22101                            pw.print(feat.name);
22102                            pw.print(",");
22103                            pw.println(feat.version);
22104                        } else {
22105                            pw.print("  ");
22106                            pw.print(feat.name);
22107                            if (feat.version > 0) {
22108                                pw.print(" version=");
22109                                pw.print(feat.version);
22110                            }
22111                            pw.println();
22112                        }
22113                    }
22114                }
22115            }
22116
22117            if (!checkin && dumpState.isDumping(DumpState.DUMP_ACTIVITY_RESOLVERS)) {
22118                if (mActivities.dump(pw, dumpState.getTitlePrinted() ? "\nActivity Resolver Table:"
22119                        : "Activity Resolver Table:", "  ", packageName,
22120                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
22121                    dumpState.setTitlePrinted(true);
22122                }
22123            }
22124            if (!checkin && dumpState.isDumping(DumpState.DUMP_RECEIVER_RESOLVERS)) {
22125                if (mReceivers.dump(pw, dumpState.getTitlePrinted() ? "\nReceiver Resolver Table:"
22126                        : "Receiver Resolver Table:", "  ", packageName,
22127                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
22128                    dumpState.setTitlePrinted(true);
22129                }
22130            }
22131            if (!checkin && dumpState.isDumping(DumpState.DUMP_SERVICE_RESOLVERS)) {
22132                if (mServices.dump(pw, dumpState.getTitlePrinted() ? "\nService Resolver Table:"
22133                        : "Service Resolver Table:", "  ", packageName,
22134                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
22135                    dumpState.setTitlePrinted(true);
22136                }
22137            }
22138            if (!checkin && dumpState.isDumping(DumpState.DUMP_CONTENT_RESOLVERS)) {
22139                if (mProviders.dump(pw, dumpState.getTitlePrinted() ? "\nProvider Resolver Table:"
22140                        : "Provider Resolver Table:", "  ", packageName,
22141                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
22142                    dumpState.setTitlePrinted(true);
22143                }
22144            }
22145
22146            if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED)) {
22147                for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
22148                    PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
22149                    int user = mSettings.mPreferredActivities.keyAt(i);
22150                    if (pir.dump(pw,
22151                            dumpState.getTitlePrinted()
22152                                ? "\nPreferred Activities User " + user + ":"
22153                                : "Preferred Activities User " + user + ":", "  ",
22154                            packageName, true, false)) {
22155                        dumpState.setTitlePrinted(true);
22156                    }
22157                }
22158            }
22159
22160            if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED_XML)) {
22161                pw.flush();
22162                FileOutputStream fout = new FileOutputStream(fd);
22163                BufferedOutputStream str = new BufferedOutputStream(fout);
22164                XmlSerializer serializer = new FastXmlSerializer();
22165                try {
22166                    serializer.setOutput(str, StandardCharsets.UTF_8.name());
22167                    serializer.startDocument(null, true);
22168                    serializer.setFeature(
22169                            "http://xmlpull.org/v1/doc/features.html#indent-output", true);
22170                    mSettings.writePreferredActivitiesLPr(serializer, 0, fullPreferred);
22171                    serializer.endDocument();
22172                    serializer.flush();
22173                } catch (IllegalArgumentException e) {
22174                    pw.println("Failed writing: " + e);
22175                } catch (IllegalStateException e) {
22176                    pw.println("Failed writing: " + e);
22177                } catch (IOException e) {
22178                    pw.println("Failed writing: " + e);
22179                }
22180            }
22181
22182            if (!checkin
22183                    && dumpState.isDumping(DumpState.DUMP_DOMAIN_PREFERRED)
22184                    && packageName == null) {
22185                pw.println();
22186                int count = mSettings.mPackages.size();
22187                if (count == 0) {
22188                    pw.println("No applications!");
22189                    pw.println();
22190                } else {
22191                    final String prefix = "  ";
22192                    Collection<PackageSetting> allPackageSettings = mSettings.mPackages.values();
22193                    if (allPackageSettings.size() == 0) {
22194                        pw.println("No domain preferred apps!");
22195                        pw.println();
22196                    } else {
22197                        pw.println("App verification status:");
22198                        pw.println();
22199                        count = 0;
22200                        for (PackageSetting ps : allPackageSettings) {
22201                            IntentFilterVerificationInfo ivi = ps.getIntentFilterVerificationInfo();
22202                            if (ivi == null || ivi.getPackageName() == null) continue;
22203                            pw.println(prefix + "Package: " + ivi.getPackageName());
22204                            pw.println(prefix + "Domains: " + ivi.getDomainsString());
22205                            pw.println(prefix + "Status:  " + ivi.getStatusString());
22206                            pw.println();
22207                            count++;
22208                        }
22209                        if (count == 0) {
22210                            pw.println(prefix + "No app verification established.");
22211                            pw.println();
22212                        }
22213                        for (int userId : sUserManager.getUserIds()) {
22214                            pw.println("App linkages for user " + userId + ":");
22215                            pw.println();
22216                            count = 0;
22217                            for (PackageSetting ps : allPackageSettings) {
22218                                final long status = ps.getDomainVerificationStatusForUser(userId);
22219                                if (status >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED
22220                                        && !DEBUG_DOMAIN_VERIFICATION) {
22221                                    continue;
22222                                }
22223                                pw.println(prefix + "Package: " + ps.name);
22224                                pw.println(prefix + "Domains: " + dumpDomainString(ps.name));
22225                                String statusStr = IntentFilterVerificationInfo.
22226                                        getStatusStringFromValue(status);
22227                                pw.println(prefix + "Status:  " + statusStr);
22228                                pw.println();
22229                                count++;
22230                            }
22231                            if (count == 0) {
22232                                pw.println(prefix + "No configured app linkages.");
22233                                pw.println();
22234                            }
22235                        }
22236                    }
22237                }
22238            }
22239
22240            if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS)) {
22241                mSettings.dumpPermissionsLPr(pw, packageName, permissionNames, dumpState);
22242                if (packageName == null && permissionNames == null) {
22243                    for (int iperm=0; iperm<mAppOpPermissionPackages.size(); iperm++) {
22244                        if (iperm == 0) {
22245                            if (dumpState.onTitlePrinted())
22246                                pw.println();
22247                            pw.println("AppOp Permissions:");
22248                        }
22249                        pw.print("  AppOp Permission ");
22250                        pw.print(mAppOpPermissionPackages.keyAt(iperm));
22251                        pw.println(":");
22252                        ArraySet<String> pkgs = mAppOpPermissionPackages.valueAt(iperm);
22253                        for (int ipkg=0; ipkg<pkgs.size(); ipkg++) {
22254                            pw.print("    "); pw.println(pkgs.valueAt(ipkg));
22255                        }
22256                    }
22257                }
22258            }
22259
22260            if (!checkin && dumpState.isDumping(DumpState.DUMP_PROVIDERS)) {
22261                boolean printedSomething = false;
22262                for (PackageParser.Provider p : mProviders.mProviders.values()) {
22263                    if (packageName != null && !packageName.equals(p.info.packageName)) {
22264                        continue;
22265                    }
22266                    if (!printedSomething) {
22267                        if (dumpState.onTitlePrinted())
22268                            pw.println();
22269                        pw.println("Registered ContentProviders:");
22270                        printedSomething = true;
22271                    }
22272                    pw.print("  "); p.printComponentShortName(pw); pw.println(":");
22273                    pw.print("    "); pw.println(p.toString());
22274                }
22275                printedSomething = false;
22276                for (Map.Entry<String, PackageParser.Provider> entry :
22277                        mProvidersByAuthority.entrySet()) {
22278                    PackageParser.Provider p = entry.getValue();
22279                    if (packageName != null && !packageName.equals(p.info.packageName)) {
22280                        continue;
22281                    }
22282                    if (!printedSomething) {
22283                        if (dumpState.onTitlePrinted())
22284                            pw.println();
22285                        pw.println("ContentProvider Authorities:");
22286                        printedSomething = true;
22287                    }
22288                    pw.print("  ["); pw.print(entry.getKey()); pw.println("]:");
22289                    pw.print("    "); pw.println(p.toString());
22290                    if (p.info != null && p.info.applicationInfo != null) {
22291                        final String appInfo = p.info.applicationInfo.toString();
22292                        pw.print("      applicationInfo="); pw.println(appInfo);
22293                    }
22294                }
22295            }
22296
22297            if (!checkin && dumpState.isDumping(DumpState.DUMP_KEYSETS)) {
22298                mSettings.mKeySetManagerService.dumpLPr(pw, packageName, dumpState);
22299            }
22300
22301            if (dumpState.isDumping(DumpState.DUMP_PACKAGES)) {
22302                mSettings.dumpPackagesLPr(pw, packageName, permissionNames, dumpState, checkin);
22303            }
22304
22305            if (dumpState.isDumping(DumpState.DUMP_SHARED_USERS)) {
22306                mSettings.dumpSharedUsersLPr(pw, packageName, permissionNames, dumpState, checkin);
22307            }
22308
22309            if (dumpState.isDumping(DumpState.DUMP_CHANGES)) {
22310                if (dumpState.onTitlePrinted()) pw.println();
22311                pw.println("Package Changes:");
22312                pw.print("  Sequence number="); pw.println(mChangedPackagesSequenceNumber);
22313                final int K = mChangedPackages.size();
22314                for (int i = 0; i < K; i++) {
22315                    final SparseArray<String> changes = mChangedPackages.valueAt(i);
22316                    pw.print("  User "); pw.print(mChangedPackages.keyAt(i)); pw.println(":");
22317                    final int N = changes.size();
22318                    if (N == 0) {
22319                        pw.print("    "); pw.println("No packages changed");
22320                    } else {
22321                        for (int j = 0; j < N; j++) {
22322                            final String pkgName = changes.valueAt(j);
22323                            final int sequenceNumber = changes.keyAt(j);
22324                            pw.print("    ");
22325                            pw.print("seq=");
22326                            pw.print(sequenceNumber);
22327                            pw.print(", package=");
22328                            pw.println(pkgName);
22329                        }
22330                    }
22331                }
22332            }
22333
22334            if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS) && packageName == null) {
22335                mSettings.dumpRestoredPermissionGrantsLPr(pw, dumpState);
22336            }
22337
22338            if (!checkin && dumpState.isDumping(DumpState.DUMP_FROZEN) && packageName == null) {
22339                // XXX should handle packageName != null by dumping only install data that
22340                // the given package is involved with.
22341                if (dumpState.onTitlePrinted()) pw.println();
22342
22343                final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, "  ", 120);
22344                ipw.println();
22345                ipw.println("Frozen packages:");
22346                ipw.increaseIndent();
22347                if (mFrozenPackages.size() == 0) {
22348                    ipw.println("(none)");
22349                } else {
22350                    for (int i = 0; i < mFrozenPackages.size(); i++) {
22351                        ipw.println(mFrozenPackages.valueAt(i));
22352                    }
22353                }
22354                ipw.decreaseIndent();
22355            }
22356
22357            if (!checkin && dumpState.isDumping(DumpState.DUMP_VOLUMES) && packageName == null) {
22358                if (dumpState.onTitlePrinted()) pw.println();
22359
22360                final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, "  ", 120);
22361                ipw.println();
22362                ipw.println("Loaded volumes:");
22363                ipw.increaseIndent();
22364                if (mLoadedVolumes.size() == 0) {
22365                    ipw.println("(none)");
22366                } else {
22367                    for (int i = 0; i < mLoadedVolumes.size(); i++) {
22368                        ipw.println(mLoadedVolumes.valueAt(i));
22369                    }
22370                }
22371                ipw.decreaseIndent();
22372            }
22373
22374            if (!checkin && dumpState.isDumping(DumpState.DUMP_DEXOPT)) {
22375                if (dumpState.onTitlePrinted()) pw.println();
22376                dumpDexoptStateLPr(pw, packageName);
22377            }
22378
22379            if (!checkin && dumpState.isDumping(DumpState.DUMP_COMPILER_STATS)) {
22380                if (dumpState.onTitlePrinted()) pw.println();
22381                dumpCompilerStatsLPr(pw, packageName);
22382            }
22383
22384            if (!checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES) && packageName == null) {
22385                if (dumpState.onTitlePrinted()) pw.println();
22386                mSettings.dumpReadMessagesLPr(pw, dumpState);
22387
22388                pw.println();
22389                pw.println("Package warning messages:");
22390                BufferedReader in = null;
22391                String line = null;
22392                try {
22393                    in = new BufferedReader(new FileReader(getSettingsProblemFile()));
22394                    while ((line = in.readLine()) != null) {
22395                        if (line.contains("ignored: updated version")) continue;
22396                        pw.println(line);
22397                    }
22398                } catch (IOException ignored) {
22399                } finally {
22400                    IoUtils.closeQuietly(in);
22401                }
22402            }
22403
22404            if (checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES)) {
22405                BufferedReader in = null;
22406                String line = null;
22407                try {
22408                    in = new BufferedReader(new FileReader(getSettingsProblemFile()));
22409                    while ((line = in.readLine()) != null) {
22410                        if (line.contains("ignored: updated version")) continue;
22411                        pw.print("msg,");
22412                        pw.println(line);
22413                    }
22414                } catch (IOException ignored) {
22415                } finally {
22416                    IoUtils.closeQuietly(in);
22417                }
22418            }
22419        }
22420
22421        // PackageInstaller should be called outside of mPackages lock
22422        if (!checkin && dumpState.isDumping(DumpState.DUMP_INSTALLS) && packageName == null) {
22423            // XXX should handle packageName != null by dumping only install data that
22424            // the given package is involved with.
22425            if (dumpState.onTitlePrinted()) pw.println();
22426            mInstallerService.dump(new IndentingPrintWriter(pw, "  ", 120));
22427        }
22428    }
22429
22430    private void dumpProto(FileDescriptor fd) {
22431        final ProtoOutputStream proto = new ProtoOutputStream(fd);
22432
22433        synchronized (mPackages) {
22434            final long requiredVerifierPackageToken =
22435                    proto.start(PackageServiceDumpProto.REQUIRED_VERIFIER_PACKAGE);
22436            proto.write(PackageServiceDumpProto.PackageShortProto.NAME, mRequiredVerifierPackage);
22437            proto.write(
22438                    PackageServiceDumpProto.PackageShortProto.UID,
22439                    getPackageUid(
22440                            mRequiredVerifierPackage,
22441                            MATCH_DEBUG_TRIAGED_MISSING,
22442                            UserHandle.USER_SYSTEM));
22443            proto.end(requiredVerifierPackageToken);
22444
22445            if (mIntentFilterVerifierComponent != null) {
22446                String verifierPackageName = mIntentFilterVerifierComponent.getPackageName();
22447                final long verifierPackageToken =
22448                        proto.start(PackageServiceDumpProto.VERIFIER_PACKAGE);
22449                proto.write(PackageServiceDumpProto.PackageShortProto.NAME, verifierPackageName);
22450                proto.write(
22451                        PackageServiceDumpProto.PackageShortProto.UID,
22452                        getPackageUid(
22453                                verifierPackageName,
22454                                MATCH_DEBUG_TRIAGED_MISSING,
22455                                UserHandle.USER_SYSTEM));
22456                proto.end(verifierPackageToken);
22457            }
22458
22459            dumpSharedLibrariesProto(proto);
22460            dumpFeaturesProto(proto);
22461            mSettings.dumpPackagesProto(proto);
22462            mSettings.dumpSharedUsersProto(proto);
22463            dumpMessagesProto(proto);
22464        }
22465        proto.flush();
22466    }
22467
22468    private void dumpMessagesProto(ProtoOutputStream proto) {
22469        BufferedReader in = null;
22470        String line = null;
22471        try {
22472            in = new BufferedReader(new FileReader(getSettingsProblemFile()));
22473            while ((line = in.readLine()) != null) {
22474                if (line.contains("ignored: updated version")) continue;
22475                proto.write(PackageServiceDumpProto.MESSAGES, line);
22476            }
22477        } catch (IOException ignored) {
22478        } finally {
22479            IoUtils.closeQuietly(in);
22480        }
22481    }
22482
22483    private void dumpFeaturesProto(ProtoOutputStream proto) {
22484        synchronized (mAvailableFeatures) {
22485            final int count = mAvailableFeatures.size();
22486            for (int i = 0; i < count; i++) {
22487                final FeatureInfo feat = mAvailableFeatures.valueAt(i);
22488                final long featureToken = proto.start(PackageServiceDumpProto.FEATURES);
22489                proto.write(PackageServiceDumpProto.FeatureProto.NAME, feat.name);
22490                proto.write(PackageServiceDumpProto.FeatureProto.VERSION, feat.version);
22491                proto.end(featureToken);
22492            }
22493        }
22494    }
22495
22496    private void dumpSharedLibrariesProto(ProtoOutputStream proto) {
22497        final int count = mSharedLibraries.size();
22498        for (int i = 0; i < count; i++) {
22499            final String libName = mSharedLibraries.keyAt(i);
22500            SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(libName);
22501            if (versionedLib == null) {
22502                continue;
22503            }
22504            final int versionCount = versionedLib.size();
22505            for (int j = 0; j < versionCount; j++) {
22506                final SharedLibraryEntry libEntry = versionedLib.valueAt(j);
22507                final long sharedLibraryToken =
22508                        proto.start(PackageServiceDumpProto.SHARED_LIBRARIES);
22509                proto.write(PackageServiceDumpProto.SharedLibraryProto.NAME, libEntry.info.getName());
22510                final boolean isJar = (libEntry.path != null);
22511                proto.write(PackageServiceDumpProto.SharedLibraryProto.IS_JAR, isJar);
22512                if (isJar) {
22513                    proto.write(PackageServiceDumpProto.SharedLibraryProto.PATH, libEntry.path);
22514                } else {
22515                    proto.write(PackageServiceDumpProto.SharedLibraryProto.APK, libEntry.apk);
22516                }
22517                proto.end(sharedLibraryToken);
22518            }
22519        }
22520    }
22521
22522    private void dumpDexoptStateLPr(PrintWriter pw, String packageName) {
22523        final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, "  ", 120);
22524        ipw.println();
22525        ipw.println("Dexopt state:");
22526        ipw.increaseIndent();
22527        Collection<PackageParser.Package> packages = null;
22528        if (packageName != null) {
22529            PackageParser.Package targetPackage = mPackages.get(packageName);
22530            if (targetPackage != null) {
22531                packages = Collections.singletonList(targetPackage);
22532            } else {
22533                ipw.println("Unable to find package: " + packageName);
22534                return;
22535            }
22536        } else {
22537            packages = mPackages.values();
22538        }
22539
22540        for (PackageParser.Package pkg : packages) {
22541            ipw.println("[" + pkg.packageName + "]");
22542            ipw.increaseIndent();
22543            mPackageDexOptimizer.dumpDexoptState(ipw, pkg);
22544            ipw.decreaseIndent();
22545        }
22546    }
22547
22548    private void dumpCompilerStatsLPr(PrintWriter pw, String packageName) {
22549        final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, "  ", 120);
22550        ipw.println();
22551        ipw.println("Compiler stats:");
22552        ipw.increaseIndent();
22553        Collection<PackageParser.Package> packages = null;
22554        if (packageName != null) {
22555            PackageParser.Package targetPackage = mPackages.get(packageName);
22556            if (targetPackage != null) {
22557                packages = Collections.singletonList(targetPackage);
22558            } else {
22559                ipw.println("Unable to find package: " + packageName);
22560                return;
22561            }
22562        } else {
22563            packages = mPackages.values();
22564        }
22565
22566        for (PackageParser.Package pkg : packages) {
22567            ipw.println("[" + pkg.packageName + "]");
22568            ipw.increaseIndent();
22569
22570            CompilerStats.PackageStats stats = getCompilerPackageStats(pkg.packageName);
22571            if (stats == null) {
22572                ipw.println("(No recorded stats)");
22573            } else {
22574                stats.dump(ipw);
22575            }
22576            ipw.decreaseIndent();
22577        }
22578    }
22579
22580    private String dumpDomainString(String packageName) {
22581        List<IntentFilterVerificationInfo> iviList = getIntentFilterVerifications(packageName)
22582                .getList();
22583        List<IntentFilter> filters = getAllIntentFilters(packageName).getList();
22584
22585        ArraySet<String> result = new ArraySet<>();
22586        if (iviList.size() > 0) {
22587            for (IntentFilterVerificationInfo ivi : iviList) {
22588                for (String host : ivi.getDomains()) {
22589                    result.add(host);
22590                }
22591            }
22592        }
22593        if (filters != null && filters.size() > 0) {
22594            for (IntentFilter filter : filters) {
22595                if (filter.hasCategory(Intent.CATEGORY_BROWSABLE)
22596                        && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) ||
22597                                filter.hasDataScheme(IntentFilter.SCHEME_HTTPS))) {
22598                    result.addAll(filter.getHostsList());
22599                }
22600            }
22601        }
22602
22603        StringBuilder sb = new StringBuilder(result.size() * 16);
22604        for (String domain : result) {
22605            if (sb.length() > 0) sb.append(" ");
22606            sb.append(domain);
22607        }
22608        return sb.toString();
22609    }
22610
22611    // ------- apps on sdcard specific code -------
22612    static final boolean DEBUG_SD_INSTALL = false;
22613
22614    private static final String SD_ENCRYPTION_KEYSTORE_NAME = "AppsOnSD";
22615
22616    private static final String SD_ENCRYPTION_ALGORITHM = "AES";
22617
22618    private boolean mMediaMounted = false;
22619
22620    static String getEncryptKey() {
22621        try {
22622            String sdEncKey = SystemKeyStore.getInstance().retrieveKeyHexString(
22623                    SD_ENCRYPTION_KEYSTORE_NAME);
22624            if (sdEncKey == null) {
22625                sdEncKey = SystemKeyStore.getInstance().generateNewKeyHexString(128,
22626                        SD_ENCRYPTION_ALGORITHM, SD_ENCRYPTION_KEYSTORE_NAME);
22627                if (sdEncKey == null) {
22628                    Slog.e(TAG, "Failed to create encryption keys");
22629                    return null;
22630                }
22631            }
22632            return sdEncKey;
22633        } catch (NoSuchAlgorithmException nsae) {
22634            Slog.e(TAG, "Failed to create encryption keys with exception: " + nsae);
22635            return null;
22636        } catch (IOException ioe) {
22637            Slog.e(TAG, "Failed to retrieve encryption keys with exception: " + ioe);
22638            return null;
22639        }
22640    }
22641
22642    /*
22643     * Update media status on PackageManager.
22644     */
22645    @Override
22646    public void updateExternalMediaStatus(final boolean mediaStatus, final boolean reportStatus) {
22647        enforceSystemOrRoot("Media status can only be updated by the system");
22648        // reader; this apparently protects mMediaMounted, but should probably
22649        // be a different lock in that case.
22650        synchronized (mPackages) {
22651            Log.i(TAG, "Updating external media status from "
22652                    + (mMediaMounted ? "mounted" : "unmounted") + " to "
22653                    + (mediaStatus ? "mounted" : "unmounted"));
22654            if (DEBUG_SD_INSTALL)
22655                Log.i(TAG, "updateExternalMediaStatus:: mediaStatus=" + mediaStatus
22656                        + ", mMediaMounted=" + mMediaMounted);
22657            if (mediaStatus == mMediaMounted) {
22658                final Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1
22659                        : 0, -1);
22660                mHandler.sendMessage(msg);
22661                return;
22662            }
22663            mMediaMounted = mediaStatus;
22664        }
22665        // Queue up an async operation since the package installation may take a
22666        // little while.
22667        mHandler.post(new Runnable() {
22668            public void run() {
22669                updateExternalMediaStatusInner(mediaStatus, reportStatus, true);
22670            }
22671        });
22672    }
22673
22674    /**
22675     * Called by StorageManagerService when the initial ASECs to scan are available.
22676     * Should block until all the ASEC containers are finished being scanned.
22677     */
22678    public void scanAvailableAsecs() {
22679        updateExternalMediaStatusInner(true, false, false);
22680    }
22681
22682    /*
22683     * Collect information of applications on external media, map them against
22684     * existing containers and update information based on current mount status.
22685     * Please note that we always have to report status if reportStatus has been
22686     * set to true especially when unloading packages.
22687     */
22688    private void updateExternalMediaStatusInner(boolean isMounted, boolean reportStatus,
22689            boolean externalStorage) {
22690        ArrayMap<AsecInstallArgs, String> processCids = new ArrayMap<>();
22691        int[] uidArr = EmptyArray.INT;
22692
22693        final String[] list = PackageHelper.getSecureContainerList();
22694        if (ArrayUtils.isEmpty(list)) {
22695            Log.i(TAG, "No secure containers found");
22696        } else {
22697            // Process list of secure containers and categorize them
22698            // as active or stale based on their package internal state.
22699
22700            // reader
22701            synchronized (mPackages) {
22702                for (String cid : list) {
22703                    // Leave stages untouched for now; installer service owns them
22704                    if (PackageInstallerService.isStageName(cid)) continue;
22705
22706                    if (DEBUG_SD_INSTALL)
22707                        Log.i(TAG, "Processing container " + cid);
22708                    String pkgName = getAsecPackageName(cid);
22709                    if (pkgName == null) {
22710                        Slog.i(TAG, "Found stale container " + cid + " with no package name");
22711                        continue;
22712                    }
22713                    if (DEBUG_SD_INSTALL)
22714                        Log.i(TAG, "Looking for pkg : " + pkgName);
22715
22716                    final PackageSetting ps = mSettings.mPackages.get(pkgName);
22717                    if (ps == null) {
22718                        Slog.i(TAG, "Found stale container " + cid + " with no matching settings");
22719                        continue;
22720                    }
22721
22722                    /*
22723                     * Skip packages that are not external if we're unmounting
22724                     * external storage.
22725                     */
22726                    if (externalStorage && !isMounted && !isExternal(ps)) {
22727                        continue;
22728                    }
22729
22730                    final AsecInstallArgs args = new AsecInstallArgs(cid,
22731                            getAppDexInstructionSets(ps), ps.isForwardLocked());
22732                    // The package status is changed only if the code path
22733                    // matches between settings and the container id.
22734                    if (ps.codePathString != null
22735                            && ps.codePathString.startsWith(args.getCodePath())) {
22736                        if (DEBUG_SD_INSTALL) {
22737                            Log.i(TAG, "Container : " + cid + " corresponds to pkg : " + pkgName
22738                                    + " at code path: " + ps.codePathString);
22739                        }
22740
22741                        // We do have a valid package installed on sdcard
22742                        processCids.put(args, ps.codePathString);
22743                        final int uid = ps.appId;
22744                        if (uid != -1) {
22745                            uidArr = ArrayUtils.appendInt(uidArr, uid);
22746                        }
22747                    } else {
22748                        Slog.i(TAG, "Found stale container " + cid + ": expected codePath="
22749                                + ps.codePathString);
22750                    }
22751                }
22752            }
22753
22754            Arrays.sort(uidArr);
22755        }
22756
22757        // Process packages with valid entries.
22758        if (isMounted) {
22759            if (DEBUG_SD_INSTALL)
22760                Log.i(TAG, "Loading packages");
22761            loadMediaPackages(processCids, uidArr, externalStorage);
22762            startCleaningPackages();
22763            mInstallerService.onSecureContainersAvailable();
22764        } else {
22765            if (DEBUG_SD_INSTALL)
22766                Log.i(TAG, "Unloading packages");
22767            unloadMediaPackages(processCids, uidArr, reportStatus);
22768        }
22769    }
22770
22771    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
22772            ArrayList<ApplicationInfo> infos, IIntentReceiver finishedReceiver) {
22773        final int size = infos.size();
22774        final String[] packageNames = new String[size];
22775        final int[] packageUids = new int[size];
22776        for (int i = 0; i < size; i++) {
22777            final ApplicationInfo info = infos.get(i);
22778            packageNames[i] = info.packageName;
22779            packageUids[i] = info.uid;
22780        }
22781        sendResourcesChangedBroadcast(mediaStatus, replacing, packageNames, packageUids,
22782                finishedReceiver);
22783    }
22784
22785    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
22786            ArrayList<String> pkgList, int uidArr[], IIntentReceiver finishedReceiver) {
22787        sendResourcesChangedBroadcast(mediaStatus, replacing,
22788                pkgList.toArray(new String[pkgList.size()]), uidArr, finishedReceiver);
22789    }
22790
22791    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
22792            String[] pkgList, int uidArr[], IIntentReceiver finishedReceiver) {
22793        int size = pkgList.length;
22794        if (size > 0) {
22795            // Send broadcasts here
22796            Bundle extras = new Bundle();
22797            extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList);
22798            if (uidArr != null) {
22799                extras.putIntArray(Intent.EXTRA_CHANGED_UID_LIST, uidArr);
22800            }
22801            if (replacing) {
22802                extras.putBoolean(Intent.EXTRA_REPLACING, replacing);
22803            }
22804            String action = mediaStatus ? Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE
22805                    : Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE;
22806            sendPackageBroadcast(action, null, extras, 0, null, finishedReceiver, null);
22807        }
22808    }
22809
22810   /*
22811     * Look at potentially valid container ids from processCids If package
22812     * information doesn't match the one on record or package scanning fails,
22813     * the cid is added to list of removeCids. We currently don't delete stale
22814     * containers.
22815     */
22816    private void loadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int[] uidArr,
22817            boolean externalStorage) {
22818        ArrayList<String> pkgList = new ArrayList<String>();
22819        Set<AsecInstallArgs> keys = processCids.keySet();
22820
22821        for (AsecInstallArgs args : keys) {
22822            String codePath = processCids.get(args);
22823            if (DEBUG_SD_INSTALL)
22824                Log.i(TAG, "Loading container : " + args.cid);
22825            int retCode = PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
22826            try {
22827                // Make sure there are no container errors first.
22828                if (args.doPreInstall(PackageManager.INSTALL_SUCCEEDED) != PackageManager.INSTALL_SUCCEEDED) {
22829                    Slog.e(TAG, "Failed to mount cid : " + args.cid
22830                            + " when installing from sdcard");
22831                    continue;
22832                }
22833                // Check code path here.
22834                if (codePath == null || !codePath.startsWith(args.getCodePath())) {
22835                    Slog.e(TAG, "Container " + args.cid + " cachepath " + args.getCodePath()
22836                            + " does not match one in settings " + codePath);
22837                    continue;
22838                }
22839                // Parse package
22840                int parseFlags = mDefParseFlags;
22841                if (args.isExternalAsec()) {
22842                    parseFlags |= PackageParser.PARSE_EXTERNAL_STORAGE;
22843                }
22844                if (args.isFwdLocked()) {
22845                    parseFlags |= PackageParser.PARSE_FORWARD_LOCK;
22846                }
22847
22848                synchronized (mInstallLock) {
22849                    PackageParser.Package pkg = null;
22850                    try {
22851                        // Sadly we don't know the package name yet to freeze it
22852                        pkg = scanPackageTracedLI(new File(codePath), parseFlags,
22853                                SCAN_IGNORE_FROZEN, 0, null);
22854                    } catch (PackageManagerException e) {
22855                        Slog.w(TAG, "Failed to scan " + codePath + ": " + e.getMessage());
22856                    }
22857                    // Scan the package
22858                    if (pkg != null) {
22859                        /*
22860                         * TODO why is the lock being held? doPostInstall is
22861                         * called in other places without the lock. This needs
22862                         * to be straightened out.
22863                         */
22864                        // writer
22865                        synchronized (mPackages) {
22866                            retCode = PackageManager.INSTALL_SUCCEEDED;
22867                            pkgList.add(pkg.packageName);
22868                            // Post process args
22869                            args.doPostInstall(PackageManager.INSTALL_SUCCEEDED,
22870                                    pkg.applicationInfo.uid);
22871                        }
22872                    } else {
22873                        Slog.i(TAG, "Failed to install pkg from  " + codePath + " from sdcard");
22874                    }
22875                }
22876
22877            } finally {
22878                if (retCode != PackageManager.INSTALL_SUCCEEDED) {
22879                    Log.w(TAG, "Container " + args.cid + " is stale, retCode=" + retCode);
22880                }
22881            }
22882        }
22883        // writer
22884        synchronized (mPackages) {
22885            // If the platform SDK has changed since the last time we booted,
22886            // we need to re-grant app permission to catch any new ones that
22887            // appear. This is really a hack, and means that apps can in some
22888            // cases get permissions that the user didn't initially explicitly
22889            // allow... it would be nice to have some better way to handle
22890            // this situation.
22891            final VersionInfo ver = externalStorage ? mSettings.getExternalVersion()
22892                    : mSettings.getInternalVersion();
22893            final String volumeUuid = externalStorage ? StorageManager.UUID_PRIMARY_PHYSICAL
22894                    : StorageManager.UUID_PRIVATE_INTERNAL;
22895
22896            int updateFlags = UPDATE_PERMISSIONS_ALL;
22897            if (ver.sdkVersion != mSdkVersion) {
22898                logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to "
22899                        + mSdkVersion + "; regranting permissions for external");
22900                updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL;
22901            }
22902            updatePermissionsLPw(null, null, volumeUuid, updateFlags);
22903
22904            // Yay, everything is now upgraded
22905            ver.forceCurrent();
22906
22907            // can downgrade to reader
22908            // Persist settings
22909            mSettings.writeLPr();
22910        }
22911        // Send a broadcast to let everyone know we are done processing
22912        if (pkgList.size() > 0) {
22913            sendResourcesChangedBroadcast(true, false, pkgList, uidArr, null);
22914        }
22915    }
22916
22917   /*
22918     * Utility method to unload a list of specified containers
22919     */
22920    private void unloadAllContainers(Set<AsecInstallArgs> cidArgs) {
22921        // Just unmount all valid containers.
22922        for (AsecInstallArgs arg : cidArgs) {
22923            synchronized (mInstallLock) {
22924                arg.doPostDeleteLI(false);
22925           }
22926       }
22927   }
22928
22929    /*
22930     * Unload packages mounted on external media. This involves deleting package
22931     * data from internal structures, sending broadcasts about disabled packages,
22932     * gc'ing to free up references, unmounting all secure containers
22933     * corresponding to packages on external media, and posting a
22934     * UPDATED_MEDIA_STATUS message if status has been requested. Please note
22935     * that we always have to post this message if status has been requested no
22936     * matter what.
22937     */
22938    private void unloadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int uidArr[],
22939            final boolean reportStatus) {
22940        if (DEBUG_SD_INSTALL)
22941            Log.i(TAG, "unloading media packages");
22942        ArrayList<String> pkgList = new ArrayList<String>();
22943        ArrayList<AsecInstallArgs> failedList = new ArrayList<AsecInstallArgs>();
22944        final Set<AsecInstallArgs> keys = processCids.keySet();
22945        for (AsecInstallArgs args : keys) {
22946            String pkgName = args.getPackageName();
22947            if (DEBUG_SD_INSTALL)
22948                Log.i(TAG, "Trying to unload pkg : " + pkgName);
22949            // Delete package internally
22950            PackageRemovedInfo outInfo = new PackageRemovedInfo(this);
22951            synchronized (mInstallLock) {
22952                final int deleteFlags = PackageManager.DELETE_KEEP_DATA;
22953                final boolean res;
22954                try (PackageFreezer freezer = freezePackageForDelete(pkgName, deleteFlags,
22955                        "unloadMediaPackages")) {
22956                    res = deletePackageLIF(pkgName, null, false, null, deleteFlags, outInfo, false,
22957                            null);
22958                }
22959                if (res) {
22960                    pkgList.add(pkgName);
22961                } else {
22962                    Slog.e(TAG, "Failed to delete pkg from sdcard : " + pkgName);
22963                    failedList.add(args);
22964                }
22965            }
22966        }
22967
22968        // reader
22969        synchronized (mPackages) {
22970            // We didn't update the settings after removing each package;
22971            // write them now for all packages.
22972            mSettings.writeLPr();
22973        }
22974
22975        // We have to absolutely send UPDATED_MEDIA_STATUS only
22976        // after confirming that all the receivers processed the ordered
22977        // broadcast when packages get disabled, force a gc to clean things up.
22978        // and unload all the containers.
22979        if (pkgList.size() > 0) {
22980            sendResourcesChangedBroadcast(false, false, pkgList, uidArr,
22981                    new IIntentReceiver.Stub() {
22982                public void performReceive(Intent intent, int resultCode, String data,
22983                        Bundle extras, boolean ordered, boolean sticky,
22984                        int sendingUser) throws RemoteException {
22985                    Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS,
22986                            reportStatus ? 1 : 0, 1, keys);
22987                    mHandler.sendMessage(msg);
22988                }
22989            });
22990        } else {
22991            Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 : 0, -1,
22992                    keys);
22993            mHandler.sendMessage(msg);
22994        }
22995    }
22996
22997    private void loadPrivatePackages(final VolumeInfo vol) {
22998        mHandler.post(new Runnable() {
22999            @Override
23000            public void run() {
23001                loadPrivatePackagesInner(vol);
23002            }
23003        });
23004    }
23005
23006    private void loadPrivatePackagesInner(VolumeInfo vol) {
23007        final String volumeUuid = vol.fsUuid;
23008        if (TextUtils.isEmpty(volumeUuid)) {
23009            Slog.e(TAG, "Loading internal storage is probably a mistake; ignoring");
23010            return;
23011        }
23012
23013        final ArrayList<PackageFreezer> freezers = new ArrayList<>();
23014        final ArrayList<ApplicationInfo> loaded = new ArrayList<>();
23015        final int parseFlags = mDefParseFlags | PackageParser.PARSE_EXTERNAL_STORAGE;
23016
23017        final VersionInfo ver;
23018        final List<PackageSetting> packages;
23019        synchronized (mPackages) {
23020            ver = mSettings.findOrCreateVersion(volumeUuid);
23021            packages = mSettings.getVolumePackagesLPr(volumeUuid);
23022        }
23023
23024        for (PackageSetting ps : packages) {
23025            freezers.add(freezePackage(ps.name, "loadPrivatePackagesInner"));
23026            synchronized (mInstallLock) {
23027                final PackageParser.Package pkg;
23028                try {
23029                    pkg = scanPackageTracedLI(ps.codePath, parseFlags, SCAN_INITIAL, 0, null);
23030                    loaded.add(pkg.applicationInfo);
23031
23032                } catch (PackageManagerException e) {
23033                    Slog.w(TAG, "Failed to scan " + ps.codePath + ": " + e.getMessage());
23034                }
23035
23036                if (!Build.FINGERPRINT.equals(ver.fingerprint)) {
23037                    clearAppDataLIF(ps.pkg, UserHandle.USER_ALL,
23038                            StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE
23039                                    | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
23040                }
23041            }
23042        }
23043
23044        // Reconcile app data for all started/unlocked users
23045        final StorageManager sm = mContext.getSystemService(StorageManager.class);
23046        final UserManager um = mContext.getSystemService(UserManager.class);
23047        UserManagerInternal umInternal = getUserManagerInternal();
23048        for (UserInfo user : um.getUsers()) {
23049            final int flags;
23050            if (umInternal.isUserUnlockingOrUnlocked(user.id)) {
23051                flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
23052            } else if (umInternal.isUserRunning(user.id)) {
23053                flags = StorageManager.FLAG_STORAGE_DE;
23054            } else {
23055                continue;
23056            }
23057
23058            try {
23059                sm.prepareUserStorage(volumeUuid, user.id, user.serialNumber, flags);
23060                synchronized (mInstallLock) {
23061                    reconcileAppsDataLI(volumeUuid, user.id, flags, true /* migrateAppData */);
23062                }
23063            } catch (IllegalStateException e) {
23064                // Device was probably ejected, and we'll process that event momentarily
23065                Slog.w(TAG, "Failed to prepare storage: " + e);
23066            }
23067        }
23068
23069        synchronized (mPackages) {
23070            int updateFlags = UPDATE_PERMISSIONS_ALL;
23071            if (ver.sdkVersion != mSdkVersion) {
23072                logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to "
23073                        + mSdkVersion + "; regranting permissions for " + volumeUuid);
23074                updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL;
23075            }
23076            updatePermissionsLPw(null, null, volumeUuid, updateFlags);
23077
23078            // Yay, everything is now upgraded
23079            ver.forceCurrent();
23080
23081            mSettings.writeLPr();
23082        }
23083
23084        for (PackageFreezer freezer : freezers) {
23085            freezer.close();
23086        }
23087
23088        if (DEBUG_INSTALL) Slog.d(TAG, "Loaded packages " + loaded);
23089        sendResourcesChangedBroadcast(true, false, loaded, null);
23090        mLoadedVolumes.add(vol.getId());
23091    }
23092
23093    private void unloadPrivatePackages(final VolumeInfo vol) {
23094        mHandler.post(new Runnable() {
23095            @Override
23096            public void run() {
23097                unloadPrivatePackagesInner(vol);
23098            }
23099        });
23100    }
23101
23102    private void unloadPrivatePackagesInner(VolumeInfo vol) {
23103        final String volumeUuid = vol.fsUuid;
23104        if (TextUtils.isEmpty(volumeUuid)) {
23105            Slog.e(TAG, "Unloading internal storage is probably a mistake; ignoring");
23106            return;
23107        }
23108
23109        final ArrayList<ApplicationInfo> unloaded = new ArrayList<>();
23110        synchronized (mInstallLock) {
23111        synchronized (mPackages) {
23112            final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(volumeUuid);
23113            for (PackageSetting ps : packages) {
23114                if (ps.pkg == null) continue;
23115
23116                final ApplicationInfo info = ps.pkg.applicationInfo;
23117                final int deleteFlags = PackageManager.DELETE_KEEP_DATA;
23118                final PackageRemovedInfo outInfo = new PackageRemovedInfo(this);
23119
23120                try (PackageFreezer freezer = freezePackageForDelete(ps.name, deleteFlags,
23121                        "unloadPrivatePackagesInner")) {
23122                    if (deletePackageLIF(ps.name, null, false, null, deleteFlags, outInfo,
23123                            false, null)) {
23124                        unloaded.add(info);
23125                    } else {
23126                        Slog.w(TAG, "Failed to unload " + ps.codePath);
23127                    }
23128                }
23129
23130                // Try very hard to release any references to this package
23131                // so we don't risk the system server being killed due to
23132                // open FDs
23133                AttributeCache.instance().removePackage(ps.name);
23134            }
23135
23136            mSettings.writeLPr();
23137        }
23138        }
23139
23140        if (DEBUG_INSTALL) Slog.d(TAG, "Unloaded packages " + unloaded);
23141        sendResourcesChangedBroadcast(false, false, unloaded, null);
23142        mLoadedVolumes.remove(vol.getId());
23143
23144        // Try very hard to release any references to this path so we don't risk
23145        // the system server being killed due to open FDs
23146        ResourcesManager.getInstance().invalidatePath(vol.getPath().getAbsolutePath());
23147
23148        for (int i = 0; i < 3; i++) {
23149            System.gc();
23150            System.runFinalization();
23151        }
23152    }
23153
23154    private void assertPackageKnown(String volumeUuid, String packageName)
23155            throws PackageManagerException {
23156        synchronized (mPackages) {
23157            // Normalize package name to handle renamed packages
23158            packageName = normalizePackageNameLPr(packageName);
23159
23160            final PackageSetting ps = mSettings.mPackages.get(packageName);
23161            if (ps == null) {
23162                throw new PackageManagerException("Package " + packageName + " is unknown");
23163            } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) {
23164                throw new PackageManagerException(
23165                        "Package " + packageName + " found on unknown volume " + volumeUuid
23166                                + "; expected volume " + ps.volumeUuid);
23167            }
23168        }
23169    }
23170
23171    private void assertPackageKnownAndInstalled(String volumeUuid, String packageName, int userId)
23172            throws PackageManagerException {
23173        synchronized (mPackages) {
23174            // Normalize package name to handle renamed packages
23175            packageName = normalizePackageNameLPr(packageName);
23176
23177            final PackageSetting ps = mSettings.mPackages.get(packageName);
23178            if (ps == null) {
23179                throw new PackageManagerException("Package " + packageName + " is unknown");
23180            } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) {
23181                throw new PackageManagerException(
23182                        "Package " + packageName + " found on unknown volume " + volumeUuid
23183                                + "; expected volume " + ps.volumeUuid);
23184            } else if (!ps.getInstalled(userId)) {
23185                throw new PackageManagerException(
23186                        "Package " + packageName + " not installed for user " + userId);
23187            }
23188        }
23189    }
23190
23191    private List<String> collectAbsoluteCodePaths() {
23192        synchronized (mPackages) {
23193            List<String> codePaths = new ArrayList<>();
23194            final int packageCount = mSettings.mPackages.size();
23195            for (int i = 0; i < packageCount; i++) {
23196                final PackageSetting ps = mSettings.mPackages.valueAt(i);
23197                codePaths.add(ps.codePath.getAbsolutePath());
23198            }
23199            return codePaths;
23200        }
23201    }
23202
23203    /**
23204     * Examine all apps present on given mounted volume, and destroy apps that
23205     * aren't expected, either due to uninstallation or reinstallation on
23206     * another volume.
23207     */
23208    private void reconcileApps(String volumeUuid) {
23209        List<String> absoluteCodePaths = collectAbsoluteCodePaths();
23210        List<File> filesToDelete = null;
23211
23212        final File[] files = FileUtils.listFilesOrEmpty(
23213                Environment.getDataAppDirectory(volumeUuid));
23214        for (File file : files) {
23215            final boolean isPackage = (isApkFile(file) || file.isDirectory())
23216                    && !PackageInstallerService.isStageName(file.getName());
23217            if (!isPackage) {
23218                // Ignore entries which are not packages
23219                continue;
23220            }
23221
23222            String absolutePath = file.getAbsolutePath();
23223
23224            boolean pathValid = false;
23225            final int absoluteCodePathCount = absoluteCodePaths.size();
23226            for (int i = 0; i < absoluteCodePathCount; i++) {
23227                String absoluteCodePath = absoluteCodePaths.get(i);
23228                if (absolutePath.startsWith(absoluteCodePath)) {
23229                    pathValid = true;
23230                    break;
23231                }
23232            }
23233
23234            if (!pathValid) {
23235                if (filesToDelete == null) {
23236                    filesToDelete = new ArrayList<>();
23237                }
23238                filesToDelete.add(file);
23239            }
23240        }
23241
23242        if (filesToDelete != null) {
23243            final int fileToDeleteCount = filesToDelete.size();
23244            for (int i = 0; i < fileToDeleteCount; i++) {
23245                File fileToDelete = filesToDelete.get(i);
23246                logCriticalInfo(Log.WARN, "Destroying orphaned" + fileToDelete);
23247                synchronized (mInstallLock) {
23248                    removeCodePathLI(fileToDelete);
23249                }
23250            }
23251        }
23252    }
23253
23254    /**
23255     * Reconcile all app data for the given user.
23256     * <p>
23257     * Verifies that directories exist and that ownership and labeling is
23258     * correct for all installed apps on all mounted volumes.
23259     */
23260    void reconcileAppsData(int userId, int flags, boolean migrateAppsData) {
23261        final StorageManager storage = mContext.getSystemService(StorageManager.class);
23262        for (VolumeInfo vol : storage.getWritablePrivateVolumes()) {
23263            final String volumeUuid = vol.getFsUuid();
23264            synchronized (mInstallLock) {
23265                reconcileAppsDataLI(volumeUuid, userId, flags, migrateAppsData);
23266            }
23267        }
23268    }
23269
23270    private void reconcileAppsDataLI(String volumeUuid, int userId, int flags,
23271            boolean migrateAppData) {
23272        reconcileAppsDataLI(volumeUuid, userId, flags, migrateAppData, false /* onlyCoreApps */);
23273    }
23274
23275    /**
23276     * Reconcile all app data on given mounted volume.
23277     * <p>
23278     * Destroys app data that isn't expected, either due to uninstallation or
23279     * reinstallation on another volume.
23280     * <p>
23281     * Verifies that directories exist and that ownership and labeling is
23282     * correct for all installed apps.
23283     * @returns list of skipped non-core packages (if {@code onlyCoreApps} is true)
23284     */
23285    private List<String> reconcileAppsDataLI(String volumeUuid, int userId, int flags,
23286            boolean migrateAppData, boolean onlyCoreApps) {
23287        Slog.v(TAG, "reconcileAppsData for " + volumeUuid + " u" + userId + " 0x"
23288                + Integer.toHexString(flags) + " migrateAppData=" + migrateAppData);
23289        List<String> result = onlyCoreApps ? new ArrayList<>() : null;
23290
23291        final File ceDir = Environment.getDataUserCeDirectory(volumeUuid, userId);
23292        final File deDir = Environment.getDataUserDeDirectory(volumeUuid, userId);
23293
23294        // First look for stale data that doesn't belong, and check if things
23295        // have changed since we did our last restorecon
23296        if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) {
23297            if (StorageManager.isFileEncryptedNativeOrEmulated()
23298                    && !StorageManager.isUserKeyUnlocked(userId)) {
23299                throw new RuntimeException(
23300                        "Yikes, someone asked us to reconcile CE storage while " + userId
23301                                + " was still locked; this would have caused massive data loss!");
23302            }
23303
23304            final File[] files = FileUtils.listFilesOrEmpty(ceDir);
23305            for (File file : files) {
23306                final String packageName = file.getName();
23307                try {
23308                    assertPackageKnownAndInstalled(volumeUuid, packageName, userId);
23309                } catch (PackageManagerException e) {
23310                    logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e);
23311                    try {
23312                        mInstaller.destroyAppData(volumeUuid, packageName, userId,
23313                                StorageManager.FLAG_STORAGE_CE, 0);
23314                    } catch (InstallerException e2) {
23315                        logCriticalInfo(Log.WARN, "Failed to destroy: " + e2);
23316                    }
23317                }
23318            }
23319        }
23320        if ((flags & StorageManager.FLAG_STORAGE_DE) != 0) {
23321            final File[] files = FileUtils.listFilesOrEmpty(deDir);
23322            for (File file : files) {
23323                final String packageName = file.getName();
23324                try {
23325                    assertPackageKnownAndInstalled(volumeUuid, packageName, userId);
23326                } catch (PackageManagerException e) {
23327                    logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e);
23328                    try {
23329                        mInstaller.destroyAppData(volumeUuid, packageName, userId,
23330                                StorageManager.FLAG_STORAGE_DE, 0);
23331                    } catch (InstallerException e2) {
23332                        logCriticalInfo(Log.WARN, "Failed to destroy: " + e2);
23333                    }
23334                }
23335            }
23336        }
23337
23338        // Ensure that data directories are ready to roll for all packages
23339        // installed for this volume and user
23340        final List<PackageSetting> packages;
23341        synchronized (mPackages) {
23342            packages = mSettings.getVolumePackagesLPr(volumeUuid);
23343        }
23344        int preparedCount = 0;
23345        for (PackageSetting ps : packages) {
23346            final String packageName = ps.name;
23347            if (ps.pkg == null) {
23348                Slog.w(TAG, "Odd, missing scanned package " + packageName);
23349                // TODO: might be due to legacy ASEC apps; we should circle back
23350                // and reconcile again once they're scanned
23351                continue;
23352            }
23353            // Skip non-core apps if requested
23354            if (onlyCoreApps && !ps.pkg.coreApp) {
23355                result.add(packageName);
23356                continue;
23357            }
23358
23359            if (ps.getInstalled(userId)) {
23360                prepareAppDataAndMigrateLIF(ps.pkg, userId, flags, migrateAppData);
23361                preparedCount++;
23362            }
23363        }
23364
23365        Slog.v(TAG, "reconcileAppsData finished " + preparedCount + " packages");
23366        return result;
23367    }
23368
23369    /**
23370     * Prepare app data for the given app just after it was installed or
23371     * upgraded. This method carefully only touches users that it's installed
23372     * for, and it forces a restorecon to handle any seinfo changes.
23373     * <p>
23374     * Verifies that directories exist and that ownership and labeling is
23375     * correct for all installed apps. If there is an ownership mismatch, it
23376     * will try recovering system apps by wiping data; third-party app data is
23377     * left intact.
23378     * <p>
23379     * <em>Note: To avoid a deadlock, do not call this method with {@code mPackages} lock held</em>
23380     */
23381    private void prepareAppDataAfterInstallLIF(PackageParser.Package pkg) {
23382        final PackageSetting ps;
23383        synchronized (mPackages) {
23384            ps = mSettings.mPackages.get(pkg.packageName);
23385            mSettings.writeKernelMappingLPr(ps);
23386        }
23387
23388        final UserManager um = mContext.getSystemService(UserManager.class);
23389        UserManagerInternal umInternal = getUserManagerInternal();
23390        for (UserInfo user : um.getUsers()) {
23391            final int flags;
23392            if (umInternal.isUserUnlockingOrUnlocked(user.id)) {
23393                flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
23394            } else if (umInternal.isUserRunning(user.id)) {
23395                flags = StorageManager.FLAG_STORAGE_DE;
23396            } else {
23397                continue;
23398            }
23399
23400            if (ps.getInstalled(user.id)) {
23401                // TODO: when user data is locked, mark that we're still dirty
23402                prepareAppDataLIF(pkg, user.id, flags);
23403            }
23404        }
23405    }
23406
23407    /**
23408     * Prepare app data for the given app.
23409     * <p>
23410     * Verifies that directories exist and that ownership and labeling is
23411     * correct for all installed apps. If there is an ownership mismatch, this
23412     * will try recovering system apps by wiping data; third-party app data is
23413     * left intact.
23414     */
23415    private void prepareAppDataLIF(PackageParser.Package pkg, int userId, int flags) {
23416        if (pkg == null) {
23417            Slog.wtf(TAG, "Package was null!", new Throwable());
23418            return;
23419        }
23420        prepareAppDataLeafLIF(pkg, userId, flags);
23421        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
23422        for (int i = 0; i < childCount; i++) {
23423            prepareAppDataLeafLIF(pkg.childPackages.get(i), userId, flags);
23424        }
23425    }
23426
23427    private void prepareAppDataAndMigrateLIF(PackageParser.Package pkg, int userId, int flags,
23428            boolean maybeMigrateAppData) {
23429        prepareAppDataLIF(pkg, userId, flags);
23430
23431        if (maybeMigrateAppData && maybeMigrateAppDataLIF(pkg, userId)) {
23432            // We may have just shuffled around app data directories, so
23433            // prepare them one more time
23434            prepareAppDataLIF(pkg, userId, flags);
23435        }
23436    }
23437
23438    private void prepareAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) {
23439        if (DEBUG_APP_DATA) {
23440            Slog.v(TAG, "prepareAppData for " + pkg.packageName + " u" + userId + " 0x"
23441                    + Integer.toHexString(flags));
23442        }
23443
23444        final String volumeUuid = pkg.volumeUuid;
23445        final String packageName = pkg.packageName;
23446        final ApplicationInfo app = pkg.applicationInfo;
23447        final int appId = UserHandle.getAppId(app.uid);
23448
23449        Preconditions.checkNotNull(app.seInfo);
23450
23451        long ceDataInode = -1;
23452        try {
23453            ceDataInode = mInstaller.createAppData(volumeUuid, packageName, userId, flags,
23454                    appId, app.seInfo, app.targetSdkVersion);
23455        } catch (InstallerException e) {
23456            if (app.isSystemApp()) {
23457                logCriticalInfo(Log.ERROR, "Failed to create app data for " + packageName
23458                        + ", but trying to recover: " + e);
23459                destroyAppDataLeafLIF(pkg, userId, flags);
23460                try {
23461                    ceDataInode = mInstaller.createAppData(volumeUuid, packageName, userId, flags,
23462                            appId, app.seInfo, app.targetSdkVersion);
23463                    logCriticalInfo(Log.DEBUG, "Recovery succeeded!");
23464                } catch (InstallerException e2) {
23465                    logCriticalInfo(Log.DEBUG, "Recovery failed!");
23466                }
23467            } else {
23468                Slog.e(TAG, "Failed to create app data for " + packageName + ": " + e);
23469            }
23470        }
23471
23472        if ((flags & StorageManager.FLAG_STORAGE_CE) != 0 && ceDataInode != -1) {
23473            // TODO: mark this structure as dirty so we persist it!
23474            synchronized (mPackages) {
23475                final PackageSetting ps = mSettings.mPackages.get(packageName);
23476                if (ps != null) {
23477                    ps.setCeDataInode(ceDataInode, userId);
23478                }
23479            }
23480        }
23481
23482        prepareAppDataContentsLeafLIF(pkg, userId, flags);
23483    }
23484
23485    private void prepareAppDataContentsLIF(PackageParser.Package pkg, int userId, int flags) {
23486        if (pkg == null) {
23487            Slog.wtf(TAG, "Package was null!", new Throwable());
23488            return;
23489        }
23490        prepareAppDataContentsLeafLIF(pkg, userId, flags);
23491        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
23492        for (int i = 0; i < childCount; i++) {
23493            prepareAppDataContentsLeafLIF(pkg.childPackages.get(i), userId, flags);
23494        }
23495    }
23496
23497    private void prepareAppDataContentsLeafLIF(PackageParser.Package pkg, int userId, int flags) {
23498        final String volumeUuid = pkg.volumeUuid;
23499        final String packageName = pkg.packageName;
23500        final ApplicationInfo app = pkg.applicationInfo;
23501
23502        if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) {
23503            // Create a native library symlink only if we have native libraries
23504            // and if the native libraries are 32 bit libraries. We do not provide
23505            // this symlink for 64 bit libraries.
23506            if (app.primaryCpuAbi != null && !VMRuntime.is64BitAbi(app.primaryCpuAbi)) {
23507                final String nativeLibPath = app.nativeLibraryDir;
23508                try {
23509                    mInstaller.linkNativeLibraryDirectory(volumeUuid, packageName,
23510                            nativeLibPath, userId);
23511                } catch (InstallerException e) {
23512                    Slog.e(TAG, "Failed to link native for " + packageName + ": " + e);
23513                }
23514            }
23515        }
23516    }
23517
23518    /**
23519     * For system apps on non-FBE devices, this method migrates any existing
23520     * CE/DE data to match the {@code defaultToDeviceProtectedStorage} flag
23521     * requested by the app.
23522     */
23523    private boolean maybeMigrateAppDataLIF(PackageParser.Package pkg, int userId) {
23524        if (pkg.isSystemApp() && !StorageManager.isFileEncryptedNativeOrEmulated()
23525                && PackageManager.APPLY_DEFAULT_TO_DEVICE_PROTECTED_STORAGE) {
23526            final int storageTarget = pkg.applicationInfo.isDefaultToDeviceProtectedStorage()
23527                    ? StorageManager.FLAG_STORAGE_DE : StorageManager.FLAG_STORAGE_CE;
23528            try {
23529                mInstaller.migrateAppData(pkg.volumeUuid, pkg.packageName, userId,
23530                        storageTarget);
23531            } catch (InstallerException e) {
23532                logCriticalInfo(Log.WARN,
23533                        "Failed to migrate " + pkg.packageName + ": " + e.getMessage());
23534            }
23535            return true;
23536        } else {
23537            return false;
23538        }
23539    }
23540
23541    public PackageFreezer freezePackage(String packageName, String killReason) {
23542        return freezePackage(packageName, UserHandle.USER_ALL, killReason);
23543    }
23544
23545    public PackageFreezer freezePackage(String packageName, int userId, String killReason) {
23546        return new PackageFreezer(packageName, userId, killReason);
23547    }
23548
23549    public PackageFreezer freezePackageForInstall(String packageName, int installFlags,
23550            String killReason) {
23551        return freezePackageForInstall(packageName, UserHandle.USER_ALL, installFlags, killReason);
23552    }
23553
23554    public PackageFreezer freezePackageForInstall(String packageName, int userId, int installFlags,
23555            String killReason) {
23556        if ((installFlags & PackageManager.INSTALL_DONT_KILL_APP) != 0) {
23557            return new PackageFreezer();
23558        } else {
23559            return freezePackage(packageName, userId, killReason);
23560        }
23561    }
23562
23563    public PackageFreezer freezePackageForDelete(String packageName, int deleteFlags,
23564            String killReason) {
23565        return freezePackageForDelete(packageName, UserHandle.USER_ALL, deleteFlags, killReason);
23566    }
23567
23568    public PackageFreezer freezePackageForDelete(String packageName, int userId, int deleteFlags,
23569            String killReason) {
23570        if ((deleteFlags & PackageManager.DELETE_DONT_KILL_APP) != 0) {
23571            return new PackageFreezer();
23572        } else {
23573            return freezePackage(packageName, userId, killReason);
23574        }
23575    }
23576
23577    /**
23578     * Class that freezes and kills the given package upon creation, and
23579     * unfreezes it upon closing. This is typically used when doing surgery on
23580     * app code/data to prevent the app from running while you're working.
23581     */
23582    private class PackageFreezer implements AutoCloseable {
23583        private final String mPackageName;
23584        private final PackageFreezer[] mChildren;
23585
23586        private final boolean mWeFroze;
23587
23588        private final AtomicBoolean mClosed = new AtomicBoolean();
23589        private final CloseGuard mCloseGuard = CloseGuard.get();
23590
23591        /**
23592         * Create and return a stub freezer that doesn't actually do anything,
23593         * typically used when someone requested
23594         * {@link PackageManager#INSTALL_DONT_KILL_APP} or
23595         * {@link PackageManager#DELETE_DONT_KILL_APP}.
23596         */
23597        public PackageFreezer() {
23598            mPackageName = null;
23599            mChildren = null;
23600            mWeFroze = false;
23601            mCloseGuard.open("close");
23602        }
23603
23604        public PackageFreezer(String packageName, int userId, String killReason) {
23605            synchronized (mPackages) {
23606                mPackageName = packageName;
23607                mWeFroze = mFrozenPackages.add(mPackageName);
23608
23609                final PackageSetting ps = mSettings.mPackages.get(mPackageName);
23610                if (ps != null) {
23611                    killApplication(ps.name, ps.appId, userId, killReason);
23612                }
23613
23614                final PackageParser.Package p = mPackages.get(packageName);
23615                if (p != null && p.childPackages != null) {
23616                    final int N = p.childPackages.size();
23617                    mChildren = new PackageFreezer[N];
23618                    for (int i = 0; i < N; i++) {
23619                        mChildren[i] = new PackageFreezer(p.childPackages.get(i).packageName,
23620                                userId, killReason);
23621                    }
23622                } else {
23623                    mChildren = null;
23624                }
23625            }
23626            mCloseGuard.open("close");
23627        }
23628
23629        @Override
23630        protected void finalize() throws Throwable {
23631            try {
23632                if (mCloseGuard != null) {
23633                    mCloseGuard.warnIfOpen();
23634                }
23635
23636                close();
23637            } finally {
23638                super.finalize();
23639            }
23640        }
23641
23642        @Override
23643        public void close() {
23644            mCloseGuard.close();
23645            if (mClosed.compareAndSet(false, true)) {
23646                synchronized (mPackages) {
23647                    if (mWeFroze) {
23648                        mFrozenPackages.remove(mPackageName);
23649                    }
23650
23651                    if (mChildren != null) {
23652                        for (PackageFreezer freezer : mChildren) {
23653                            freezer.close();
23654                        }
23655                    }
23656                }
23657            }
23658        }
23659    }
23660
23661    /**
23662     * Verify that given package is currently frozen.
23663     */
23664    private void checkPackageFrozen(String packageName) {
23665        synchronized (mPackages) {
23666            if (!mFrozenPackages.contains(packageName)) {
23667                Slog.wtf(TAG, "Expected " + packageName + " to be frozen!", new Throwable());
23668            }
23669        }
23670    }
23671
23672    @Override
23673    public int movePackage(final String packageName, final String volumeUuid) {
23674        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null);
23675
23676        final int callingUid = Binder.getCallingUid();
23677        final UserHandle user = new UserHandle(UserHandle.getUserId(callingUid));
23678        final int moveId = mNextMoveId.getAndIncrement();
23679        mHandler.post(new Runnable() {
23680            @Override
23681            public void run() {
23682                try {
23683                    movePackageInternal(packageName, volumeUuid, moveId, callingUid, user);
23684                } catch (PackageManagerException e) {
23685                    Slog.w(TAG, "Failed to move " + packageName, e);
23686                    mMoveCallbacks.notifyStatusChanged(moveId, e.error);
23687                }
23688            }
23689        });
23690        return moveId;
23691    }
23692
23693    private void movePackageInternal(final String packageName, final String volumeUuid,
23694            final int moveId, final int callingUid, UserHandle user)
23695                    throws PackageManagerException {
23696        final StorageManager storage = mContext.getSystemService(StorageManager.class);
23697        final PackageManager pm = mContext.getPackageManager();
23698
23699        final boolean currentAsec;
23700        final String currentVolumeUuid;
23701        final File codeFile;
23702        final String installerPackageName;
23703        final String packageAbiOverride;
23704        final int appId;
23705        final String seinfo;
23706        final String label;
23707        final int targetSdkVersion;
23708        final PackageFreezer freezer;
23709        final int[] installedUserIds;
23710
23711        // reader
23712        synchronized (mPackages) {
23713            final PackageParser.Package pkg = mPackages.get(packageName);
23714            final PackageSetting ps = mSettings.mPackages.get(packageName);
23715            if (pkg == null
23716                    || ps == null
23717                    || filterAppAccessLPr(ps, callingUid, user.getIdentifier())) {
23718                throw new PackageManagerException(MOVE_FAILED_DOESNT_EXIST, "Missing package");
23719            }
23720            if (pkg.applicationInfo.isSystemApp()) {
23721                throw new PackageManagerException(MOVE_FAILED_SYSTEM_PACKAGE,
23722                        "Cannot move system application");
23723            }
23724
23725            final boolean isInternalStorage = VolumeInfo.ID_PRIVATE_INTERNAL.equals(volumeUuid);
23726            final boolean allow3rdPartyOnInternal = mContext.getResources().getBoolean(
23727                    com.android.internal.R.bool.config_allow3rdPartyAppOnInternal);
23728            if (isInternalStorage && !allow3rdPartyOnInternal) {
23729                throw new PackageManagerException(MOVE_FAILED_3RD_PARTY_NOT_ALLOWED_ON_INTERNAL,
23730                        "3rd party apps are not allowed on internal storage");
23731            }
23732
23733            if (pkg.applicationInfo.isExternalAsec()) {
23734                currentAsec = true;
23735                currentVolumeUuid = StorageManager.UUID_PRIMARY_PHYSICAL;
23736            } else if (pkg.applicationInfo.isForwardLocked()) {
23737                currentAsec = true;
23738                currentVolumeUuid = "forward_locked";
23739            } else {
23740                currentAsec = false;
23741                currentVolumeUuid = ps.volumeUuid;
23742
23743                final File probe = new File(pkg.codePath);
23744                final File probeOat = new File(probe, "oat");
23745                if (!probe.isDirectory() || !probeOat.isDirectory()) {
23746                    throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
23747                            "Move only supported for modern cluster style installs");
23748                }
23749            }
23750
23751            if (Objects.equals(currentVolumeUuid, volumeUuid)) {
23752                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
23753                        "Package already moved to " + volumeUuid);
23754            }
23755            if (pkg.applicationInfo.isInternal() && isPackageDeviceAdminOnAnyUser(packageName)) {
23756                throw new PackageManagerException(MOVE_FAILED_DEVICE_ADMIN,
23757                        "Device admin cannot be moved");
23758            }
23759
23760            if (mFrozenPackages.contains(packageName)) {
23761                throw new PackageManagerException(MOVE_FAILED_OPERATION_PENDING,
23762                        "Failed to move already frozen package");
23763            }
23764
23765            codeFile = new File(pkg.codePath);
23766            installerPackageName = ps.installerPackageName;
23767            packageAbiOverride = ps.cpuAbiOverrideString;
23768            appId = UserHandle.getAppId(pkg.applicationInfo.uid);
23769            seinfo = pkg.applicationInfo.seInfo;
23770            label = String.valueOf(pm.getApplicationLabel(pkg.applicationInfo));
23771            targetSdkVersion = pkg.applicationInfo.targetSdkVersion;
23772            freezer = freezePackage(packageName, "movePackageInternal");
23773            installedUserIds = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
23774        }
23775
23776        final Bundle extras = new Bundle();
23777        extras.putString(Intent.EXTRA_PACKAGE_NAME, packageName);
23778        extras.putString(Intent.EXTRA_TITLE, label);
23779        mMoveCallbacks.notifyCreated(moveId, extras);
23780
23781        int installFlags;
23782        final boolean moveCompleteApp;
23783        final File measurePath;
23784
23785        if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, volumeUuid)) {
23786            installFlags = INSTALL_INTERNAL;
23787            moveCompleteApp = !currentAsec;
23788            measurePath = Environment.getDataAppDirectory(volumeUuid);
23789        } else if (Objects.equals(StorageManager.UUID_PRIMARY_PHYSICAL, volumeUuid)) {
23790            installFlags = INSTALL_EXTERNAL;
23791            moveCompleteApp = false;
23792            measurePath = storage.getPrimaryPhysicalVolume().getPath();
23793        } else {
23794            final VolumeInfo volume = storage.findVolumeByUuid(volumeUuid);
23795            if (volume == null || volume.getType() != VolumeInfo.TYPE_PRIVATE
23796                    || !volume.isMountedWritable()) {
23797                freezer.close();
23798                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
23799                        "Move location not mounted private volume");
23800            }
23801
23802            Preconditions.checkState(!currentAsec);
23803
23804            installFlags = INSTALL_INTERNAL;
23805            moveCompleteApp = true;
23806            measurePath = Environment.getDataAppDirectory(volumeUuid);
23807        }
23808
23809        // If we're moving app data around, we need all the users unlocked
23810        if (moveCompleteApp) {
23811            for (int userId : installedUserIds) {
23812                if (StorageManager.isFileEncryptedNativeOrEmulated()
23813                        && !StorageManager.isUserKeyUnlocked(userId)) {
23814                    throw new PackageManagerException(MOVE_FAILED_LOCKED_USER,
23815                            "User " + userId + " must be unlocked");
23816                }
23817            }
23818        }
23819
23820        final PackageStats stats = new PackageStats(null, -1);
23821        synchronized (mInstaller) {
23822            for (int userId : installedUserIds) {
23823                if (!getPackageSizeInfoLI(packageName, userId, stats)) {
23824                    freezer.close();
23825                    throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
23826                            "Failed to measure package size");
23827                }
23828            }
23829        }
23830
23831        if (DEBUG_INSTALL) Slog.d(TAG, "Measured code size " + stats.codeSize + ", data size "
23832                + stats.dataSize);
23833
23834        final long startFreeBytes = measurePath.getUsableSpace();
23835        final long sizeBytes;
23836        if (moveCompleteApp) {
23837            sizeBytes = stats.codeSize + stats.dataSize;
23838        } else {
23839            sizeBytes = stats.codeSize;
23840        }
23841
23842        if (sizeBytes > storage.getStorageBytesUntilLow(measurePath)) {
23843            freezer.close();
23844            throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
23845                    "Not enough free space to move");
23846        }
23847
23848        mMoveCallbacks.notifyStatusChanged(moveId, 10);
23849
23850        final CountDownLatch installedLatch = new CountDownLatch(1);
23851        final IPackageInstallObserver2 installObserver = new IPackageInstallObserver2.Stub() {
23852            @Override
23853            public void onUserActionRequired(Intent intent) throws RemoteException {
23854                throw new IllegalStateException();
23855            }
23856
23857            @Override
23858            public void onPackageInstalled(String basePackageName, int returnCode, String msg,
23859                    Bundle extras) throws RemoteException {
23860                if (DEBUG_INSTALL) Slog.d(TAG, "Install result for move: "
23861                        + PackageManager.installStatusToString(returnCode, msg));
23862
23863                installedLatch.countDown();
23864                freezer.close();
23865
23866                final int status = PackageManager.installStatusToPublicStatus(returnCode);
23867                switch (status) {
23868                    case PackageInstaller.STATUS_SUCCESS:
23869                        mMoveCallbacks.notifyStatusChanged(moveId,
23870                                PackageManager.MOVE_SUCCEEDED);
23871                        break;
23872                    case PackageInstaller.STATUS_FAILURE_STORAGE:
23873                        mMoveCallbacks.notifyStatusChanged(moveId,
23874                                PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE);
23875                        break;
23876                    default:
23877                        mMoveCallbacks.notifyStatusChanged(moveId,
23878                                PackageManager.MOVE_FAILED_INTERNAL_ERROR);
23879                        break;
23880                }
23881            }
23882        };
23883
23884        final MoveInfo move;
23885        if (moveCompleteApp) {
23886            // Kick off a thread to report progress estimates
23887            new Thread() {
23888                @Override
23889                public void run() {
23890                    while (true) {
23891                        try {
23892                            if (installedLatch.await(1, TimeUnit.SECONDS)) {
23893                                break;
23894                            }
23895                        } catch (InterruptedException ignored) {
23896                        }
23897
23898                        final long deltaFreeBytes = startFreeBytes - measurePath.getUsableSpace();
23899                        final int progress = 10 + (int) MathUtils.constrain(
23900                                ((deltaFreeBytes * 80) / sizeBytes), 0, 80);
23901                        mMoveCallbacks.notifyStatusChanged(moveId, progress);
23902                    }
23903                }
23904            }.start();
23905
23906            final String dataAppName = codeFile.getName();
23907            move = new MoveInfo(moveId, currentVolumeUuid, volumeUuid, packageName,
23908                    dataAppName, appId, seinfo, targetSdkVersion);
23909        } else {
23910            move = null;
23911        }
23912
23913        installFlags |= PackageManager.INSTALL_REPLACE_EXISTING;
23914
23915        final Message msg = mHandler.obtainMessage(INIT_COPY);
23916        final OriginInfo origin = OriginInfo.fromExistingFile(codeFile);
23917        final InstallParams params = new InstallParams(origin, move, installObserver, installFlags,
23918                installerPackageName, volumeUuid, null /*verificationInfo*/, user,
23919                packageAbiOverride, null /*grantedPermissions*/, null /*certificates*/,
23920                PackageManager.INSTALL_REASON_UNKNOWN);
23921        params.setTraceMethod("movePackage").setTraceCookie(System.identityHashCode(params));
23922        msg.obj = params;
23923
23924        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "movePackage",
23925                System.identityHashCode(msg.obj));
23926        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
23927                System.identityHashCode(msg.obj));
23928
23929        mHandler.sendMessage(msg);
23930    }
23931
23932    @Override
23933    public int movePrimaryStorage(String volumeUuid) throws RemoteException {
23934        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null);
23935
23936        final int realMoveId = mNextMoveId.getAndIncrement();
23937        final Bundle extras = new Bundle();
23938        extras.putString(VolumeRecord.EXTRA_FS_UUID, volumeUuid);
23939        mMoveCallbacks.notifyCreated(realMoveId, extras);
23940
23941        final IPackageMoveObserver callback = new IPackageMoveObserver.Stub() {
23942            @Override
23943            public void onCreated(int moveId, Bundle extras) {
23944                // Ignored
23945            }
23946
23947            @Override
23948            public void onStatusChanged(int moveId, int status, long estMillis) {
23949                mMoveCallbacks.notifyStatusChanged(realMoveId, status, estMillis);
23950            }
23951        };
23952
23953        final StorageManager storage = mContext.getSystemService(StorageManager.class);
23954        storage.setPrimaryStorageUuid(volumeUuid, callback);
23955        return realMoveId;
23956    }
23957
23958    @Override
23959    public int getMoveStatus(int moveId) {
23960        mContext.enforceCallingOrSelfPermission(
23961                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
23962        return mMoveCallbacks.mLastStatus.get(moveId);
23963    }
23964
23965    @Override
23966    public void registerMoveCallback(IPackageMoveObserver callback) {
23967        mContext.enforceCallingOrSelfPermission(
23968                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
23969        mMoveCallbacks.register(callback);
23970    }
23971
23972    @Override
23973    public void unregisterMoveCallback(IPackageMoveObserver callback) {
23974        mContext.enforceCallingOrSelfPermission(
23975                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
23976        mMoveCallbacks.unregister(callback);
23977    }
23978
23979    @Override
23980    public boolean setInstallLocation(int loc) {
23981        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WRITE_SECURE_SETTINGS,
23982                null);
23983        if (getInstallLocation() == loc) {
23984            return true;
23985        }
23986        if (loc == PackageHelper.APP_INSTALL_AUTO || loc == PackageHelper.APP_INSTALL_INTERNAL
23987                || loc == PackageHelper.APP_INSTALL_EXTERNAL) {
23988            android.provider.Settings.Global.putInt(mContext.getContentResolver(),
23989                    android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, loc);
23990            return true;
23991        }
23992        return false;
23993   }
23994
23995    @Override
23996    public int getInstallLocation() {
23997        // allow instant app access
23998        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
23999                android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION,
24000                PackageHelper.APP_INSTALL_AUTO);
24001    }
24002
24003    /** Called by UserManagerService */
24004    void cleanUpUser(UserManagerService userManager, int userHandle) {
24005        synchronized (mPackages) {
24006            mDirtyUsers.remove(userHandle);
24007            mUserNeedsBadging.delete(userHandle);
24008            mSettings.removeUserLPw(userHandle);
24009            mPendingBroadcasts.remove(userHandle);
24010            mInstantAppRegistry.onUserRemovedLPw(userHandle);
24011            removeUnusedPackagesLPw(userManager, userHandle);
24012        }
24013    }
24014
24015    /**
24016     * We're removing userHandle and would like to remove any downloaded packages
24017     * that are no longer in use by any other user.
24018     * @param userHandle the user being removed
24019     */
24020    private void removeUnusedPackagesLPw(UserManagerService userManager, final int userHandle) {
24021        final boolean DEBUG_CLEAN_APKS = false;
24022        int [] users = userManager.getUserIds();
24023        Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator();
24024        while (psit.hasNext()) {
24025            PackageSetting ps = psit.next();
24026            if (ps.pkg == null) {
24027                continue;
24028            }
24029            final String packageName = ps.pkg.packageName;
24030            // Skip over if system app
24031            if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0) {
24032                continue;
24033            }
24034            if (DEBUG_CLEAN_APKS) {
24035                Slog.i(TAG, "Checking package " + packageName);
24036            }
24037            boolean keep = shouldKeepUninstalledPackageLPr(packageName);
24038            if (keep) {
24039                if (DEBUG_CLEAN_APKS) {
24040                    Slog.i(TAG, "  Keeping package " + packageName + " - requested by DO");
24041                }
24042            } else {
24043                for (int i = 0; i < users.length; i++) {
24044                    if (users[i] != userHandle && ps.getInstalled(users[i])) {
24045                        keep = true;
24046                        if (DEBUG_CLEAN_APKS) {
24047                            Slog.i(TAG, "  Keeping package " + packageName + " for user "
24048                                    + users[i]);
24049                        }
24050                        break;
24051                    }
24052                }
24053            }
24054            if (!keep) {
24055                if (DEBUG_CLEAN_APKS) {
24056                    Slog.i(TAG, "  Removing package " + packageName);
24057                }
24058                mHandler.post(new Runnable() {
24059                    public void run() {
24060                        deletePackageX(packageName, PackageManager.VERSION_CODE_HIGHEST,
24061                                userHandle, 0);
24062                    } //end run
24063                });
24064            }
24065        }
24066    }
24067
24068    /** Called by UserManagerService */
24069    void createNewUser(int userId, String[] disallowedPackages) {
24070        synchronized (mInstallLock) {
24071            mSettings.createNewUserLI(this, mInstaller, userId, disallowedPackages);
24072        }
24073        synchronized (mPackages) {
24074            scheduleWritePackageRestrictionsLocked(userId);
24075            scheduleWritePackageListLocked(userId);
24076            applyFactoryDefaultBrowserLPw(userId);
24077            primeDomainVerificationsLPw(userId);
24078        }
24079    }
24080
24081    void onNewUserCreated(final int userId) {
24082        mDefaultPermissionPolicy.grantDefaultPermissions(userId);
24083        // If permission review for legacy apps is required, we represent
24084        // dagerous permissions for such apps as always granted runtime
24085        // permissions to keep per user flag state whether review is needed.
24086        // Hence, if a new user is added we have to propagate dangerous
24087        // permission grants for these legacy apps.
24088        if (mPermissionReviewRequired) {
24089            updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL
24090                    | UPDATE_PERMISSIONS_REPLACE_ALL);
24091        }
24092    }
24093
24094    @Override
24095    public VerifierDeviceIdentity getVerifierDeviceIdentity() throws RemoteException {
24096        mContext.enforceCallingOrSelfPermission(
24097                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
24098                "Only package verification agents can read the verifier device identity");
24099
24100        synchronized (mPackages) {
24101            return mSettings.getVerifierDeviceIdentityLPw();
24102        }
24103    }
24104
24105    @Override
24106    public void setPermissionEnforced(String permission, boolean enforced) {
24107        // TODO: Now that we no longer change GID for storage, this should to away.
24108        mContext.enforceCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS,
24109                "setPermissionEnforced");
24110        if (READ_EXTERNAL_STORAGE.equals(permission)) {
24111            synchronized (mPackages) {
24112                if (mSettings.mReadExternalStorageEnforced == null
24113                        || mSettings.mReadExternalStorageEnforced != enforced) {
24114                    mSettings.mReadExternalStorageEnforced = enforced;
24115                    mSettings.writeLPr();
24116                }
24117            }
24118            // kill any non-foreground processes so we restart them and
24119            // grant/revoke the GID.
24120            final IActivityManager am = ActivityManager.getService();
24121            if (am != null) {
24122                final long token = Binder.clearCallingIdentity();
24123                try {
24124                    am.killProcessesBelowForeground("setPermissionEnforcement");
24125                } catch (RemoteException e) {
24126                } finally {
24127                    Binder.restoreCallingIdentity(token);
24128                }
24129            }
24130        } else {
24131            throw new IllegalArgumentException("No selective enforcement for " + permission);
24132        }
24133    }
24134
24135    @Override
24136    @Deprecated
24137    public boolean isPermissionEnforced(String permission) {
24138        // allow instant applications
24139        return true;
24140    }
24141
24142    @Override
24143    public boolean isStorageLow() {
24144        // allow instant applications
24145        final long token = Binder.clearCallingIdentity();
24146        try {
24147            final DeviceStorageMonitorInternal
24148                    dsm = LocalServices.getService(DeviceStorageMonitorInternal.class);
24149            if (dsm != null) {
24150                return dsm.isMemoryLow();
24151            } else {
24152                return false;
24153            }
24154        } finally {
24155            Binder.restoreCallingIdentity(token);
24156        }
24157    }
24158
24159    @Override
24160    public IPackageInstaller getPackageInstaller() {
24161        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
24162            return null;
24163        }
24164        return mInstallerService;
24165    }
24166
24167    private boolean userNeedsBadging(int userId) {
24168        int index = mUserNeedsBadging.indexOfKey(userId);
24169        if (index < 0) {
24170            final UserInfo userInfo;
24171            final long token = Binder.clearCallingIdentity();
24172            try {
24173                userInfo = sUserManager.getUserInfo(userId);
24174            } finally {
24175                Binder.restoreCallingIdentity(token);
24176            }
24177            final boolean b;
24178            if (userInfo != null && userInfo.isManagedProfile()) {
24179                b = true;
24180            } else {
24181                b = false;
24182            }
24183            mUserNeedsBadging.put(userId, b);
24184            return b;
24185        }
24186        return mUserNeedsBadging.valueAt(index);
24187    }
24188
24189    @Override
24190    public KeySet getKeySetByAlias(String packageName, String alias) {
24191        if (packageName == null || alias == null) {
24192            return null;
24193        }
24194        synchronized(mPackages) {
24195            final PackageParser.Package pkg = mPackages.get(packageName);
24196            if (pkg == null) {
24197                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
24198                throw new IllegalArgumentException("Unknown package: " + packageName);
24199            }
24200            final PackageSetting ps = (PackageSetting) pkg.mExtras;
24201            if (filterAppAccessLPr(ps, Binder.getCallingUid(), UserHandle.getCallingUserId())) {
24202                Slog.w(TAG, "KeySet requested for filtered package: " + packageName);
24203                throw new IllegalArgumentException("Unknown package: " + packageName);
24204            }
24205            KeySetManagerService ksms = mSettings.mKeySetManagerService;
24206            return new KeySet(ksms.getKeySetByAliasAndPackageNameLPr(packageName, alias));
24207        }
24208    }
24209
24210    @Override
24211    public KeySet getSigningKeySet(String packageName) {
24212        if (packageName == null) {
24213            return null;
24214        }
24215        synchronized(mPackages) {
24216            final int callingUid = Binder.getCallingUid();
24217            final int callingUserId = UserHandle.getUserId(callingUid);
24218            final PackageParser.Package pkg = mPackages.get(packageName);
24219            if (pkg == null) {
24220                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
24221                throw new IllegalArgumentException("Unknown package: " + packageName);
24222            }
24223            final PackageSetting ps = (PackageSetting) pkg.mExtras;
24224            if (filterAppAccessLPr(ps, callingUid, callingUserId)) {
24225                // filter and pretend the package doesn't exist
24226                Slog.w(TAG, "KeySet requested for filtered package: " + packageName
24227                        + ", uid:" + callingUid);
24228                throw new IllegalArgumentException("Unknown package: " + packageName);
24229            }
24230            if (pkg.applicationInfo.uid != callingUid
24231                    && Process.SYSTEM_UID != callingUid) {
24232                throw new SecurityException("May not access signing KeySet of other apps.");
24233            }
24234            KeySetManagerService ksms = mSettings.mKeySetManagerService;
24235            return new KeySet(ksms.getSigningKeySetByPackageNameLPr(packageName));
24236        }
24237    }
24238
24239    @Override
24240    public boolean isPackageSignedByKeySet(String packageName, KeySet ks) {
24241        final int callingUid = Binder.getCallingUid();
24242        if (getInstantAppPackageName(callingUid) != null) {
24243            return false;
24244        }
24245        if (packageName == null || ks == null) {
24246            return false;
24247        }
24248        synchronized(mPackages) {
24249            final PackageParser.Package pkg = mPackages.get(packageName);
24250            if (pkg == null
24251                    || filterAppAccessLPr((PackageSetting) pkg.mExtras, callingUid,
24252                            UserHandle.getUserId(callingUid))) {
24253                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
24254                throw new IllegalArgumentException("Unknown package: " + packageName);
24255            }
24256            IBinder ksh = ks.getToken();
24257            if (ksh instanceof KeySetHandle) {
24258                KeySetManagerService ksms = mSettings.mKeySetManagerService;
24259                return ksms.packageIsSignedByLPr(packageName, (KeySetHandle) ksh);
24260            }
24261            return false;
24262        }
24263    }
24264
24265    @Override
24266    public boolean isPackageSignedByKeySetExactly(String packageName, KeySet ks) {
24267        final int callingUid = Binder.getCallingUid();
24268        if (getInstantAppPackageName(callingUid) != null) {
24269            return false;
24270        }
24271        if (packageName == null || ks == null) {
24272            return false;
24273        }
24274        synchronized(mPackages) {
24275            final PackageParser.Package pkg = mPackages.get(packageName);
24276            if (pkg == null
24277                    || filterAppAccessLPr((PackageSetting) pkg.mExtras, callingUid,
24278                            UserHandle.getUserId(callingUid))) {
24279                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
24280                throw new IllegalArgumentException("Unknown package: " + packageName);
24281            }
24282            IBinder ksh = ks.getToken();
24283            if (ksh instanceof KeySetHandle) {
24284                KeySetManagerService ksms = mSettings.mKeySetManagerService;
24285                return ksms.packageIsSignedByExactlyLPr(packageName, (KeySetHandle) ksh);
24286            }
24287            return false;
24288        }
24289    }
24290
24291    private void deletePackageIfUnusedLPr(final String packageName) {
24292        PackageSetting ps = mSettings.mPackages.get(packageName);
24293        if (ps == null) {
24294            return;
24295        }
24296        if (!ps.isAnyInstalled(sUserManager.getUserIds())) {
24297            // TODO Implement atomic delete if package is unused
24298            // It is currently possible that the package will be deleted even if it is installed
24299            // after this method returns.
24300            mHandler.post(new Runnable() {
24301                public void run() {
24302                    deletePackageX(packageName, PackageManager.VERSION_CODE_HIGHEST,
24303                            0, PackageManager.DELETE_ALL_USERS);
24304                }
24305            });
24306        }
24307    }
24308
24309    /**
24310     * Check and throw if the given before/after packages would be considered a
24311     * downgrade.
24312     */
24313    private static void checkDowngrade(PackageParser.Package before, PackageInfoLite after)
24314            throws PackageManagerException {
24315        if (after.versionCode < before.mVersionCode) {
24316            throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
24317                    "Update version code " + after.versionCode + " is older than current "
24318                    + before.mVersionCode);
24319        } else if (after.versionCode == before.mVersionCode) {
24320            if (after.baseRevisionCode < before.baseRevisionCode) {
24321                throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
24322                        "Update base revision code " + after.baseRevisionCode
24323                        + " is older than current " + before.baseRevisionCode);
24324            }
24325
24326            if (!ArrayUtils.isEmpty(after.splitNames)) {
24327                for (int i = 0; i < after.splitNames.length; i++) {
24328                    final String splitName = after.splitNames[i];
24329                    final int j = ArrayUtils.indexOf(before.splitNames, splitName);
24330                    if (j != -1) {
24331                        if (after.splitRevisionCodes[i] < before.splitRevisionCodes[j]) {
24332                            throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
24333                                    "Update split " + splitName + " revision code "
24334                                    + after.splitRevisionCodes[i] + " is older than current "
24335                                    + before.splitRevisionCodes[j]);
24336                        }
24337                    }
24338                }
24339            }
24340        }
24341    }
24342
24343    private static class MoveCallbacks extends Handler {
24344        private static final int MSG_CREATED = 1;
24345        private static final int MSG_STATUS_CHANGED = 2;
24346
24347        private final RemoteCallbackList<IPackageMoveObserver>
24348                mCallbacks = new RemoteCallbackList<>();
24349
24350        private final SparseIntArray mLastStatus = new SparseIntArray();
24351
24352        public MoveCallbacks(Looper looper) {
24353            super(looper);
24354        }
24355
24356        public void register(IPackageMoveObserver callback) {
24357            mCallbacks.register(callback);
24358        }
24359
24360        public void unregister(IPackageMoveObserver callback) {
24361            mCallbacks.unregister(callback);
24362        }
24363
24364        @Override
24365        public void handleMessage(Message msg) {
24366            final SomeArgs args = (SomeArgs) msg.obj;
24367            final int n = mCallbacks.beginBroadcast();
24368            for (int i = 0; i < n; i++) {
24369                final IPackageMoveObserver callback = mCallbacks.getBroadcastItem(i);
24370                try {
24371                    invokeCallback(callback, msg.what, args);
24372                } catch (RemoteException ignored) {
24373                }
24374            }
24375            mCallbacks.finishBroadcast();
24376            args.recycle();
24377        }
24378
24379        private void invokeCallback(IPackageMoveObserver callback, int what, SomeArgs args)
24380                throws RemoteException {
24381            switch (what) {
24382                case MSG_CREATED: {
24383                    callback.onCreated(args.argi1, (Bundle) args.arg2);
24384                    break;
24385                }
24386                case MSG_STATUS_CHANGED: {
24387                    callback.onStatusChanged(args.argi1, args.argi2, (long) args.arg3);
24388                    break;
24389                }
24390            }
24391        }
24392
24393        private void notifyCreated(int moveId, Bundle extras) {
24394            Slog.v(TAG, "Move " + moveId + " created " + extras.toString());
24395
24396            final SomeArgs args = SomeArgs.obtain();
24397            args.argi1 = moveId;
24398            args.arg2 = extras;
24399            obtainMessage(MSG_CREATED, args).sendToTarget();
24400        }
24401
24402        private void notifyStatusChanged(int moveId, int status) {
24403            notifyStatusChanged(moveId, status, -1);
24404        }
24405
24406        private void notifyStatusChanged(int moveId, int status, long estMillis) {
24407            Slog.v(TAG, "Move " + moveId + " status " + status);
24408
24409            final SomeArgs args = SomeArgs.obtain();
24410            args.argi1 = moveId;
24411            args.argi2 = status;
24412            args.arg3 = estMillis;
24413            obtainMessage(MSG_STATUS_CHANGED, args).sendToTarget();
24414
24415            synchronized (mLastStatus) {
24416                mLastStatus.put(moveId, status);
24417            }
24418        }
24419    }
24420
24421    private final static class OnPermissionChangeListeners extends Handler {
24422        private static final int MSG_ON_PERMISSIONS_CHANGED = 1;
24423
24424        private final RemoteCallbackList<IOnPermissionsChangeListener> mPermissionListeners =
24425                new RemoteCallbackList<>();
24426
24427        public OnPermissionChangeListeners(Looper looper) {
24428            super(looper);
24429        }
24430
24431        @Override
24432        public void handleMessage(Message msg) {
24433            switch (msg.what) {
24434                case MSG_ON_PERMISSIONS_CHANGED: {
24435                    final int uid = msg.arg1;
24436                    handleOnPermissionsChanged(uid);
24437                } break;
24438            }
24439        }
24440
24441        public void addListenerLocked(IOnPermissionsChangeListener listener) {
24442            mPermissionListeners.register(listener);
24443
24444        }
24445
24446        public void removeListenerLocked(IOnPermissionsChangeListener listener) {
24447            mPermissionListeners.unregister(listener);
24448        }
24449
24450        public void onPermissionsChanged(int uid) {
24451            if (mPermissionListeners.getRegisteredCallbackCount() > 0) {
24452                obtainMessage(MSG_ON_PERMISSIONS_CHANGED, uid, 0).sendToTarget();
24453            }
24454        }
24455
24456        private void handleOnPermissionsChanged(int uid) {
24457            final int count = mPermissionListeners.beginBroadcast();
24458            try {
24459                for (int i = 0; i < count; i++) {
24460                    IOnPermissionsChangeListener callback = mPermissionListeners
24461                            .getBroadcastItem(i);
24462                    try {
24463                        callback.onPermissionsChanged(uid);
24464                    } catch (RemoteException e) {
24465                        Log.e(TAG, "Permission listener is dead", e);
24466                    }
24467                }
24468            } finally {
24469                mPermissionListeners.finishBroadcast();
24470            }
24471        }
24472    }
24473
24474    private class PackageManagerInternalImpl extends PackageManagerInternal {
24475        @Override
24476        public void setLocationPackagesProvider(PackagesProvider provider) {
24477            synchronized (mPackages) {
24478                mDefaultPermissionPolicy.setLocationPackagesProviderLPw(provider);
24479            }
24480        }
24481
24482        @Override
24483        public void setVoiceInteractionPackagesProvider(PackagesProvider provider) {
24484            synchronized (mPackages) {
24485                mDefaultPermissionPolicy.setVoiceInteractionPackagesProviderLPw(provider);
24486            }
24487        }
24488
24489        @Override
24490        public void setSmsAppPackagesProvider(PackagesProvider provider) {
24491            synchronized (mPackages) {
24492                mDefaultPermissionPolicy.setSmsAppPackagesProviderLPw(provider);
24493            }
24494        }
24495
24496        @Override
24497        public void setDialerAppPackagesProvider(PackagesProvider provider) {
24498            synchronized (mPackages) {
24499                mDefaultPermissionPolicy.setDialerAppPackagesProviderLPw(provider);
24500            }
24501        }
24502
24503        @Override
24504        public void setSimCallManagerPackagesProvider(PackagesProvider provider) {
24505            synchronized (mPackages) {
24506                mDefaultPermissionPolicy.setSimCallManagerPackagesProviderLPw(provider);
24507            }
24508        }
24509
24510        @Override
24511        public void setSyncAdapterPackagesprovider(SyncAdapterPackagesProvider provider) {
24512            synchronized (mPackages) {
24513                mDefaultPermissionPolicy.setSyncAdapterPackagesProviderLPw(provider);
24514            }
24515        }
24516
24517        @Override
24518        public void grantDefaultPermissionsToDefaultSmsApp(String packageName, int userId) {
24519            synchronized (mPackages) {
24520                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSmsAppLPr(
24521                        packageName, userId);
24522            }
24523        }
24524
24525        @Override
24526        public void grantDefaultPermissionsToDefaultDialerApp(String packageName, int userId) {
24527            synchronized (mPackages) {
24528                mSettings.setDefaultDialerPackageNameLPw(packageName, userId);
24529                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultDialerAppLPr(
24530                        packageName, userId);
24531            }
24532        }
24533
24534        @Override
24535        public void grantDefaultPermissionsToDefaultSimCallManager(String packageName, int userId) {
24536            synchronized (mPackages) {
24537                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSimCallManagerLPr(
24538                        packageName, userId);
24539            }
24540        }
24541
24542        @Override
24543        public void setKeepUninstalledPackages(final List<String> packageList) {
24544            Preconditions.checkNotNull(packageList);
24545            List<String> removedFromList = null;
24546            synchronized (mPackages) {
24547                if (mKeepUninstalledPackages != null) {
24548                    final int packagesCount = mKeepUninstalledPackages.size();
24549                    for (int i = 0; i < packagesCount; i++) {
24550                        String oldPackage = mKeepUninstalledPackages.get(i);
24551                        if (packageList != null && packageList.contains(oldPackage)) {
24552                            continue;
24553                        }
24554                        if (removedFromList == null) {
24555                            removedFromList = new ArrayList<>();
24556                        }
24557                        removedFromList.add(oldPackage);
24558                    }
24559                }
24560                mKeepUninstalledPackages = new ArrayList<>(packageList);
24561                if (removedFromList != null) {
24562                    final int removedCount = removedFromList.size();
24563                    for (int i = 0; i < removedCount; i++) {
24564                        deletePackageIfUnusedLPr(removedFromList.get(i));
24565                    }
24566                }
24567            }
24568        }
24569
24570        @Override
24571        public boolean isPermissionsReviewRequired(String packageName, int userId) {
24572            synchronized (mPackages) {
24573                // If we do not support permission review, done.
24574                if (!mPermissionReviewRequired) {
24575                    return false;
24576                }
24577
24578                PackageSetting packageSetting = mSettings.mPackages.get(packageName);
24579                if (packageSetting == null) {
24580                    return false;
24581                }
24582
24583                // Permission review applies only to apps not supporting the new permission model.
24584                if (packageSetting.pkg.applicationInfo.targetSdkVersion >= Build.VERSION_CODES.M) {
24585                    return false;
24586                }
24587
24588                // Legacy apps have the permission and get user consent on launch.
24589                PermissionsState permissionsState = packageSetting.getPermissionsState();
24590                return permissionsState.isPermissionReviewRequired(userId);
24591            }
24592        }
24593
24594        @Override
24595        public PackageInfo getPackageInfo(
24596                String packageName, int flags, int filterCallingUid, int userId) {
24597            return PackageManagerService.this
24598                    .getPackageInfoInternal(packageName, PackageManager.VERSION_CODE_HIGHEST,
24599                            flags, filterCallingUid, userId);
24600        }
24601
24602        @Override
24603        public ApplicationInfo getApplicationInfo(
24604                String packageName, int flags, int filterCallingUid, int userId) {
24605            return PackageManagerService.this
24606                    .getApplicationInfoInternal(packageName, flags, filterCallingUid, userId);
24607        }
24608
24609        @Override
24610        public ActivityInfo getActivityInfo(
24611                ComponentName component, int flags, int filterCallingUid, int userId) {
24612            return PackageManagerService.this
24613                    .getActivityInfoInternal(component, flags, filterCallingUid, userId);
24614        }
24615
24616        @Override
24617        public List<ResolveInfo> queryIntentActivities(
24618                Intent intent, int flags, int filterCallingUid, int userId) {
24619            final String resolvedType = intent.resolveTypeIfNeeded(mContext.getContentResolver());
24620            return PackageManagerService.this
24621                    .queryIntentActivitiesInternal(intent, resolvedType, flags, filterCallingUid,
24622                            userId, false /*resolveForStart*/);
24623        }
24624
24625        @Override
24626        public ComponentName getHomeActivitiesAsUser(List<ResolveInfo> allHomeCandidates,
24627                int userId) {
24628            return PackageManagerService.this.getHomeActivitiesAsUser(allHomeCandidates, userId);
24629        }
24630
24631        @Override
24632        public void setDeviceAndProfileOwnerPackages(
24633                int deviceOwnerUserId, String deviceOwnerPackage,
24634                SparseArray<String> profileOwnerPackages) {
24635            mProtectedPackages.setDeviceAndProfileOwnerPackages(
24636                    deviceOwnerUserId, deviceOwnerPackage, profileOwnerPackages);
24637        }
24638
24639        @Override
24640        public boolean isPackageDataProtected(int userId, String packageName) {
24641            return mProtectedPackages.isPackageDataProtected(userId, packageName);
24642        }
24643
24644        @Override
24645        public boolean isPackageEphemeral(int userId, String packageName) {
24646            synchronized (mPackages) {
24647                final PackageSetting ps = mSettings.mPackages.get(packageName);
24648                return ps != null ? ps.getInstantApp(userId) : false;
24649            }
24650        }
24651
24652        @Override
24653        public boolean wasPackageEverLaunched(String packageName, int userId) {
24654            synchronized (mPackages) {
24655                return mSettings.wasPackageEverLaunchedLPr(packageName, userId);
24656            }
24657        }
24658
24659        @Override
24660        public void grantRuntimePermission(String packageName, String name, int userId,
24661                boolean overridePolicy) {
24662            PackageManagerService.this.grantRuntimePermission(packageName, name, userId,
24663                    overridePolicy);
24664        }
24665
24666        @Override
24667        public void revokeRuntimePermission(String packageName, String name, int userId,
24668                boolean overridePolicy) {
24669            PackageManagerService.this.revokeRuntimePermission(packageName, name, userId,
24670                    overridePolicy);
24671        }
24672
24673        @Override
24674        public String getNameForUid(int uid) {
24675            return PackageManagerService.this.getNameForUid(uid);
24676        }
24677
24678        @Override
24679        public void requestInstantAppResolutionPhaseTwo(AuxiliaryResolveInfo responseObj,
24680                Intent origIntent, String resolvedType, String callingPackage,
24681                Bundle verificationBundle, int userId) {
24682            PackageManagerService.this.requestInstantAppResolutionPhaseTwo(
24683                    responseObj, origIntent, resolvedType, callingPackage, verificationBundle,
24684                    userId);
24685        }
24686
24687        @Override
24688        public void grantEphemeralAccess(int userId, Intent intent,
24689                int targetAppId, int ephemeralAppId) {
24690            synchronized (mPackages) {
24691                mInstantAppRegistry.grantInstantAccessLPw(userId, intent,
24692                        targetAppId, ephemeralAppId);
24693            }
24694        }
24695
24696        @Override
24697        public boolean isInstantAppInstallerComponent(ComponentName component) {
24698            synchronized (mPackages) {
24699                return mInstantAppInstallerActivity != null
24700                        && mInstantAppInstallerActivity.getComponentName().equals(component);
24701            }
24702        }
24703
24704        @Override
24705        public void pruneInstantApps() {
24706            mInstantAppRegistry.pruneInstantApps();
24707        }
24708
24709        @Override
24710        public String getSetupWizardPackageName() {
24711            return mSetupWizardPackage;
24712        }
24713
24714        public void setExternalSourcesPolicy(ExternalSourcesPolicy policy) {
24715            if (policy != null) {
24716                mExternalSourcesPolicy = policy;
24717            }
24718        }
24719
24720        @Override
24721        public boolean isPackagePersistent(String packageName) {
24722            synchronized (mPackages) {
24723                PackageParser.Package pkg = mPackages.get(packageName);
24724                return pkg != null
24725                        ? ((pkg.applicationInfo.flags&(ApplicationInfo.FLAG_SYSTEM
24726                                        | ApplicationInfo.FLAG_PERSISTENT)) ==
24727                                (ApplicationInfo.FLAG_SYSTEM | ApplicationInfo.FLAG_PERSISTENT))
24728                        : false;
24729            }
24730        }
24731
24732        @Override
24733        public List<PackageInfo> getOverlayPackages(int userId) {
24734            final ArrayList<PackageInfo> overlayPackages = new ArrayList<PackageInfo>();
24735            synchronized (mPackages) {
24736                for (PackageParser.Package p : mPackages.values()) {
24737                    if (p.mOverlayTarget != null) {
24738                        PackageInfo pkg = generatePackageInfo((PackageSetting)p.mExtras, 0, userId);
24739                        if (pkg != null) {
24740                            overlayPackages.add(pkg);
24741                        }
24742                    }
24743                }
24744            }
24745            return overlayPackages;
24746        }
24747
24748        @Override
24749        public List<String> getTargetPackageNames(int userId) {
24750            List<String> targetPackages = new ArrayList<>();
24751            synchronized (mPackages) {
24752                for (PackageParser.Package p : mPackages.values()) {
24753                    if (p.mOverlayTarget == null) {
24754                        targetPackages.add(p.packageName);
24755                    }
24756                }
24757            }
24758            return targetPackages;
24759        }
24760
24761        @Override
24762        public boolean setEnabledOverlayPackages(int userId, @NonNull String targetPackageName,
24763                @Nullable List<String> overlayPackageNames) {
24764            synchronized (mPackages) {
24765                if (targetPackageName == null || mPackages.get(targetPackageName) == null) {
24766                    Slog.e(TAG, "failed to find package " + targetPackageName);
24767                    return false;
24768                }
24769                ArrayList<String> overlayPaths = null;
24770                if (overlayPackageNames != null && overlayPackageNames.size() > 0) {
24771                    final int N = overlayPackageNames.size();
24772                    overlayPaths = new ArrayList<>(N);
24773                    for (int i = 0; i < N; i++) {
24774                        final String packageName = overlayPackageNames.get(i);
24775                        final PackageParser.Package pkg = mPackages.get(packageName);
24776                        if (pkg == null) {
24777                            Slog.e(TAG, "failed to find package " + packageName);
24778                            return false;
24779                        }
24780                        overlayPaths.add(pkg.baseCodePath);
24781                    }
24782                }
24783
24784                final PackageSetting ps = mSettings.mPackages.get(targetPackageName);
24785                ps.setOverlayPaths(overlayPaths, userId);
24786                return true;
24787            }
24788        }
24789
24790        @Override
24791        public ResolveInfo resolveIntent(Intent intent, String resolvedType,
24792                int flags, int userId) {
24793            return resolveIntentInternal(
24794                    intent, resolvedType, flags, userId, true /*resolveForStart*/);
24795        }
24796
24797        @Override
24798        public ResolveInfo resolveService(Intent intent, String resolvedType,
24799                int flags, int userId, int callingUid) {
24800            return resolveServiceInternal(intent, resolvedType, flags, userId, callingUid);
24801        }
24802
24803        @Override
24804        public void addIsolatedUid(int isolatedUid, int ownerUid) {
24805            synchronized (mPackages) {
24806                mIsolatedOwners.put(isolatedUid, ownerUid);
24807            }
24808        }
24809
24810        @Override
24811        public void removeIsolatedUid(int isolatedUid) {
24812            synchronized (mPackages) {
24813                mIsolatedOwners.delete(isolatedUid);
24814            }
24815        }
24816
24817        @Override
24818        public int getUidTargetSdkVersion(int uid) {
24819            synchronized (mPackages) {
24820                return getUidTargetSdkVersionLockedLPr(uid);
24821            }
24822        }
24823
24824        @Override
24825        public boolean canAccessInstantApps(int callingUid, int userId) {
24826            return PackageManagerService.this.canViewInstantApps(callingUid, userId);
24827        }
24828    }
24829
24830    @Override
24831    public void grantDefaultPermissionsToEnabledCarrierApps(String[] packageNames, int userId) {
24832        enforceSystemOrPhoneCaller("grantPermissionsToEnabledCarrierApps");
24833        synchronized (mPackages) {
24834            final long identity = Binder.clearCallingIdentity();
24835            try {
24836                mDefaultPermissionPolicy.grantDefaultPermissionsToEnabledCarrierAppsLPr(
24837                        packageNames, userId);
24838            } finally {
24839                Binder.restoreCallingIdentity(identity);
24840            }
24841        }
24842    }
24843
24844    @Override
24845    public void grantDefaultPermissionsToEnabledImsServices(String[] packageNames, int userId) {
24846        enforceSystemOrPhoneCaller("grantDefaultPermissionsToEnabledImsServices");
24847        synchronized (mPackages) {
24848            final long identity = Binder.clearCallingIdentity();
24849            try {
24850                mDefaultPermissionPolicy.grantDefaultPermissionsToEnabledImsServicesLPr(
24851                        packageNames, userId);
24852            } finally {
24853                Binder.restoreCallingIdentity(identity);
24854            }
24855        }
24856    }
24857
24858    private static void enforceSystemOrPhoneCaller(String tag) {
24859        int callingUid = Binder.getCallingUid();
24860        if (callingUid != Process.PHONE_UID && callingUid != Process.SYSTEM_UID) {
24861            throw new SecurityException(
24862                    "Cannot call " + tag + " from UID " + callingUid);
24863        }
24864    }
24865
24866    boolean isHistoricalPackageUsageAvailable() {
24867        return mPackageUsage.isHistoricalPackageUsageAvailable();
24868    }
24869
24870    /**
24871     * Return a <b>copy</b> of the collection of packages known to the package manager.
24872     * @return A copy of the values of mPackages.
24873     */
24874    Collection<PackageParser.Package> getPackages() {
24875        synchronized (mPackages) {
24876            return new ArrayList<>(mPackages.values());
24877        }
24878    }
24879
24880    /**
24881     * Logs process start information (including base APK hash) to the security log.
24882     * @hide
24883     */
24884    @Override
24885    public void logAppProcessStartIfNeeded(String processName, int uid, String seinfo,
24886            String apkFile, int pid) {
24887        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
24888            return;
24889        }
24890        if (!SecurityLog.isLoggingEnabled()) {
24891            return;
24892        }
24893        Bundle data = new Bundle();
24894        data.putLong("startTimestamp", System.currentTimeMillis());
24895        data.putString("processName", processName);
24896        data.putInt("uid", uid);
24897        data.putString("seinfo", seinfo);
24898        data.putString("apkFile", apkFile);
24899        data.putInt("pid", pid);
24900        Message msg = mProcessLoggingHandler.obtainMessage(
24901                ProcessLoggingHandler.LOG_APP_PROCESS_START_MSG);
24902        msg.setData(data);
24903        mProcessLoggingHandler.sendMessage(msg);
24904    }
24905
24906    public CompilerStats.PackageStats getCompilerPackageStats(String pkgName) {
24907        return mCompilerStats.getPackageStats(pkgName);
24908    }
24909
24910    public CompilerStats.PackageStats getOrCreateCompilerPackageStats(PackageParser.Package pkg) {
24911        return getOrCreateCompilerPackageStats(pkg.packageName);
24912    }
24913
24914    public CompilerStats.PackageStats getOrCreateCompilerPackageStats(String pkgName) {
24915        return mCompilerStats.getOrCreatePackageStats(pkgName);
24916    }
24917
24918    public void deleteCompilerPackageStats(String pkgName) {
24919        mCompilerStats.deletePackageStats(pkgName);
24920    }
24921
24922    @Override
24923    public int getInstallReason(String packageName, int userId) {
24924        final int callingUid = Binder.getCallingUid();
24925        enforceCrossUserPermission(callingUid, userId,
24926                true /* requireFullPermission */, false /* checkShell */,
24927                "get install reason");
24928        synchronized (mPackages) {
24929            final PackageSetting ps = mSettings.mPackages.get(packageName);
24930            if (filterAppAccessLPr(ps, callingUid, userId)) {
24931                return PackageManager.INSTALL_REASON_UNKNOWN;
24932            }
24933            if (ps != null) {
24934                return ps.getInstallReason(userId);
24935            }
24936        }
24937        return PackageManager.INSTALL_REASON_UNKNOWN;
24938    }
24939
24940    @Override
24941    public boolean canRequestPackageInstalls(String packageName, int userId) {
24942        return canRequestPackageInstallsInternal(packageName, 0, userId,
24943                true /* throwIfPermNotDeclared*/);
24944    }
24945
24946    private boolean canRequestPackageInstallsInternal(String packageName, int flags, int userId,
24947            boolean throwIfPermNotDeclared) {
24948        int callingUid = Binder.getCallingUid();
24949        int uid = getPackageUid(packageName, 0, userId);
24950        if (callingUid != uid && callingUid != Process.ROOT_UID
24951                && callingUid != Process.SYSTEM_UID) {
24952            throw new SecurityException(
24953                    "Caller uid " + callingUid + " does not own package " + packageName);
24954        }
24955        ApplicationInfo info = getApplicationInfo(packageName, flags, userId);
24956        if (info == null) {
24957            return false;
24958        }
24959        if (info.targetSdkVersion < Build.VERSION_CODES.O) {
24960            return false;
24961        }
24962        String appOpPermission = Manifest.permission.REQUEST_INSTALL_PACKAGES;
24963        String[] packagesDeclaringPermission = getAppOpPermissionPackages(appOpPermission);
24964        if (!ArrayUtils.contains(packagesDeclaringPermission, packageName)) {
24965            if (throwIfPermNotDeclared) {
24966                throw new SecurityException("Need to declare " + appOpPermission
24967                        + " to call this api");
24968            } else {
24969                Slog.e(TAG, "Need to declare " + appOpPermission + " to call this api");
24970                return false;
24971            }
24972        }
24973        if (sUserManager.hasUserRestriction(UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES, userId)) {
24974            return false;
24975        }
24976        if (mExternalSourcesPolicy != null) {
24977            int isTrusted = mExternalSourcesPolicy.getPackageTrustedToInstallApps(packageName, uid);
24978            if (isTrusted != PackageManagerInternal.ExternalSourcesPolicy.USER_DEFAULT) {
24979                return isTrusted == PackageManagerInternal.ExternalSourcesPolicy.USER_TRUSTED;
24980            }
24981        }
24982        return checkUidPermission(appOpPermission, uid) == PERMISSION_GRANTED;
24983    }
24984
24985    @Override
24986    public ComponentName getInstantAppResolverSettingsComponent() {
24987        return mInstantAppResolverSettingsComponent;
24988    }
24989
24990    @Override
24991    public ComponentName getInstantAppInstallerComponent() {
24992        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
24993            return null;
24994        }
24995        return mInstantAppInstallerActivity == null
24996                ? null : mInstantAppInstallerActivity.getComponentName();
24997    }
24998
24999    @Override
25000    public String getInstantAppAndroidId(String packageName, int userId) {
25001        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.ACCESS_INSTANT_APPS,
25002                "getInstantAppAndroidId");
25003        enforceCrossUserPermission(Binder.getCallingUid(), userId,
25004                true /* requireFullPermission */, false /* checkShell */,
25005                "getInstantAppAndroidId");
25006        // Make sure the target is an Instant App.
25007        if (!isInstantApp(packageName, userId)) {
25008            return null;
25009        }
25010        synchronized (mPackages) {
25011            return mInstantAppRegistry.getInstantAppAndroidIdLPw(packageName, userId);
25012        }
25013    }
25014
25015    boolean canHaveOatDir(String packageName) {
25016        synchronized (mPackages) {
25017            PackageParser.Package p = mPackages.get(packageName);
25018            if (p == null) {
25019                return false;
25020            }
25021            return p.canHaveOatDir();
25022        }
25023    }
25024
25025    private String getOatDir(PackageParser.Package pkg) {
25026        if (!pkg.canHaveOatDir()) {
25027            return null;
25028        }
25029        File codePath = new File(pkg.codePath);
25030        if (codePath.isDirectory()) {
25031            return PackageDexOptimizer.getOatDir(codePath).getAbsolutePath();
25032        }
25033        return null;
25034    }
25035
25036    void deleteOatArtifactsOfPackage(String packageName) {
25037        final String[] instructionSets;
25038        final List<String> codePaths;
25039        final String oatDir;
25040        final PackageParser.Package pkg;
25041        synchronized (mPackages) {
25042            pkg = mPackages.get(packageName);
25043        }
25044        instructionSets = getAppDexInstructionSets(pkg.applicationInfo);
25045        codePaths = pkg.getAllCodePaths();
25046        oatDir = getOatDir(pkg);
25047
25048        for (String codePath : codePaths) {
25049            for (String isa : instructionSets) {
25050                try {
25051                    mInstaller.deleteOdex(codePath, isa, oatDir);
25052                } catch (InstallerException e) {
25053                    Log.e(TAG, "Failed deleting oat files for " + codePath, e);
25054                }
25055            }
25056        }
25057    }
25058
25059    Set<String> getUnusedPackages(long downgradeTimeThresholdMillis) {
25060        Set<String> unusedPackages = new HashSet<>();
25061        long currentTimeInMillis = System.currentTimeMillis();
25062        synchronized (mPackages) {
25063            for (PackageParser.Package pkg : mPackages.values()) {
25064                PackageSetting ps =  mSettings.mPackages.get(pkg.packageName);
25065                if (ps == null) {
25066                    continue;
25067                }
25068                PackageDexUsage.PackageUseInfo packageUseInfo = getDexManager().getPackageUseInfo(
25069                        pkg.packageName);
25070                if (PackageManagerServiceUtils
25071                        .isUnusedSinceTimeInMillis(ps.firstInstallTime, currentTimeInMillis,
25072                                downgradeTimeThresholdMillis, packageUseInfo,
25073                                pkg.getLatestPackageUseTimeInMills(),
25074                                pkg.getLatestForegroundPackageUseTimeInMills())) {
25075                    unusedPackages.add(pkg.packageName);
25076                }
25077            }
25078        }
25079        return unusedPackages;
25080    }
25081}
25082
25083interface PackageSender {
25084    void sendPackageBroadcast(final String action, final String pkg,
25085        final Bundle extras, final int flags, final String targetPkg,
25086        final IIntentReceiver finishedReceiver, final int[] userIds);
25087    void sendPackageAddedForNewUsers(String packageName, boolean isSystem,
25088        int appId, int... userIds);
25089}
25090