PackageManagerService.java revision a65e6491e4aa90611045ecf696db4bf3328d09bc
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.storage.DeviceStorageMonitorInternal;
287
288import dalvik.system.CloseGuard;
289import dalvik.system.DexFile;
290import dalvik.system.VMRuntime;
291
292import libcore.io.IoUtils;
293import libcore.util.EmptyArray;
294
295import org.xmlpull.v1.XmlPullParser;
296import org.xmlpull.v1.XmlPullParserException;
297import org.xmlpull.v1.XmlSerializer;
298
299import java.io.BufferedOutputStream;
300import java.io.BufferedReader;
301import java.io.ByteArrayInputStream;
302import java.io.ByteArrayOutputStream;
303import java.io.File;
304import java.io.FileDescriptor;
305import java.io.FileInputStream;
306import java.io.FileOutputStream;
307import java.io.FileReader;
308import java.io.FilenameFilter;
309import java.io.IOException;
310import java.io.PrintWriter;
311import java.lang.annotation.Retention;
312import java.lang.annotation.RetentionPolicy;
313import java.nio.charset.StandardCharsets;
314import java.security.DigestInputStream;
315import java.security.MessageDigest;
316import java.security.NoSuchAlgorithmException;
317import java.security.PublicKey;
318import java.security.SecureRandom;
319import java.security.cert.Certificate;
320import java.security.cert.CertificateEncodingException;
321import java.security.cert.CertificateException;
322import java.text.SimpleDateFormat;
323import java.util.ArrayList;
324import java.util.Arrays;
325import java.util.Collection;
326import java.util.Collections;
327import java.util.Comparator;
328import java.util.Date;
329import java.util.HashMap;
330import java.util.HashSet;
331import java.util.Iterator;
332import java.util.List;
333import java.util.Map;
334import java.util.Objects;
335import java.util.Set;
336import java.util.concurrent.CountDownLatch;
337import java.util.concurrent.Future;
338import java.util.concurrent.TimeUnit;
339import java.util.concurrent.atomic.AtomicBoolean;
340import java.util.concurrent.atomic.AtomicInteger;
341
342/**
343 * Keep track of all those APKs everywhere.
344 * <p>
345 * Internally there are two important locks:
346 * <ul>
347 * <li>{@link #mPackages} is used to guard all in-memory parsed package details
348 * and other related state. It is a fine-grained lock that should only be held
349 * momentarily, as it's one of the most contended locks in the system.
350 * <li>{@link #mInstallLock} is used to guard all {@code installd} access, whose
351 * operations typically involve heavy lifting of application data on disk. Since
352 * {@code installd} is single-threaded, and it's operations can often be slow,
353 * this lock should never be acquired while already holding {@link #mPackages}.
354 * Conversely, it's safe to acquire {@link #mPackages} momentarily while already
355 * holding {@link #mInstallLock}.
356 * </ul>
357 * Many internal methods rely on the caller to hold the appropriate locks, and
358 * this contract is expressed through method name suffixes:
359 * <ul>
360 * <li>fooLI(): the caller must hold {@link #mInstallLock}
361 * <li>fooLIF(): the caller must hold {@link #mInstallLock} and the package
362 * being modified must be frozen
363 * <li>fooLPr(): the caller must hold {@link #mPackages} for reading
364 * <li>fooLPw(): the caller must hold {@link #mPackages} for writing
365 * </ul>
366 * <p>
367 * Because this class is very central to the platform's security; please run all
368 * CTS and unit tests whenever making modifications:
369 *
370 * <pre>
371 * $ runtest -c android.content.pm.PackageManagerTests frameworks-core
372 * $ cts-tradefed run commandAndExit cts -m CtsAppSecurityHostTestCases
373 * </pre>
374 */
375public class PackageManagerService extends IPackageManager.Stub
376        implements PackageSender {
377    static final String TAG = "PackageManager";
378    static final boolean DEBUG_SETTINGS = false;
379    static final boolean DEBUG_PREFERRED = false;
380    static final boolean DEBUG_UPGRADE = false;
381    static final boolean DEBUG_DOMAIN_VERIFICATION = false;
382    private static final boolean DEBUG_BACKUP = false;
383    private static final boolean DEBUG_INSTALL = false;
384    private static final boolean DEBUG_REMOVE = false;
385    private static final boolean DEBUG_BROADCASTS = false;
386    private static final boolean DEBUG_SHOW_INFO = false;
387    private static final boolean DEBUG_PACKAGE_INFO = false;
388    private static final boolean DEBUG_INTENT_MATCHING = false;
389    private static final boolean DEBUG_PACKAGE_SCANNING = false;
390    private static final boolean DEBUG_VERIFY = false;
391    private static final boolean DEBUG_FILTERS = false;
392    private static final boolean DEBUG_PERMISSIONS = false;
393    private static final boolean DEBUG_SHARED_LIBRARIES = false;
394
395    // Debug output for dexopting. This is shared between PackageManagerService, OtaDexoptService
396    // and PackageDexOptimizer. All these classes have their own flag to allow switching a single
397    // user, but by default initialize to this.
398    public static final boolean DEBUG_DEXOPT = false;
399
400    private static final boolean DEBUG_ABI_SELECTION = false;
401    private static final boolean DEBUG_EPHEMERAL = Build.IS_DEBUGGABLE;
402    private static final boolean DEBUG_TRIAGED_MISSING = false;
403    private static final boolean DEBUG_APP_DATA = false;
404
405    /** REMOVE. According to Svet, this was only used to reset permissions during development. */
406    static final boolean CLEAR_RUNTIME_PERMISSIONS_ON_UPGRADE = false;
407
408    private static final boolean HIDE_EPHEMERAL_APIS = false;
409
410    private static final boolean ENABLE_FREE_CACHE_V2 =
411            SystemProperties.getBoolean("fw.free_cache_v2", true);
412
413    private static final int RADIO_UID = Process.PHONE_UID;
414    private static final int LOG_UID = Process.LOG_UID;
415    private static final int NFC_UID = Process.NFC_UID;
416    private static final int BLUETOOTH_UID = Process.BLUETOOTH_UID;
417    private static final int SHELL_UID = Process.SHELL_UID;
418
419    // Cap the size of permission trees that 3rd party apps can define
420    private static final int MAX_PERMISSION_TREE_FOOTPRINT = 32768;     // characters of text
421
422    // Suffix used during package installation when copying/moving
423    // package apks to install directory.
424    private static final String INSTALL_PACKAGE_SUFFIX = "-";
425
426    static final int SCAN_NO_DEX = 1<<1;
427    static final int SCAN_FORCE_DEX = 1<<2;
428    static final int SCAN_UPDATE_SIGNATURE = 1<<3;
429    static final int SCAN_NEW_INSTALL = 1<<4;
430    static final int SCAN_UPDATE_TIME = 1<<5;
431    static final int SCAN_BOOTING = 1<<6;
432    static final int SCAN_TRUSTED_OVERLAY = 1<<7;
433    static final int SCAN_DELETE_DATA_ON_FAILURES = 1<<8;
434    static final int SCAN_REPLACING = 1<<9;
435    static final int SCAN_REQUIRE_KNOWN = 1<<10;
436    static final int SCAN_MOVE = 1<<11;
437    static final int SCAN_INITIAL = 1<<12;
438    static final int SCAN_CHECK_ONLY = 1<<13;
439    static final int SCAN_DONT_KILL_APP = 1<<14;
440    static final int SCAN_IGNORE_FROZEN = 1<<15;
441    static final int SCAN_FIRST_BOOT_OR_UPGRADE = 1<<16;
442    static final int SCAN_AS_INSTANT_APP = 1<<17;
443    static final int SCAN_AS_FULL_APP = 1<<18;
444    /** Should not be with the scan flags */
445    static final int FLAGS_REMOVE_CHATTY = 1<<31;
446
447    private static final String STATIC_SHARED_LIB_DELIMITER = "_";
448
449    private static final int[] EMPTY_INT_ARRAY = new int[0];
450
451    private static final int TYPE_UNKNOWN = 0;
452    private static final int TYPE_ACTIVITY = 1;
453    private static final int TYPE_RECEIVER = 2;
454    private static final int TYPE_SERVICE = 3;
455    private static final int TYPE_PROVIDER = 4;
456    @IntDef(prefix = { "TYPE_" }, value = {
457            TYPE_UNKNOWN,
458            TYPE_ACTIVITY,
459            TYPE_RECEIVER,
460            TYPE_SERVICE,
461            TYPE_PROVIDER,
462    })
463    @Retention(RetentionPolicy.SOURCE)
464    public @interface ComponentType {}
465
466    /**
467     * Timeout (in milliseconds) after which the watchdog should declare that
468     * our handler thread is wedged.  The usual default for such things is one
469     * minute but we sometimes do very lengthy I/O operations on this thread,
470     * such as installing multi-gigabyte applications, so ours needs to be longer.
471     */
472    static final long WATCHDOG_TIMEOUT = 1000*60*10;     // ten minutes
473
474    /**
475     * Wall-clock timeout (in milliseconds) after which we *require* that an fstrim
476     * be run on this device.  We use the value in the Settings.Global.MANDATORY_FSTRIM_INTERVAL
477     * settings entry if available, otherwise we use the hardcoded default.  If it's been
478     * more than this long since the last fstrim, we force one during the boot sequence.
479     *
480     * This backstops other fstrim scheduling:  if the device is alive at midnight+idle,
481     * one gets run at the next available charging+idle time.  This final mandatory
482     * no-fstrim check kicks in only of the other scheduling criteria is never met.
483     */
484    private static final long DEFAULT_MANDATORY_FSTRIM_INTERVAL = 3 * DateUtils.DAY_IN_MILLIS;
485
486    /**
487     * Whether verification is enabled by default.
488     */
489    private static final boolean DEFAULT_VERIFY_ENABLE = true;
490
491    /**
492     * The default maximum time to wait for the verification agent to return in
493     * milliseconds.
494     */
495    private static final long DEFAULT_VERIFICATION_TIMEOUT = 10 * 1000;
496
497    /**
498     * The default response for package verification timeout.
499     *
500     * This can be either PackageManager.VERIFICATION_ALLOW or
501     * PackageManager.VERIFICATION_REJECT.
502     */
503    private static final int DEFAULT_VERIFICATION_RESPONSE = PackageManager.VERIFICATION_ALLOW;
504
505    static final String PLATFORM_PACKAGE_NAME = "android";
506
507    static final String DEFAULT_CONTAINER_PACKAGE = "com.android.defcontainer";
508
509    static final ComponentName DEFAULT_CONTAINER_COMPONENT = new ComponentName(
510            DEFAULT_CONTAINER_PACKAGE,
511            "com.android.defcontainer.DefaultContainerService");
512
513    private static final String KILL_APP_REASON_GIDS_CHANGED =
514            "permission grant or revoke changed gids";
515
516    private static final String KILL_APP_REASON_PERMISSIONS_REVOKED =
517            "permissions revoked";
518
519    private static final String PACKAGE_MIME_TYPE = "application/vnd.android.package-archive";
520
521    private static final String PACKAGE_SCHEME = "package";
522
523    private static final String VENDOR_OVERLAY_DIR = "/vendor/overlay";
524
525    /** Permission grant: not grant the permission. */
526    private static final int GRANT_DENIED = 1;
527
528    /** Permission grant: grant the permission as an install permission. */
529    private static final int GRANT_INSTALL = 2;
530
531    /** Permission grant: grant the permission as a runtime one. */
532    private static final int GRANT_RUNTIME = 3;
533
534    /** Permission grant: grant as runtime a permission that was granted as an install time one. */
535    private static final int GRANT_UPGRADE = 4;
536
537    /** Canonical intent used to identify what counts as a "web browser" app */
538    private static final Intent sBrowserIntent;
539    static {
540        sBrowserIntent = new Intent();
541        sBrowserIntent.setAction(Intent.ACTION_VIEW);
542        sBrowserIntent.addCategory(Intent.CATEGORY_BROWSABLE);
543        sBrowserIntent.setData(Uri.parse("http:"));
544    }
545
546    /**
547     * The set of all protected actions [i.e. those actions for which a high priority
548     * intent filter is disallowed].
549     */
550    private static final Set<String> PROTECTED_ACTIONS = new ArraySet<>();
551    static {
552        PROTECTED_ACTIONS.add(Intent.ACTION_SEND);
553        PROTECTED_ACTIONS.add(Intent.ACTION_SENDTO);
554        PROTECTED_ACTIONS.add(Intent.ACTION_SEND_MULTIPLE);
555        PROTECTED_ACTIONS.add(Intent.ACTION_VIEW);
556    }
557
558    // Compilation reasons.
559    public static final int REASON_FIRST_BOOT = 0;
560    public static final int REASON_BOOT = 1;
561    public static final int REASON_INSTALL = 2;
562    public static final int REASON_BACKGROUND_DEXOPT = 3;
563    public static final int REASON_AB_OTA = 4;
564
565    public static final int REASON_LAST = REASON_AB_OTA;
566
567    /** All dangerous permission names in the same order as the events in MetricsEvent */
568    private static final List<String> ALL_DANGEROUS_PERMISSIONS = Arrays.asList(
569            Manifest.permission.READ_CALENDAR,
570            Manifest.permission.WRITE_CALENDAR,
571            Manifest.permission.CAMERA,
572            Manifest.permission.READ_CONTACTS,
573            Manifest.permission.WRITE_CONTACTS,
574            Manifest.permission.GET_ACCOUNTS,
575            Manifest.permission.ACCESS_FINE_LOCATION,
576            Manifest.permission.ACCESS_COARSE_LOCATION,
577            Manifest.permission.RECORD_AUDIO,
578            Manifest.permission.READ_PHONE_STATE,
579            Manifest.permission.CALL_PHONE,
580            Manifest.permission.READ_CALL_LOG,
581            Manifest.permission.WRITE_CALL_LOG,
582            Manifest.permission.ADD_VOICEMAIL,
583            Manifest.permission.USE_SIP,
584            Manifest.permission.PROCESS_OUTGOING_CALLS,
585            Manifest.permission.READ_CELL_BROADCASTS,
586            Manifest.permission.BODY_SENSORS,
587            Manifest.permission.SEND_SMS,
588            Manifest.permission.RECEIVE_SMS,
589            Manifest.permission.READ_SMS,
590            Manifest.permission.RECEIVE_WAP_PUSH,
591            Manifest.permission.RECEIVE_MMS,
592            Manifest.permission.READ_EXTERNAL_STORAGE,
593            Manifest.permission.WRITE_EXTERNAL_STORAGE,
594            Manifest.permission.READ_PHONE_NUMBERS,
595            Manifest.permission.ANSWER_PHONE_CALLS);
596
597
598    /**
599     * Version number for the package parser cache. Increment this whenever the format or
600     * extent of cached data changes. See {@code PackageParser#setCacheDir}.
601     */
602    private static final String PACKAGE_PARSER_CACHE_VERSION = "1";
603
604    /**
605     * Whether the package parser cache is enabled.
606     */
607    private static final boolean DEFAULT_PACKAGE_PARSER_CACHE_ENABLED = true;
608
609    final ServiceThread mHandlerThread;
610
611    final PackageHandler mHandler;
612
613    private final ProcessLoggingHandler mProcessLoggingHandler;
614
615    /**
616     * Messages for {@link #mHandler} that need to wait for system ready before
617     * being dispatched.
618     */
619    private ArrayList<Message> mPostSystemReadyMessages;
620
621    final int mSdkVersion = Build.VERSION.SDK_INT;
622
623    final Context mContext;
624    final boolean mFactoryTest;
625    final boolean mOnlyCore;
626    final DisplayMetrics mMetrics;
627    final int mDefParseFlags;
628    final String[] mSeparateProcesses;
629    final boolean mIsUpgrade;
630    final boolean mIsPreNUpgrade;
631    final boolean mIsPreNMR1Upgrade;
632
633    // Have we told the Activity Manager to whitelist the default container service by uid yet?
634    @GuardedBy("mPackages")
635    boolean mDefaultContainerWhitelisted = false;
636
637    @GuardedBy("mPackages")
638    private boolean mDexOptDialogShown;
639
640    /** The location for ASEC container files on internal storage. */
641    final String mAsecInternalPath;
642
643    // Used for privilege escalation. MUST NOT BE CALLED WITH mPackages
644    // LOCK HELD.  Can be called with mInstallLock held.
645    @GuardedBy("mInstallLock")
646    final Installer mInstaller;
647
648    /** Directory where installed third-party apps stored */
649    final File mAppInstallDir;
650
651    /**
652     * Directory to which applications installed internally have their
653     * 32 bit native libraries copied.
654     */
655    private File mAppLib32InstallDir;
656
657    // Directory containing the private parts (e.g. code and non-resource assets) of forward-locked
658    // apps.
659    final File mDrmAppPrivateInstallDir;
660
661    // ----------------------------------------------------------------
662
663    // Lock for state used when installing and doing other long running
664    // operations.  Methods that must be called with this lock held have
665    // the suffix "LI".
666    final Object mInstallLock = new Object();
667
668    // ----------------------------------------------------------------
669
670    // Keys are String (package name), values are Package.  This also serves
671    // as the lock for the global state.  Methods that must be called with
672    // this lock held have the prefix "LP".
673    @GuardedBy("mPackages")
674    final ArrayMap<String, PackageParser.Package> mPackages =
675            new ArrayMap<String, PackageParser.Package>();
676
677    final ArrayMap<String, Set<String>> mKnownCodebase =
678            new ArrayMap<String, Set<String>>();
679
680    // Keys are isolated uids and values are the uid of the application
681    // that created the isolated proccess.
682    @GuardedBy("mPackages")
683    final SparseIntArray mIsolatedOwners = new SparseIntArray();
684
685    /**
686     * Tracks new system packages [received in an OTA] that we expect to
687     * find updated user-installed versions. Keys are package name, values
688     * are package location.
689     */
690    final private ArrayMap<String, File> mExpectingBetter = new ArrayMap<>();
691    /**
692     * Tracks high priority intent filters for protected actions. During boot, certain
693     * filter actions are protected and should never be allowed to have a high priority
694     * intent filter for them. However, there is one, and only one exception -- the
695     * setup wizard. It must be able to define a high priority intent filter for these
696     * actions to ensure there are no escapes from the wizard. We need to delay processing
697     * of these during boot as we need to look at all of the system packages in order
698     * to know which component is the setup wizard.
699     */
700    private final List<PackageParser.ActivityIntentInfo> mProtectedFilters = new ArrayList<>();
701    /**
702     * Whether or not processing protected filters should be deferred.
703     */
704    private boolean mDeferProtectedFilters = true;
705
706    /**
707     * Tracks existing system packages prior to receiving an OTA. Keys are package name.
708     */
709    final private ArraySet<String> mExistingSystemPackages = new ArraySet<>();
710    /**
711     * Whether or not system app permissions should be promoted from install to runtime.
712     */
713    boolean mPromoteSystemApps;
714
715    @GuardedBy("mPackages")
716    final Settings mSettings;
717
718    /**
719     * Set of package names that are currently "frozen", which means active
720     * surgery is being done on the code/data for that package. The platform
721     * will refuse to launch frozen packages to avoid race conditions.
722     *
723     * @see PackageFreezer
724     */
725    @GuardedBy("mPackages")
726    final ArraySet<String> mFrozenPackages = new ArraySet<>();
727
728    final ProtectedPackages mProtectedPackages;
729
730    @GuardedBy("mLoadedVolumes")
731    final ArraySet<String> mLoadedVolumes = new ArraySet<>();
732
733    boolean mFirstBoot;
734
735    PackageManagerInternal.ExternalSourcesPolicy mExternalSourcesPolicy;
736
737    // System configuration read by SystemConfig.
738    final int[] mGlobalGids;
739    final SparseArray<ArraySet<String>> mSystemPermissions;
740    @GuardedBy("mAvailableFeatures")
741    final ArrayMap<String, FeatureInfo> mAvailableFeatures;
742
743    // If mac_permissions.xml was found for seinfo labeling.
744    boolean mFoundPolicyFile;
745
746    private final InstantAppRegistry mInstantAppRegistry;
747
748    @GuardedBy("mPackages")
749    int mChangedPackagesSequenceNumber;
750    /**
751     * List of changed [installed, removed or updated] packages.
752     * mapping from user id -> sequence number -> package name
753     */
754    @GuardedBy("mPackages")
755    final SparseArray<SparseArray<String>> mChangedPackages = new SparseArray<>();
756    /**
757     * The sequence number of the last change to a package.
758     * mapping from user id -> package name -> sequence number
759     */
760    @GuardedBy("mPackages")
761    final SparseArray<Map<String, Integer>> mChangedPackagesSequenceNumbers = new SparseArray<>();
762
763    class PackageParserCallback implements PackageParser.Callback {
764        @Override public final boolean hasFeature(String feature) {
765            return PackageManagerService.this.hasSystemFeature(feature, 0);
766        }
767
768        final List<PackageParser.Package> getStaticOverlayPackagesLocked(
769                Collection<PackageParser.Package> allPackages, String targetPackageName) {
770            List<PackageParser.Package> overlayPackages = null;
771            for (PackageParser.Package p : allPackages) {
772                if (targetPackageName.equals(p.mOverlayTarget) && p.mIsStaticOverlay) {
773                    if (overlayPackages == null) {
774                        overlayPackages = new ArrayList<PackageParser.Package>();
775                    }
776                    overlayPackages.add(p);
777                }
778            }
779            if (overlayPackages != null) {
780                Comparator<PackageParser.Package> cmp = new Comparator<PackageParser.Package>() {
781                    public int compare(PackageParser.Package p1, PackageParser.Package p2) {
782                        return p1.mOverlayPriority - p2.mOverlayPriority;
783                    }
784                };
785                Collections.sort(overlayPackages, cmp);
786            }
787            return overlayPackages;
788        }
789
790        final String[] getStaticOverlayPathsLocked(Collection<PackageParser.Package> allPackages,
791                String targetPackageName, String targetPath) {
792            if ("android".equals(targetPackageName)) {
793                // Static RROs targeting to "android", ie framework-res.apk, are already applied by
794                // native AssetManager.
795                return null;
796            }
797            List<PackageParser.Package> overlayPackages =
798                    getStaticOverlayPackagesLocked(allPackages, targetPackageName);
799            if (overlayPackages == null || overlayPackages.isEmpty()) {
800                return null;
801            }
802            List<String> overlayPathList = null;
803            for (PackageParser.Package overlayPackage : overlayPackages) {
804                if (targetPath == null) {
805                    if (overlayPathList == null) {
806                        overlayPathList = new ArrayList<String>();
807                    }
808                    overlayPathList.add(overlayPackage.baseCodePath);
809                    continue;
810                }
811
812                try {
813                    // Creates idmaps for system to parse correctly the Android manifest of the
814                    // target package.
815                    //
816                    // OverlayManagerService will update each of them with a correct gid from its
817                    // target package app id.
818                    mInstaller.idmap(targetPath, overlayPackage.baseCodePath,
819                            UserHandle.getSharedAppGid(
820                                    UserHandle.getUserGid(UserHandle.USER_SYSTEM)));
821                    if (overlayPathList == null) {
822                        overlayPathList = new ArrayList<String>();
823                    }
824                    overlayPathList.add(overlayPackage.baseCodePath);
825                } catch (InstallerException e) {
826                    Slog.e(TAG, "Failed to generate idmap for " + targetPath + " and " +
827                            overlayPackage.baseCodePath);
828                }
829            }
830            return overlayPathList == null ? null : overlayPathList.toArray(new String[0]);
831        }
832
833        String[] getStaticOverlayPaths(String targetPackageName, String targetPath) {
834            synchronized (mPackages) {
835                return getStaticOverlayPathsLocked(
836                        mPackages.values(), targetPackageName, targetPath);
837            }
838        }
839
840        @Override public final String[] getOverlayApks(String targetPackageName) {
841            return getStaticOverlayPaths(targetPackageName, null);
842        }
843
844        @Override public final String[] getOverlayPaths(String targetPackageName,
845                String targetPath) {
846            return getStaticOverlayPaths(targetPackageName, targetPath);
847        }
848    };
849
850    class ParallelPackageParserCallback extends PackageParserCallback {
851        List<PackageParser.Package> mOverlayPackages = null;
852
853        void findStaticOverlayPackages() {
854            synchronized (mPackages) {
855                for (PackageParser.Package p : mPackages.values()) {
856                    if (p.mIsStaticOverlay) {
857                        if (mOverlayPackages == null) {
858                            mOverlayPackages = new ArrayList<PackageParser.Package>();
859                        }
860                        mOverlayPackages.add(p);
861                    }
862                }
863            }
864        }
865
866        @Override
867        synchronized String[] getStaticOverlayPaths(String targetPackageName, String targetPath) {
868            // We can trust mOverlayPackages without holding mPackages because package uninstall
869            // can't happen while running parallel parsing.
870            // Moreover holding mPackages on each parsing thread causes dead-lock.
871            return mOverlayPackages == null ? null :
872                    getStaticOverlayPathsLocked(mOverlayPackages, targetPackageName, targetPath);
873        }
874    }
875
876    final PackageParser.Callback mPackageParserCallback = new PackageParserCallback();
877    final ParallelPackageParserCallback mParallelPackageParserCallback =
878            new ParallelPackageParserCallback();
879
880    public static final class SharedLibraryEntry {
881        public final @Nullable String path;
882        public final @Nullable String apk;
883        public final @NonNull SharedLibraryInfo info;
884
885        SharedLibraryEntry(String _path, String _apk, String name, int version, int type,
886                String declaringPackageName, int declaringPackageVersionCode) {
887            path = _path;
888            apk = _apk;
889            info = new SharedLibraryInfo(name, version, type, new VersionedPackage(
890                    declaringPackageName, declaringPackageVersionCode), null);
891        }
892    }
893
894    // Currently known shared libraries.
895    final ArrayMap<String, SparseArray<SharedLibraryEntry>> mSharedLibraries = new ArrayMap<>();
896    final ArrayMap<String, SparseArray<SharedLibraryEntry>> mStaticLibsByDeclaringPackage =
897            new ArrayMap<>();
898
899    // All available activities, for your resolving pleasure.
900    final ActivityIntentResolver mActivities =
901            new ActivityIntentResolver();
902
903    // All available receivers, for your resolving pleasure.
904    final ActivityIntentResolver mReceivers =
905            new ActivityIntentResolver();
906
907    // All available services, for your resolving pleasure.
908    final ServiceIntentResolver mServices = new ServiceIntentResolver();
909
910    // All available providers, for your resolving pleasure.
911    final ProviderIntentResolver mProviders = new ProviderIntentResolver();
912
913    // Mapping from provider base names (first directory in content URI codePath)
914    // to the provider information.
915    final ArrayMap<String, PackageParser.Provider> mProvidersByAuthority =
916            new ArrayMap<String, PackageParser.Provider>();
917
918    // Mapping from instrumentation class names to info about them.
919    final ArrayMap<ComponentName, PackageParser.Instrumentation> mInstrumentation =
920            new ArrayMap<ComponentName, PackageParser.Instrumentation>();
921
922    // Mapping from permission names to info about them.
923    final ArrayMap<String, PackageParser.PermissionGroup> mPermissionGroups =
924            new ArrayMap<String, PackageParser.PermissionGroup>();
925
926    // Packages whose data we have transfered into another package, thus
927    // should no longer exist.
928    final ArraySet<String> mTransferedPackages = new ArraySet<String>();
929
930    // Broadcast actions that are only available to the system.
931    @GuardedBy("mProtectedBroadcasts")
932    final ArraySet<String> mProtectedBroadcasts = new ArraySet<>();
933
934    /** List of packages waiting for verification. */
935    final SparseArray<PackageVerificationState> mPendingVerification
936            = new SparseArray<PackageVerificationState>();
937
938    /** Set of packages associated with each app op permission. */
939    final ArrayMap<String, ArraySet<String>> mAppOpPermissionPackages = new ArrayMap<>();
940
941    final PackageInstallerService mInstallerService;
942
943    private final PackageDexOptimizer mPackageDexOptimizer;
944    // DexManager handles the usage of dex files (e.g. secondary files, whether or not a package
945    // is used by other apps).
946    private final DexManager mDexManager;
947
948    private AtomicInteger mNextMoveId = new AtomicInteger();
949    private final MoveCallbacks mMoveCallbacks;
950
951    private final OnPermissionChangeListeners mOnPermissionChangeListeners;
952
953    // Cache of users who need badging.
954    SparseBooleanArray mUserNeedsBadging = new SparseBooleanArray();
955
956    /** Token for keys in mPendingVerification. */
957    private int mPendingVerificationToken = 0;
958
959    volatile boolean mSystemReady;
960    volatile boolean mSafeMode;
961    volatile boolean mHasSystemUidErrors;
962    private volatile boolean mEphemeralAppsDisabled;
963
964    ApplicationInfo mAndroidApplication;
965    final ActivityInfo mResolveActivity = new ActivityInfo();
966    final ResolveInfo mResolveInfo = new ResolveInfo();
967    ComponentName mResolveComponentName;
968    PackageParser.Package mPlatformPackage;
969    ComponentName mCustomResolverComponentName;
970
971    boolean mResolverReplaced = false;
972
973    private final @Nullable ComponentName mIntentFilterVerifierComponent;
974    private final @Nullable IntentFilterVerifier<ActivityIntentInfo> mIntentFilterVerifier;
975
976    private int mIntentFilterVerificationToken = 0;
977
978    /** The service connection to the ephemeral resolver */
979    final EphemeralResolverConnection mInstantAppResolverConnection;
980    /** Component used to show resolver settings for Instant Apps */
981    final ComponentName mInstantAppResolverSettingsComponent;
982
983    /** Activity used to install instant applications */
984    ActivityInfo mInstantAppInstallerActivity;
985    final ResolveInfo mInstantAppInstallerInfo = new ResolveInfo();
986
987    final SparseArray<IntentFilterVerificationState> mIntentFilterVerificationStates
988            = new SparseArray<IntentFilterVerificationState>();
989
990    final DefaultPermissionGrantPolicy mDefaultPermissionPolicy;
991
992    // List of packages names to keep cached, even if they are uninstalled for all users
993    private List<String> mKeepUninstalledPackages;
994
995    private UserManagerInternal mUserManagerInternal;
996
997    private DeviceIdleController.LocalService mDeviceIdleController;
998
999    private File mCacheDir;
1000
1001    private ArraySet<String> mPrivappPermissionsViolations;
1002
1003    private Future<?> mPrepareAppDataFuture;
1004
1005    private static class IFVerificationParams {
1006        PackageParser.Package pkg;
1007        boolean replacing;
1008        int userId;
1009        int verifierUid;
1010
1011        public IFVerificationParams(PackageParser.Package _pkg, boolean _replacing,
1012                int _userId, int _verifierUid) {
1013            pkg = _pkg;
1014            replacing = _replacing;
1015            userId = _userId;
1016            replacing = _replacing;
1017            verifierUid = _verifierUid;
1018        }
1019    }
1020
1021    private interface IntentFilterVerifier<T extends IntentFilter> {
1022        boolean addOneIntentFilterVerification(int verifierId, int userId, int verificationId,
1023                                               T filter, String packageName);
1024        void startVerifications(int userId);
1025        void receiveVerificationResponse(int verificationId);
1026    }
1027
1028    private class IntentVerifierProxy implements IntentFilterVerifier<ActivityIntentInfo> {
1029        private Context mContext;
1030        private ComponentName mIntentFilterVerifierComponent;
1031        private ArrayList<Integer> mCurrentIntentFilterVerifications = new ArrayList<Integer>();
1032
1033        public IntentVerifierProxy(Context context, ComponentName verifierComponent) {
1034            mContext = context;
1035            mIntentFilterVerifierComponent = verifierComponent;
1036        }
1037
1038        private String getDefaultScheme() {
1039            return IntentFilter.SCHEME_HTTPS;
1040        }
1041
1042        @Override
1043        public void startVerifications(int userId) {
1044            // Launch verifications requests
1045            int count = mCurrentIntentFilterVerifications.size();
1046            for (int n=0; n<count; n++) {
1047                int verificationId = mCurrentIntentFilterVerifications.get(n);
1048                final IntentFilterVerificationState ivs =
1049                        mIntentFilterVerificationStates.get(verificationId);
1050
1051                String packageName = ivs.getPackageName();
1052
1053                ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters();
1054                final int filterCount = filters.size();
1055                ArraySet<String> domainsSet = new ArraySet<>();
1056                for (int m=0; m<filterCount; m++) {
1057                    PackageParser.ActivityIntentInfo filter = filters.get(m);
1058                    domainsSet.addAll(filter.getHostsList());
1059                }
1060                synchronized (mPackages) {
1061                    if (mSettings.createIntentFilterVerificationIfNeededLPw(
1062                            packageName, domainsSet) != null) {
1063                        scheduleWriteSettingsLocked();
1064                    }
1065                }
1066                sendVerificationRequest(userId, verificationId, ivs);
1067            }
1068            mCurrentIntentFilterVerifications.clear();
1069        }
1070
1071        private void sendVerificationRequest(int userId, int verificationId,
1072                IntentFilterVerificationState ivs) {
1073
1074            Intent verificationIntent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION);
1075            verificationIntent.putExtra(
1076                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_ID,
1077                    verificationId);
1078            verificationIntent.putExtra(
1079                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_URI_SCHEME,
1080                    getDefaultScheme());
1081            verificationIntent.putExtra(
1082                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_HOSTS,
1083                    ivs.getHostsString());
1084            verificationIntent.putExtra(
1085                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_PACKAGE_NAME,
1086                    ivs.getPackageName());
1087            verificationIntent.setComponent(mIntentFilterVerifierComponent);
1088            verificationIntent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
1089
1090            DeviceIdleController.LocalService idleController = getDeviceIdleController();
1091            idleController.addPowerSaveTempWhitelistApp(Process.myUid(),
1092                    mIntentFilterVerifierComponent.getPackageName(), getVerificationTimeout(),
1093                    userId, false, "intent filter verifier");
1094
1095            UserHandle user = new UserHandle(userId);
1096            mContext.sendBroadcastAsUser(verificationIntent, user);
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
2706            if (!mOnlyCore) {
2707                EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_DATA_SCAN_START,
2708                        SystemClock.uptimeMillis());
2709                scanDirTracedLI(mAppInstallDir, 0, scanFlags | SCAN_REQUIRE_KNOWN, 0);
2710
2711                scanDirTracedLI(mDrmAppPrivateInstallDir, mDefParseFlags
2712                        | PackageParser.PARSE_FORWARD_LOCK,
2713                        scanFlags | SCAN_REQUIRE_KNOWN, 0);
2714
2715                /**
2716                 * Remove disable package settings for any updated system
2717                 * apps that were removed via an OTA. If they're not a
2718                 * previously-updated app, remove them completely.
2719                 * Otherwise, just revoke their system-level permissions.
2720                 */
2721                for (String deletedAppName : possiblyDeletedUpdatedSystemApps) {
2722                    PackageParser.Package deletedPkg = mPackages.get(deletedAppName);
2723                    mSettings.removeDisabledSystemPackageLPw(deletedAppName);
2724
2725                    String msg;
2726                    if (deletedPkg == null) {
2727                        msg = "Updated system package " + deletedAppName
2728                                + " no longer exists; it's data will be wiped";
2729                        // Actual deletion of code and data will be handled by later
2730                        // reconciliation step
2731                    } else {
2732                        msg = "Updated system app + " + deletedAppName
2733                                + " no longer present; removing system privileges for "
2734                                + deletedAppName;
2735
2736                        deletedPkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_SYSTEM;
2737
2738                        PackageSetting deletedPs = mSettings.mPackages.get(deletedAppName);
2739                        deletedPs.pkgFlags &= ~ApplicationInfo.FLAG_SYSTEM;
2740                    }
2741                    logCriticalInfo(Log.WARN, msg);
2742                }
2743
2744                /**
2745                 * Make sure all system apps that we expected to appear on
2746                 * the userdata partition actually showed up. If they never
2747                 * appeared, crawl back and revive the system version.
2748                 */
2749                for (int i = 0; i < mExpectingBetter.size(); i++) {
2750                    final String packageName = mExpectingBetter.keyAt(i);
2751                    if (!mPackages.containsKey(packageName)) {
2752                        final File scanFile = mExpectingBetter.valueAt(i);
2753
2754                        logCriticalInfo(Log.WARN, "Expected better " + packageName
2755                                + " but never showed up; reverting to system");
2756
2757                        int reparseFlags = mDefParseFlags;
2758                        if (FileUtils.contains(privilegedAppDir, scanFile)) {
2759                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2760                                    | PackageParser.PARSE_IS_SYSTEM_DIR
2761                                    | PackageParser.PARSE_IS_PRIVILEGED;
2762                        } else if (FileUtils.contains(systemAppDir, scanFile)) {
2763                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2764                                    | PackageParser.PARSE_IS_SYSTEM_DIR;
2765                        } else if (FileUtils.contains(vendorAppDir, scanFile)) {
2766                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2767                                    | PackageParser.PARSE_IS_SYSTEM_DIR;
2768                        } else if (FileUtils.contains(oemAppDir, scanFile)) {
2769                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2770                                    | PackageParser.PARSE_IS_SYSTEM_DIR;
2771                        } else {
2772                            Slog.e(TAG, "Ignoring unexpected fallback path " + scanFile);
2773                            continue;
2774                        }
2775
2776                        mSettings.enableSystemPackageLPw(packageName);
2777
2778                        try {
2779                            scanPackageTracedLI(scanFile, reparseFlags, scanFlags, 0, null);
2780                        } catch (PackageManagerException e) {
2781                            Slog.e(TAG, "Failed to parse original system package: "
2782                                    + e.getMessage());
2783                        }
2784                    }
2785                }
2786            }
2787            mExpectingBetter.clear();
2788
2789            // Resolve the storage manager.
2790            mStorageManagerPackage = getStorageManagerPackageName();
2791
2792            // Resolve protected action filters. Only the setup wizard is allowed to
2793            // have a high priority filter for these actions.
2794            mSetupWizardPackage = getSetupWizardPackageName();
2795            if (mProtectedFilters.size() > 0) {
2796                if (DEBUG_FILTERS && mSetupWizardPackage == null) {
2797                    Slog.i(TAG, "No setup wizard;"
2798                        + " All protected intents capped to priority 0");
2799                }
2800                for (ActivityIntentInfo filter : mProtectedFilters) {
2801                    if (filter.activity.info.packageName.equals(mSetupWizardPackage)) {
2802                        if (DEBUG_FILTERS) {
2803                            Slog.i(TAG, "Found setup wizard;"
2804                                + " allow priority " + filter.getPriority() + ";"
2805                                + " package: " + filter.activity.info.packageName
2806                                + " activity: " + filter.activity.className
2807                                + " priority: " + filter.getPriority());
2808                        }
2809                        // skip setup wizard; allow it to keep the high priority filter
2810                        continue;
2811                    }
2812                    if (DEBUG_FILTERS) {
2813                        Slog.i(TAG, "Protected action; cap priority to 0;"
2814                                + " package: " + filter.activity.info.packageName
2815                                + " activity: " + filter.activity.className
2816                                + " origPrio: " + filter.getPriority());
2817                    }
2818                    filter.setPriority(0);
2819                }
2820            }
2821            mDeferProtectedFilters = false;
2822            mProtectedFilters.clear();
2823
2824            // Now that we know all of the shared libraries, update all clients to have
2825            // the correct library paths.
2826            updateAllSharedLibrariesLPw(null);
2827
2828            for (SharedUserSetting setting : mSettings.getAllSharedUsersLPw()) {
2829                // NOTE: We ignore potential failures here during a system scan (like
2830                // the rest of the commands above) because there's precious little we
2831                // can do about it. A settings error is reported, though.
2832                adjustCpuAbisForSharedUserLPw(setting.packages, null /*scannedPackage*/);
2833            }
2834
2835            // Now that we know all the packages we are keeping,
2836            // read and update their last usage times.
2837            mPackageUsage.read(mPackages);
2838            mCompilerStats.read();
2839
2840            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SCAN_END,
2841                    SystemClock.uptimeMillis());
2842            Slog.i(TAG, "Time to scan packages: "
2843                    + ((SystemClock.uptimeMillis()-startTime)/1000f)
2844                    + " seconds");
2845
2846            // If the platform SDK has changed since the last time we booted,
2847            // we need to re-grant app permission to catch any new ones that
2848            // appear.  This is really a hack, and means that apps can in some
2849            // cases get permissions that the user didn't initially explicitly
2850            // allow...  it would be nice to have some better way to handle
2851            // this situation.
2852            int updateFlags = UPDATE_PERMISSIONS_ALL;
2853            if (ver.sdkVersion != mSdkVersion) {
2854                Slog.i(TAG, "Platform changed from " + ver.sdkVersion + " to "
2855                        + mSdkVersion + "; regranting permissions for internal storage");
2856                updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL;
2857            }
2858            updatePermissionsLPw(null, null, StorageManager.UUID_PRIVATE_INTERNAL, updateFlags);
2859            ver.sdkVersion = mSdkVersion;
2860
2861            // If this is the first boot or an update from pre-M, and it is a normal
2862            // boot, then we need to initialize the default preferred apps across
2863            // all defined users.
2864            if (!onlyCore && (mPromoteSystemApps || mFirstBoot)) {
2865                for (UserInfo user : sUserManager.getUsers(true)) {
2866                    mSettings.applyDefaultPreferredAppsLPw(this, user.id);
2867                    applyFactoryDefaultBrowserLPw(user.id);
2868                    primeDomainVerificationsLPw(user.id);
2869                }
2870            }
2871
2872            // Prepare storage for system user really early during boot,
2873            // since core system apps like SettingsProvider and SystemUI
2874            // can't wait for user to start
2875            final int storageFlags;
2876            if (StorageManager.isFileEncryptedNativeOrEmulated()) {
2877                storageFlags = StorageManager.FLAG_STORAGE_DE;
2878            } else {
2879                storageFlags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
2880            }
2881            List<String> deferPackages = reconcileAppsDataLI(StorageManager.UUID_PRIVATE_INTERNAL,
2882                    UserHandle.USER_SYSTEM, storageFlags, true /* migrateAppData */,
2883                    true /* onlyCoreApps */);
2884            mPrepareAppDataFuture = SystemServerInitThreadPool.get().submit(() -> {
2885                BootTimingsTraceLog traceLog = new BootTimingsTraceLog("SystemServerTimingAsync",
2886                        Trace.TRACE_TAG_PACKAGE_MANAGER);
2887                traceLog.traceBegin("AppDataFixup");
2888                try {
2889                    mInstaller.fixupAppData(StorageManager.UUID_PRIVATE_INTERNAL,
2890                            StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
2891                } catch (InstallerException e) {
2892                    Slog.w(TAG, "Trouble fixing GIDs", e);
2893                }
2894                traceLog.traceEnd();
2895
2896                traceLog.traceBegin("AppDataPrepare");
2897                if (deferPackages == null || deferPackages.isEmpty()) {
2898                    return;
2899                }
2900                int count = 0;
2901                for (String pkgName : deferPackages) {
2902                    PackageParser.Package pkg = null;
2903                    synchronized (mPackages) {
2904                        PackageSetting ps = mSettings.getPackageLPr(pkgName);
2905                        if (ps != null && ps.getInstalled(UserHandle.USER_SYSTEM)) {
2906                            pkg = ps.pkg;
2907                        }
2908                    }
2909                    if (pkg != null) {
2910                        synchronized (mInstallLock) {
2911                            prepareAppDataAndMigrateLIF(pkg, UserHandle.USER_SYSTEM, storageFlags,
2912                                    true /* maybeMigrateAppData */);
2913                        }
2914                        count++;
2915                    }
2916                }
2917                traceLog.traceEnd();
2918                Slog.i(TAG, "Deferred reconcileAppsData finished " + count + " packages");
2919            }, "prepareAppData");
2920
2921            // If this is first boot after an OTA, and a normal boot, then
2922            // we need to clear code cache directories.
2923            // Note that we do *not* clear the application profiles. These remain valid
2924            // across OTAs and are used to drive profile verification (post OTA) and
2925            // profile compilation (without waiting to collect a fresh set of profiles).
2926            if (mIsUpgrade && !onlyCore) {
2927                Slog.i(TAG, "Build fingerprint changed; clearing code caches");
2928                for (int i = 0; i < mSettings.mPackages.size(); i++) {
2929                    final PackageSetting ps = mSettings.mPackages.valueAt(i);
2930                    if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, ps.volumeUuid)) {
2931                        // No apps are running this early, so no need to freeze
2932                        clearAppDataLIF(ps.pkg, UserHandle.USER_ALL,
2933                                StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE
2934                                        | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
2935                    }
2936                }
2937                ver.fingerprint = Build.FINGERPRINT;
2938            }
2939
2940            checkDefaultBrowser();
2941
2942            // clear only after permissions and other defaults have been updated
2943            mExistingSystemPackages.clear();
2944            mPromoteSystemApps = false;
2945
2946            // All the changes are done during package scanning.
2947            ver.databaseVersion = Settings.CURRENT_DATABASE_VERSION;
2948
2949            // can downgrade to reader
2950            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "write settings");
2951            mSettings.writeLPr();
2952            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
2953            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_READY,
2954                    SystemClock.uptimeMillis());
2955
2956            if (!mOnlyCore) {
2957                mRequiredVerifierPackage = getRequiredButNotReallyRequiredVerifierLPr();
2958                mRequiredInstallerPackage = getRequiredInstallerLPr();
2959                mRequiredUninstallerPackage = getRequiredUninstallerLPr();
2960                mIntentFilterVerifierComponent = getIntentFilterVerifierComponentNameLPr();
2961                if (mIntentFilterVerifierComponent != null) {
2962                    mIntentFilterVerifier = new IntentVerifierProxy(mContext,
2963                            mIntentFilterVerifierComponent);
2964                } else {
2965                    mIntentFilterVerifier = null;
2966                }
2967                mServicesSystemSharedLibraryPackageName = getRequiredSharedLibraryLPr(
2968                        PackageManager.SYSTEM_SHARED_LIBRARY_SERVICES,
2969                        SharedLibraryInfo.VERSION_UNDEFINED);
2970                mSharedSystemSharedLibraryPackageName = getRequiredSharedLibraryLPr(
2971                        PackageManager.SYSTEM_SHARED_LIBRARY_SHARED,
2972                        SharedLibraryInfo.VERSION_UNDEFINED);
2973            } else {
2974                mRequiredVerifierPackage = null;
2975                mRequiredInstallerPackage = null;
2976                mRequiredUninstallerPackage = null;
2977                mIntentFilterVerifierComponent = null;
2978                mIntentFilterVerifier = null;
2979                mServicesSystemSharedLibraryPackageName = null;
2980                mSharedSystemSharedLibraryPackageName = null;
2981            }
2982
2983            mInstallerService = new PackageInstallerService(context, this);
2984            final Pair<ComponentName, String> instantAppResolverComponent =
2985                    getInstantAppResolverLPr();
2986            if (instantAppResolverComponent != null) {
2987                if (DEBUG_EPHEMERAL) {
2988                    Slog.d(TAG, "Set ephemeral resolver: " + instantAppResolverComponent);
2989                }
2990                mInstantAppResolverConnection = new EphemeralResolverConnection(
2991                        mContext, instantAppResolverComponent.first,
2992                        instantAppResolverComponent.second);
2993                mInstantAppResolverSettingsComponent =
2994                        getInstantAppResolverSettingsLPr(instantAppResolverComponent.first);
2995            } else {
2996                mInstantAppResolverConnection = null;
2997                mInstantAppResolverSettingsComponent = null;
2998            }
2999            updateInstantAppInstallerLocked(null);
3000
3001            // Read and update the usage of dex files.
3002            // Do this at the end of PM init so that all the packages have their
3003            // data directory reconciled.
3004            // At this point we know the code paths of the packages, so we can validate
3005            // the disk file and build the internal cache.
3006            // The usage file is expected to be small so loading and verifying it
3007            // should take a fairly small time compare to the other activities (e.g. package
3008            // scanning).
3009            final Map<Integer, List<PackageInfo>> userPackages = new HashMap<>();
3010            final int[] currentUserIds = UserManagerService.getInstance().getUserIds();
3011            for (int userId : currentUserIds) {
3012                userPackages.put(userId, getInstalledPackages(/*flags*/ 0, userId).getList());
3013            }
3014            mDexManager.load(userPackages);
3015        } // synchronized (mPackages)
3016        } // synchronized (mInstallLock)
3017
3018        // Now after opening every single application zip, make sure they
3019        // are all flushed.  Not really needed, but keeps things nice and
3020        // tidy.
3021        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "GC");
3022        Runtime.getRuntime().gc();
3023        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
3024
3025        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "loadFallbacks");
3026        FallbackCategoryProvider.loadFallbacks();
3027        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
3028
3029        // The initial scanning above does many calls into installd while
3030        // holding the mPackages lock, but we're mostly interested in yelling
3031        // once we have a booted system.
3032        mInstaller.setWarnIfHeld(mPackages);
3033
3034        // Expose private service for system components to use.
3035        LocalServices.addService(PackageManagerInternal.class, new PackageManagerInternalImpl());
3036        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
3037    }
3038
3039    private void updateInstantAppInstallerLocked(String modifiedPackage) {
3040        // we're only interested in updating the installer appliction when 1) it's not
3041        // already set or 2) the modified package is the installer
3042        if (mInstantAppInstallerActivity != null
3043                && !mInstantAppInstallerActivity.getComponentName().getPackageName()
3044                        .equals(modifiedPackage)) {
3045            return;
3046        }
3047        setUpInstantAppInstallerActivityLP(getInstantAppInstallerLPr());
3048    }
3049
3050    private static File preparePackageParserCache(boolean isUpgrade) {
3051        if (!DEFAULT_PACKAGE_PARSER_CACHE_ENABLED) {
3052            return null;
3053        }
3054
3055        // Disable package parsing on eng builds to allow for faster incremental development.
3056        if ("eng".equals(Build.TYPE)) {
3057            return null;
3058        }
3059
3060        if (SystemProperties.getBoolean("pm.boot.disable_package_cache", false)) {
3061            Slog.i(TAG, "Disabling package parser cache due to system property.");
3062            return null;
3063        }
3064
3065        // The base directory for the package parser cache lives under /data/system/.
3066        final File cacheBaseDir = FileUtils.createDir(Environment.getDataSystemDirectory(),
3067                "package_cache");
3068        if (cacheBaseDir == null) {
3069            return null;
3070        }
3071
3072        // If this is a system upgrade scenario, delete the contents of the package cache dir.
3073        // This also serves to "GC" unused entries when the package cache version changes (which
3074        // can only happen during upgrades).
3075        if (isUpgrade) {
3076            FileUtils.deleteContents(cacheBaseDir);
3077        }
3078
3079
3080        // Return the versioned package cache directory. This is something like
3081        // "/data/system/package_cache/1"
3082        File cacheDir = FileUtils.createDir(cacheBaseDir, PACKAGE_PARSER_CACHE_VERSION);
3083
3084        // The following is a workaround to aid development on non-numbered userdebug
3085        // builds or cases where "adb sync" is used on userdebug builds. If we detect that
3086        // the system partition is newer.
3087        //
3088        // NOTE: When no BUILD_NUMBER is set by the build system, it defaults to a build
3089        // that starts with "eng." to signify that this is an engineering build and not
3090        // destined for release.
3091        if ("userdebug".equals(Build.TYPE) && Build.VERSION.INCREMENTAL.startsWith("eng.")) {
3092            Slog.w(TAG, "Wiping cache directory because the system partition changed.");
3093
3094            // Heuristic: If the /system directory has been modified recently due to an "adb sync"
3095            // or a regular make, then blow away the cache. Note that mtimes are *NOT* reliable
3096            // in general and should not be used for production changes. In this specific case,
3097            // we know that they will work.
3098            File frameworkDir = new File(Environment.getRootDirectory(), "framework");
3099            if (cacheDir.lastModified() < frameworkDir.lastModified()) {
3100                FileUtils.deleteContents(cacheBaseDir);
3101                cacheDir = FileUtils.createDir(cacheBaseDir, PACKAGE_PARSER_CACHE_VERSION);
3102            }
3103        }
3104
3105        return cacheDir;
3106    }
3107
3108    @Override
3109    public boolean isFirstBoot() {
3110        // allow instant applications
3111        return mFirstBoot;
3112    }
3113
3114    @Override
3115    public boolean isOnlyCoreApps() {
3116        // allow instant applications
3117        return mOnlyCore;
3118    }
3119
3120    @Override
3121    public boolean isUpgrade() {
3122        // allow instant applications
3123        return mIsUpgrade;
3124    }
3125
3126    private @Nullable String getRequiredButNotReallyRequiredVerifierLPr() {
3127        final Intent intent = new Intent(Intent.ACTION_PACKAGE_NEEDS_VERIFICATION);
3128
3129        final List<ResolveInfo> matches = queryIntentReceiversInternal(intent, PACKAGE_MIME_TYPE,
3130                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
3131                UserHandle.USER_SYSTEM);
3132        if (matches.size() == 1) {
3133            return matches.get(0).getComponentInfo().packageName;
3134        } else if (matches.size() == 0) {
3135            Log.e(TAG, "There should probably be a verifier, but, none were found");
3136            return null;
3137        }
3138        throw new RuntimeException("There must be exactly one verifier; found " + matches);
3139    }
3140
3141    private @NonNull String getRequiredSharedLibraryLPr(String name, int version) {
3142        synchronized (mPackages) {
3143            SharedLibraryEntry libraryEntry = getSharedLibraryEntryLPr(name, version);
3144            if (libraryEntry == null) {
3145                throw new IllegalStateException("Missing required shared library:" + name);
3146            }
3147            return libraryEntry.apk;
3148        }
3149    }
3150
3151    private @NonNull String getRequiredInstallerLPr() {
3152        final Intent intent = new Intent(Intent.ACTION_INSTALL_PACKAGE);
3153        intent.addCategory(Intent.CATEGORY_DEFAULT);
3154        intent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE);
3155
3156        final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, PACKAGE_MIME_TYPE,
3157                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
3158                UserHandle.USER_SYSTEM);
3159        if (matches.size() == 1) {
3160            ResolveInfo resolveInfo = matches.get(0);
3161            if (!resolveInfo.activityInfo.applicationInfo.isPrivilegedApp()) {
3162                throw new RuntimeException("The installer must be a privileged app");
3163            }
3164            return matches.get(0).getComponentInfo().packageName;
3165        } else {
3166            throw new RuntimeException("There must be exactly one installer; found " + matches);
3167        }
3168    }
3169
3170    private @NonNull String getRequiredUninstallerLPr() {
3171        final Intent intent = new Intent(Intent.ACTION_UNINSTALL_PACKAGE);
3172        intent.addCategory(Intent.CATEGORY_DEFAULT);
3173        intent.setData(Uri.fromParts(PACKAGE_SCHEME, "foo.bar", null));
3174
3175        final ResolveInfo resolveInfo = resolveIntent(intent, null,
3176                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
3177                UserHandle.USER_SYSTEM);
3178        if (resolveInfo == null ||
3179                mResolveActivity.name.equals(resolveInfo.getComponentInfo().name)) {
3180            throw new RuntimeException("There must be exactly one uninstaller; found "
3181                    + resolveInfo);
3182        }
3183        return resolveInfo.getComponentInfo().packageName;
3184    }
3185
3186    private @NonNull ComponentName getIntentFilterVerifierComponentNameLPr() {
3187        final Intent intent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION);
3188
3189        final List<ResolveInfo> matches = queryIntentReceiversInternal(intent, PACKAGE_MIME_TYPE,
3190                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
3191                UserHandle.USER_SYSTEM);
3192        ResolveInfo best = null;
3193        final int N = matches.size();
3194        for (int i = 0; i < N; i++) {
3195            final ResolveInfo cur = matches.get(i);
3196            final String packageName = cur.getComponentInfo().packageName;
3197            if (checkPermission(android.Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT,
3198                    packageName, UserHandle.USER_SYSTEM) != PackageManager.PERMISSION_GRANTED) {
3199                continue;
3200            }
3201
3202            if (best == null || cur.priority > best.priority) {
3203                best = cur;
3204            }
3205        }
3206
3207        if (best != null) {
3208            return best.getComponentInfo().getComponentName();
3209        }
3210        Slog.w(TAG, "Intent filter verifier not found");
3211        return null;
3212    }
3213
3214    @Override
3215    public @Nullable ComponentName getInstantAppResolverComponent() {
3216        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
3217            return null;
3218        }
3219        synchronized (mPackages) {
3220            final Pair<ComponentName, String> instantAppResolver = getInstantAppResolverLPr();
3221            if (instantAppResolver == null) {
3222                return null;
3223            }
3224            return instantAppResolver.first;
3225        }
3226    }
3227
3228    private @Nullable Pair<ComponentName, String> getInstantAppResolverLPr() {
3229        final String[] packageArray =
3230                mContext.getResources().getStringArray(R.array.config_ephemeralResolverPackage);
3231        if (packageArray.length == 0 && !Build.IS_DEBUGGABLE) {
3232            if (DEBUG_EPHEMERAL) {
3233                Slog.d(TAG, "Ephemeral resolver NOT found; empty package list");
3234            }
3235            return null;
3236        }
3237
3238        final int callingUid = Binder.getCallingUid();
3239        final int resolveFlags =
3240                MATCH_DIRECT_BOOT_AWARE
3241                | MATCH_DIRECT_BOOT_UNAWARE
3242                | (!Build.IS_DEBUGGABLE ? MATCH_SYSTEM_ONLY : 0);
3243        String actionName = Intent.ACTION_RESOLVE_INSTANT_APP_PACKAGE;
3244        final Intent resolverIntent = new Intent(actionName);
3245        List<ResolveInfo> resolvers = queryIntentServicesInternal(resolverIntent, null,
3246                resolveFlags, UserHandle.USER_SYSTEM, callingUid, false /*includeInstantApps*/);
3247        // temporarily look for the old action
3248        if (resolvers.size() == 0) {
3249            if (DEBUG_EPHEMERAL) {
3250                Slog.d(TAG, "Ephemeral resolver not found with new action; try old one");
3251            }
3252            actionName = Intent.ACTION_RESOLVE_EPHEMERAL_PACKAGE;
3253            resolverIntent.setAction(actionName);
3254            resolvers = queryIntentServicesInternal(resolverIntent, null,
3255                    resolveFlags, UserHandle.USER_SYSTEM, callingUid, false /*includeInstantApps*/);
3256        }
3257        final int N = resolvers.size();
3258        if (N == 0) {
3259            if (DEBUG_EPHEMERAL) {
3260                Slog.d(TAG, "Ephemeral resolver NOT found; no matching intent filters");
3261            }
3262            return null;
3263        }
3264
3265        final Set<String> possiblePackages = new ArraySet<>(Arrays.asList(packageArray));
3266        for (int i = 0; i < N; i++) {
3267            final ResolveInfo info = resolvers.get(i);
3268
3269            if (info.serviceInfo == null) {
3270                continue;
3271            }
3272
3273            final String packageName = info.serviceInfo.packageName;
3274            if (!possiblePackages.contains(packageName) && !Build.IS_DEBUGGABLE) {
3275                if (DEBUG_EPHEMERAL) {
3276                    Slog.d(TAG, "Ephemeral resolver not in allowed package list;"
3277                            + " pkg: " + packageName + ", info:" + info);
3278                }
3279                continue;
3280            }
3281
3282            if (DEBUG_EPHEMERAL) {
3283                Slog.v(TAG, "Ephemeral resolver found;"
3284                        + " pkg: " + packageName + ", info:" + info);
3285            }
3286            return new Pair<>(new ComponentName(packageName, info.serviceInfo.name), actionName);
3287        }
3288        if (DEBUG_EPHEMERAL) {
3289            Slog.v(TAG, "Ephemeral resolver NOT found");
3290        }
3291        return null;
3292    }
3293
3294    private @Nullable ActivityInfo getInstantAppInstallerLPr() {
3295        final Intent intent = new Intent(Intent.ACTION_INSTALL_INSTANT_APP_PACKAGE);
3296        intent.addCategory(Intent.CATEGORY_DEFAULT);
3297        intent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE);
3298
3299        final int resolveFlags =
3300                MATCH_DIRECT_BOOT_AWARE
3301                | MATCH_DIRECT_BOOT_UNAWARE
3302                | (!Build.IS_DEBUGGABLE ? MATCH_SYSTEM_ONLY : 0);
3303        List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, PACKAGE_MIME_TYPE,
3304                resolveFlags, UserHandle.USER_SYSTEM);
3305        // temporarily look for the old action
3306        if (matches.isEmpty()) {
3307            if (DEBUG_EPHEMERAL) {
3308                Slog.d(TAG, "Ephemeral installer not found with new action; try old one");
3309            }
3310            intent.setAction(Intent.ACTION_INSTALL_EPHEMERAL_PACKAGE);
3311            matches = queryIntentActivitiesInternal(intent, PACKAGE_MIME_TYPE,
3312                    resolveFlags, UserHandle.USER_SYSTEM);
3313        }
3314        Iterator<ResolveInfo> iter = matches.iterator();
3315        while (iter.hasNext()) {
3316            final ResolveInfo rInfo = iter.next();
3317            final PackageSetting ps = mSettings.mPackages.get(rInfo.activityInfo.packageName);
3318            if (ps != null) {
3319                final PermissionsState permissionsState = ps.getPermissionsState();
3320                if (permissionsState.hasPermission(Manifest.permission.INSTALL_PACKAGES, 0)) {
3321                    continue;
3322                }
3323            }
3324            iter.remove();
3325        }
3326        if (matches.size() == 0) {
3327            return null;
3328        } else if (matches.size() == 1) {
3329            return (ActivityInfo) matches.get(0).getComponentInfo();
3330        } else {
3331            throw new RuntimeException(
3332                    "There must be at most one ephemeral installer; found " + matches);
3333        }
3334    }
3335
3336    private @Nullable ComponentName getInstantAppResolverSettingsLPr(
3337            @NonNull ComponentName resolver) {
3338        final Intent intent =  new Intent(Intent.ACTION_INSTANT_APP_RESOLVER_SETTINGS)
3339                .addCategory(Intent.CATEGORY_DEFAULT)
3340                .setPackage(resolver.getPackageName());
3341        final int resolveFlags = MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE;
3342        List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, null, resolveFlags,
3343                UserHandle.USER_SYSTEM);
3344        // temporarily look for the old action
3345        if (matches.isEmpty()) {
3346            if (DEBUG_EPHEMERAL) {
3347                Slog.d(TAG, "Ephemeral resolver settings not found with new action; try old one");
3348            }
3349            intent.setAction(Intent.ACTION_EPHEMERAL_RESOLVER_SETTINGS);
3350            matches = queryIntentActivitiesInternal(intent, null, resolveFlags,
3351                    UserHandle.USER_SYSTEM);
3352        }
3353        if (matches.isEmpty()) {
3354            return null;
3355        }
3356        return matches.get(0).getComponentInfo().getComponentName();
3357    }
3358
3359    private void primeDomainVerificationsLPw(int userId) {
3360        if (DEBUG_DOMAIN_VERIFICATION) {
3361            Slog.d(TAG, "Priming domain verifications in user " + userId);
3362        }
3363
3364        SystemConfig systemConfig = SystemConfig.getInstance();
3365        ArraySet<String> packages = systemConfig.getLinkedApps();
3366
3367        for (String packageName : packages) {
3368            PackageParser.Package pkg = mPackages.get(packageName);
3369            if (pkg != null) {
3370                if (!pkg.isSystemApp()) {
3371                    Slog.w(TAG, "Non-system app '" + packageName + "' in sysconfig <app-link>");
3372                    continue;
3373                }
3374
3375                ArraySet<String> domains = null;
3376                for (PackageParser.Activity a : pkg.activities) {
3377                    for (ActivityIntentInfo filter : a.intents) {
3378                        if (hasValidDomains(filter)) {
3379                            if (domains == null) {
3380                                domains = new ArraySet<String>();
3381                            }
3382                            domains.addAll(filter.getHostsList());
3383                        }
3384                    }
3385                }
3386
3387                if (domains != null && domains.size() > 0) {
3388                    if (DEBUG_DOMAIN_VERIFICATION) {
3389                        Slog.v(TAG, "      + " + packageName);
3390                    }
3391                    // 'Undefined' in the global IntentFilterVerificationInfo, i.e. the usual
3392                    // state w.r.t. the formal app-linkage "no verification attempted" state;
3393                    // and then 'always' in the per-user state actually used for intent resolution.
3394                    final IntentFilterVerificationInfo ivi;
3395                    ivi = mSettings.createIntentFilterVerificationIfNeededLPw(packageName, domains);
3396                    ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED);
3397                    mSettings.updateIntentFilterVerificationStatusLPw(packageName,
3398                            INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS, userId);
3399                } else {
3400                    Slog.w(TAG, "Sysconfig <app-link> package '" + packageName
3401                            + "' does not handle web links");
3402                }
3403            } else {
3404                Slog.w(TAG, "Unknown package " + packageName + " in sysconfig <app-link>");
3405            }
3406        }
3407
3408        scheduleWritePackageRestrictionsLocked(userId);
3409        scheduleWriteSettingsLocked();
3410    }
3411
3412    private void applyFactoryDefaultBrowserLPw(int userId) {
3413        // The default browser app's package name is stored in a string resource,
3414        // with a product-specific overlay used for vendor customization.
3415        String browserPkg = mContext.getResources().getString(
3416                com.android.internal.R.string.default_browser);
3417        if (!TextUtils.isEmpty(browserPkg)) {
3418            // non-empty string => required to be a known package
3419            PackageSetting ps = mSettings.mPackages.get(browserPkg);
3420            if (ps == null) {
3421                Slog.e(TAG, "Product default browser app does not exist: " + browserPkg);
3422                browserPkg = null;
3423            } else {
3424                mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId);
3425            }
3426        }
3427
3428        // Nothing valid explicitly set? Make the factory-installed browser the explicit
3429        // default.  If there's more than one, just leave everything alone.
3430        if (browserPkg == null) {
3431            calculateDefaultBrowserLPw(userId);
3432        }
3433    }
3434
3435    private void calculateDefaultBrowserLPw(int userId) {
3436        List<String> allBrowsers = resolveAllBrowserApps(userId);
3437        final String browserPkg = (allBrowsers.size() == 1) ? allBrowsers.get(0) : null;
3438        mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId);
3439    }
3440
3441    private List<String> resolveAllBrowserApps(int userId) {
3442        // Resolve the canonical browser intent and check that the handleAllWebDataURI boolean is set
3443        List<ResolveInfo> list = queryIntentActivitiesInternal(sBrowserIntent, null,
3444                PackageManager.MATCH_ALL, userId);
3445
3446        final int count = list.size();
3447        List<String> result = new ArrayList<String>(count);
3448        for (int i=0; i<count; i++) {
3449            ResolveInfo info = list.get(i);
3450            if (info.activityInfo == null
3451                    || !info.handleAllWebDataURI
3452                    || (info.activityInfo.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) == 0
3453                    || result.contains(info.activityInfo.packageName)) {
3454                continue;
3455            }
3456            result.add(info.activityInfo.packageName);
3457        }
3458
3459        return result;
3460    }
3461
3462    private boolean packageIsBrowser(String packageName, int userId) {
3463        List<ResolveInfo> list = queryIntentActivitiesInternal(sBrowserIntent, null,
3464                PackageManager.MATCH_ALL, userId);
3465        final int N = list.size();
3466        for (int i = 0; i < N; i++) {
3467            ResolveInfo info = list.get(i);
3468            if (packageName.equals(info.activityInfo.packageName)) {
3469                return true;
3470            }
3471        }
3472        return false;
3473    }
3474
3475    private void checkDefaultBrowser() {
3476        final int myUserId = UserHandle.myUserId();
3477        final String packageName = getDefaultBrowserPackageName(myUserId);
3478        if (packageName != null) {
3479            PackageInfo info = getPackageInfo(packageName, 0, myUserId);
3480            if (info == null) {
3481                Slog.w(TAG, "Default browser no longer installed: " + packageName);
3482                synchronized (mPackages) {
3483                    applyFactoryDefaultBrowserLPw(myUserId);    // leaves ambiguous when > 1
3484                }
3485            }
3486        }
3487    }
3488
3489    @Override
3490    public boolean onTransact(int code, Parcel data, Parcel reply, int flags)
3491            throws RemoteException {
3492        try {
3493            return super.onTransact(code, data, reply, flags);
3494        } catch (RuntimeException e) {
3495            if (!(e instanceof SecurityException) && !(e instanceof IllegalArgumentException)) {
3496                Slog.wtf(TAG, "Package Manager Crash", e);
3497            }
3498            throw e;
3499        }
3500    }
3501
3502    static int[] appendInts(int[] cur, int[] add) {
3503        if (add == null) return cur;
3504        if (cur == null) return add;
3505        final int N = add.length;
3506        for (int i=0; i<N; i++) {
3507            cur = appendInt(cur, add[i]);
3508        }
3509        return cur;
3510    }
3511
3512    /**
3513     * Returns whether or not a full application can see an instant application.
3514     * <p>
3515     * Currently, there are three cases in which this can occur:
3516     * <ol>
3517     * <li>The calling application is a "special" process. The special
3518     *     processes are {@link Process#SYSTEM_UID}, {@link Process#SHELL_UID}
3519     *     and {@code 0}</li>
3520     * <li>The calling application has the permission
3521     *     {@link android.Manifest.permission#ACCESS_INSTANT_APPS}</li>
3522     * <li>The calling application is the default launcher on the
3523     *     system partition.</li>
3524     * </ol>
3525     */
3526    private boolean canViewInstantApps(int callingUid, int userId) {
3527        if (callingUid == Process.SYSTEM_UID
3528                || callingUid == Process.SHELL_UID
3529                || callingUid == Process.ROOT_UID) {
3530            return true;
3531        }
3532        if (mContext.checkCallingOrSelfPermission(
3533                android.Manifest.permission.ACCESS_INSTANT_APPS) == PERMISSION_GRANTED) {
3534            return true;
3535        }
3536        if (mContext.checkCallingOrSelfPermission(
3537                android.Manifest.permission.VIEW_INSTANT_APPS) == PERMISSION_GRANTED) {
3538            final ComponentName homeComponent = getDefaultHomeActivity(userId);
3539            if (homeComponent != null
3540                    && isCallerSameApp(homeComponent.getPackageName(), callingUid)) {
3541                return true;
3542            }
3543        }
3544        return false;
3545    }
3546
3547    private PackageInfo generatePackageInfo(PackageSetting ps, int flags, int userId) {
3548        if (!sUserManager.exists(userId)) return null;
3549        if (ps == null) {
3550            return null;
3551        }
3552        PackageParser.Package p = ps.pkg;
3553        if (p == null) {
3554            return null;
3555        }
3556        final int callingUid = Binder.getCallingUid();
3557        // Filter out ephemeral app metadata:
3558        //   * The system/shell/root can see metadata for any app
3559        //   * An installed app can see metadata for 1) other installed apps
3560        //     and 2) ephemeral apps that have explicitly interacted with it
3561        //   * Ephemeral apps can only see their own data and exposed installed apps
3562        //   * Holding a signature permission allows seeing instant apps
3563        if (filterAppAccessLPr(ps, callingUid, userId)) {
3564            return null;
3565        }
3566
3567        final PermissionsState permissionsState = ps.getPermissionsState();
3568
3569        // Compute GIDs only if requested
3570        final int[] gids = (flags & PackageManager.GET_GIDS) == 0
3571                ? EMPTY_INT_ARRAY : permissionsState.computeGids(userId);
3572        // Compute granted permissions only if package has requested permissions
3573        final Set<String> permissions = ArrayUtils.isEmpty(p.requestedPermissions)
3574                ? Collections.<String>emptySet() : permissionsState.getPermissions(userId);
3575        final PackageUserState state = ps.readUserState(userId);
3576
3577        if ((flags & MATCH_UNINSTALLED_PACKAGES) != 0
3578                && ps.isSystem()) {
3579            flags |= MATCH_ANY_USER;
3580        }
3581
3582        PackageInfo packageInfo = PackageParser.generatePackageInfo(p, gids, flags,
3583                ps.firstInstallTime, ps.lastUpdateTime, permissions, state, userId);
3584
3585        if (packageInfo == null) {
3586            return null;
3587        }
3588
3589        packageInfo.packageName = packageInfo.applicationInfo.packageName =
3590                resolveExternalPackageNameLPr(p);
3591
3592        return packageInfo;
3593    }
3594
3595    @Override
3596    public void checkPackageStartable(String packageName, int userId) {
3597        final int callingUid = Binder.getCallingUid();
3598        if (getInstantAppPackageName(callingUid) != null) {
3599            throw new SecurityException("Instant applications don't have access to this method");
3600        }
3601        final boolean userKeyUnlocked = StorageManager.isUserKeyUnlocked(userId);
3602        synchronized (mPackages) {
3603            final PackageSetting ps = mSettings.mPackages.get(packageName);
3604            if (ps == null || filterAppAccessLPr(ps, callingUid, userId)) {
3605                throw new SecurityException("Package " + packageName + " was not found!");
3606            }
3607
3608            if (!ps.getInstalled(userId)) {
3609                throw new SecurityException(
3610                        "Package " + packageName + " was not installed for user " + userId + "!");
3611            }
3612
3613            if (mSafeMode && !ps.isSystem()) {
3614                throw new SecurityException("Package " + packageName + " not a system app!");
3615            }
3616
3617            if (mFrozenPackages.contains(packageName)) {
3618                throw new SecurityException("Package " + packageName + " is currently frozen!");
3619            }
3620
3621            if (!userKeyUnlocked && !(ps.pkg.applicationInfo.isDirectBootAware()
3622                    || ps.pkg.applicationInfo.isPartiallyDirectBootAware())) {
3623                throw new SecurityException("Package " + packageName + " is not encryption aware!");
3624            }
3625        }
3626    }
3627
3628    @Override
3629    public boolean isPackageAvailable(String packageName, int userId) {
3630        if (!sUserManager.exists(userId)) return false;
3631        final int callingUid = Binder.getCallingUid();
3632        enforceCrossUserPermission(callingUid, userId,
3633                false /*requireFullPermission*/, false /*checkShell*/, "is package available");
3634        synchronized (mPackages) {
3635            PackageParser.Package p = mPackages.get(packageName);
3636            if (p != null) {
3637                final PackageSetting ps = (PackageSetting) p.mExtras;
3638                if (filterAppAccessLPr(ps, callingUid, userId)) {
3639                    return false;
3640                }
3641                if (ps != null) {
3642                    final PackageUserState state = ps.readUserState(userId);
3643                    if (state != null) {
3644                        return PackageParser.isAvailable(state);
3645                    }
3646                }
3647            }
3648        }
3649        return false;
3650    }
3651
3652    @Override
3653    public PackageInfo getPackageInfo(String packageName, int flags, int userId) {
3654        return getPackageInfoInternal(packageName, PackageManager.VERSION_CODE_HIGHEST,
3655                flags, Binder.getCallingUid(), userId);
3656    }
3657
3658    @Override
3659    public PackageInfo getPackageInfoVersioned(VersionedPackage versionedPackage,
3660            int flags, int userId) {
3661        return getPackageInfoInternal(versionedPackage.getPackageName(),
3662                versionedPackage.getVersionCode(), flags, Binder.getCallingUid(), userId);
3663    }
3664
3665    /**
3666     * Important: The provided filterCallingUid is used exclusively to filter out packages
3667     * that can be seen based on user state. It's typically the original caller uid prior
3668     * to clearing. Because it can only be provided by trusted code, it's value can be
3669     * trusted and will be used as-is; unlike userId which will be validated by this method.
3670     */
3671    private PackageInfo getPackageInfoInternal(String packageName, int versionCode,
3672            int flags, int filterCallingUid, int userId) {
3673        if (!sUserManager.exists(userId)) return null;
3674        flags = updateFlagsForPackage(flags, userId, packageName);
3675        enforceCrossUserPermission(Binder.getCallingUid(), userId,
3676                false /* requireFullPermission */, false /* checkShell */, "get package info");
3677
3678        // reader
3679        synchronized (mPackages) {
3680            // Normalize package name to handle renamed packages and static libs
3681            packageName = resolveInternalPackageNameLPr(packageName, versionCode);
3682
3683            final boolean matchFactoryOnly = (flags & MATCH_FACTORY_ONLY) != 0;
3684            if (matchFactoryOnly) {
3685                final PackageSetting ps = mSettings.getDisabledSystemPkgLPr(packageName);
3686                if (ps != null) {
3687                    if (filterSharedLibPackageLPr(ps, filterCallingUid, userId, flags)) {
3688                        return null;
3689                    }
3690                    if (filterAppAccessLPr(ps, filterCallingUid, userId)) {
3691                        return null;
3692                    }
3693                    return generatePackageInfo(ps, flags, userId);
3694                }
3695            }
3696
3697            PackageParser.Package p = mPackages.get(packageName);
3698            if (matchFactoryOnly && p != null && !isSystemApp(p)) {
3699                return null;
3700            }
3701            if (DEBUG_PACKAGE_INFO)
3702                Log.v(TAG, "getPackageInfo " + packageName + ": " + p);
3703            if (p != null) {
3704                final PackageSetting ps = (PackageSetting) p.mExtras;
3705                if (filterSharedLibPackageLPr(ps, filterCallingUid, userId, flags)) {
3706                    return null;
3707                }
3708                if (ps != null && filterAppAccessLPr(ps, filterCallingUid, userId)) {
3709                    return null;
3710                }
3711                return generatePackageInfo((PackageSetting)p.mExtras, flags, userId);
3712            }
3713            if (!matchFactoryOnly && (flags & MATCH_KNOWN_PACKAGES) != 0) {
3714                final PackageSetting ps = mSettings.mPackages.get(packageName);
3715                if (ps == null) return null;
3716                if (filterSharedLibPackageLPr(ps, filterCallingUid, userId, flags)) {
3717                    return null;
3718                }
3719                if (filterAppAccessLPr(ps, filterCallingUid, userId)) {
3720                    return null;
3721                }
3722                return generatePackageInfo(ps, flags, userId);
3723            }
3724        }
3725        return null;
3726    }
3727
3728    private boolean isComponentVisibleToInstantApp(@Nullable ComponentName component) {
3729        if (isComponentVisibleToInstantApp(component, TYPE_ACTIVITY)) {
3730            return true;
3731        }
3732        if (isComponentVisibleToInstantApp(component, TYPE_SERVICE)) {
3733            return true;
3734        }
3735        if (isComponentVisibleToInstantApp(component, TYPE_PROVIDER)) {
3736            return true;
3737        }
3738        return false;
3739    }
3740
3741    private boolean isComponentVisibleToInstantApp(
3742            @Nullable ComponentName component, @ComponentType int type) {
3743        if (type == TYPE_ACTIVITY) {
3744            final PackageParser.Activity activity = mActivities.mActivities.get(component);
3745            return activity != null
3746                    ? (activity.info.flags & ActivityInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0
3747                    : false;
3748        } else if (type == TYPE_RECEIVER) {
3749            final PackageParser.Activity activity = mReceivers.mActivities.get(component);
3750            return activity != null
3751                    ? (activity.info.flags & ActivityInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0
3752                    : false;
3753        } else if (type == TYPE_SERVICE) {
3754            final PackageParser.Service service = mServices.mServices.get(component);
3755            return service != null
3756                    ? (service.info.flags & ServiceInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0
3757                    : false;
3758        } else if (type == TYPE_PROVIDER) {
3759            final PackageParser.Provider provider = mProviders.mProviders.get(component);
3760            return provider != null
3761                    ? (provider.info.flags & ProviderInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0
3762                    : false;
3763        } else if (type == TYPE_UNKNOWN) {
3764            return isComponentVisibleToInstantApp(component);
3765        }
3766        return false;
3767    }
3768
3769    /**
3770     * Returns whether or not access to the application should be filtered.
3771     * <p>
3772     * Access may be limited based upon whether the calling or target applications
3773     * are instant applications.
3774     *
3775     * @see #canAccessInstantApps(int)
3776     */
3777    private boolean filterAppAccessLPr(@Nullable PackageSetting ps, int callingUid,
3778            @Nullable ComponentName component, @ComponentType int componentType, int userId) {
3779        // if we're in an isolated process, get the real calling UID
3780        if (Process.isIsolated(callingUid)) {
3781            callingUid = mIsolatedOwners.get(callingUid);
3782        }
3783        final String instantAppPkgName = getInstantAppPackageName(callingUid);
3784        final boolean callerIsInstantApp = instantAppPkgName != null;
3785        if (ps == null) {
3786            if (callerIsInstantApp) {
3787                // pretend the application exists, but, needs to be filtered
3788                return true;
3789            }
3790            return false;
3791        }
3792        // if the target and caller are the same application, don't filter
3793        if (isCallerSameApp(ps.name, callingUid)) {
3794            return false;
3795        }
3796        if (callerIsInstantApp) {
3797            // request for a specific component; if it hasn't been explicitly exposed, filter
3798            if (component != null) {
3799                return !isComponentVisibleToInstantApp(component, componentType);
3800            }
3801            // request for application; if no components have been explicitly exposed, filter
3802            return ps.getInstantApp(userId) || !ps.pkg.visibleToInstantApps;
3803        }
3804        if (ps.getInstantApp(userId)) {
3805            // caller can see all components of all instant applications, don't filter
3806            if (canViewInstantApps(callingUid, userId)) {
3807                return false;
3808            }
3809            // request for a specific instant application component, filter
3810            if (component != null) {
3811                return true;
3812            }
3813            // request for an instant application; if the caller hasn't been granted access, filter
3814            return !mInstantAppRegistry.isInstantAccessGranted(
3815                    userId, UserHandle.getAppId(callingUid), ps.appId);
3816        }
3817        return false;
3818    }
3819
3820    /**
3821     * @see #filterAppAccessLPr(PackageSetting, int, ComponentName, boolean, int)
3822     */
3823    private boolean filterAppAccessLPr(@Nullable PackageSetting ps, int callingUid, int userId) {
3824        return filterAppAccessLPr(ps, callingUid, null, TYPE_UNKNOWN, userId);
3825    }
3826
3827    private boolean filterSharedLibPackageLPr(@Nullable PackageSetting ps, int uid, int userId,
3828            int flags) {
3829        // Callers can access only the libs they depend on, otherwise they need to explicitly
3830        // ask for the shared libraries given the caller is allowed to access all static libs.
3831        if ((flags & PackageManager.MATCH_STATIC_SHARED_LIBRARIES) != 0) {
3832            // System/shell/root get to see all static libs
3833            final int appId = UserHandle.getAppId(uid);
3834            if (appId == Process.SYSTEM_UID || appId == Process.SHELL_UID
3835                    || appId == Process.ROOT_UID) {
3836                return false;
3837            }
3838        }
3839
3840        // No package means no static lib as it is always on internal storage
3841        if (ps == null || ps.pkg == null || !ps.pkg.applicationInfo.isStaticSharedLibrary()) {
3842            return false;
3843        }
3844
3845        final SharedLibraryEntry libEntry = getSharedLibraryEntryLPr(ps.pkg.staticSharedLibName,
3846                ps.pkg.staticSharedLibVersion);
3847        if (libEntry == null) {
3848            return false;
3849        }
3850
3851        final int resolvedUid = UserHandle.getUid(userId, UserHandle.getAppId(uid));
3852        final String[] uidPackageNames = getPackagesForUid(resolvedUid);
3853        if (uidPackageNames == null) {
3854            return true;
3855        }
3856
3857        for (String uidPackageName : uidPackageNames) {
3858            if (ps.name.equals(uidPackageName)) {
3859                return false;
3860            }
3861            PackageSetting uidPs = mSettings.getPackageLPr(uidPackageName);
3862            if (uidPs != null) {
3863                final int index = ArrayUtils.indexOf(uidPs.usesStaticLibraries,
3864                        libEntry.info.getName());
3865                if (index < 0) {
3866                    continue;
3867                }
3868                if (uidPs.pkg.usesStaticLibrariesVersions[index] == libEntry.info.getVersion()) {
3869                    return false;
3870                }
3871            }
3872        }
3873        return true;
3874    }
3875
3876    @Override
3877    public String[] currentToCanonicalPackageNames(String[] names) {
3878        final int callingUid = Binder.getCallingUid();
3879        if (getInstantAppPackageName(callingUid) != null) {
3880            return names;
3881        }
3882        final String[] out = new String[names.length];
3883        // reader
3884        synchronized (mPackages) {
3885            final int callingUserId = UserHandle.getUserId(callingUid);
3886            final boolean canViewInstantApps = canViewInstantApps(callingUid, callingUserId);
3887            for (int i=names.length-1; i>=0; i--) {
3888                final PackageSetting ps = mSettings.mPackages.get(names[i]);
3889                boolean translateName = false;
3890                if (ps != null && ps.realName != null) {
3891                    final boolean targetIsInstantApp = ps.getInstantApp(callingUserId);
3892                    translateName = !targetIsInstantApp
3893                            || canViewInstantApps
3894                            || mInstantAppRegistry.isInstantAccessGranted(callingUserId,
3895                                    UserHandle.getAppId(callingUid), ps.appId);
3896                }
3897                out[i] = translateName ? ps.realName : names[i];
3898            }
3899        }
3900        return out;
3901    }
3902
3903    @Override
3904    public String[] canonicalToCurrentPackageNames(String[] names) {
3905        final int callingUid = Binder.getCallingUid();
3906        if (getInstantAppPackageName(callingUid) != null) {
3907            return names;
3908        }
3909        final String[] out = new String[names.length];
3910        // reader
3911        synchronized (mPackages) {
3912            final int callingUserId = UserHandle.getUserId(callingUid);
3913            final boolean canViewInstantApps = canViewInstantApps(callingUid, callingUserId);
3914            for (int i=names.length-1; i>=0; i--) {
3915                final String cur = mSettings.getRenamedPackageLPr(names[i]);
3916                boolean translateName = false;
3917                if (cur != null) {
3918                    final PackageSetting ps = mSettings.mPackages.get(names[i]);
3919                    final boolean targetIsInstantApp =
3920                            ps != null && ps.getInstantApp(callingUserId);
3921                    translateName = !targetIsInstantApp
3922                            || canViewInstantApps
3923                            || mInstantAppRegistry.isInstantAccessGranted(callingUserId,
3924                                    UserHandle.getAppId(callingUid), ps.appId);
3925                }
3926                out[i] = translateName ? cur : names[i];
3927            }
3928        }
3929        return out;
3930    }
3931
3932    @Override
3933    public int getPackageUid(String packageName, int flags, int userId) {
3934        if (!sUserManager.exists(userId)) return -1;
3935        final int callingUid = Binder.getCallingUid();
3936        flags = updateFlagsForPackage(flags, userId, packageName);
3937        enforceCrossUserPermission(callingUid, userId,
3938                false /*requireFullPermission*/, false /*checkShell*/, "getPackageUid");
3939
3940        // reader
3941        synchronized (mPackages) {
3942            final PackageParser.Package p = mPackages.get(packageName);
3943            if (p != null && p.isMatch(flags)) {
3944                PackageSetting ps = (PackageSetting) p.mExtras;
3945                if (filterAppAccessLPr(ps, callingUid, userId)) {
3946                    return -1;
3947                }
3948                return UserHandle.getUid(userId, p.applicationInfo.uid);
3949            }
3950            if ((flags & MATCH_KNOWN_PACKAGES) != 0) {
3951                final PackageSetting ps = mSettings.mPackages.get(packageName);
3952                if (ps != null && ps.isMatch(flags)
3953                        && !filterAppAccessLPr(ps, callingUid, userId)) {
3954                    return UserHandle.getUid(userId, ps.appId);
3955                }
3956            }
3957        }
3958
3959        return -1;
3960    }
3961
3962    @Override
3963    public int[] getPackageGids(String packageName, int flags, int userId) {
3964        if (!sUserManager.exists(userId)) return null;
3965        final int callingUid = Binder.getCallingUid();
3966        flags = updateFlagsForPackage(flags, userId, packageName);
3967        enforceCrossUserPermission(callingUid, userId,
3968                false /*requireFullPermission*/, false /*checkShell*/, "getPackageGids");
3969
3970        // reader
3971        synchronized (mPackages) {
3972            final PackageParser.Package p = mPackages.get(packageName);
3973            if (p != null && p.isMatch(flags)) {
3974                PackageSetting ps = (PackageSetting) p.mExtras;
3975                if (filterAppAccessLPr(ps, callingUid, userId)) {
3976                    return null;
3977                }
3978                // TODO: Shouldn't this be checking for package installed state for userId and
3979                // return null?
3980                return ps.getPermissionsState().computeGids(userId);
3981            }
3982            if ((flags & MATCH_KNOWN_PACKAGES) != 0) {
3983                final PackageSetting ps = mSettings.mPackages.get(packageName);
3984                if (ps != null && ps.isMatch(flags)
3985                        && !filterAppAccessLPr(ps, callingUid, userId)) {
3986                    return ps.getPermissionsState().computeGids(userId);
3987                }
3988            }
3989        }
3990
3991        return null;
3992    }
3993
3994    static PermissionInfo generatePermissionInfo(BasePermission bp, int flags) {
3995        if (bp.perm != null) {
3996            return PackageParser.generatePermissionInfo(bp.perm, flags);
3997        }
3998        PermissionInfo pi = new PermissionInfo();
3999        pi.name = bp.name;
4000        pi.packageName = bp.sourcePackage;
4001        pi.nonLocalizedLabel = bp.name;
4002        pi.protectionLevel = bp.protectionLevel;
4003        return pi;
4004    }
4005
4006    @Override
4007    public PermissionInfo getPermissionInfo(String name, int flags) {
4008        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
4009            return null;
4010        }
4011        // reader
4012        synchronized (mPackages) {
4013            final BasePermission p = mSettings.mPermissions.get(name);
4014            if (p != null) {
4015                return generatePermissionInfo(p, flags);
4016            }
4017            return null;
4018        }
4019    }
4020
4021    @Override
4022    public @Nullable ParceledListSlice<PermissionInfo> queryPermissionsByGroup(String group,
4023            int flags) {
4024        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
4025            return null;
4026        }
4027        // reader
4028        synchronized (mPackages) {
4029            if (group != null && !mPermissionGroups.containsKey(group)) {
4030                // This is thrown as NameNotFoundException
4031                return null;
4032            }
4033
4034            ArrayList<PermissionInfo> out = new ArrayList<PermissionInfo>(10);
4035            for (BasePermission p : mSettings.mPermissions.values()) {
4036                if (group == null) {
4037                    if (p.perm == null || p.perm.info.group == null) {
4038                        out.add(generatePermissionInfo(p, flags));
4039                    }
4040                } else {
4041                    if (p.perm != null && group.equals(p.perm.info.group)) {
4042                        out.add(PackageParser.generatePermissionInfo(p.perm, flags));
4043                    }
4044                }
4045            }
4046            return new ParceledListSlice<>(out);
4047        }
4048    }
4049
4050    @Override
4051    public PermissionGroupInfo getPermissionGroupInfo(String name, int flags) {
4052        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
4053            return null;
4054        }
4055        // reader
4056        synchronized (mPackages) {
4057            return PackageParser.generatePermissionGroupInfo(
4058                    mPermissionGroups.get(name), flags);
4059        }
4060    }
4061
4062    @Override
4063    public @NonNull ParceledListSlice<PermissionGroupInfo> getAllPermissionGroups(int flags) {
4064        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
4065            return ParceledListSlice.emptyList();
4066        }
4067        // reader
4068        synchronized (mPackages) {
4069            final int N = mPermissionGroups.size();
4070            ArrayList<PermissionGroupInfo> out
4071                    = new ArrayList<PermissionGroupInfo>(N);
4072            for (PackageParser.PermissionGroup pg : mPermissionGroups.values()) {
4073                out.add(PackageParser.generatePermissionGroupInfo(pg, flags));
4074            }
4075            return new ParceledListSlice<>(out);
4076        }
4077    }
4078
4079    private ApplicationInfo generateApplicationInfoFromSettingsLPw(String packageName, int flags,
4080            int filterCallingUid, int userId) {
4081        if (!sUserManager.exists(userId)) return null;
4082        PackageSetting ps = mSettings.mPackages.get(packageName);
4083        if (ps != null) {
4084            if (filterSharedLibPackageLPr(ps, filterCallingUid, userId, flags)) {
4085                return null;
4086            }
4087            if (filterAppAccessLPr(ps, filterCallingUid, userId)) {
4088                return null;
4089            }
4090            if (ps.pkg == null) {
4091                final PackageInfo pInfo = generatePackageInfo(ps, flags, userId);
4092                if (pInfo != null) {
4093                    return pInfo.applicationInfo;
4094                }
4095                return null;
4096            }
4097            ApplicationInfo ai = PackageParser.generateApplicationInfo(ps.pkg, flags,
4098                    ps.readUserState(userId), userId);
4099            if (ai != null) {
4100                ai.packageName = resolveExternalPackageNameLPr(ps.pkg);
4101            }
4102            return ai;
4103        }
4104        return null;
4105    }
4106
4107    @Override
4108    public ApplicationInfo getApplicationInfo(String packageName, int flags, int userId) {
4109        return getApplicationInfoInternal(packageName, flags, Binder.getCallingUid(), userId);
4110    }
4111
4112    /**
4113     * Important: The provided filterCallingUid is used exclusively to filter out applications
4114     * that can be seen based on user state. It's typically the original caller uid prior
4115     * to clearing. Because it can only be provided by trusted code, it's value can be
4116     * trusted and will be used as-is; unlike userId which will be validated by this method.
4117     */
4118    private ApplicationInfo getApplicationInfoInternal(String packageName, int flags,
4119            int filterCallingUid, int userId) {
4120        if (!sUserManager.exists(userId)) return null;
4121        flags = updateFlagsForApplication(flags, userId, packageName);
4122        enforceCrossUserPermission(Binder.getCallingUid(), userId,
4123                false /* requireFullPermission */, false /* checkShell */, "get application info");
4124
4125        // writer
4126        synchronized (mPackages) {
4127            // Normalize package name to handle renamed packages and static libs
4128            packageName = resolveInternalPackageNameLPr(packageName,
4129                    PackageManager.VERSION_CODE_HIGHEST);
4130
4131            PackageParser.Package p = mPackages.get(packageName);
4132            if (DEBUG_PACKAGE_INFO) Log.v(
4133                    TAG, "getApplicationInfo " + packageName
4134                    + ": " + p);
4135            if (p != null) {
4136                PackageSetting ps = mSettings.mPackages.get(packageName);
4137                if (ps == null) return null;
4138                if (filterSharedLibPackageLPr(ps, filterCallingUid, userId, flags)) {
4139                    return null;
4140                }
4141                if (filterAppAccessLPr(ps, filterCallingUid, userId)) {
4142                    return null;
4143                }
4144                // Note: isEnabledLP() does not apply here - always return info
4145                ApplicationInfo ai = PackageParser.generateApplicationInfo(
4146                        p, flags, ps.readUserState(userId), userId);
4147                if (ai != null) {
4148                    ai.packageName = resolveExternalPackageNameLPr(p);
4149                }
4150                return ai;
4151            }
4152            if ("android".equals(packageName)||"system".equals(packageName)) {
4153                return mAndroidApplication;
4154            }
4155            if ((flags & MATCH_KNOWN_PACKAGES) != 0) {
4156                // Already generates the external package name
4157                return generateApplicationInfoFromSettingsLPw(packageName,
4158                        flags, filterCallingUid, userId);
4159            }
4160        }
4161        return null;
4162    }
4163
4164    private String normalizePackageNameLPr(String packageName) {
4165        String normalizedPackageName = mSettings.getRenamedPackageLPr(packageName);
4166        return normalizedPackageName != null ? normalizedPackageName : packageName;
4167    }
4168
4169    @Override
4170    public void deletePreloadsFileCache() {
4171        if (!UserHandle.isSameApp(Binder.getCallingUid(), Process.SYSTEM_UID)) {
4172            throw new SecurityException("Only system or settings may call deletePreloadsFileCache");
4173        }
4174        File dir = Environment.getDataPreloadsFileCacheDirectory();
4175        Slog.i(TAG, "Deleting preloaded file cache " + dir);
4176        FileUtils.deleteContents(dir);
4177    }
4178
4179    @Override
4180    public void freeStorageAndNotify(final String volumeUuid, final long freeStorageSize,
4181            final int storageFlags, final IPackageDataObserver observer) {
4182        mContext.enforceCallingOrSelfPermission(
4183                android.Manifest.permission.CLEAR_APP_CACHE, null);
4184        mHandler.post(() -> {
4185            boolean success = false;
4186            try {
4187                freeStorage(volumeUuid, freeStorageSize, storageFlags);
4188                success = true;
4189            } catch (IOException e) {
4190                Slog.w(TAG, e);
4191            }
4192            if (observer != null) {
4193                try {
4194                    observer.onRemoveCompleted(null, success);
4195                } catch (RemoteException e) {
4196                    Slog.w(TAG, e);
4197                }
4198            }
4199        });
4200    }
4201
4202    @Override
4203    public void freeStorage(final String volumeUuid, final long freeStorageSize,
4204            final int storageFlags, final IntentSender pi) {
4205        mContext.enforceCallingOrSelfPermission(
4206                android.Manifest.permission.CLEAR_APP_CACHE, TAG);
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 (pi != null) {
4216                try {
4217                    pi.sendIntent(null, success ? 1 : 0, null, null, null);
4218                } catch (SendIntentException e) {
4219                    Slog.w(TAG, e);
4220                }
4221            }
4222        });
4223    }
4224
4225    /**
4226     * Blocking call to clear various types of cached data across the system
4227     * until the requested bytes are available.
4228     */
4229    public void freeStorage(String volumeUuid, long bytes, int storageFlags) throws IOException {
4230        final StorageManager storage = mContext.getSystemService(StorageManager.class);
4231        final File file = storage.findPathForUuid(volumeUuid);
4232        if (file.getUsableSpace() >= bytes) return;
4233
4234        if (ENABLE_FREE_CACHE_V2) {
4235            final boolean internalVolume = Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL,
4236                    volumeUuid);
4237            final boolean aggressive = (storageFlags
4238                    & StorageManager.FLAG_ALLOCATE_AGGRESSIVE) != 0;
4239            final long reservedBytes = storage.getStorageCacheBytes(file, storageFlags);
4240
4241            // 1. Pre-flight to determine if we have any chance to succeed
4242            // 2. Consider preloaded data (after 1w honeymoon, unless aggressive)
4243            if (internalVolume && (aggressive || SystemProperties
4244                    .getBoolean("persist.sys.preloads.file_cache_expired", false))) {
4245                deletePreloadsFileCache();
4246                if (file.getUsableSpace() >= bytes) return;
4247            }
4248
4249            // 3. Consider parsed APK data (aggressive only)
4250            if (internalVolume && aggressive) {
4251                FileUtils.deleteContents(mCacheDir);
4252                if (file.getUsableSpace() >= bytes) return;
4253            }
4254
4255            // 4. Consider cached app data (above quotas)
4256            try {
4257                mInstaller.freeCache(volumeUuid, bytes, reservedBytes,
4258                        Installer.FLAG_FREE_CACHE_V2);
4259            } catch (InstallerException ignored) {
4260            }
4261            if (file.getUsableSpace() >= bytes) return;
4262
4263            // 5. Consider shared libraries with refcount=0 and age>min cache period
4264            if (internalVolume && pruneUnusedStaticSharedLibraries(bytes,
4265                    android.provider.Settings.Global.getLong(mContext.getContentResolver(),
4266                            Global.UNUSED_STATIC_SHARED_LIB_MIN_CACHE_PERIOD,
4267                            DEFAULT_UNUSED_STATIC_SHARED_LIB_MIN_CACHE_PERIOD))) {
4268                return;
4269            }
4270
4271            // 6. Consider dexopt output (aggressive only)
4272            // TODO: Implement
4273
4274            // 7. Consider installed instant apps unused longer than min cache period
4275            if (internalVolume && mInstantAppRegistry.pruneInstalledInstantApps(bytes,
4276                    android.provider.Settings.Global.getLong(mContext.getContentResolver(),
4277                            Global.INSTALLED_INSTANT_APP_MIN_CACHE_PERIOD,
4278                            InstantAppRegistry.DEFAULT_INSTALLED_INSTANT_APP_MIN_CACHE_PERIOD))) {
4279                return;
4280            }
4281
4282            // 8. Consider cached app data (below quotas)
4283            try {
4284                mInstaller.freeCache(volumeUuid, bytes, reservedBytes,
4285                        Installer.FLAG_FREE_CACHE_V2 | Installer.FLAG_FREE_CACHE_V2_DEFY_QUOTA);
4286            } catch (InstallerException ignored) {
4287            }
4288            if (file.getUsableSpace() >= bytes) return;
4289
4290            // 9. Consider DropBox entries
4291            // TODO: Implement
4292
4293            // 10. Consider instant meta-data (uninstalled apps) older that min cache period
4294            if (internalVolume && mInstantAppRegistry.pruneUninstalledInstantApps(bytes,
4295                    android.provider.Settings.Global.getLong(mContext.getContentResolver(),
4296                            Global.UNINSTALLED_INSTANT_APP_MIN_CACHE_PERIOD,
4297                            InstantAppRegistry.DEFAULT_UNINSTALLED_INSTANT_APP_MIN_CACHE_PERIOD))) {
4298                return;
4299            }
4300        } else {
4301            try {
4302                mInstaller.freeCache(volumeUuid, bytes, 0, 0);
4303            } catch (InstallerException ignored) {
4304            }
4305            if (file.getUsableSpace() >= bytes) return;
4306        }
4307
4308        throw new IOException("Failed to free " + bytes + " on storage device at " + file);
4309    }
4310
4311    private boolean pruneUnusedStaticSharedLibraries(long neededSpace, long maxCachePeriod)
4312            throws IOException {
4313        final StorageManager storage = mContext.getSystemService(StorageManager.class);
4314        final File volume = storage.findPathForUuid(StorageManager.UUID_PRIVATE_INTERNAL);
4315
4316        List<VersionedPackage> packagesToDelete = null;
4317        final long now = System.currentTimeMillis();
4318
4319        synchronized (mPackages) {
4320            final int[] allUsers = sUserManager.getUserIds();
4321            final int libCount = mSharedLibraries.size();
4322            for (int i = 0; i < libCount; i++) {
4323                final SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.valueAt(i);
4324                if (versionedLib == null) {
4325                    continue;
4326                }
4327                final int versionCount = versionedLib.size();
4328                for (int j = 0; j < versionCount; j++) {
4329                    SharedLibraryInfo libInfo = versionedLib.valueAt(j).info;
4330                    // Skip packages that are not static shared libs.
4331                    if (!libInfo.isStatic()) {
4332                        break;
4333                    }
4334                    // Important: We skip static shared libs used for some user since
4335                    // in such a case we need to keep the APK on the device. The check for
4336                    // a lib being used for any user is performed by the uninstall call.
4337                    final VersionedPackage declaringPackage = libInfo.getDeclaringPackage();
4338                    // Resolve the package name - we use synthetic package names internally
4339                    final String internalPackageName = resolveInternalPackageNameLPr(
4340                            declaringPackage.getPackageName(), declaringPackage.getVersionCode());
4341                    final PackageSetting ps = mSettings.getPackageLPr(internalPackageName);
4342                    // Skip unused static shared libs cached less than the min period
4343                    // to prevent pruning a lib needed by a subsequently installed package.
4344                    if (ps == null || now - ps.lastUpdateTime < maxCachePeriod) {
4345                        continue;
4346                    }
4347                    if (packagesToDelete == null) {
4348                        packagesToDelete = new ArrayList<>();
4349                    }
4350                    packagesToDelete.add(new VersionedPackage(internalPackageName,
4351                            declaringPackage.getVersionCode()));
4352                }
4353            }
4354        }
4355
4356        if (packagesToDelete != null) {
4357            final int packageCount = packagesToDelete.size();
4358            for (int i = 0; i < packageCount; i++) {
4359                final VersionedPackage pkgToDelete = packagesToDelete.get(i);
4360                // Delete the package synchronously (will fail of the lib used for any user).
4361                if (deletePackageX(pkgToDelete.getPackageName(), pkgToDelete.getVersionCode(),
4362                        UserHandle.USER_SYSTEM, PackageManager.DELETE_ALL_USERS)
4363                                == PackageManager.DELETE_SUCCEEDED) {
4364                    if (volume.getUsableSpace() >= neededSpace) {
4365                        return true;
4366                    }
4367                }
4368            }
4369        }
4370
4371        return false;
4372    }
4373
4374    /**
4375     * Update given flags based on encryption status of current user.
4376     */
4377    private int updateFlags(int flags, int userId) {
4378        if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE
4379                | PackageManager.MATCH_DIRECT_BOOT_AWARE)) != 0) {
4380            // Caller expressed an explicit opinion about what encryption
4381            // aware/unaware components they want to see, so fall through and
4382            // give them what they want
4383        } else {
4384            // Caller expressed no opinion, so match based on user state
4385            if (getUserManagerInternal().isUserUnlockingOrUnlocked(userId)) {
4386                flags |= PackageManager.MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE;
4387            } else {
4388                flags |= PackageManager.MATCH_DIRECT_BOOT_AWARE;
4389            }
4390        }
4391        return flags;
4392    }
4393
4394    private UserManagerInternal getUserManagerInternal() {
4395        if (mUserManagerInternal == null) {
4396            mUserManagerInternal = LocalServices.getService(UserManagerInternal.class);
4397        }
4398        return mUserManagerInternal;
4399    }
4400
4401    private DeviceIdleController.LocalService getDeviceIdleController() {
4402        if (mDeviceIdleController == null) {
4403            mDeviceIdleController =
4404                    LocalServices.getService(DeviceIdleController.LocalService.class);
4405        }
4406        return mDeviceIdleController;
4407    }
4408
4409    /**
4410     * Update given flags when being used to request {@link PackageInfo}.
4411     */
4412    private int updateFlagsForPackage(int flags, int userId, Object cookie) {
4413        final boolean isCallerSystemUser = UserHandle.getCallingUserId() == UserHandle.USER_SYSTEM;
4414        boolean triaged = true;
4415        if ((flags & (PackageManager.GET_ACTIVITIES | PackageManager.GET_RECEIVERS
4416                | PackageManager.GET_SERVICES | PackageManager.GET_PROVIDERS)) != 0) {
4417            // Caller is asking for component details, so they'd better be
4418            // asking for specific encryption matching behavior, or be triaged
4419            if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE
4420                    | PackageManager.MATCH_DIRECT_BOOT_AWARE
4421                    | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) {
4422                triaged = false;
4423            }
4424        }
4425        if ((flags & (PackageManager.MATCH_UNINSTALLED_PACKAGES
4426                | PackageManager.MATCH_SYSTEM_ONLY
4427                | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) {
4428            triaged = false;
4429        }
4430        if ((flags & PackageManager.MATCH_ANY_USER) != 0) {
4431            enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false,
4432                    "MATCH_ANY_USER flag requires INTERACT_ACROSS_USERS permission at "
4433                    + Debug.getCallers(5));
4434        } else if ((flags & PackageManager.MATCH_UNINSTALLED_PACKAGES) != 0 && isCallerSystemUser
4435                && sUserManager.hasManagedProfile(UserHandle.USER_SYSTEM)) {
4436            // If the caller wants all packages and has a restricted profile associated with it,
4437            // then match all users. This is to make sure that launchers that need to access work
4438            // profile apps don't start breaking. TODO: Remove this hack when launchers stop using
4439            // MATCH_UNINSTALLED_PACKAGES to query apps in other profiles. b/31000380
4440            flags |= PackageManager.MATCH_ANY_USER;
4441        }
4442        if (DEBUG_TRIAGED_MISSING && (Binder.getCallingUid() == Process.SYSTEM_UID) && !triaged) {
4443            Log.w(TAG, "Caller hasn't been triaged for missing apps; they asked about " + cookie
4444                    + " with flags 0x" + Integer.toHexString(flags), new Throwable());
4445        }
4446        return updateFlags(flags, userId);
4447    }
4448
4449    /**
4450     * Update given flags when being used to request {@link ApplicationInfo}.
4451     */
4452    private int updateFlagsForApplication(int flags, int userId, Object cookie) {
4453        return updateFlagsForPackage(flags, userId, cookie);
4454    }
4455
4456    /**
4457     * Update given flags when being used to request {@link ComponentInfo}.
4458     */
4459    private int updateFlagsForComponent(int flags, int userId, Object cookie) {
4460        if (cookie instanceof Intent) {
4461            if ((((Intent) cookie).getFlags() & Intent.FLAG_DEBUG_TRIAGED_MISSING) != 0) {
4462                flags |= PackageManager.MATCH_DEBUG_TRIAGED_MISSING;
4463            }
4464        }
4465
4466        boolean triaged = true;
4467        // Caller is asking for component details, so they'd better be
4468        // asking for specific encryption matching behavior, or be triaged
4469        if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE
4470                | PackageManager.MATCH_DIRECT_BOOT_AWARE
4471                | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) {
4472            triaged = false;
4473        }
4474        if (DEBUG_TRIAGED_MISSING && (Binder.getCallingUid() == Process.SYSTEM_UID) && !triaged) {
4475            Log.w(TAG, "Caller hasn't been triaged for missing apps; they asked about " + cookie
4476                    + " with flags 0x" + Integer.toHexString(flags), new Throwable());
4477        }
4478
4479        return updateFlags(flags, userId);
4480    }
4481
4482    /**
4483     * Update given intent when being used to request {@link ResolveInfo}.
4484     */
4485    private Intent updateIntentForResolve(Intent intent) {
4486        if (intent.getSelector() != null) {
4487            intent = intent.getSelector();
4488        }
4489        if (DEBUG_PREFERRED) {
4490            intent.addFlags(Intent.FLAG_DEBUG_LOG_RESOLUTION);
4491        }
4492        return intent;
4493    }
4494
4495    /**
4496     * Update given flags when being used to request {@link ResolveInfo}.
4497     * <p>Instant apps are resolved specially, depending upon context. Minimally,
4498     * {@code}flags{@code} must have the {@link PackageManager#MATCH_INSTANT}
4499     * flag set. However, this flag is only honoured in three circumstances:
4500     * <ul>
4501     * <li>when called from a system process</li>
4502     * <li>when the caller holds the permission {@code android.permission.ACCESS_INSTANT_APPS}</li>
4503     * <li>when resolution occurs to start an activity with a {@code android.intent.action.VIEW}
4504     * action and a {@code android.intent.category.BROWSABLE} category</li>
4505     * </ul>
4506     */
4507    int updateFlagsForResolve(int flags, int userId, Intent intent, int callingUid) {
4508        return updateFlagsForResolve(flags, userId, intent, callingUid,
4509                false /*wantInstantApps*/, false /*onlyExposedExplicitly*/);
4510    }
4511    int updateFlagsForResolve(int flags, int userId, Intent intent, int callingUid,
4512            boolean wantInstantApps) {
4513        return updateFlagsForResolve(flags, userId, intent, callingUid,
4514                wantInstantApps, false /*onlyExposedExplicitly*/);
4515    }
4516    int updateFlagsForResolve(int flags, int userId, Intent intent, int callingUid,
4517            boolean wantInstantApps, boolean onlyExposedExplicitly) {
4518        // Safe mode means we shouldn't match any third-party components
4519        if (mSafeMode) {
4520            flags |= PackageManager.MATCH_SYSTEM_ONLY;
4521        }
4522        if (getInstantAppPackageName(callingUid) != null) {
4523            // But, ephemeral apps see both ephemeral and exposed, non-ephemeral components
4524            if (onlyExposedExplicitly) {
4525                flags |= PackageManager.MATCH_EXPLICITLY_VISIBLE_ONLY;
4526            }
4527            flags |= PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY;
4528            flags |= PackageManager.MATCH_INSTANT;
4529        } else {
4530            final boolean wantMatchInstant = (flags & PackageManager.MATCH_INSTANT) != 0;
4531            final boolean allowMatchInstant =
4532                    (wantInstantApps
4533                            && Intent.ACTION_VIEW.equals(intent.getAction())
4534                            && hasWebURI(intent))
4535                    || (wantMatchInstant && canViewInstantApps(callingUid, userId));
4536            flags &= ~(PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY
4537                    | PackageManager.MATCH_EXPLICITLY_VISIBLE_ONLY);
4538            if (!allowMatchInstant) {
4539                flags &= ~PackageManager.MATCH_INSTANT;
4540            }
4541        }
4542        return updateFlagsForComponent(flags, userId, intent /*cookie*/);
4543    }
4544
4545    @Override
4546    public ActivityInfo getActivityInfo(ComponentName component, int flags, int userId) {
4547        return getActivityInfoInternal(component, flags, Binder.getCallingUid(), userId);
4548    }
4549
4550    /**
4551     * Important: The provided filterCallingUid is used exclusively to filter out activities
4552     * that can be seen based on user state. It's typically the original caller uid prior
4553     * to clearing. Because it can only be provided by trusted code, it's value can be
4554     * trusted and will be used as-is; unlike userId which will be validated by this method.
4555     */
4556    private ActivityInfo getActivityInfoInternal(ComponentName component, int flags,
4557            int filterCallingUid, int userId) {
4558        if (!sUserManager.exists(userId)) return null;
4559        flags = updateFlagsForComponent(flags, userId, component);
4560        enforceCrossUserPermission(Binder.getCallingUid(), userId,
4561                false /* requireFullPermission */, false /* checkShell */, "get activity info");
4562        synchronized (mPackages) {
4563            PackageParser.Activity a = mActivities.mActivities.get(component);
4564
4565            if (DEBUG_PACKAGE_INFO) Log.v(TAG, "getActivityInfo " + component + ": " + a);
4566            if (a != null && mSettings.isEnabledAndMatchLPr(a.info, flags, userId)) {
4567                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
4568                if (ps == null) return null;
4569                if (filterAppAccessLPr(ps, filterCallingUid, component, TYPE_ACTIVITY, userId)) {
4570                    return null;
4571                }
4572                return PackageParser.generateActivityInfo(
4573                        a, flags, ps.readUserState(userId), userId);
4574            }
4575            if (mResolveComponentName.equals(component)) {
4576                return PackageParser.generateActivityInfo(
4577                        mResolveActivity, flags, new PackageUserState(), userId);
4578            }
4579        }
4580        return null;
4581    }
4582
4583    @Override
4584    public boolean activitySupportsIntent(ComponentName component, Intent intent,
4585            String resolvedType) {
4586        synchronized (mPackages) {
4587            if (component.equals(mResolveComponentName)) {
4588                // The resolver supports EVERYTHING!
4589                return true;
4590            }
4591            final int callingUid = Binder.getCallingUid();
4592            final int callingUserId = UserHandle.getUserId(callingUid);
4593            PackageParser.Activity a = mActivities.mActivities.get(component);
4594            if (a == null) {
4595                return false;
4596            }
4597            PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
4598            if (ps == null) {
4599                return false;
4600            }
4601            if (filterAppAccessLPr(ps, callingUid, component, TYPE_ACTIVITY, callingUserId)) {
4602                return false;
4603            }
4604            for (int i=0; i<a.intents.size(); i++) {
4605                if (a.intents.get(i).match(intent.getAction(), resolvedType, intent.getScheme(),
4606                        intent.getData(), intent.getCategories(), TAG) >= 0) {
4607                    return true;
4608                }
4609            }
4610            return false;
4611        }
4612    }
4613
4614    @Override
4615    public ActivityInfo getReceiverInfo(ComponentName component, int flags, int userId) {
4616        if (!sUserManager.exists(userId)) return null;
4617        final int callingUid = Binder.getCallingUid();
4618        flags = updateFlagsForComponent(flags, userId, component);
4619        enforceCrossUserPermission(callingUid, userId,
4620                false /* requireFullPermission */, false /* checkShell */, "get receiver info");
4621        synchronized (mPackages) {
4622            PackageParser.Activity a = mReceivers.mActivities.get(component);
4623            if (DEBUG_PACKAGE_INFO) Log.v(
4624                TAG, "getReceiverInfo " + component + ": " + a);
4625            if (a != null && mSettings.isEnabledAndMatchLPr(a.info, flags, userId)) {
4626                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
4627                if (ps == null) return null;
4628                if (filterAppAccessLPr(ps, callingUid, component, TYPE_RECEIVER, userId)) {
4629                    return null;
4630                }
4631                return PackageParser.generateActivityInfo(
4632                        a, flags, ps.readUserState(userId), userId);
4633            }
4634        }
4635        return null;
4636    }
4637
4638    @Override
4639    public ParceledListSlice<SharedLibraryInfo> getSharedLibraries(String packageName,
4640            int flags, int userId) {
4641        if (!sUserManager.exists(userId)) return null;
4642        Preconditions.checkArgumentNonnegative(userId, "userId must be >= 0");
4643        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
4644            return null;
4645        }
4646
4647        flags = updateFlagsForPackage(flags, userId, null);
4648
4649        final boolean canSeeStaticLibraries =
4650                mContext.checkCallingOrSelfPermission(INSTALL_PACKAGES)
4651                        == PERMISSION_GRANTED
4652                || mContext.checkCallingOrSelfPermission(DELETE_PACKAGES)
4653                        == PERMISSION_GRANTED
4654                || canRequestPackageInstallsInternal(packageName,
4655                        PackageManager.MATCH_STATIC_SHARED_LIBRARIES, userId,
4656                        false  /* throwIfPermNotDeclared*/)
4657                || mContext.checkCallingOrSelfPermission(REQUEST_DELETE_PACKAGES)
4658                        == PERMISSION_GRANTED;
4659
4660        synchronized (mPackages) {
4661            List<SharedLibraryInfo> result = null;
4662
4663            final int libCount = mSharedLibraries.size();
4664            for (int i = 0; i < libCount; i++) {
4665                SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.valueAt(i);
4666                if (versionedLib == null) {
4667                    continue;
4668                }
4669
4670                final int versionCount = versionedLib.size();
4671                for (int j = 0; j < versionCount; j++) {
4672                    SharedLibraryInfo libInfo = versionedLib.valueAt(j).info;
4673                    if (!canSeeStaticLibraries && libInfo.isStatic()) {
4674                        break;
4675                    }
4676                    final long identity = Binder.clearCallingIdentity();
4677                    try {
4678                        PackageInfo packageInfo = getPackageInfoVersioned(
4679                                libInfo.getDeclaringPackage(), flags
4680                                        | PackageManager.MATCH_STATIC_SHARED_LIBRARIES, userId);
4681                        if (packageInfo == null) {
4682                            continue;
4683                        }
4684                    } finally {
4685                        Binder.restoreCallingIdentity(identity);
4686                    }
4687
4688                    SharedLibraryInfo resLibInfo = new SharedLibraryInfo(libInfo.getName(),
4689                            libInfo.getVersion(), libInfo.getType(),
4690                            libInfo.getDeclaringPackage(), getPackagesUsingSharedLibraryLPr(libInfo,
4691                            flags, userId));
4692
4693                    if (result == null) {
4694                        result = new ArrayList<>();
4695                    }
4696                    result.add(resLibInfo);
4697                }
4698            }
4699
4700            return result != null ? new ParceledListSlice<>(result) : null;
4701        }
4702    }
4703
4704    private List<VersionedPackage> getPackagesUsingSharedLibraryLPr(
4705            SharedLibraryInfo libInfo, int flags, int userId) {
4706        List<VersionedPackage> versionedPackages = null;
4707        final int packageCount = mSettings.mPackages.size();
4708        for (int i = 0; i < packageCount; i++) {
4709            PackageSetting ps = mSettings.mPackages.valueAt(i);
4710
4711            if (ps == null) {
4712                continue;
4713            }
4714
4715            if (!ps.getUserState().get(userId).isAvailable(flags)) {
4716                continue;
4717            }
4718
4719            final String libName = libInfo.getName();
4720            if (libInfo.isStatic()) {
4721                final int libIdx = ArrayUtils.indexOf(ps.usesStaticLibraries, libName);
4722                if (libIdx < 0) {
4723                    continue;
4724                }
4725                if (ps.usesStaticLibrariesVersions[libIdx] != libInfo.getVersion()) {
4726                    continue;
4727                }
4728                if (versionedPackages == null) {
4729                    versionedPackages = new ArrayList<>();
4730                }
4731                // If the dependent is a static shared lib, use the public package name
4732                String dependentPackageName = ps.name;
4733                if (ps.pkg != null && ps.pkg.applicationInfo.isStaticSharedLibrary()) {
4734                    dependentPackageName = ps.pkg.manifestPackageName;
4735                }
4736                versionedPackages.add(new VersionedPackage(dependentPackageName, ps.versionCode));
4737            } else if (ps.pkg != null) {
4738                if (ArrayUtils.contains(ps.pkg.usesLibraries, libName)
4739                        || ArrayUtils.contains(ps.pkg.usesOptionalLibraries, libName)) {
4740                    if (versionedPackages == null) {
4741                        versionedPackages = new ArrayList<>();
4742                    }
4743                    versionedPackages.add(new VersionedPackage(ps.name, ps.versionCode));
4744                }
4745            }
4746        }
4747
4748        return versionedPackages;
4749    }
4750
4751    @Override
4752    public ServiceInfo getServiceInfo(ComponentName component, int flags, int userId) {
4753        if (!sUserManager.exists(userId)) return null;
4754        final int callingUid = Binder.getCallingUid();
4755        flags = updateFlagsForComponent(flags, userId, component);
4756        enforceCrossUserPermission(callingUid, userId,
4757                false /* requireFullPermission */, false /* checkShell */, "get service info");
4758        synchronized (mPackages) {
4759            PackageParser.Service s = mServices.mServices.get(component);
4760            if (DEBUG_PACKAGE_INFO) Log.v(
4761                TAG, "getServiceInfo " + component + ": " + s);
4762            if (s != null && mSettings.isEnabledAndMatchLPr(s.info, flags, userId)) {
4763                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
4764                if (ps == null) return null;
4765                if (filterAppAccessLPr(ps, callingUid, component, TYPE_SERVICE, userId)) {
4766                    return null;
4767                }
4768                return PackageParser.generateServiceInfo(
4769                        s, flags, ps.readUserState(userId), userId);
4770            }
4771        }
4772        return null;
4773    }
4774
4775    @Override
4776    public ProviderInfo getProviderInfo(ComponentName component, int flags, int userId) {
4777        if (!sUserManager.exists(userId)) return null;
4778        final int callingUid = Binder.getCallingUid();
4779        flags = updateFlagsForComponent(flags, userId, component);
4780        enforceCrossUserPermission(callingUid, userId,
4781                false /* requireFullPermission */, false /* checkShell */, "get provider info");
4782        synchronized (mPackages) {
4783            PackageParser.Provider p = mProviders.mProviders.get(component);
4784            if (DEBUG_PACKAGE_INFO) Log.v(
4785                TAG, "getProviderInfo " + component + ": " + p);
4786            if (p != null && mSettings.isEnabledAndMatchLPr(p.info, flags, userId)) {
4787                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
4788                if (ps == null) return null;
4789                if (filterAppAccessLPr(ps, callingUid, component, TYPE_PROVIDER, userId)) {
4790                    return null;
4791                }
4792                return PackageParser.generateProviderInfo(
4793                        p, flags, ps.readUserState(userId), userId);
4794            }
4795        }
4796        return null;
4797    }
4798
4799    @Override
4800    public String[] getSystemSharedLibraryNames() {
4801        // allow instant applications
4802        synchronized (mPackages) {
4803            Set<String> libs = null;
4804            final int libCount = mSharedLibraries.size();
4805            for (int i = 0; i < libCount; i++) {
4806                SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.valueAt(i);
4807                if (versionedLib == null) {
4808                    continue;
4809                }
4810                final int versionCount = versionedLib.size();
4811                for (int j = 0; j < versionCount; j++) {
4812                    SharedLibraryEntry libEntry = versionedLib.valueAt(j);
4813                    if (!libEntry.info.isStatic()) {
4814                        if (libs == null) {
4815                            libs = new ArraySet<>();
4816                        }
4817                        libs.add(libEntry.info.getName());
4818                        break;
4819                    }
4820                    PackageSetting ps = mSettings.getPackageLPr(libEntry.apk);
4821                    if (ps != null && !filterSharedLibPackageLPr(ps, Binder.getCallingUid(),
4822                            UserHandle.getUserId(Binder.getCallingUid()),
4823                            PackageManager.MATCH_STATIC_SHARED_LIBRARIES)) {
4824                        if (libs == null) {
4825                            libs = new ArraySet<>();
4826                        }
4827                        libs.add(libEntry.info.getName());
4828                        break;
4829                    }
4830                }
4831            }
4832
4833            if (libs != null) {
4834                String[] libsArray = new String[libs.size()];
4835                libs.toArray(libsArray);
4836                return libsArray;
4837            }
4838
4839            return null;
4840        }
4841    }
4842
4843    @Override
4844    public @NonNull String getServicesSystemSharedLibraryPackageName() {
4845        // allow instant applications
4846        synchronized (mPackages) {
4847            return mServicesSystemSharedLibraryPackageName;
4848        }
4849    }
4850
4851    @Override
4852    public @NonNull String getSharedSystemSharedLibraryPackageName() {
4853        // allow instant applications
4854        synchronized (mPackages) {
4855            return mSharedSystemSharedLibraryPackageName;
4856        }
4857    }
4858
4859    private void updateSequenceNumberLP(PackageSetting pkgSetting, int[] userList) {
4860        for (int i = userList.length - 1; i >= 0; --i) {
4861            final int userId = userList[i];
4862            // don't add instant app to the list of updates
4863            if (pkgSetting.getInstantApp(userId)) {
4864                continue;
4865            }
4866            SparseArray<String> changedPackages = mChangedPackages.get(userId);
4867            if (changedPackages == null) {
4868                changedPackages = new SparseArray<>();
4869                mChangedPackages.put(userId, changedPackages);
4870            }
4871            Map<String, Integer> sequenceNumbers = mChangedPackagesSequenceNumbers.get(userId);
4872            if (sequenceNumbers == null) {
4873                sequenceNumbers = new HashMap<>();
4874                mChangedPackagesSequenceNumbers.put(userId, sequenceNumbers);
4875            }
4876            final Integer sequenceNumber = sequenceNumbers.get(pkgSetting.name);
4877            if (sequenceNumber != null) {
4878                changedPackages.remove(sequenceNumber);
4879            }
4880            changedPackages.put(mChangedPackagesSequenceNumber, pkgSetting.name);
4881            sequenceNumbers.put(pkgSetting.name, mChangedPackagesSequenceNumber);
4882        }
4883        mChangedPackagesSequenceNumber++;
4884    }
4885
4886    @Override
4887    public ChangedPackages getChangedPackages(int sequenceNumber, int userId) {
4888        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
4889            return null;
4890        }
4891        synchronized (mPackages) {
4892            if (sequenceNumber >= mChangedPackagesSequenceNumber) {
4893                return null;
4894            }
4895            final SparseArray<String> changedPackages = mChangedPackages.get(userId);
4896            if (changedPackages == null) {
4897                return null;
4898            }
4899            final List<String> packageNames =
4900                    new ArrayList<>(mChangedPackagesSequenceNumber - sequenceNumber);
4901            for (int i = sequenceNumber; i < mChangedPackagesSequenceNumber; i++) {
4902                final String packageName = changedPackages.get(i);
4903                if (packageName != null) {
4904                    packageNames.add(packageName);
4905                }
4906            }
4907            return packageNames.isEmpty()
4908                    ? null : new ChangedPackages(mChangedPackagesSequenceNumber, packageNames);
4909        }
4910    }
4911
4912    @Override
4913    public @NonNull ParceledListSlice<FeatureInfo> getSystemAvailableFeatures() {
4914        // allow instant applications
4915        ArrayList<FeatureInfo> res;
4916        synchronized (mAvailableFeatures) {
4917            res = new ArrayList<>(mAvailableFeatures.size() + 1);
4918            res.addAll(mAvailableFeatures.values());
4919        }
4920        final FeatureInfo fi = new FeatureInfo();
4921        fi.reqGlEsVersion = SystemProperties.getInt("ro.opengles.version",
4922                FeatureInfo.GL_ES_VERSION_UNDEFINED);
4923        res.add(fi);
4924
4925        return new ParceledListSlice<>(res);
4926    }
4927
4928    @Override
4929    public boolean hasSystemFeature(String name, int version) {
4930        // allow instant applications
4931        synchronized (mAvailableFeatures) {
4932            final FeatureInfo feat = mAvailableFeatures.get(name);
4933            if (feat == null) {
4934                return false;
4935            } else {
4936                return feat.version >= version;
4937            }
4938        }
4939    }
4940
4941    @Override
4942    public int checkPermission(String permName, String pkgName, int userId) {
4943        if (!sUserManager.exists(userId)) {
4944            return PackageManager.PERMISSION_DENIED;
4945        }
4946        final int callingUid = Binder.getCallingUid();
4947
4948        synchronized (mPackages) {
4949            final PackageParser.Package p = mPackages.get(pkgName);
4950            if (p != null && p.mExtras != null) {
4951                final PackageSetting ps = (PackageSetting) p.mExtras;
4952                if (filterAppAccessLPr(ps, callingUid, userId)) {
4953                    return PackageManager.PERMISSION_DENIED;
4954                }
4955                final boolean instantApp = ps.getInstantApp(userId);
4956                final PermissionsState permissionsState = ps.getPermissionsState();
4957                if (permissionsState.hasPermission(permName, userId)) {
4958                    if (instantApp) {
4959                        BasePermission bp = mSettings.mPermissions.get(permName);
4960                        if (bp != null && bp.isInstant()) {
4961                            return PackageManager.PERMISSION_GRANTED;
4962                        }
4963                    } else {
4964                        return PackageManager.PERMISSION_GRANTED;
4965                    }
4966                }
4967                // Special case: ACCESS_FINE_LOCATION permission includes ACCESS_COARSE_LOCATION
4968                if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && permissionsState
4969                        .hasPermission(Manifest.permission.ACCESS_FINE_LOCATION, userId)) {
4970                    return PackageManager.PERMISSION_GRANTED;
4971                }
4972            }
4973        }
4974
4975        return PackageManager.PERMISSION_DENIED;
4976    }
4977
4978    @Override
4979    public int checkUidPermission(String permName, int uid) {
4980        final int callingUid = Binder.getCallingUid();
4981        final int callingUserId = UserHandle.getUserId(callingUid);
4982        final boolean isCallerInstantApp = getInstantAppPackageName(callingUid) != null;
4983        final boolean isUidInstantApp = getInstantAppPackageName(uid) != null;
4984        final int userId = UserHandle.getUserId(uid);
4985        if (!sUserManager.exists(userId)) {
4986            return PackageManager.PERMISSION_DENIED;
4987        }
4988
4989        synchronized (mPackages) {
4990            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
4991            if (obj != null) {
4992                if (obj instanceof SharedUserSetting) {
4993                    if (isCallerInstantApp) {
4994                        return PackageManager.PERMISSION_DENIED;
4995                    }
4996                } else if (obj instanceof PackageSetting) {
4997                    final PackageSetting ps = (PackageSetting) obj;
4998                    if (filterAppAccessLPr(ps, callingUid, callingUserId)) {
4999                        return PackageManager.PERMISSION_DENIED;
5000                    }
5001                }
5002                final SettingBase settingBase = (SettingBase) obj;
5003                final PermissionsState permissionsState = settingBase.getPermissionsState();
5004                if (permissionsState.hasPermission(permName, userId)) {
5005                    if (isUidInstantApp) {
5006                        BasePermission bp = mSettings.mPermissions.get(permName);
5007                        if (bp != null && bp.isInstant()) {
5008                            return PackageManager.PERMISSION_GRANTED;
5009                        }
5010                    } else {
5011                        return PackageManager.PERMISSION_GRANTED;
5012                    }
5013                }
5014                // Special case: ACCESS_FINE_LOCATION permission includes ACCESS_COARSE_LOCATION
5015                if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && permissionsState
5016                        .hasPermission(Manifest.permission.ACCESS_FINE_LOCATION, userId)) {
5017                    return PackageManager.PERMISSION_GRANTED;
5018                }
5019            } else {
5020                ArraySet<String> perms = mSystemPermissions.get(uid);
5021                if (perms != null) {
5022                    if (perms.contains(permName)) {
5023                        return PackageManager.PERMISSION_GRANTED;
5024                    }
5025                    if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && perms
5026                            .contains(Manifest.permission.ACCESS_FINE_LOCATION)) {
5027                        return PackageManager.PERMISSION_GRANTED;
5028                    }
5029                }
5030            }
5031        }
5032
5033        return PackageManager.PERMISSION_DENIED;
5034    }
5035
5036    @Override
5037    public boolean isPermissionRevokedByPolicy(String permission, String packageName, int userId) {
5038        if (UserHandle.getCallingUserId() != userId) {
5039            mContext.enforceCallingPermission(
5040                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
5041                    "isPermissionRevokedByPolicy for user " + userId);
5042        }
5043
5044        if (checkPermission(permission, packageName, userId)
5045                == PackageManager.PERMISSION_GRANTED) {
5046            return false;
5047        }
5048
5049        final int callingUid = Binder.getCallingUid();
5050        if (getInstantAppPackageName(callingUid) != null) {
5051            if (!isCallerSameApp(packageName, callingUid)) {
5052                return false;
5053            }
5054        } else {
5055            if (isInstantApp(packageName, userId)) {
5056                return false;
5057            }
5058        }
5059
5060        final long identity = Binder.clearCallingIdentity();
5061        try {
5062            final int flags = getPermissionFlags(permission, packageName, userId);
5063            return (flags & PackageManager.FLAG_PERMISSION_POLICY_FIXED) != 0;
5064        } finally {
5065            Binder.restoreCallingIdentity(identity);
5066        }
5067    }
5068
5069    @Override
5070    public String getPermissionControllerPackageName() {
5071        synchronized (mPackages) {
5072            return mRequiredInstallerPackage;
5073        }
5074    }
5075
5076    /**
5077     * Checks if the request is from the system or an app that has INTERACT_ACROSS_USERS
5078     * or INTERACT_ACROSS_USERS_FULL permissions, if the userid is not for the caller.
5079     * @param checkShell whether to prevent shell from access if there's a debugging restriction
5080     * @param message the message to log on security exception
5081     */
5082    void enforceCrossUserPermission(int callingUid, int userId, boolean requireFullPermission,
5083            boolean checkShell, String message) {
5084        if (userId < 0) {
5085            throw new IllegalArgumentException("Invalid userId " + userId);
5086        }
5087        if (checkShell) {
5088            enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, userId);
5089        }
5090        if (userId == UserHandle.getUserId(callingUid)) return;
5091        if (callingUid != Process.SYSTEM_UID && callingUid != 0) {
5092            if (requireFullPermission) {
5093                mContext.enforceCallingOrSelfPermission(
5094                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message);
5095            } else {
5096                try {
5097                    mContext.enforceCallingOrSelfPermission(
5098                            android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message);
5099                } catch (SecurityException se) {
5100                    mContext.enforceCallingOrSelfPermission(
5101                            android.Manifest.permission.INTERACT_ACROSS_USERS, message);
5102                }
5103            }
5104        }
5105    }
5106
5107    void enforceShellRestriction(String restriction, int callingUid, int userHandle) {
5108        if (callingUid == Process.SHELL_UID) {
5109            if (userHandle >= 0
5110                    && sUserManager.hasUserRestriction(restriction, userHandle)) {
5111                throw new SecurityException("Shell does not have permission to access user "
5112                        + userHandle);
5113            } else if (userHandle < 0) {
5114                Slog.e(TAG, "Unable to check shell permission for user " + userHandle + "\n\t"
5115                        + Debug.getCallers(3));
5116            }
5117        }
5118    }
5119
5120    private BasePermission findPermissionTreeLP(String permName) {
5121        for(BasePermission bp : mSettings.mPermissionTrees.values()) {
5122            if (permName.startsWith(bp.name) &&
5123                    permName.length() > bp.name.length() &&
5124                    permName.charAt(bp.name.length()) == '.') {
5125                return bp;
5126            }
5127        }
5128        return null;
5129    }
5130
5131    private BasePermission checkPermissionTreeLP(String permName) {
5132        if (permName != null) {
5133            BasePermission bp = findPermissionTreeLP(permName);
5134            if (bp != null) {
5135                if (bp.uid == UserHandle.getAppId(Binder.getCallingUid())) {
5136                    return bp;
5137                }
5138                throw new SecurityException("Calling uid "
5139                        + Binder.getCallingUid()
5140                        + " is not allowed to add to permission tree "
5141                        + bp.name + " owned by uid " + bp.uid);
5142            }
5143        }
5144        throw new SecurityException("No permission tree found for " + permName);
5145    }
5146
5147    static boolean compareStrings(CharSequence s1, CharSequence s2) {
5148        if (s1 == null) {
5149            return s2 == null;
5150        }
5151        if (s2 == null) {
5152            return false;
5153        }
5154        if (s1.getClass() != s2.getClass()) {
5155            return false;
5156        }
5157        return s1.equals(s2);
5158    }
5159
5160    static boolean comparePermissionInfos(PermissionInfo pi1, PermissionInfo pi2) {
5161        if (pi1.icon != pi2.icon) return false;
5162        if (pi1.logo != pi2.logo) return false;
5163        if (pi1.protectionLevel != pi2.protectionLevel) return false;
5164        if (!compareStrings(pi1.name, pi2.name)) return false;
5165        if (!compareStrings(pi1.nonLocalizedLabel, pi2.nonLocalizedLabel)) return false;
5166        // We'll take care of setting this one.
5167        if (!compareStrings(pi1.packageName, pi2.packageName)) return false;
5168        // These are not currently stored in settings.
5169        //if (!compareStrings(pi1.group, pi2.group)) return false;
5170        //if (!compareStrings(pi1.nonLocalizedDescription, pi2.nonLocalizedDescription)) return false;
5171        //if (pi1.labelRes != pi2.labelRes) return false;
5172        //if (pi1.descriptionRes != pi2.descriptionRes) return false;
5173        return true;
5174    }
5175
5176    int permissionInfoFootprint(PermissionInfo info) {
5177        int size = info.name.length();
5178        if (info.nonLocalizedLabel != null) size += info.nonLocalizedLabel.length();
5179        if (info.nonLocalizedDescription != null) size += info.nonLocalizedDescription.length();
5180        return size;
5181    }
5182
5183    int calculateCurrentPermissionFootprintLocked(BasePermission tree) {
5184        int size = 0;
5185        for (BasePermission perm : mSettings.mPermissions.values()) {
5186            if (perm.uid == tree.uid) {
5187                size += perm.name.length() + permissionInfoFootprint(perm.perm.info);
5188            }
5189        }
5190        return size;
5191    }
5192
5193    void enforcePermissionCapLocked(PermissionInfo info, BasePermission tree) {
5194        // We calculate the max size of permissions defined by this uid and throw
5195        // if that plus the size of 'info' would exceed our stated maximum.
5196        if (tree.uid != Process.SYSTEM_UID) {
5197            final int curTreeSize = calculateCurrentPermissionFootprintLocked(tree);
5198            if (curTreeSize + permissionInfoFootprint(info) > MAX_PERMISSION_TREE_FOOTPRINT) {
5199                throw new SecurityException("Permission tree size cap exceeded");
5200            }
5201        }
5202    }
5203
5204    boolean addPermissionLocked(PermissionInfo info, boolean async) {
5205        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
5206            throw new SecurityException("Instant apps can't add permissions");
5207        }
5208        if (info.labelRes == 0 && info.nonLocalizedLabel == null) {
5209            throw new SecurityException("Label must be specified in permission");
5210        }
5211        BasePermission tree = checkPermissionTreeLP(info.name);
5212        BasePermission bp = mSettings.mPermissions.get(info.name);
5213        boolean added = bp == null;
5214        boolean changed = true;
5215        int fixedLevel = PermissionInfo.fixProtectionLevel(info.protectionLevel);
5216        if (added) {
5217            enforcePermissionCapLocked(info, tree);
5218            bp = new BasePermission(info.name, tree.sourcePackage,
5219                    BasePermission.TYPE_DYNAMIC);
5220        } else if (bp.type != BasePermission.TYPE_DYNAMIC) {
5221            throw new SecurityException(
5222                    "Not allowed to modify non-dynamic permission "
5223                    + info.name);
5224        } else {
5225            if (bp.protectionLevel == fixedLevel
5226                    && bp.perm.owner.equals(tree.perm.owner)
5227                    && bp.uid == tree.uid
5228                    && comparePermissionInfos(bp.perm.info, info)) {
5229                changed = false;
5230            }
5231        }
5232        bp.protectionLevel = fixedLevel;
5233        info = new PermissionInfo(info);
5234        info.protectionLevel = fixedLevel;
5235        bp.perm = new PackageParser.Permission(tree.perm.owner, info);
5236        bp.perm.info.packageName = tree.perm.info.packageName;
5237        bp.uid = tree.uid;
5238        if (added) {
5239            mSettings.mPermissions.put(info.name, bp);
5240        }
5241        if (changed) {
5242            if (!async) {
5243                mSettings.writeLPr();
5244            } else {
5245                scheduleWriteSettingsLocked();
5246            }
5247        }
5248        return added;
5249    }
5250
5251    @Override
5252    public boolean addPermission(PermissionInfo info) {
5253        synchronized (mPackages) {
5254            return addPermissionLocked(info, false);
5255        }
5256    }
5257
5258    @Override
5259    public boolean addPermissionAsync(PermissionInfo info) {
5260        synchronized (mPackages) {
5261            return addPermissionLocked(info, true);
5262        }
5263    }
5264
5265    @Override
5266    public void removePermission(String name) {
5267        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
5268            throw new SecurityException("Instant applications don't have access to this method");
5269        }
5270        synchronized (mPackages) {
5271            checkPermissionTreeLP(name);
5272            BasePermission bp = mSettings.mPermissions.get(name);
5273            if (bp != null) {
5274                if (bp.type != BasePermission.TYPE_DYNAMIC) {
5275                    throw new SecurityException(
5276                            "Not allowed to modify non-dynamic permission "
5277                            + name);
5278                }
5279                mSettings.mPermissions.remove(name);
5280                mSettings.writeLPr();
5281            }
5282        }
5283    }
5284
5285    private static void enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(
5286            PackageParser.Package pkg, BasePermission bp) {
5287        int index = pkg.requestedPermissions.indexOf(bp.name);
5288        if (index == -1) {
5289            throw new SecurityException("Package " + pkg.packageName
5290                    + " has not requested permission " + bp.name);
5291        }
5292        if (!bp.isRuntime() && !bp.isDevelopment()) {
5293            throw new SecurityException("Permission " + bp.name
5294                    + " is not a changeable permission type");
5295        }
5296    }
5297
5298    @Override
5299    public void grantRuntimePermission(String packageName, String name, final int userId) {
5300        grantRuntimePermission(packageName, name, userId, false /* Only if not fixed by policy */);
5301    }
5302
5303    private void grantRuntimePermission(String packageName, String name, final int userId,
5304            boolean overridePolicy) {
5305        if (!sUserManager.exists(userId)) {
5306            Log.e(TAG, "No such user:" + userId);
5307            return;
5308        }
5309        final int callingUid = Binder.getCallingUid();
5310
5311        mContext.enforceCallingOrSelfPermission(
5312                android.Manifest.permission.GRANT_RUNTIME_PERMISSIONS,
5313                "grantRuntimePermission");
5314
5315        enforceCrossUserPermission(callingUid, userId,
5316                true /* requireFullPermission */, true /* checkShell */,
5317                "grantRuntimePermission");
5318
5319        final int uid;
5320        final PackageSetting ps;
5321
5322        synchronized (mPackages) {
5323            final PackageParser.Package pkg = mPackages.get(packageName);
5324            if (pkg == null) {
5325                throw new IllegalArgumentException("Unknown package: " + packageName);
5326            }
5327            final BasePermission bp = mSettings.mPermissions.get(name);
5328            if (bp == null) {
5329                throw new IllegalArgumentException("Unknown permission: " + name);
5330            }
5331            ps = (PackageSetting) pkg.mExtras;
5332            if (ps == null
5333                    || filterAppAccessLPr(ps, callingUid, userId)) {
5334                throw new IllegalArgumentException("Unknown package: " + packageName);
5335            }
5336
5337            enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(pkg, bp);
5338
5339            // If a permission review is required for legacy apps we represent
5340            // their permissions as always granted runtime ones since we need
5341            // to keep the review required permission flag per user while an
5342            // install permission's state is shared across all users.
5343            if (mPermissionReviewRequired
5344                    && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M
5345                    && bp.isRuntime()) {
5346                return;
5347            }
5348
5349            uid = UserHandle.getUid(userId, pkg.applicationInfo.uid);
5350
5351            final PermissionsState permissionsState = ps.getPermissionsState();
5352
5353            final int flags = permissionsState.getPermissionFlags(name, userId);
5354            if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) {
5355                throw new SecurityException("Cannot grant system fixed permission "
5356                        + name + " for package " + packageName);
5357            }
5358            if (!overridePolicy && (flags & PackageManager.FLAG_PERMISSION_POLICY_FIXED) != 0) {
5359                throw new SecurityException("Cannot grant policy fixed permission "
5360                        + name + " for package " + packageName);
5361            }
5362
5363            if (bp.isDevelopment()) {
5364                // Development permissions must be handled specially, since they are not
5365                // normal runtime permissions.  For now they apply to all users.
5366                if (permissionsState.grantInstallPermission(bp) !=
5367                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
5368                    scheduleWriteSettingsLocked();
5369                }
5370                return;
5371            }
5372
5373            if (ps.getInstantApp(userId) && !bp.isInstant()) {
5374                throw new SecurityException("Cannot grant non-ephemeral permission"
5375                        + name + " for package " + packageName);
5376            }
5377
5378            if (pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) {
5379                Slog.w(TAG, "Cannot grant runtime permission to a legacy app");
5380                return;
5381            }
5382
5383            final int result = permissionsState.grantRuntimePermission(bp, userId);
5384            switch (result) {
5385                case PermissionsState.PERMISSION_OPERATION_FAILURE: {
5386                    return;
5387                }
5388
5389                case PermissionsState.PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: {
5390                    final int appId = UserHandle.getAppId(pkg.applicationInfo.uid);
5391                    mHandler.post(new Runnable() {
5392                        @Override
5393                        public void run() {
5394                            killUid(appId, userId, KILL_APP_REASON_GIDS_CHANGED);
5395                        }
5396                    });
5397                }
5398                break;
5399            }
5400
5401            if (bp.isRuntime()) {
5402                logPermissionGranted(mContext, name, packageName);
5403            }
5404
5405            mOnPermissionChangeListeners.onPermissionsChanged(uid);
5406
5407            // Not critical if that is lost - app has to request again.
5408            mSettings.writeRuntimePermissionsForUserLPr(userId, false);
5409        }
5410
5411        // Only need to do this if user is initialized. Otherwise it's a new user
5412        // and there are no processes running as the user yet and there's no need
5413        // to make an expensive call to remount processes for the changed permissions.
5414        if (READ_EXTERNAL_STORAGE.equals(name)
5415                || WRITE_EXTERNAL_STORAGE.equals(name)) {
5416            final long token = Binder.clearCallingIdentity();
5417            try {
5418                if (sUserManager.isInitialized(userId)) {
5419                    StorageManagerInternal storageManagerInternal = LocalServices.getService(
5420                            StorageManagerInternal.class);
5421                    storageManagerInternal.onExternalStoragePolicyChanged(uid, packageName);
5422                }
5423            } finally {
5424                Binder.restoreCallingIdentity(token);
5425            }
5426        }
5427    }
5428
5429    @Override
5430    public void revokeRuntimePermission(String packageName, String name, int userId) {
5431        revokeRuntimePermission(packageName, name, userId, false /* Only if not fixed by policy */);
5432    }
5433
5434    private void revokeRuntimePermission(String packageName, String name, int userId,
5435            boolean overridePolicy) {
5436        if (!sUserManager.exists(userId)) {
5437            Log.e(TAG, "No such user:" + userId);
5438            return;
5439        }
5440
5441        mContext.enforceCallingOrSelfPermission(
5442                android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS,
5443                "revokeRuntimePermission");
5444
5445        enforceCrossUserPermission(Binder.getCallingUid(), userId,
5446                true /* requireFullPermission */, true /* checkShell */,
5447                "revokeRuntimePermission");
5448
5449        final int appId;
5450
5451        synchronized (mPackages) {
5452            final PackageParser.Package pkg = mPackages.get(packageName);
5453            if (pkg == null) {
5454                throw new IllegalArgumentException("Unknown package: " + packageName);
5455            }
5456            final PackageSetting ps = (PackageSetting) pkg.mExtras;
5457            if (ps == null
5458                    || filterAppAccessLPr(ps, Binder.getCallingUid(), userId)) {
5459                throw new IllegalArgumentException("Unknown package: " + packageName);
5460            }
5461            final BasePermission bp = mSettings.mPermissions.get(name);
5462            if (bp == null) {
5463                throw new IllegalArgumentException("Unknown permission: " + name);
5464            }
5465
5466            enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(pkg, bp);
5467
5468            // If a permission review is required for legacy apps we represent
5469            // their permissions as always granted runtime ones since we need
5470            // to keep the review required permission flag per user while an
5471            // install permission's state is shared across all users.
5472            if (mPermissionReviewRequired
5473                    && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M
5474                    && bp.isRuntime()) {
5475                return;
5476            }
5477
5478            final PermissionsState permissionsState = ps.getPermissionsState();
5479
5480            final int flags = permissionsState.getPermissionFlags(name, userId);
5481            if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) {
5482                throw new SecurityException("Cannot revoke system fixed permission "
5483                        + name + " for package " + packageName);
5484            }
5485            if (!overridePolicy && (flags & PackageManager.FLAG_PERMISSION_POLICY_FIXED) != 0) {
5486                throw new SecurityException("Cannot revoke policy fixed permission "
5487                        + name + " for package " + packageName);
5488            }
5489
5490            if (bp.isDevelopment()) {
5491                // Development permissions must be handled specially, since they are not
5492                // normal runtime permissions.  For now they apply to all users.
5493                if (permissionsState.revokeInstallPermission(bp) !=
5494                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
5495                    scheduleWriteSettingsLocked();
5496                }
5497                return;
5498            }
5499
5500            if (permissionsState.revokeRuntimePermission(bp, userId) ==
5501                    PermissionsState.PERMISSION_OPERATION_FAILURE) {
5502                return;
5503            }
5504
5505            if (bp.isRuntime()) {
5506                logPermissionRevoked(mContext, name, packageName);
5507            }
5508
5509            mOnPermissionChangeListeners.onPermissionsChanged(pkg.applicationInfo.uid);
5510
5511            // Critical, after this call app should never have the permission.
5512            mSettings.writeRuntimePermissionsForUserLPr(userId, true);
5513
5514            appId = UserHandle.getAppId(pkg.applicationInfo.uid);
5515        }
5516
5517        killUid(appId, userId, KILL_APP_REASON_PERMISSIONS_REVOKED);
5518    }
5519
5520    /**
5521     * Get the first event id for the permission.
5522     *
5523     * <p>There are four events for each permission: <ul>
5524     *     <li>Request permission: first id + 0</li>
5525     *     <li>Grant permission: first id + 1</li>
5526     *     <li>Request for permission denied: first id + 2</li>
5527     *     <li>Revoke permission: first id + 3</li>
5528     * </ul></p>
5529     *
5530     * @param name name of the permission
5531     *
5532     * @return The first event id for the permission
5533     */
5534    private static int getBaseEventId(@NonNull String name) {
5535        int eventIdIndex = ALL_DANGEROUS_PERMISSIONS.indexOf(name);
5536
5537        if (eventIdIndex == -1) {
5538            if (AppOpsManager.permissionToOpCode(name) == AppOpsManager.OP_NONE
5539                    || "user".equals(Build.TYPE)) {
5540                Log.i(TAG, "Unknown permission " + name);
5541
5542                return MetricsEvent.ACTION_PERMISSION_REQUEST_UNKNOWN;
5543            } else {
5544                // Most likely #ALL_DANGEROUS_PERMISSIONS needs to be updated.
5545                //
5546                // Also update
5547                // - EventLogger#ALL_DANGEROUS_PERMISSIONS
5548                // - metrics_constants.proto
5549                throw new IllegalStateException("Unknown permission " + name);
5550            }
5551        }
5552
5553        return MetricsEvent.ACTION_PERMISSION_REQUEST_READ_CALENDAR + eventIdIndex * 4;
5554    }
5555
5556    /**
5557     * Log that a permission was revoked.
5558     *
5559     * @param context Context of the caller
5560     * @param name name of the permission
5561     * @param packageName package permission if for
5562     */
5563    private static void logPermissionRevoked(@NonNull Context context, @NonNull String name,
5564            @NonNull String packageName) {
5565        MetricsLogger.action(context, getBaseEventId(name) + 3, packageName);
5566    }
5567
5568    /**
5569     * Log that a permission request was granted.
5570     *
5571     * @param context Context of the caller
5572     * @param name name of the permission
5573     * @param packageName package permission if for
5574     */
5575    private static void logPermissionGranted(@NonNull Context context, @NonNull String name,
5576            @NonNull String packageName) {
5577        MetricsLogger.action(context, getBaseEventId(name) + 1, packageName);
5578    }
5579
5580    @Override
5581    public void resetRuntimePermissions() {
5582        mContext.enforceCallingOrSelfPermission(
5583                android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS,
5584                "revokeRuntimePermission");
5585
5586        int callingUid = Binder.getCallingUid();
5587        if (callingUid != Process.SYSTEM_UID && callingUid != 0) {
5588            mContext.enforceCallingOrSelfPermission(
5589                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
5590                    "resetRuntimePermissions");
5591        }
5592
5593        synchronized (mPackages) {
5594            updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL);
5595            for (int userId : UserManagerService.getInstance().getUserIds()) {
5596                final int packageCount = mPackages.size();
5597                for (int i = 0; i < packageCount; i++) {
5598                    PackageParser.Package pkg = mPackages.valueAt(i);
5599                    if (!(pkg.mExtras instanceof PackageSetting)) {
5600                        continue;
5601                    }
5602                    PackageSetting ps = (PackageSetting) pkg.mExtras;
5603                    resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
5604                }
5605            }
5606        }
5607    }
5608
5609    @Override
5610    public int getPermissionFlags(String name, String packageName, int userId) {
5611        if (!sUserManager.exists(userId)) {
5612            return 0;
5613        }
5614
5615        enforceGrantRevokeRuntimePermissionPermissions("getPermissionFlags");
5616
5617        final int callingUid = Binder.getCallingUid();
5618        enforceCrossUserPermission(callingUid, userId,
5619                true /* requireFullPermission */, false /* checkShell */,
5620                "getPermissionFlags");
5621
5622        synchronized (mPackages) {
5623            final PackageParser.Package pkg = mPackages.get(packageName);
5624            if (pkg == null) {
5625                return 0;
5626            }
5627            final BasePermission bp = mSettings.mPermissions.get(name);
5628            if (bp == null) {
5629                return 0;
5630            }
5631            final PackageSetting ps = (PackageSetting) pkg.mExtras;
5632            if (ps == null
5633                    || filterAppAccessLPr(ps, callingUid, userId)) {
5634                return 0;
5635            }
5636            PermissionsState permissionsState = ps.getPermissionsState();
5637            return permissionsState.getPermissionFlags(name, userId);
5638        }
5639    }
5640
5641    @Override
5642    public void updatePermissionFlags(String name, String packageName, int flagMask,
5643            int flagValues, int userId) {
5644        if (!sUserManager.exists(userId)) {
5645            return;
5646        }
5647
5648        enforceGrantRevokeRuntimePermissionPermissions("updatePermissionFlags");
5649
5650        final int callingUid = Binder.getCallingUid();
5651        enforceCrossUserPermission(callingUid, userId,
5652                true /* requireFullPermission */, true /* checkShell */,
5653                "updatePermissionFlags");
5654
5655        // Only the system can change these flags and nothing else.
5656        if (getCallingUid() != Process.SYSTEM_UID) {
5657            flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
5658            flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
5659            flagMask &= ~PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT;
5660            flagValues &= ~PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT;
5661            flagValues &= ~PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED;
5662        }
5663
5664        synchronized (mPackages) {
5665            final PackageParser.Package pkg = mPackages.get(packageName);
5666            if (pkg == null) {
5667                throw new IllegalArgumentException("Unknown package: " + packageName);
5668            }
5669            final PackageSetting ps = (PackageSetting) pkg.mExtras;
5670            if (ps == null
5671                    || filterAppAccessLPr(ps, callingUid, userId)) {
5672                throw new IllegalArgumentException("Unknown package: " + packageName);
5673            }
5674
5675            final BasePermission bp = mSettings.mPermissions.get(name);
5676            if (bp == null) {
5677                throw new IllegalArgumentException("Unknown permission: " + name);
5678            }
5679
5680            PermissionsState permissionsState = ps.getPermissionsState();
5681
5682            boolean hadState = permissionsState.getRuntimePermissionState(name, userId) != null;
5683
5684            if (permissionsState.updatePermissionFlags(bp, userId, flagMask, flagValues)) {
5685                // Install and runtime permissions are stored in different places,
5686                // so figure out what permission changed and persist the change.
5687                if (permissionsState.getInstallPermissionState(name) != null) {
5688                    scheduleWriteSettingsLocked();
5689                } else if (permissionsState.getRuntimePermissionState(name, userId) != null
5690                        || hadState) {
5691                    mSettings.writeRuntimePermissionsForUserLPr(userId, false);
5692                }
5693            }
5694        }
5695    }
5696
5697    /**
5698     * Update the permission flags for all packages and runtime permissions of a user in order
5699     * to allow device or profile owner to remove POLICY_FIXED.
5700     */
5701    @Override
5702    public void updatePermissionFlagsForAllApps(int flagMask, int flagValues, int userId) {
5703        if (!sUserManager.exists(userId)) {
5704            return;
5705        }
5706
5707        enforceGrantRevokeRuntimePermissionPermissions("updatePermissionFlagsForAllApps");
5708
5709        enforceCrossUserPermission(Binder.getCallingUid(), userId,
5710                true /* requireFullPermission */, true /* checkShell */,
5711                "updatePermissionFlagsForAllApps");
5712
5713        // Only the system can change system fixed flags.
5714        if (getCallingUid() != Process.SYSTEM_UID) {
5715            flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
5716            flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
5717        }
5718
5719        synchronized (mPackages) {
5720            boolean changed = false;
5721            final int packageCount = mPackages.size();
5722            for (int pkgIndex = 0; pkgIndex < packageCount; pkgIndex++) {
5723                final PackageParser.Package pkg = mPackages.valueAt(pkgIndex);
5724                final PackageSetting ps = (PackageSetting) pkg.mExtras;
5725                if (ps == null) {
5726                    continue;
5727                }
5728                PermissionsState permissionsState = ps.getPermissionsState();
5729                changed |= permissionsState.updatePermissionFlagsForAllPermissions(
5730                        userId, flagMask, flagValues);
5731            }
5732            if (changed) {
5733                mSettings.writeRuntimePermissionsForUserLPr(userId, false);
5734            }
5735        }
5736    }
5737
5738    private void enforceGrantRevokeRuntimePermissionPermissions(String message) {
5739        if (mContext.checkCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS)
5740                != PackageManager.PERMISSION_GRANTED
5741            && mContext.checkCallingOrSelfPermission(Manifest.permission.REVOKE_RUNTIME_PERMISSIONS)
5742                != PackageManager.PERMISSION_GRANTED) {
5743            throw new SecurityException(message + " requires "
5744                    + Manifest.permission.GRANT_RUNTIME_PERMISSIONS + " or "
5745                    + Manifest.permission.REVOKE_RUNTIME_PERMISSIONS);
5746        }
5747    }
5748
5749    @Override
5750    public boolean shouldShowRequestPermissionRationale(String permissionName,
5751            String packageName, int userId) {
5752        if (UserHandle.getCallingUserId() != userId) {
5753            mContext.enforceCallingPermission(
5754                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
5755                    "canShowRequestPermissionRationale for user " + userId);
5756        }
5757
5758        final int uid = getPackageUid(packageName, MATCH_DEBUG_TRIAGED_MISSING, userId);
5759        if (UserHandle.getAppId(getCallingUid()) != UserHandle.getAppId(uid)) {
5760            return false;
5761        }
5762
5763        if (checkPermission(permissionName, packageName, userId)
5764                == PackageManager.PERMISSION_GRANTED) {
5765            return false;
5766        }
5767
5768        final int flags;
5769
5770        final long identity = Binder.clearCallingIdentity();
5771        try {
5772            flags = getPermissionFlags(permissionName,
5773                    packageName, userId);
5774        } finally {
5775            Binder.restoreCallingIdentity(identity);
5776        }
5777
5778        final int fixedFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED
5779                | PackageManager.FLAG_PERMISSION_POLICY_FIXED
5780                | PackageManager.FLAG_PERMISSION_USER_FIXED;
5781
5782        if ((flags & fixedFlags) != 0) {
5783            return false;
5784        }
5785
5786        return (flags & PackageManager.FLAG_PERMISSION_USER_SET) != 0;
5787    }
5788
5789    @Override
5790    public void addOnPermissionsChangeListener(IOnPermissionsChangeListener listener) {
5791        mContext.enforceCallingOrSelfPermission(
5792                Manifest.permission.OBSERVE_GRANT_REVOKE_PERMISSIONS,
5793                "addOnPermissionsChangeListener");
5794
5795        synchronized (mPackages) {
5796            mOnPermissionChangeListeners.addListenerLocked(listener);
5797        }
5798    }
5799
5800    @Override
5801    public void removeOnPermissionsChangeListener(IOnPermissionsChangeListener listener) {
5802        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
5803            throw new SecurityException("Instant applications don't have access to this method");
5804        }
5805        synchronized (mPackages) {
5806            mOnPermissionChangeListeners.removeListenerLocked(listener);
5807        }
5808    }
5809
5810    @Override
5811    public boolean isProtectedBroadcast(String actionName) {
5812        // allow instant applications
5813        synchronized (mProtectedBroadcasts) {
5814            if (mProtectedBroadcasts.contains(actionName)) {
5815                return true;
5816            } else if (actionName != null) {
5817                // TODO: remove these terrible hacks
5818                if (actionName.startsWith("android.net.netmon.lingerExpired")
5819                        || actionName.startsWith("com.android.server.sip.SipWakeupTimer")
5820                        || actionName.startsWith("com.android.internal.telephony.data-reconnect")
5821                        || actionName.startsWith("android.net.netmon.launchCaptivePortalApp")) {
5822                    return true;
5823                }
5824            }
5825        }
5826        return false;
5827    }
5828
5829    @Override
5830    public int checkSignatures(String pkg1, String pkg2) {
5831        synchronized (mPackages) {
5832            final PackageParser.Package p1 = mPackages.get(pkg1);
5833            final PackageParser.Package p2 = mPackages.get(pkg2);
5834            if (p1 == null || p1.mExtras == null
5835                    || p2 == null || p2.mExtras == null) {
5836                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5837            }
5838            final int callingUid = Binder.getCallingUid();
5839            final int callingUserId = UserHandle.getUserId(callingUid);
5840            final PackageSetting ps1 = (PackageSetting) p1.mExtras;
5841            final PackageSetting ps2 = (PackageSetting) p2.mExtras;
5842            if (filterAppAccessLPr(ps1, callingUid, callingUserId)
5843                    || filterAppAccessLPr(ps2, callingUid, callingUserId)) {
5844                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5845            }
5846            return compareSignatures(p1.mSignatures, p2.mSignatures);
5847        }
5848    }
5849
5850    @Override
5851    public int checkUidSignatures(int uid1, int uid2) {
5852        final int callingUid = Binder.getCallingUid();
5853        final int callingUserId = UserHandle.getUserId(callingUid);
5854        final boolean isCallerInstantApp = getInstantAppPackageName(callingUid) != null;
5855        // Map to base uids.
5856        uid1 = UserHandle.getAppId(uid1);
5857        uid2 = UserHandle.getAppId(uid2);
5858        // reader
5859        synchronized (mPackages) {
5860            Signature[] s1;
5861            Signature[] s2;
5862            Object obj = mSettings.getUserIdLPr(uid1);
5863            if (obj != null) {
5864                if (obj instanceof SharedUserSetting) {
5865                    if (isCallerInstantApp) {
5866                        return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5867                    }
5868                    s1 = ((SharedUserSetting)obj).signatures.mSignatures;
5869                } else if (obj instanceof PackageSetting) {
5870                    final PackageSetting ps = (PackageSetting) obj;
5871                    if (filterAppAccessLPr(ps, callingUid, callingUserId)) {
5872                        return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5873                    }
5874                    s1 = ps.signatures.mSignatures;
5875                } else {
5876                    return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5877                }
5878            } else {
5879                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5880            }
5881            obj = mSettings.getUserIdLPr(uid2);
5882            if (obj != null) {
5883                if (obj instanceof SharedUserSetting) {
5884                    if (isCallerInstantApp) {
5885                        return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5886                    }
5887                    s2 = ((SharedUserSetting)obj).signatures.mSignatures;
5888                } else if (obj instanceof PackageSetting) {
5889                    final PackageSetting ps = (PackageSetting) obj;
5890                    if (filterAppAccessLPr(ps, callingUid, callingUserId)) {
5891                        return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5892                    }
5893                    s2 = ps.signatures.mSignatures;
5894                } else {
5895                    return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5896                }
5897            } else {
5898                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5899            }
5900            return compareSignatures(s1, s2);
5901        }
5902    }
5903
5904    /**
5905     * This method should typically only be used when granting or revoking
5906     * permissions, since the app may immediately restart after this call.
5907     * <p>
5908     * If you're doing surgery on app code/data, use {@link PackageFreezer} to
5909     * guard your work against the app being relaunched.
5910     */
5911    private void killUid(int appId, int userId, String reason) {
5912        final long identity = Binder.clearCallingIdentity();
5913        try {
5914            IActivityManager am = ActivityManager.getService();
5915            if (am != null) {
5916                try {
5917                    am.killUid(appId, userId, reason);
5918                } catch (RemoteException e) {
5919                    /* ignore - same process */
5920                }
5921            }
5922        } finally {
5923            Binder.restoreCallingIdentity(identity);
5924        }
5925    }
5926
5927    /**
5928     * Compares two sets of signatures. Returns:
5929     * <br />
5930     * {@link PackageManager#SIGNATURE_NEITHER_SIGNED}: if both signature sets are null,
5931     * <br />
5932     * {@link PackageManager#SIGNATURE_FIRST_NOT_SIGNED}: if the first signature set is null,
5933     * <br />
5934     * {@link PackageManager#SIGNATURE_SECOND_NOT_SIGNED}: if the second signature set is null,
5935     * <br />
5936     * {@link PackageManager#SIGNATURE_MATCH}: if the two signature sets are identical,
5937     * <br />
5938     * {@link PackageManager#SIGNATURE_NO_MATCH}: if the two signature sets differ.
5939     */
5940    static int compareSignatures(Signature[] s1, Signature[] s2) {
5941        if (s1 == null) {
5942            return s2 == null
5943                    ? PackageManager.SIGNATURE_NEITHER_SIGNED
5944                    : PackageManager.SIGNATURE_FIRST_NOT_SIGNED;
5945        }
5946
5947        if (s2 == null) {
5948            return PackageManager.SIGNATURE_SECOND_NOT_SIGNED;
5949        }
5950
5951        if (s1.length != s2.length) {
5952            return PackageManager.SIGNATURE_NO_MATCH;
5953        }
5954
5955        // Since both signature sets are of size 1, we can compare without HashSets.
5956        if (s1.length == 1) {
5957            return s1[0].equals(s2[0]) ?
5958                    PackageManager.SIGNATURE_MATCH :
5959                    PackageManager.SIGNATURE_NO_MATCH;
5960        }
5961
5962        ArraySet<Signature> set1 = new ArraySet<Signature>();
5963        for (Signature sig : s1) {
5964            set1.add(sig);
5965        }
5966        ArraySet<Signature> set2 = new ArraySet<Signature>();
5967        for (Signature sig : s2) {
5968            set2.add(sig);
5969        }
5970        // Make sure s2 contains all signatures in s1.
5971        if (set1.equals(set2)) {
5972            return PackageManager.SIGNATURE_MATCH;
5973        }
5974        return PackageManager.SIGNATURE_NO_MATCH;
5975    }
5976
5977    /**
5978     * If the database version for this type of package (internal storage or
5979     * external storage) is less than the version where package signatures
5980     * were updated, return true.
5981     */
5982    private boolean isCompatSignatureUpdateNeeded(PackageParser.Package scannedPkg) {
5983        final VersionInfo ver = getSettingsVersionForPackage(scannedPkg);
5984        return ver.databaseVersion < DatabaseVersion.SIGNATURE_END_ENTITY;
5985    }
5986
5987    /**
5988     * Used for backward compatibility to make sure any packages with
5989     * certificate chains get upgraded to the new style. {@code existingSigs}
5990     * will be in the old format (since they were stored on disk from before the
5991     * system upgrade) and {@code scannedSigs} will be in the newer format.
5992     */
5993    private int compareSignaturesCompat(PackageSignatures existingSigs,
5994            PackageParser.Package scannedPkg) {
5995        if (!isCompatSignatureUpdateNeeded(scannedPkg)) {
5996            return PackageManager.SIGNATURE_NO_MATCH;
5997        }
5998
5999        ArraySet<Signature> existingSet = new ArraySet<Signature>();
6000        for (Signature sig : existingSigs.mSignatures) {
6001            existingSet.add(sig);
6002        }
6003        ArraySet<Signature> scannedCompatSet = new ArraySet<Signature>();
6004        for (Signature sig : scannedPkg.mSignatures) {
6005            try {
6006                Signature[] chainSignatures = sig.getChainSignatures();
6007                for (Signature chainSig : chainSignatures) {
6008                    scannedCompatSet.add(chainSig);
6009                }
6010            } catch (CertificateEncodingException e) {
6011                scannedCompatSet.add(sig);
6012            }
6013        }
6014        /*
6015         * Make sure the expanded scanned set contains all signatures in the
6016         * existing one.
6017         */
6018        if (scannedCompatSet.equals(existingSet)) {
6019            // Migrate the old signatures to the new scheme.
6020            existingSigs.assignSignatures(scannedPkg.mSignatures);
6021            // The new KeySets will be re-added later in the scanning process.
6022            synchronized (mPackages) {
6023                mSettings.mKeySetManagerService.removeAppKeySetDataLPw(scannedPkg.packageName);
6024            }
6025            return PackageManager.SIGNATURE_MATCH;
6026        }
6027        return PackageManager.SIGNATURE_NO_MATCH;
6028    }
6029
6030    private boolean isRecoverSignatureUpdateNeeded(PackageParser.Package scannedPkg) {
6031        final VersionInfo ver = getSettingsVersionForPackage(scannedPkg);
6032        return ver.databaseVersion < DatabaseVersion.SIGNATURE_MALFORMED_RECOVER;
6033    }
6034
6035    private int compareSignaturesRecover(PackageSignatures existingSigs,
6036            PackageParser.Package scannedPkg) {
6037        if (!isRecoverSignatureUpdateNeeded(scannedPkg)) {
6038            return PackageManager.SIGNATURE_NO_MATCH;
6039        }
6040
6041        String msg = null;
6042        try {
6043            if (Signature.areEffectiveMatch(existingSigs.mSignatures, scannedPkg.mSignatures)) {
6044                logCriticalInfo(Log.INFO, "Recovered effectively matching certificates for "
6045                        + scannedPkg.packageName);
6046                return PackageManager.SIGNATURE_MATCH;
6047            }
6048        } catch (CertificateException e) {
6049            msg = e.getMessage();
6050        }
6051
6052        logCriticalInfo(Log.INFO,
6053                "Failed to recover certificates for " + scannedPkg.packageName + ": " + msg);
6054        return PackageManager.SIGNATURE_NO_MATCH;
6055    }
6056
6057    @Override
6058    public List<String> getAllPackages() {
6059        final int callingUid = Binder.getCallingUid();
6060        final int callingUserId = UserHandle.getUserId(callingUid);
6061        synchronized (mPackages) {
6062            if (canViewInstantApps(callingUid, callingUserId)) {
6063                return new ArrayList<String>(mPackages.keySet());
6064            }
6065            final String instantAppPkgName = getInstantAppPackageName(callingUid);
6066            final List<String> result = new ArrayList<>();
6067            if (instantAppPkgName != null) {
6068                // caller is an instant application; filter unexposed applications
6069                for (PackageParser.Package pkg : mPackages.values()) {
6070                    if (!pkg.visibleToInstantApps) {
6071                        continue;
6072                    }
6073                    result.add(pkg.packageName);
6074                }
6075            } else {
6076                // caller is a normal application; filter instant applications
6077                for (PackageParser.Package pkg : mPackages.values()) {
6078                    final PackageSetting ps =
6079                            pkg.mExtras != null ? (PackageSetting) pkg.mExtras : null;
6080                    if (ps != null
6081                            && ps.getInstantApp(callingUserId)
6082                            && !mInstantAppRegistry.isInstantAccessGranted(
6083                                    callingUserId, UserHandle.getAppId(callingUid), ps.appId)) {
6084                        continue;
6085                    }
6086                    result.add(pkg.packageName);
6087                }
6088            }
6089            return result;
6090        }
6091    }
6092
6093    @Override
6094    public String[] getPackagesForUid(int uid) {
6095        final int callingUid = Binder.getCallingUid();
6096        final boolean isCallerInstantApp = getInstantAppPackageName(callingUid) != null;
6097        final int userId = UserHandle.getUserId(uid);
6098        uid = UserHandle.getAppId(uid);
6099        // reader
6100        synchronized (mPackages) {
6101            Object obj = mSettings.getUserIdLPr(uid);
6102            if (obj instanceof SharedUserSetting) {
6103                if (isCallerInstantApp) {
6104                    return null;
6105                }
6106                final SharedUserSetting sus = (SharedUserSetting) obj;
6107                final int N = sus.packages.size();
6108                String[] res = new String[N];
6109                final Iterator<PackageSetting> it = sus.packages.iterator();
6110                int i = 0;
6111                while (it.hasNext()) {
6112                    PackageSetting ps = it.next();
6113                    if (ps.getInstalled(userId)) {
6114                        res[i++] = ps.name;
6115                    } else {
6116                        res = ArrayUtils.removeElement(String.class, res, res[i]);
6117                    }
6118                }
6119                return res;
6120            } else if (obj instanceof PackageSetting) {
6121                final PackageSetting ps = (PackageSetting) obj;
6122                if (ps.getInstalled(userId) && !filterAppAccessLPr(ps, callingUid, userId)) {
6123                    return new String[]{ps.name};
6124                }
6125            }
6126        }
6127        return null;
6128    }
6129
6130    @Override
6131    public String getNameForUid(int uid) {
6132        final int callingUid = Binder.getCallingUid();
6133        if (getInstantAppPackageName(callingUid) != null) {
6134            return null;
6135        }
6136        synchronized (mPackages) {
6137            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
6138            if (obj instanceof SharedUserSetting) {
6139                final SharedUserSetting sus = (SharedUserSetting) obj;
6140                return sus.name + ":" + sus.userId;
6141            } else if (obj instanceof PackageSetting) {
6142                final PackageSetting ps = (PackageSetting) obj;
6143                if (filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
6144                    return null;
6145                }
6146                return ps.name;
6147            }
6148        }
6149        return null;
6150    }
6151
6152    @Override
6153    public int getUidForSharedUser(String sharedUserName) {
6154        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
6155            return -1;
6156        }
6157        if (sharedUserName == null) {
6158            return -1;
6159        }
6160        // reader
6161        synchronized (mPackages) {
6162            SharedUserSetting suid;
6163            try {
6164                suid = mSettings.getSharedUserLPw(sharedUserName, 0, 0, false);
6165                if (suid != null) {
6166                    return suid.userId;
6167                }
6168            } catch (PackageManagerException ignore) {
6169                // can't happen, but, still need to catch it
6170            }
6171            return -1;
6172        }
6173    }
6174
6175    @Override
6176    public int getFlagsForUid(int uid) {
6177        final int callingUid = Binder.getCallingUid();
6178        if (getInstantAppPackageName(callingUid) != null) {
6179            return 0;
6180        }
6181        synchronized (mPackages) {
6182            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
6183            if (obj instanceof SharedUserSetting) {
6184                final SharedUserSetting sus = (SharedUserSetting) obj;
6185                return sus.pkgFlags;
6186            } else if (obj instanceof PackageSetting) {
6187                final PackageSetting ps = (PackageSetting) obj;
6188                if (filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
6189                    return 0;
6190                }
6191                return ps.pkgFlags;
6192            }
6193        }
6194        return 0;
6195    }
6196
6197    @Override
6198    public int getPrivateFlagsForUid(int uid) {
6199        final int callingUid = Binder.getCallingUid();
6200        if (getInstantAppPackageName(callingUid) != null) {
6201            return 0;
6202        }
6203        synchronized (mPackages) {
6204            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
6205            if (obj instanceof SharedUserSetting) {
6206                final SharedUserSetting sus = (SharedUserSetting) obj;
6207                return sus.pkgPrivateFlags;
6208            } else if (obj instanceof PackageSetting) {
6209                final PackageSetting ps = (PackageSetting) obj;
6210                if (filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
6211                    return 0;
6212                }
6213                return ps.pkgPrivateFlags;
6214            }
6215        }
6216        return 0;
6217    }
6218
6219    @Override
6220    public boolean isUidPrivileged(int uid) {
6221        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
6222            return false;
6223        }
6224        uid = UserHandle.getAppId(uid);
6225        // reader
6226        synchronized (mPackages) {
6227            Object obj = mSettings.getUserIdLPr(uid);
6228            if (obj instanceof SharedUserSetting) {
6229                final SharedUserSetting sus = (SharedUserSetting) obj;
6230                final Iterator<PackageSetting> it = sus.packages.iterator();
6231                while (it.hasNext()) {
6232                    if (it.next().isPrivileged()) {
6233                        return true;
6234                    }
6235                }
6236            } else if (obj instanceof PackageSetting) {
6237                final PackageSetting ps = (PackageSetting) obj;
6238                return ps.isPrivileged();
6239            }
6240        }
6241        return false;
6242    }
6243
6244    @Override
6245    public String[] getAppOpPermissionPackages(String permissionName) {
6246        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
6247            return null;
6248        }
6249        synchronized (mPackages) {
6250            ArraySet<String> pkgs = mAppOpPermissionPackages.get(permissionName);
6251            if (pkgs == null) {
6252                return null;
6253            }
6254            return pkgs.toArray(new String[pkgs.size()]);
6255        }
6256    }
6257
6258    @Override
6259    public ResolveInfo resolveIntent(Intent intent, String resolvedType,
6260            int flags, int userId) {
6261        return resolveIntentInternal(
6262                intent, resolvedType, flags, userId, false /*includeInstantApps*/);
6263    }
6264
6265    private ResolveInfo resolveIntentInternal(Intent intent, String resolvedType,
6266            int flags, int userId, boolean resolveForStart) {
6267        try {
6268            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "resolveIntent");
6269
6270            if (!sUserManager.exists(userId)) return null;
6271            final int callingUid = Binder.getCallingUid();
6272            flags = updateFlagsForResolve(flags, userId, intent, callingUid, resolveForStart);
6273            enforceCrossUserPermission(callingUid, userId,
6274                    false /*requireFullPermission*/, false /*checkShell*/, "resolve intent");
6275
6276            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "queryIntentActivities");
6277            final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType,
6278                    flags, callingUid, userId, resolveForStart);
6279            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
6280
6281            final ResolveInfo bestChoice =
6282                    chooseBestActivity(intent, resolvedType, flags, query, userId);
6283            return bestChoice;
6284        } finally {
6285            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
6286        }
6287    }
6288
6289    @Override
6290    public ResolveInfo findPersistentPreferredActivity(Intent intent, int userId) {
6291        if (!UserHandle.isSameApp(Binder.getCallingUid(), Process.SYSTEM_UID)) {
6292            throw new SecurityException(
6293                    "findPersistentPreferredActivity can only be run by the system");
6294        }
6295        if (!sUserManager.exists(userId)) {
6296            return null;
6297        }
6298        final int callingUid = Binder.getCallingUid();
6299        intent = updateIntentForResolve(intent);
6300        final String resolvedType = intent.resolveTypeIfNeeded(mContext.getContentResolver());
6301        final int flags = updateFlagsForResolve(
6302                0, userId, intent, callingUid, false /*includeInstantApps*/);
6303        final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags,
6304                userId);
6305        synchronized (mPackages) {
6306            return findPersistentPreferredActivityLP(intent, resolvedType, flags, query, false,
6307                    userId);
6308        }
6309    }
6310
6311    @Override
6312    public void setLastChosenActivity(Intent intent, String resolvedType, int flags,
6313            IntentFilter filter, int match, ComponentName activity) {
6314        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
6315            return;
6316        }
6317        final int userId = UserHandle.getCallingUserId();
6318        if (DEBUG_PREFERRED) {
6319            Log.v(TAG, "setLastChosenActivity intent=" + intent
6320                + " resolvedType=" + resolvedType
6321                + " flags=" + flags
6322                + " filter=" + filter
6323                + " match=" + match
6324                + " activity=" + activity);
6325            filter.dump(new PrintStreamPrinter(System.out), "    ");
6326        }
6327        intent.setComponent(null);
6328        final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags,
6329                userId);
6330        // Find any earlier preferred or last chosen entries and nuke them
6331        findPreferredActivity(intent, resolvedType,
6332                flags, query, 0, false, true, false, userId);
6333        // Add the new activity as the last chosen for this filter
6334        addPreferredActivityInternal(filter, match, null, activity, false, userId,
6335                "Setting last chosen");
6336    }
6337
6338    @Override
6339    public ResolveInfo getLastChosenActivity(Intent intent, String resolvedType, int flags) {
6340        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
6341            return null;
6342        }
6343        final int userId = UserHandle.getCallingUserId();
6344        if (DEBUG_PREFERRED) Log.v(TAG, "Querying last chosen activity for " + intent);
6345        final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags,
6346                userId);
6347        return findPreferredActivity(intent, resolvedType, flags, query, 0,
6348                false, false, false, userId);
6349    }
6350
6351    /**
6352     * Returns whether or not instant apps have been disabled remotely.
6353     */
6354    private boolean isEphemeralDisabled() {
6355        return mEphemeralAppsDisabled;
6356    }
6357
6358    private boolean isInstantAppAllowed(
6359            Intent intent, List<ResolveInfo> resolvedActivities, int userId,
6360            boolean skipPackageCheck) {
6361        if (mInstantAppResolverConnection == null) {
6362            return false;
6363        }
6364        if (mInstantAppInstallerActivity == null) {
6365            return false;
6366        }
6367        if (intent.getComponent() != null) {
6368            return false;
6369        }
6370        if ((intent.getFlags() & Intent.FLAG_IGNORE_EPHEMERAL) != 0) {
6371            return false;
6372        }
6373        if (!skipPackageCheck && intent.getPackage() != null) {
6374            return false;
6375        }
6376        final boolean isWebUri = hasWebURI(intent);
6377        if (!isWebUri || intent.getData().getHost() == null) {
6378            return false;
6379        }
6380        // Deny ephemeral apps if the user chose _ALWAYS or _ALWAYS_ASK for intent resolution.
6381        // Or if there's already an ephemeral app installed that handles the action
6382        synchronized (mPackages) {
6383            final int count = (resolvedActivities == null ? 0 : resolvedActivities.size());
6384            for (int n = 0; n < count; n++) {
6385                final ResolveInfo info = resolvedActivities.get(n);
6386                final String packageName = info.activityInfo.packageName;
6387                final PackageSetting ps = mSettings.mPackages.get(packageName);
6388                if (ps != null) {
6389                    // only check domain verification status if the app is not a browser
6390                    if (!info.handleAllWebDataURI) {
6391                        // Try to get the status from User settings first
6392                        final long packedStatus = getDomainVerificationStatusLPr(ps, userId);
6393                        final int status = (int) (packedStatus >> 32);
6394                        if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS
6395                            || status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) {
6396                            if (DEBUG_EPHEMERAL) {
6397                                Slog.v(TAG, "DENY instant app;"
6398                                    + " pkg: " + packageName + ", status: " + status);
6399                            }
6400                            return false;
6401                        }
6402                    }
6403                    if (ps.getInstantApp(userId)) {
6404                        if (DEBUG_EPHEMERAL) {
6405                            Slog.v(TAG, "DENY instant app installed;"
6406                                    + " pkg: " + packageName);
6407                        }
6408                        return false;
6409                    }
6410                }
6411            }
6412        }
6413        // We've exhausted all ways to deny ephemeral application; let the system look for them.
6414        return true;
6415    }
6416
6417    private void requestInstantAppResolutionPhaseTwo(AuxiliaryResolveInfo responseObj,
6418            Intent origIntent, String resolvedType, String callingPackage,
6419            Bundle verificationBundle, int userId) {
6420        final Message msg = mHandler.obtainMessage(INSTANT_APP_RESOLUTION_PHASE_TWO,
6421                new InstantAppRequest(responseObj, origIntent, resolvedType,
6422                        callingPackage, userId, verificationBundle));
6423        mHandler.sendMessage(msg);
6424    }
6425
6426    private ResolveInfo chooseBestActivity(Intent intent, String resolvedType,
6427            int flags, List<ResolveInfo> query, int userId) {
6428        if (query != null) {
6429            final int N = query.size();
6430            if (N == 1) {
6431                return query.get(0);
6432            } else if (N > 1) {
6433                final boolean debug = ((intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0);
6434                // If there is more than one activity with the same priority,
6435                // then let the user decide between them.
6436                ResolveInfo r0 = query.get(0);
6437                ResolveInfo r1 = query.get(1);
6438                if (DEBUG_INTENT_MATCHING || debug) {
6439                    Slog.v(TAG, r0.activityInfo.name + "=" + r0.priority + " vs "
6440                            + r1.activityInfo.name + "=" + r1.priority);
6441                }
6442                // If the first activity has a higher priority, or a different
6443                // default, then it is always desirable to pick it.
6444                if (r0.priority != r1.priority
6445                        || r0.preferredOrder != r1.preferredOrder
6446                        || r0.isDefault != r1.isDefault) {
6447                    return query.get(0);
6448                }
6449                // If we have saved a preference for a preferred activity for
6450                // this Intent, use that.
6451                ResolveInfo ri = findPreferredActivity(intent, resolvedType,
6452                        flags, query, r0.priority, true, false, debug, userId);
6453                if (ri != null) {
6454                    return ri;
6455                }
6456                // If we have an ephemeral app, use it
6457                for (int i = 0; i < N; i++) {
6458                    ri = query.get(i);
6459                    if (ri.activityInfo.applicationInfo.isInstantApp()) {
6460                        final String packageName = ri.activityInfo.packageName;
6461                        final PackageSetting ps = mSettings.mPackages.get(packageName);
6462                        final long packedStatus = getDomainVerificationStatusLPr(ps, userId);
6463                        final int status = (int)(packedStatus >> 32);
6464                        if (status != INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) {
6465                            return ri;
6466                        }
6467                    }
6468                }
6469                ri = new ResolveInfo(mResolveInfo);
6470                ri.activityInfo = new ActivityInfo(ri.activityInfo);
6471                ri.activityInfo.labelRes = ResolverActivity.getLabelRes(intent.getAction());
6472                // If all of the options come from the same package, show the application's
6473                // label and icon instead of the generic resolver's.
6474                // Some calls like Intent.resolveActivityInfo query the ResolveInfo from here
6475                // and then throw away the ResolveInfo itself, meaning that the caller loses
6476                // the resolvePackageName. Therefore the activityInfo.labelRes above provides
6477                // a fallback for this case; we only set the target package's resources on
6478                // the ResolveInfo, not the ActivityInfo.
6479                final String intentPackage = intent.getPackage();
6480                if (!TextUtils.isEmpty(intentPackage) && allHavePackage(query, intentPackage)) {
6481                    final ApplicationInfo appi = query.get(0).activityInfo.applicationInfo;
6482                    ri.resolvePackageName = intentPackage;
6483                    if (userNeedsBadging(userId)) {
6484                        ri.noResourceId = true;
6485                    } else {
6486                        ri.icon = appi.icon;
6487                    }
6488                    ri.iconResourceId = appi.icon;
6489                    ri.labelRes = appi.labelRes;
6490                }
6491                ri.activityInfo.applicationInfo = new ApplicationInfo(
6492                        ri.activityInfo.applicationInfo);
6493                if (userId != 0) {
6494                    ri.activityInfo.applicationInfo.uid = UserHandle.getUid(userId,
6495                            UserHandle.getAppId(ri.activityInfo.applicationInfo.uid));
6496                }
6497                // Make sure that the resolver is displayable in car mode
6498                if (ri.activityInfo.metaData == null) ri.activityInfo.metaData = new Bundle();
6499                ri.activityInfo.metaData.putBoolean(Intent.METADATA_DOCK_HOME, true);
6500                return ri;
6501            }
6502        }
6503        return null;
6504    }
6505
6506    /**
6507     * Return true if the given list is not empty and all of its contents have
6508     * an activityInfo with the given package name.
6509     */
6510    private boolean allHavePackage(List<ResolveInfo> list, String packageName) {
6511        if (ArrayUtils.isEmpty(list)) {
6512            return false;
6513        }
6514        for (int i = 0, N = list.size(); i < N; i++) {
6515            final ResolveInfo ri = list.get(i);
6516            final ActivityInfo ai = ri != null ? ri.activityInfo : null;
6517            if (ai == null || !packageName.equals(ai.packageName)) {
6518                return false;
6519            }
6520        }
6521        return true;
6522    }
6523
6524    private ResolveInfo findPersistentPreferredActivityLP(Intent intent, String resolvedType,
6525            int flags, List<ResolveInfo> query, boolean debug, int userId) {
6526        final int N = query.size();
6527        PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities
6528                .get(userId);
6529        // Get the list of persistent preferred activities that handle the intent
6530        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for presistent preferred activities...");
6531        List<PersistentPreferredActivity> pprefs = ppir != null
6532                ? ppir.queryIntent(intent, resolvedType,
6533                        (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0,
6534                        userId)
6535                : null;
6536        if (pprefs != null && pprefs.size() > 0) {
6537            final int M = pprefs.size();
6538            for (int i=0; i<M; i++) {
6539                final PersistentPreferredActivity ppa = pprefs.get(i);
6540                if (DEBUG_PREFERRED || debug) {
6541                    Slog.v(TAG, "Checking PersistentPreferredActivity ds="
6542                            + (ppa.countDataSchemes() > 0 ? ppa.getDataScheme(0) : "<none>")
6543                            + "\n  component=" + ppa.mComponent);
6544                    ppa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
6545                }
6546                final ActivityInfo ai = getActivityInfo(ppa.mComponent,
6547                        flags | MATCH_DISABLED_COMPONENTS, userId);
6548                if (DEBUG_PREFERRED || debug) {
6549                    Slog.v(TAG, "Found persistent preferred activity:");
6550                    if (ai != null) {
6551                        ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
6552                    } else {
6553                        Slog.v(TAG, "  null");
6554                    }
6555                }
6556                if (ai == null) {
6557                    // This previously registered persistent preferred activity
6558                    // component is no longer known. Ignore it and do NOT remove it.
6559                    continue;
6560                }
6561                for (int j=0; j<N; j++) {
6562                    final ResolveInfo ri = query.get(j);
6563                    if (!ri.activityInfo.applicationInfo.packageName
6564                            .equals(ai.applicationInfo.packageName)) {
6565                        continue;
6566                    }
6567                    if (!ri.activityInfo.name.equals(ai.name)) {
6568                        continue;
6569                    }
6570                    //  Found a persistent preference that can handle the intent.
6571                    if (DEBUG_PREFERRED || debug) {
6572                        Slog.v(TAG, "Returning persistent preferred activity: " +
6573                                ri.activityInfo.packageName + "/" + ri.activityInfo.name);
6574                    }
6575                    return ri;
6576                }
6577            }
6578        }
6579        return null;
6580    }
6581
6582    // TODO: handle preferred activities missing while user has amnesia
6583    ResolveInfo findPreferredActivity(Intent intent, String resolvedType, int flags,
6584            List<ResolveInfo> query, int priority, boolean always,
6585            boolean removeMatches, boolean debug, int userId) {
6586        if (!sUserManager.exists(userId)) return null;
6587        final int callingUid = Binder.getCallingUid();
6588        flags = updateFlagsForResolve(
6589                flags, userId, intent, callingUid, false /*includeInstantApps*/);
6590        intent = updateIntentForResolve(intent);
6591        // writer
6592        synchronized (mPackages) {
6593            // Try to find a matching persistent preferred activity.
6594            ResolveInfo pri = findPersistentPreferredActivityLP(intent, resolvedType, flags, query,
6595                    debug, userId);
6596
6597            // If a persistent preferred activity matched, use it.
6598            if (pri != null) {
6599                return pri;
6600            }
6601
6602            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
6603            // Get the list of preferred activities that handle the intent
6604            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for preferred activities...");
6605            List<PreferredActivity> prefs = pir != null
6606                    ? pir.queryIntent(intent, resolvedType,
6607                            (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0,
6608                            userId)
6609                    : null;
6610            if (prefs != null && prefs.size() > 0) {
6611                boolean changed = false;
6612                try {
6613                    // First figure out how good the original match set is.
6614                    // We will only allow preferred activities that came
6615                    // from the same match quality.
6616                    int match = 0;
6617
6618                    if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Figuring out best match...");
6619
6620                    final int N = query.size();
6621                    for (int j=0; j<N; j++) {
6622                        final ResolveInfo ri = query.get(j);
6623                        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Match for " + ri.activityInfo
6624                                + ": 0x" + Integer.toHexString(match));
6625                        if (ri.match > match) {
6626                            match = ri.match;
6627                        }
6628                    }
6629
6630                    if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Best match: 0x"
6631                            + Integer.toHexString(match));
6632
6633                    match &= IntentFilter.MATCH_CATEGORY_MASK;
6634                    final int M = prefs.size();
6635                    for (int i=0; i<M; i++) {
6636                        final PreferredActivity pa = prefs.get(i);
6637                        if (DEBUG_PREFERRED || debug) {
6638                            Slog.v(TAG, "Checking PreferredActivity ds="
6639                                    + (pa.countDataSchemes() > 0 ? pa.getDataScheme(0) : "<none>")
6640                                    + "\n  component=" + pa.mPref.mComponent);
6641                            pa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
6642                        }
6643                        if (pa.mPref.mMatch != match) {
6644                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping bad match "
6645                                    + Integer.toHexString(pa.mPref.mMatch));
6646                            continue;
6647                        }
6648                        // If it's not an "always" type preferred activity and that's what we're
6649                        // looking for, skip it.
6650                        if (always && !pa.mPref.mAlways) {
6651                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping mAlways=false entry");
6652                            continue;
6653                        }
6654                        final ActivityInfo ai = getActivityInfo(
6655                                pa.mPref.mComponent, flags | MATCH_DISABLED_COMPONENTS
6656                                        | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
6657                                userId);
6658                        if (DEBUG_PREFERRED || debug) {
6659                            Slog.v(TAG, "Found preferred activity:");
6660                            if (ai != null) {
6661                                ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
6662                            } else {
6663                                Slog.v(TAG, "  null");
6664                            }
6665                        }
6666                        if (ai == null) {
6667                            // This previously registered preferred activity
6668                            // component is no longer known.  Most likely an update
6669                            // to the app was installed and in the new version this
6670                            // component no longer exists.  Clean it up by removing
6671                            // it from the preferred activities list, and skip it.
6672                            Slog.w(TAG, "Removing dangling preferred activity: "
6673                                    + pa.mPref.mComponent);
6674                            pir.removeFilter(pa);
6675                            changed = true;
6676                            continue;
6677                        }
6678                        for (int j=0; j<N; j++) {
6679                            final ResolveInfo ri = query.get(j);
6680                            if (!ri.activityInfo.applicationInfo.packageName
6681                                    .equals(ai.applicationInfo.packageName)) {
6682                                continue;
6683                            }
6684                            if (!ri.activityInfo.name.equals(ai.name)) {
6685                                continue;
6686                            }
6687
6688                            if (removeMatches) {
6689                                pir.removeFilter(pa);
6690                                changed = true;
6691                                if (DEBUG_PREFERRED) {
6692                                    Slog.v(TAG, "Removing match " + pa.mPref.mComponent);
6693                                }
6694                                break;
6695                            }
6696
6697                            // Okay we found a previously set preferred or last chosen app.
6698                            // If the result set is different from when this
6699                            // was created, we need to clear it and re-ask the
6700                            // user their preference, if we're looking for an "always" type entry.
6701                            if (always && !pa.mPref.sameSet(query)) {
6702                                Slog.i(TAG, "Result set changed, dropping preferred activity for "
6703                                        + intent + " type " + resolvedType);
6704                                if (DEBUG_PREFERRED) {
6705                                    Slog.v(TAG, "Removing preferred activity since set changed "
6706                                            + pa.mPref.mComponent);
6707                                }
6708                                pir.removeFilter(pa);
6709                                // Re-add the filter as a "last chosen" entry (!always)
6710                                PreferredActivity lastChosen = new PreferredActivity(
6711                                        pa, pa.mPref.mMatch, null, pa.mPref.mComponent, false);
6712                                pir.addFilter(lastChosen);
6713                                changed = true;
6714                                return null;
6715                            }
6716
6717                            // Yay! Either the set matched or we're looking for the last chosen
6718                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Returning preferred activity: "
6719                                    + ri.activityInfo.packageName + "/" + ri.activityInfo.name);
6720                            return ri;
6721                        }
6722                    }
6723                } finally {
6724                    if (changed) {
6725                        if (DEBUG_PREFERRED) {
6726                            Slog.v(TAG, "Preferred activity bookkeeping changed; writing restrictions");
6727                        }
6728                        scheduleWritePackageRestrictionsLocked(userId);
6729                    }
6730                }
6731            }
6732        }
6733        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "No preferred activity to return");
6734        return null;
6735    }
6736
6737    /*
6738     * Returns if intent can be forwarded from the sourceUserId to the targetUserId
6739     */
6740    @Override
6741    public boolean canForwardTo(Intent intent, String resolvedType, int sourceUserId,
6742            int targetUserId) {
6743        mContext.enforceCallingOrSelfPermission(
6744                android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
6745        List<CrossProfileIntentFilter> matches =
6746                getMatchingCrossProfileIntentFilters(intent, resolvedType, sourceUserId);
6747        if (matches != null) {
6748            int size = matches.size();
6749            for (int i = 0; i < size; i++) {
6750                if (matches.get(i).getTargetUserId() == targetUserId) return true;
6751            }
6752        }
6753        if (hasWebURI(intent)) {
6754            // cross-profile app linking works only towards the parent.
6755            final int callingUid = Binder.getCallingUid();
6756            final UserInfo parent = getProfileParent(sourceUserId);
6757            synchronized(mPackages) {
6758                int flags = updateFlagsForResolve(0, parent.id, intent, callingUid,
6759                        false /*includeInstantApps*/);
6760                CrossProfileDomainInfo xpDomainInfo = getCrossProfileDomainPreferredLpr(
6761                        intent, resolvedType, flags, sourceUserId, parent.id);
6762                return xpDomainInfo != null;
6763            }
6764        }
6765        return false;
6766    }
6767
6768    private UserInfo getProfileParent(int userId) {
6769        final long identity = Binder.clearCallingIdentity();
6770        try {
6771            return sUserManager.getProfileParent(userId);
6772        } finally {
6773            Binder.restoreCallingIdentity(identity);
6774        }
6775    }
6776
6777    private List<CrossProfileIntentFilter> getMatchingCrossProfileIntentFilters(Intent intent,
6778            String resolvedType, int userId) {
6779        CrossProfileIntentResolver resolver = mSettings.mCrossProfileIntentResolvers.get(userId);
6780        if (resolver != null) {
6781            return resolver.queryIntent(intent, resolvedType, false /*defaultOnly*/, userId);
6782        }
6783        return null;
6784    }
6785
6786    @Override
6787    public @NonNull ParceledListSlice<ResolveInfo> queryIntentActivities(Intent intent,
6788            String resolvedType, int flags, int userId) {
6789        try {
6790            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "queryIntentActivities");
6791
6792            return new ParceledListSlice<>(
6793                    queryIntentActivitiesInternal(intent, resolvedType, flags, userId));
6794        } finally {
6795            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
6796        }
6797    }
6798
6799    /**
6800     * Returns the package name of the calling Uid if it's an instant app. If it isn't
6801     * instant, returns {@code null}.
6802     */
6803    private String getInstantAppPackageName(int callingUid) {
6804        synchronized (mPackages) {
6805            // If the caller is an isolated app use the owner's uid for the lookup.
6806            if (Process.isIsolated(callingUid)) {
6807                callingUid = mIsolatedOwners.get(callingUid);
6808            }
6809            final int appId = UserHandle.getAppId(callingUid);
6810            final Object obj = mSettings.getUserIdLPr(appId);
6811            if (obj instanceof PackageSetting) {
6812                final PackageSetting ps = (PackageSetting) obj;
6813                final boolean isInstantApp = ps.getInstantApp(UserHandle.getUserId(callingUid));
6814                return isInstantApp ? ps.pkg.packageName : null;
6815            }
6816        }
6817        return null;
6818    }
6819
6820    private @NonNull List<ResolveInfo> queryIntentActivitiesInternal(Intent intent,
6821            String resolvedType, int flags, int userId) {
6822        return queryIntentActivitiesInternal(
6823                intent, resolvedType, flags, Binder.getCallingUid(), userId, false);
6824    }
6825
6826    private @NonNull List<ResolveInfo> queryIntentActivitiesInternal(Intent intent,
6827            String resolvedType, int flags, int filterCallingUid, int userId,
6828            boolean resolveForStart) {
6829        if (!sUserManager.exists(userId)) return Collections.emptyList();
6830        final String instantAppPkgName = getInstantAppPackageName(filterCallingUid);
6831        enforceCrossUserPermission(Binder.getCallingUid(), userId,
6832                false /* requireFullPermission */, false /* checkShell */,
6833                "query intent activities");
6834        final String pkgName = intent.getPackage();
6835        ComponentName comp = intent.getComponent();
6836        if (comp == null) {
6837            if (intent.getSelector() != null) {
6838                intent = intent.getSelector();
6839                comp = intent.getComponent();
6840            }
6841        }
6842
6843        flags = updateFlagsForResolve(flags, userId, intent, filterCallingUid, resolveForStart,
6844                comp != null || pkgName != null /*onlyExposedExplicitly*/);
6845        if (comp != null) {
6846            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
6847            final ActivityInfo ai = getActivityInfo(comp, flags, userId);
6848            if (ai != null) {
6849                // When specifying an explicit component, we prevent the activity from being
6850                // used when either 1) the calling package is normal and the activity is within
6851                // an ephemeral application or 2) the calling package is ephemeral and the
6852                // activity is not visible to ephemeral applications.
6853                final boolean matchInstantApp =
6854                        (flags & PackageManager.MATCH_INSTANT) != 0;
6855                final boolean matchVisibleToInstantAppOnly =
6856                        (flags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
6857                final boolean matchExplicitlyVisibleOnly =
6858                        (flags & PackageManager.MATCH_EXPLICITLY_VISIBLE_ONLY) != 0;
6859                final boolean isCallerInstantApp =
6860                        instantAppPkgName != null;
6861                final boolean isTargetSameInstantApp =
6862                        comp.getPackageName().equals(instantAppPkgName);
6863                final boolean isTargetInstantApp =
6864                        (ai.applicationInfo.privateFlags
6865                                & ApplicationInfo.PRIVATE_FLAG_INSTANT) != 0;
6866                final boolean isTargetVisibleToInstantApp =
6867                        (ai.flags & ActivityInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0;
6868                final boolean isTargetExplicitlyVisibleToInstantApp =
6869                        isTargetVisibleToInstantApp
6870                        && (ai.flags & ActivityInfo.FLAG_IMPLICITLY_VISIBLE_TO_INSTANT_APP) == 0;
6871                final boolean isTargetHiddenFromInstantApp =
6872                        !isTargetVisibleToInstantApp
6873                        || (matchExplicitlyVisibleOnly && !isTargetExplicitlyVisibleToInstantApp);
6874                final boolean blockResolution =
6875                        !isTargetSameInstantApp
6876                        && ((!matchInstantApp && !isCallerInstantApp && isTargetInstantApp)
6877                                || (matchVisibleToInstantAppOnly && isCallerInstantApp
6878                                        && isTargetHiddenFromInstantApp));
6879                if (!blockResolution) {
6880                    final ResolveInfo ri = new ResolveInfo();
6881                    ri.activityInfo = ai;
6882                    list.add(ri);
6883                }
6884            }
6885            return applyPostResolutionFilter(list, instantAppPkgName);
6886        }
6887
6888        // reader
6889        boolean sortResult = false;
6890        boolean addEphemeral = false;
6891        List<ResolveInfo> result;
6892        final boolean ephemeralDisabled = isEphemeralDisabled();
6893        synchronized (mPackages) {
6894            if (pkgName == null) {
6895                List<CrossProfileIntentFilter> matchingFilters =
6896                        getMatchingCrossProfileIntentFilters(intent, resolvedType, userId);
6897                // Check for results that need to skip the current profile.
6898                ResolveInfo xpResolveInfo  = querySkipCurrentProfileIntents(matchingFilters, intent,
6899                        resolvedType, flags, userId);
6900                if (xpResolveInfo != null) {
6901                    List<ResolveInfo> xpResult = new ArrayList<ResolveInfo>(1);
6902                    xpResult.add(xpResolveInfo);
6903                    return applyPostResolutionFilter(
6904                            filterIfNotSystemUser(xpResult, userId), instantAppPkgName);
6905                }
6906
6907                // Check for results in the current profile.
6908                result = filterIfNotSystemUser(mActivities.queryIntent(
6909                        intent, resolvedType, flags, userId), userId);
6910                addEphemeral = !ephemeralDisabled
6911                        && isInstantAppAllowed(intent, result, userId, false /*skipPackageCheck*/);
6912                // Check for cross profile results.
6913                boolean hasNonNegativePriorityResult = hasNonNegativePriority(result);
6914                xpResolveInfo = queryCrossProfileIntents(
6915                        matchingFilters, intent, resolvedType, flags, userId,
6916                        hasNonNegativePriorityResult);
6917                if (xpResolveInfo != null && isUserEnabled(xpResolveInfo.targetUserId)) {
6918                    boolean isVisibleToUser = filterIfNotSystemUser(
6919                            Collections.singletonList(xpResolveInfo), userId).size() > 0;
6920                    if (isVisibleToUser) {
6921                        result.add(xpResolveInfo);
6922                        sortResult = true;
6923                    }
6924                }
6925                if (hasWebURI(intent)) {
6926                    CrossProfileDomainInfo xpDomainInfo = null;
6927                    final UserInfo parent = getProfileParent(userId);
6928                    if (parent != null) {
6929                        xpDomainInfo = getCrossProfileDomainPreferredLpr(intent, resolvedType,
6930                                flags, userId, parent.id);
6931                    }
6932                    if (xpDomainInfo != null) {
6933                        if (xpResolveInfo != null) {
6934                            // If we didn't remove it, the cross-profile ResolveInfo would be twice
6935                            // in the result.
6936                            result.remove(xpResolveInfo);
6937                        }
6938                        if (result.size() == 0 && !addEphemeral) {
6939                            // No result in current profile, but found candidate in parent user.
6940                            // And we are not going to add emphemeral app, so we can return the
6941                            // result straight away.
6942                            result.add(xpDomainInfo.resolveInfo);
6943                            return applyPostResolutionFilter(result, instantAppPkgName);
6944                        }
6945                    } else if (result.size() <= 1 && !addEphemeral) {
6946                        // No result in parent user and <= 1 result in current profile, and we
6947                        // are not going to add emphemeral app, so we can return the result without
6948                        // further processing.
6949                        return applyPostResolutionFilter(result, instantAppPkgName);
6950                    }
6951                    // We have more than one candidate (combining results from current and parent
6952                    // profile), so we need filtering and sorting.
6953                    result = filterCandidatesWithDomainPreferredActivitiesLPr(
6954                            intent, flags, result, xpDomainInfo, userId);
6955                    sortResult = true;
6956                }
6957            } else {
6958                final PackageParser.Package pkg = mPackages.get(pkgName);
6959                result = null;
6960                if (pkg != null) {
6961                    result = filterIfNotSystemUser(
6962                            mActivities.queryIntentForPackage(
6963                                    intent, resolvedType, flags, pkg.activities, userId),
6964                            userId);
6965                }
6966                if (result == null || result.size() == 0) {
6967                    // the caller wants to resolve for a particular package; however, there
6968                    // were no installed results, so, try to find an ephemeral result
6969                    addEphemeral = !ephemeralDisabled
6970                            && isInstantAppAllowed(
6971                                    intent, null /*result*/, userId, true /*skipPackageCheck*/);
6972                    if (result == null) {
6973                        result = new ArrayList<>();
6974                    }
6975                }
6976            }
6977        }
6978        if (addEphemeral) {
6979            result = maybeAddInstantAppInstaller(result, intent, resolvedType, flags, userId);
6980        }
6981        if (sortResult) {
6982            Collections.sort(result, mResolvePrioritySorter);
6983        }
6984        return applyPostResolutionFilter(result, instantAppPkgName);
6985    }
6986
6987    private List<ResolveInfo> maybeAddInstantAppInstaller(List<ResolveInfo> result, Intent intent,
6988            String resolvedType, int flags, int userId) {
6989        // first, check to see if we've got an instant app already installed
6990        final boolean alreadyResolvedLocally = (flags & PackageManager.MATCH_INSTANT) != 0;
6991        ResolveInfo localInstantApp = null;
6992        boolean blockResolution = false;
6993        if (!alreadyResolvedLocally) {
6994            final List<ResolveInfo> instantApps = mActivities.queryIntent(intent, resolvedType,
6995                    flags
6996                        | PackageManager.GET_RESOLVED_FILTER
6997                        | PackageManager.MATCH_INSTANT
6998                        | PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY,
6999                    userId);
7000            for (int i = instantApps.size() - 1; i >= 0; --i) {
7001                final ResolveInfo info = instantApps.get(i);
7002                final String packageName = info.activityInfo.packageName;
7003                final PackageSetting ps = mSettings.mPackages.get(packageName);
7004                if (ps.getInstantApp(userId)) {
7005                    final long packedStatus = getDomainVerificationStatusLPr(ps, userId);
7006                    final int status = (int)(packedStatus >> 32);
7007                    final int linkGeneration = (int)(packedStatus & 0xFFFFFFFF);
7008                    if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
7009                        // there's a local instant application installed, but, the user has
7010                        // chosen to never use it; skip resolution and don't acknowledge
7011                        // an instant application is even available
7012                        if (DEBUG_EPHEMERAL) {
7013                            Slog.v(TAG, "Instant app marked to never run; pkg: " + packageName);
7014                        }
7015                        blockResolution = true;
7016                        break;
7017                    } else {
7018                        // we have a locally installed instant application; skip resolution
7019                        // but acknowledge there's an instant application available
7020                        if (DEBUG_EPHEMERAL) {
7021                            Slog.v(TAG, "Found installed instant app; pkg: " + packageName);
7022                        }
7023                        localInstantApp = info;
7024                        break;
7025                    }
7026                }
7027            }
7028        }
7029        // no app installed, let's see if one's available
7030        AuxiliaryResolveInfo auxiliaryResponse = null;
7031        if (!blockResolution) {
7032            if (localInstantApp == null) {
7033                // we don't have an instant app locally, resolve externally
7034                Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "resolveEphemeral");
7035                final InstantAppRequest requestObject = new InstantAppRequest(
7036                        null /*responseObj*/, intent /*origIntent*/, resolvedType,
7037                        null /*callingPackage*/, userId, null /*verificationBundle*/);
7038                auxiliaryResponse =
7039                        InstantAppResolver.doInstantAppResolutionPhaseOne(
7040                                mContext, mInstantAppResolverConnection, requestObject);
7041                Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
7042            } else {
7043                // we have an instant application locally, but, we can't admit that since
7044                // callers shouldn't be able to determine prior browsing. create a dummy
7045                // auxiliary response so the downstream code behaves as if there's an
7046                // instant application available externally. when it comes time to start
7047                // the instant application, we'll do the right thing.
7048                final ApplicationInfo ai = localInstantApp.activityInfo.applicationInfo;
7049                auxiliaryResponse = new AuxiliaryResolveInfo(
7050                        ai.packageName, null /*splitName*/, ai.versionCode, null /*failureIntent*/);
7051            }
7052        }
7053        if (auxiliaryResponse != null) {
7054            if (DEBUG_EPHEMERAL) {
7055                Slog.v(TAG, "Adding ephemeral installer to the ResolveInfo list");
7056            }
7057            final ResolveInfo ephemeralInstaller = new ResolveInfo(mInstantAppInstallerInfo);
7058            final PackageSetting ps =
7059                    mSettings.mPackages.get(mInstantAppInstallerActivity.packageName);
7060            if (ps != null) {
7061                ephemeralInstaller.activityInfo = PackageParser.generateActivityInfo(
7062                        mInstantAppInstallerActivity, 0, ps.readUserState(userId), userId);
7063                ephemeralInstaller.activityInfo.launchToken = auxiliaryResponse.token;
7064                ephemeralInstaller.auxiliaryInfo = auxiliaryResponse;
7065                // make sure this resolver is the default
7066                ephemeralInstaller.isDefault = true;
7067                ephemeralInstaller.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART
7068                        | IntentFilter.MATCH_ADJUSTMENT_NORMAL;
7069                // add a non-generic filter
7070                ephemeralInstaller.filter = new IntentFilter(intent.getAction());
7071                ephemeralInstaller.filter.addDataPath(
7072                        intent.getData().getPath(), PatternMatcher.PATTERN_LITERAL);
7073                ephemeralInstaller.isInstantAppAvailable = true;
7074                result.add(ephemeralInstaller);
7075            }
7076        }
7077        return result;
7078    }
7079
7080    private static class CrossProfileDomainInfo {
7081        /* ResolveInfo for IntentForwarderActivity to send the intent to the other profile */
7082        ResolveInfo resolveInfo;
7083        /* Best domain verification status of the activities found in the other profile */
7084        int bestDomainVerificationStatus;
7085    }
7086
7087    private CrossProfileDomainInfo getCrossProfileDomainPreferredLpr(Intent intent,
7088            String resolvedType, int flags, int sourceUserId, int parentUserId) {
7089        if (!sUserManager.hasUserRestriction(UserManager.ALLOW_PARENT_PROFILE_APP_LINKING,
7090                sourceUserId)) {
7091            return null;
7092        }
7093        List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent,
7094                resolvedType, flags, parentUserId);
7095
7096        if (resultTargetUser == null || resultTargetUser.isEmpty()) {
7097            return null;
7098        }
7099        CrossProfileDomainInfo result = null;
7100        int size = resultTargetUser.size();
7101        for (int i = 0; i < size; i++) {
7102            ResolveInfo riTargetUser = resultTargetUser.get(i);
7103            // Intent filter verification is only for filters that specify a host. So don't return
7104            // those that handle all web uris.
7105            if (riTargetUser.handleAllWebDataURI) {
7106                continue;
7107            }
7108            String packageName = riTargetUser.activityInfo.packageName;
7109            PackageSetting ps = mSettings.mPackages.get(packageName);
7110            if (ps == null) {
7111                continue;
7112            }
7113            long verificationState = getDomainVerificationStatusLPr(ps, parentUserId);
7114            int status = (int)(verificationState >> 32);
7115            if (result == null) {
7116                result = new CrossProfileDomainInfo();
7117                result.resolveInfo = createForwardingResolveInfoUnchecked(new IntentFilter(),
7118                        sourceUserId, parentUserId);
7119                result.bestDomainVerificationStatus = status;
7120            } else {
7121                result.bestDomainVerificationStatus = bestDomainVerificationStatus(status,
7122                        result.bestDomainVerificationStatus);
7123            }
7124        }
7125        // Don't consider matches with status NEVER across profiles.
7126        if (result != null && result.bestDomainVerificationStatus
7127                == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
7128            return null;
7129        }
7130        return result;
7131    }
7132
7133    /**
7134     * Verification statuses are ordered from the worse to the best, except for
7135     * INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER, which is the worse.
7136     */
7137    private int bestDomainVerificationStatus(int status1, int status2) {
7138        if (status1 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
7139            return status2;
7140        }
7141        if (status2 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
7142            return status1;
7143        }
7144        return (int) MathUtils.max(status1, status2);
7145    }
7146
7147    private boolean isUserEnabled(int userId) {
7148        long callingId = Binder.clearCallingIdentity();
7149        try {
7150            UserInfo userInfo = sUserManager.getUserInfo(userId);
7151            return userInfo != null && userInfo.isEnabled();
7152        } finally {
7153            Binder.restoreCallingIdentity(callingId);
7154        }
7155    }
7156
7157    /**
7158     * Filter out activities with systemUserOnly flag set, when current user is not System.
7159     *
7160     * @return filtered list
7161     */
7162    private List<ResolveInfo> filterIfNotSystemUser(List<ResolveInfo> resolveInfos, int userId) {
7163        if (userId == UserHandle.USER_SYSTEM) {
7164            return resolveInfos;
7165        }
7166        for (int i = resolveInfos.size() - 1; i >= 0; i--) {
7167            ResolveInfo info = resolveInfos.get(i);
7168            if ((info.activityInfo.flags & ActivityInfo.FLAG_SYSTEM_USER_ONLY) != 0) {
7169                resolveInfos.remove(i);
7170            }
7171        }
7172        return resolveInfos;
7173    }
7174
7175    /**
7176     * Filters out ephemeral activities.
7177     * <p>When resolving for an ephemeral app, only activities that 1) are defined in the
7178     * ephemeral app or 2) marked with {@code visibleToEphemeral} are returned.
7179     *
7180     * @param resolveInfos The pre-filtered list of resolved activities
7181     * @param ephemeralPkgName The ephemeral package name. If {@code null}, no filtering
7182     *          is performed.
7183     * @return A filtered list of resolved activities.
7184     */
7185    private List<ResolveInfo> applyPostResolutionFilter(List<ResolveInfo> resolveInfos,
7186            String ephemeralPkgName) {
7187        // TODO: When adding on-demand split support for non-instant apps, remove this check
7188        // and always apply post filtering
7189        if (ephemeralPkgName == null) {
7190            return resolveInfos;
7191        }
7192        for (int i = resolveInfos.size() - 1; i >= 0; i--) {
7193            final ResolveInfo info = resolveInfos.get(i);
7194            final boolean isEphemeralApp = info.activityInfo.applicationInfo.isInstantApp();
7195            // allow activities that are defined in the provided package
7196            if (isEphemeralApp && ephemeralPkgName.equals(info.activityInfo.packageName)) {
7197                if (info.activityInfo.splitName != null
7198                        && !ArrayUtils.contains(info.activityInfo.applicationInfo.splitNames,
7199                                info.activityInfo.splitName)) {
7200                    // requested activity is defined in a split that hasn't been installed yet.
7201                    // add the installer to the resolve list
7202                    if (DEBUG_EPHEMERAL) {
7203                        Slog.v(TAG, "Adding ephemeral installer to the ResolveInfo list");
7204                    }
7205                    final ResolveInfo installerInfo = new ResolveInfo(mInstantAppInstallerInfo);
7206                    installerInfo.auxiliaryInfo = new AuxiliaryResolveInfo(
7207                            info.activityInfo.packageName, info.activityInfo.splitName,
7208                            info.activityInfo.applicationInfo.versionCode, null /*failureIntent*/);
7209                    // make sure this resolver is the default
7210                    installerInfo.isDefault = true;
7211                    installerInfo.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART
7212                            | IntentFilter.MATCH_ADJUSTMENT_NORMAL;
7213                    // add a non-generic filter
7214                    installerInfo.filter = new IntentFilter();
7215                    // load resources from the correct package
7216                    installerInfo.resolvePackageName = info.getComponentInfo().packageName;
7217                    resolveInfos.set(i, installerInfo);
7218                }
7219                continue;
7220            }
7221            // allow activities that have been explicitly exposed to ephemeral apps
7222            if (!isEphemeralApp
7223                    && ((info.activityInfo.flags & ActivityInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0)) {
7224                continue;
7225            }
7226            resolveInfos.remove(i);
7227        }
7228        return resolveInfos;
7229    }
7230
7231    /**
7232     * @param resolveInfos list of resolve infos in descending priority order
7233     * @return if the list contains a resolve info with non-negative priority
7234     */
7235    private boolean hasNonNegativePriority(List<ResolveInfo> resolveInfos) {
7236        return resolveInfos.size() > 0 && resolveInfos.get(0).priority >= 0;
7237    }
7238
7239    private static boolean hasWebURI(Intent intent) {
7240        if (intent.getData() == null) {
7241            return false;
7242        }
7243        final String scheme = intent.getScheme();
7244        if (TextUtils.isEmpty(scheme)) {
7245            return false;
7246        }
7247        return scheme.equals(IntentFilter.SCHEME_HTTP) || scheme.equals(IntentFilter.SCHEME_HTTPS);
7248    }
7249
7250    private List<ResolveInfo> filterCandidatesWithDomainPreferredActivitiesLPr(Intent intent,
7251            int matchFlags, List<ResolveInfo> candidates, CrossProfileDomainInfo xpDomainInfo,
7252            int userId) {
7253        final boolean debug = (intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0;
7254
7255        if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) {
7256            Slog.v(TAG, "Filtering results with preferred activities. Candidates count: " +
7257                    candidates.size());
7258        }
7259
7260        ArrayList<ResolveInfo> result = new ArrayList<ResolveInfo>();
7261        ArrayList<ResolveInfo> alwaysList = new ArrayList<ResolveInfo>();
7262        ArrayList<ResolveInfo> undefinedList = new ArrayList<ResolveInfo>();
7263        ArrayList<ResolveInfo> alwaysAskList = new ArrayList<ResolveInfo>();
7264        ArrayList<ResolveInfo> neverList = new ArrayList<ResolveInfo>();
7265        ArrayList<ResolveInfo> matchAllList = new ArrayList<ResolveInfo>();
7266
7267        synchronized (mPackages) {
7268            final int count = candidates.size();
7269            // First, try to use linked apps. Partition the candidates into four lists:
7270            // one for the final results, one for the "do not use ever", one for "undefined status"
7271            // and finally one for "browser app type".
7272            for (int n=0; n<count; n++) {
7273                ResolveInfo info = candidates.get(n);
7274                String packageName = info.activityInfo.packageName;
7275                PackageSetting ps = mSettings.mPackages.get(packageName);
7276                if (ps != null) {
7277                    // Add to the special match all list (Browser use case)
7278                    if (info.handleAllWebDataURI) {
7279                        matchAllList.add(info);
7280                        continue;
7281                    }
7282                    // Try to get the status from User settings first
7283                    long packedStatus = getDomainVerificationStatusLPr(ps, userId);
7284                    int status = (int)(packedStatus >> 32);
7285                    int linkGeneration = (int)(packedStatus & 0xFFFFFFFF);
7286                    if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS) {
7287                        if (DEBUG_DOMAIN_VERIFICATION || debug) {
7288                            Slog.i(TAG, "  + always: " + info.activityInfo.packageName
7289                                    + " : linkgen=" + linkGeneration);
7290                        }
7291                        // Use link-enabled generation as preferredOrder, i.e.
7292                        // prefer newly-enabled over earlier-enabled.
7293                        info.preferredOrder = linkGeneration;
7294                        alwaysList.add(info);
7295                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
7296                        if (DEBUG_DOMAIN_VERIFICATION || debug) {
7297                            Slog.i(TAG, "  + never: " + info.activityInfo.packageName);
7298                        }
7299                        neverList.add(info);
7300                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) {
7301                        if (DEBUG_DOMAIN_VERIFICATION || debug) {
7302                            Slog.i(TAG, "  + always-ask: " + info.activityInfo.packageName);
7303                        }
7304                        alwaysAskList.add(info);
7305                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED ||
7306                            status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK) {
7307                        if (DEBUG_DOMAIN_VERIFICATION || debug) {
7308                            Slog.i(TAG, "  + ask: " + info.activityInfo.packageName);
7309                        }
7310                        undefinedList.add(info);
7311                    }
7312                }
7313            }
7314
7315            // We'll want to include browser possibilities in a few cases
7316            boolean includeBrowser = false;
7317
7318            // First try to add the "always" resolution(s) for the current user, if any
7319            if (alwaysList.size() > 0) {
7320                result.addAll(alwaysList);
7321            } else {
7322                // Add all undefined apps as we want them to appear in the disambiguation dialog.
7323                result.addAll(undefinedList);
7324                // Maybe add one for the other profile.
7325                if (xpDomainInfo != null && (
7326                        xpDomainInfo.bestDomainVerificationStatus
7327                        != INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER)) {
7328                    result.add(xpDomainInfo.resolveInfo);
7329                }
7330                includeBrowser = true;
7331            }
7332
7333            // The presence of any 'always ask' alternatives means we'll also offer browsers.
7334            // If there were 'always' entries their preferred order has been set, so we also
7335            // back that off to make the alternatives equivalent
7336            if (alwaysAskList.size() > 0) {
7337                for (ResolveInfo i : result) {
7338                    i.preferredOrder = 0;
7339                }
7340                result.addAll(alwaysAskList);
7341                includeBrowser = true;
7342            }
7343
7344            if (includeBrowser) {
7345                // Also add browsers (all of them or only the default one)
7346                if (DEBUG_DOMAIN_VERIFICATION) {
7347                    Slog.v(TAG, "   ...including browsers in candidate set");
7348                }
7349                if ((matchFlags & MATCH_ALL) != 0) {
7350                    result.addAll(matchAllList);
7351                } else {
7352                    // Browser/generic handling case.  If there's a default browser, go straight
7353                    // to that (but only if there is no other higher-priority match).
7354                    final String defaultBrowserPackageName = getDefaultBrowserPackageName(userId);
7355                    int maxMatchPrio = 0;
7356                    ResolveInfo defaultBrowserMatch = null;
7357                    final int numCandidates = matchAllList.size();
7358                    for (int n = 0; n < numCandidates; n++) {
7359                        ResolveInfo info = matchAllList.get(n);
7360                        // track the highest overall match priority...
7361                        if (info.priority > maxMatchPrio) {
7362                            maxMatchPrio = info.priority;
7363                        }
7364                        // ...and the highest-priority default browser match
7365                        if (info.activityInfo.packageName.equals(defaultBrowserPackageName)) {
7366                            if (defaultBrowserMatch == null
7367                                    || (defaultBrowserMatch.priority < info.priority)) {
7368                                if (debug) {
7369                                    Slog.v(TAG, "Considering default browser match " + info);
7370                                }
7371                                defaultBrowserMatch = info;
7372                            }
7373                        }
7374                    }
7375                    if (defaultBrowserMatch != null
7376                            && defaultBrowserMatch.priority >= maxMatchPrio
7377                            && !TextUtils.isEmpty(defaultBrowserPackageName))
7378                    {
7379                        if (debug) {
7380                            Slog.v(TAG, "Default browser match " + defaultBrowserMatch);
7381                        }
7382                        result.add(defaultBrowserMatch);
7383                    } else {
7384                        result.addAll(matchAllList);
7385                    }
7386                }
7387
7388                // If there is nothing selected, add all candidates and remove the ones that the user
7389                // has explicitly put into the INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER state
7390                if (result.size() == 0) {
7391                    result.addAll(candidates);
7392                    result.removeAll(neverList);
7393                }
7394            }
7395        }
7396        if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) {
7397            Slog.v(TAG, "Filtered results with preferred activities. New candidates count: " +
7398                    result.size());
7399            for (ResolveInfo info : result) {
7400                Slog.v(TAG, "  + " + info.activityInfo);
7401            }
7402        }
7403        return result;
7404    }
7405
7406    // Returns a packed value as a long:
7407    //
7408    // high 'int'-sized word: link status: undefined/ask/never/always.
7409    // low 'int'-sized word: relative priority among 'always' results.
7410    private long getDomainVerificationStatusLPr(PackageSetting ps, int userId) {
7411        long result = ps.getDomainVerificationStatusForUser(userId);
7412        // if none available, get the master status
7413        if (result >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) {
7414            if (ps.getIntentFilterVerificationInfo() != null) {
7415                result = ((long)ps.getIntentFilterVerificationInfo().getStatus()) << 32;
7416            }
7417        }
7418        return result;
7419    }
7420
7421    private ResolveInfo querySkipCurrentProfileIntents(
7422            List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType,
7423            int flags, int sourceUserId) {
7424        if (matchingFilters != null) {
7425            int size = matchingFilters.size();
7426            for (int i = 0; i < size; i ++) {
7427                CrossProfileIntentFilter filter = matchingFilters.get(i);
7428                if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0) {
7429                    // Checking if there are activities in the target user that can handle the
7430                    // intent.
7431                    ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent,
7432                            resolvedType, flags, sourceUserId);
7433                    if (resolveInfo != null) {
7434                        return resolveInfo;
7435                    }
7436                }
7437            }
7438        }
7439        return null;
7440    }
7441
7442    // Return matching ResolveInfo in target user if any.
7443    private ResolveInfo queryCrossProfileIntents(
7444            List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType,
7445            int flags, int sourceUserId, boolean matchInCurrentProfile) {
7446        if (matchingFilters != null) {
7447            // Two {@link CrossProfileIntentFilter}s can have the same targetUserId and
7448            // match the same intent. For performance reasons, it is better not to
7449            // run queryIntent twice for the same userId
7450            SparseBooleanArray alreadyTriedUserIds = new SparseBooleanArray();
7451            int size = matchingFilters.size();
7452            for (int i = 0; i < size; i++) {
7453                CrossProfileIntentFilter filter = matchingFilters.get(i);
7454                int targetUserId = filter.getTargetUserId();
7455                boolean skipCurrentProfile =
7456                        (filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0;
7457                boolean skipCurrentProfileIfNoMatchFound =
7458                        (filter.getFlags() & PackageManager.ONLY_IF_NO_MATCH_FOUND) != 0;
7459                if (!skipCurrentProfile && !alreadyTriedUserIds.get(targetUserId)
7460                        && (!skipCurrentProfileIfNoMatchFound || !matchInCurrentProfile)) {
7461                    // Checking if there are activities in the target user that can handle the
7462                    // intent.
7463                    ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent,
7464                            resolvedType, flags, sourceUserId);
7465                    if (resolveInfo != null) return resolveInfo;
7466                    alreadyTriedUserIds.put(targetUserId, true);
7467                }
7468            }
7469        }
7470        return null;
7471    }
7472
7473    /**
7474     * If the filter's target user can handle the intent and is enabled: returns a ResolveInfo that
7475     * will forward the intent to the filter's target user.
7476     * Otherwise, returns null.
7477     */
7478    private ResolveInfo createForwardingResolveInfo(CrossProfileIntentFilter filter, Intent intent,
7479            String resolvedType, int flags, int sourceUserId) {
7480        int targetUserId = filter.getTargetUserId();
7481        List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent,
7482                resolvedType, flags, targetUserId);
7483        if (resultTargetUser != null && isUserEnabled(targetUserId)) {
7484            // If all the matches in the target profile are suspended, return null.
7485            for (int i = resultTargetUser.size() - 1; i >= 0; i--) {
7486                if ((resultTargetUser.get(i).activityInfo.applicationInfo.flags
7487                        & ApplicationInfo.FLAG_SUSPENDED) == 0) {
7488                    return createForwardingResolveInfoUnchecked(filter, sourceUserId,
7489                            targetUserId);
7490                }
7491            }
7492        }
7493        return null;
7494    }
7495
7496    private ResolveInfo createForwardingResolveInfoUnchecked(IntentFilter filter,
7497            int sourceUserId, int targetUserId) {
7498        ResolveInfo forwardingResolveInfo = new ResolveInfo();
7499        long ident = Binder.clearCallingIdentity();
7500        boolean targetIsProfile;
7501        try {
7502            targetIsProfile = sUserManager.getUserInfo(targetUserId).isManagedProfile();
7503        } finally {
7504            Binder.restoreCallingIdentity(ident);
7505        }
7506        String className;
7507        if (targetIsProfile) {
7508            className = FORWARD_INTENT_TO_MANAGED_PROFILE;
7509        } else {
7510            className = FORWARD_INTENT_TO_PARENT;
7511        }
7512        ComponentName forwardingActivityComponentName = new ComponentName(
7513                mAndroidApplication.packageName, className);
7514        ActivityInfo forwardingActivityInfo = getActivityInfo(forwardingActivityComponentName, 0,
7515                sourceUserId);
7516        if (!targetIsProfile) {
7517            forwardingActivityInfo.showUserIcon = targetUserId;
7518            forwardingResolveInfo.noResourceId = true;
7519        }
7520        forwardingResolveInfo.activityInfo = forwardingActivityInfo;
7521        forwardingResolveInfo.priority = 0;
7522        forwardingResolveInfo.preferredOrder = 0;
7523        forwardingResolveInfo.match = 0;
7524        forwardingResolveInfo.isDefault = true;
7525        forwardingResolveInfo.filter = filter;
7526        forwardingResolveInfo.targetUserId = targetUserId;
7527        return forwardingResolveInfo;
7528    }
7529
7530    @Override
7531    public @NonNull ParceledListSlice<ResolveInfo> queryIntentActivityOptions(ComponentName caller,
7532            Intent[] specifics, String[] specificTypes, Intent intent,
7533            String resolvedType, int flags, int userId) {
7534        return new ParceledListSlice<>(queryIntentActivityOptionsInternal(caller, specifics,
7535                specificTypes, intent, resolvedType, flags, userId));
7536    }
7537
7538    private @NonNull List<ResolveInfo> queryIntentActivityOptionsInternal(ComponentName caller,
7539            Intent[] specifics, String[] specificTypes, Intent intent,
7540            String resolvedType, int flags, int userId) {
7541        if (!sUserManager.exists(userId)) return Collections.emptyList();
7542        final int callingUid = Binder.getCallingUid();
7543        flags = updateFlagsForResolve(flags, userId, intent, callingUid,
7544                false /*includeInstantApps*/);
7545        enforceCrossUserPermission(callingUid, userId,
7546                false /*requireFullPermission*/, false /*checkShell*/,
7547                "query intent activity options");
7548        final String resultsAction = intent.getAction();
7549
7550        final List<ResolveInfo> results = queryIntentActivitiesInternal(intent, resolvedType, flags
7551                | PackageManager.GET_RESOLVED_FILTER, userId);
7552
7553        if (DEBUG_INTENT_MATCHING) {
7554            Log.v(TAG, "Query " + intent + ": " + results);
7555        }
7556
7557        int specificsPos = 0;
7558        int N;
7559
7560        // todo: note that the algorithm used here is O(N^2).  This
7561        // isn't a problem in our current environment, but if we start running
7562        // into situations where we have more than 5 or 10 matches then this
7563        // should probably be changed to something smarter...
7564
7565        // First we go through and resolve each of the specific items
7566        // that were supplied, taking care of removing any corresponding
7567        // duplicate items in the generic resolve list.
7568        if (specifics != null) {
7569            for (int i=0; i<specifics.length; i++) {
7570                final Intent sintent = specifics[i];
7571                if (sintent == null) {
7572                    continue;
7573                }
7574
7575                if (DEBUG_INTENT_MATCHING) {
7576                    Log.v(TAG, "Specific #" + i + ": " + sintent);
7577                }
7578
7579                String action = sintent.getAction();
7580                if (resultsAction != null && resultsAction.equals(action)) {
7581                    // If this action was explicitly requested, then don't
7582                    // remove things that have it.
7583                    action = null;
7584                }
7585
7586                ResolveInfo ri = null;
7587                ActivityInfo ai = null;
7588
7589                ComponentName comp = sintent.getComponent();
7590                if (comp == null) {
7591                    ri = resolveIntent(
7592                        sintent,
7593                        specificTypes != null ? specificTypes[i] : null,
7594                            flags, userId);
7595                    if (ri == null) {
7596                        continue;
7597                    }
7598                    if (ri == mResolveInfo) {
7599                        // ACK!  Must do something better with this.
7600                    }
7601                    ai = ri.activityInfo;
7602                    comp = new ComponentName(ai.applicationInfo.packageName,
7603                            ai.name);
7604                } else {
7605                    ai = getActivityInfo(comp, flags, userId);
7606                    if (ai == null) {
7607                        continue;
7608                    }
7609                }
7610
7611                // Look for any generic query activities that are duplicates
7612                // of this specific one, and remove them from the results.
7613                if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Specific #" + i + ": " + ai);
7614                N = results.size();
7615                int j;
7616                for (j=specificsPos; j<N; j++) {
7617                    ResolveInfo sri = results.get(j);
7618                    if ((sri.activityInfo.name.equals(comp.getClassName())
7619                            && sri.activityInfo.applicationInfo.packageName.equals(
7620                                    comp.getPackageName()))
7621                        || (action != null && sri.filter.matchAction(action))) {
7622                        results.remove(j);
7623                        if (DEBUG_INTENT_MATCHING) Log.v(
7624                            TAG, "Removing duplicate item from " + j
7625                            + " due to specific " + specificsPos);
7626                        if (ri == null) {
7627                            ri = sri;
7628                        }
7629                        j--;
7630                        N--;
7631                    }
7632                }
7633
7634                // Add this specific item to its proper place.
7635                if (ri == null) {
7636                    ri = new ResolveInfo();
7637                    ri.activityInfo = ai;
7638                }
7639                results.add(specificsPos, ri);
7640                ri.specificIndex = i;
7641                specificsPos++;
7642            }
7643        }
7644
7645        // Now we go through the remaining generic results and remove any
7646        // duplicate actions that are found here.
7647        N = results.size();
7648        for (int i=specificsPos; i<N-1; i++) {
7649            final ResolveInfo rii = results.get(i);
7650            if (rii.filter == null) {
7651                continue;
7652            }
7653
7654            // Iterate over all of the actions of this result's intent
7655            // filter...  typically this should be just one.
7656            final Iterator<String> it = rii.filter.actionsIterator();
7657            if (it == null) {
7658                continue;
7659            }
7660            while (it.hasNext()) {
7661                final String action = it.next();
7662                if (resultsAction != null && resultsAction.equals(action)) {
7663                    // If this action was explicitly requested, then don't
7664                    // remove things that have it.
7665                    continue;
7666                }
7667                for (int j=i+1; j<N; j++) {
7668                    final ResolveInfo rij = results.get(j);
7669                    if (rij.filter != null && rij.filter.hasAction(action)) {
7670                        results.remove(j);
7671                        if (DEBUG_INTENT_MATCHING) Log.v(
7672                            TAG, "Removing duplicate item from " + j
7673                            + " due to action " + action + " at " + i);
7674                        j--;
7675                        N--;
7676                    }
7677                }
7678            }
7679
7680            // If the caller didn't request filter information, drop it now
7681            // so we don't have to marshall/unmarshall it.
7682            if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
7683                rii.filter = null;
7684            }
7685        }
7686
7687        // Filter out the caller activity if so requested.
7688        if (caller != null) {
7689            N = results.size();
7690            for (int i=0; i<N; i++) {
7691                ActivityInfo ainfo = results.get(i).activityInfo;
7692                if (caller.getPackageName().equals(ainfo.applicationInfo.packageName)
7693                        && caller.getClassName().equals(ainfo.name)) {
7694                    results.remove(i);
7695                    break;
7696                }
7697            }
7698        }
7699
7700        // If the caller didn't request filter information,
7701        // drop them now so we don't have to
7702        // marshall/unmarshall it.
7703        if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
7704            N = results.size();
7705            for (int i=0; i<N; i++) {
7706                results.get(i).filter = null;
7707            }
7708        }
7709
7710        if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Result: " + results);
7711        return results;
7712    }
7713
7714    @Override
7715    public @NonNull ParceledListSlice<ResolveInfo> queryIntentReceivers(Intent intent,
7716            String resolvedType, int flags, int userId) {
7717        return new ParceledListSlice<>(
7718                queryIntentReceiversInternal(intent, resolvedType, flags, userId));
7719    }
7720
7721    private @NonNull List<ResolveInfo> queryIntentReceiversInternal(Intent intent,
7722            String resolvedType, int flags, int userId) {
7723        if (!sUserManager.exists(userId)) return Collections.emptyList();
7724        final int callingUid = Binder.getCallingUid();
7725        final String instantAppPkgName = getInstantAppPackageName(callingUid);
7726        flags = updateFlagsForResolve(flags, userId, intent, callingUid,
7727                false /*includeInstantApps*/);
7728        ComponentName comp = intent.getComponent();
7729        if (comp == null) {
7730            if (intent.getSelector() != null) {
7731                intent = intent.getSelector();
7732                comp = intent.getComponent();
7733            }
7734        }
7735        if (comp != null) {
7736            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
7737            final ActivityInfo ai = getReceiverInfo(comp, flags, userId);
7738            if (ai != null) {
7739                // When specifying an explicit component, we prevent the activity from being
7740                // used when either 1) the calling package is normal and the activity is within
7741                // an instant application or 2) the calling package is ephemeral and the
7742                // activity is not visible to instant applications.
7743                final boolean matchInstantApp =
7744                        (flags & PackageManager.MATCH_INSTANT) != 0;
7745                final boolean matchVisibleToInstantAppOnly =
7746                        (flags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
7747                final boolean matchExplicitlyVisibleOnly =
7748                        (flags & PackageManager.MATCH_EXPLICITLY_VISIBLE_ONLY) != 0;
7749                final boolean isCallerInstantApp =
7750                        instantAppPkgName != null;
7751                final boolean isTargetSameInstantApp =
7752                        comp.getPackageName().equals(instantAppPkgName);
7753                final boolean isTargetInstantApp =
7754                        (ai.applicationInfo.privateFlags
7755                                & ApplicationInfo.PRIVATE_FLAG_INSTANT) != 0;
7756                final boolean isTargetVisibleToInstantApp =
7757                        (ai.flags & ActivityInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0;
7758                final boolean isTargetExplicitlyVisibleToInstantApp =
7759                        isTargetVisibleToInstantApp
7760                        && (ai.flags & ActivityInfo.FLAG_IMPLICITLY_VISIBLE_TO_INSTANT_APP) == 0;
7761                final boolean isTargetHiddenFromInstantApp =
7762                        !isTargetVisibleToInstantApp
7763                        || (matchExplicitlyVisibleOnly && !isTargetExplicitlyVisibleToInstantApp);
7764                final boolean blockResolution =
7765                        !isTargetSameInstantApp
7766                        && ((!matchInstantApp && !isCallerInstantApp && isTargetInstantApp)
7767                                || (matchVisibleToInstantAppOnly && isCallerInstantApp
7768                                        && isTargetHiddenFromInstantApp));
7769                if (!blockResolution) {
7770                    ResolveInfo ri = new ResolveInfo();
7771                    ri.activityInfo = ai;
7772                    list.add(ri);
7773                }
7774            }
7775            return applyPostResolutionFilter(list, instantAppPkgName);
7776        }
7777
7778        // reader
7779        synchronized (mPackages) {
7780            String pkgName = intent.getPackage();
7781            if (pkgName == null) {
7782                final List<ResolveInfo> result =
7783                        mReceivers.queryIntent(intent, resolvedType, flags, userId);
7784                return applyPostResolutionFilter(result, instantAppPkgName);
7785            }
7786            final PackageParser.Package pkg = mPackages.get(pkgName);
7787            if (pkg != null) {
7788                final List<ResolveInfo> result = mReceivers.queryIntentForPackage(
7789                        intent, resolvedType, flags, pkg.receivers, userId);
7790                return applyPostResolutionFilter(result, instantAppPkgName);
7791            }
7792            return Collections.emptyList();
7793        }
7794    }
7795
7796    @Override
7797    public ResolveInfo resolveService(Intent intent, String resolvedType, int flags, int userId) {
7798        final int callingUid = Binder.getCallingUid();
7799        return resolveServiceInternal(intent, resolvedType, flags, userId, callingUid);
7800    }
7801
7802    private ResolveInfo resolveServiceInternal(Intent intent, String resolvedType, int flags,
7803            int userId, int callingUid) {
7804        if (!sUserManager.exists(userId)) return null;
7805        flags = updateFlagsForResolve(
7806                flags, userId, intent, callingUid, false /*includeInstantApps*/);
7807        List<ResolveInfo> query = queryIntentServicesInternal(
7808                intent, resolvedType, flags, userId, callingUid, false /*includeInstantApps*/);
7809        if (query != null) {
7810            if (query.size() >= 1) {
7811                // If there is more than one service with the same priority,
7812                // just arbitrarily pick the first one.
7813                return query.get(0);
7814            }
7815        }
7816        return null;
7817    }
7818
7819    @Override
7820    public @NonNull ParceledListSlice<ResolveInfo> queryIntentServices(Intent intent,
7821            String resolvedType, int flags, int userId) {
7822        final int callingUid = Binder.getCallingUid();
7823        return new ParceledListSlice<>(queryIntentServicesInternal(
7824                intent, resolvedType, flags, userId, callingUid, false /*includeInstantApps*/));
7825    }
7826
7827    private @NonNull List<ResolveInfo> queryIntentServicesInternal(Intent intent,
7828            String resolvedType, int flags, int userId, int callingUid,
7829            boolean includeInstantApps) {
7830        if (!sUserManager.exists(userId)) return Collections.emptyList();
7831        final String instantAppPkgName = getInstantAppPackageName(callingUid);
7832        flags = updateFlagsForResolve(flags, userId, intent, callingUid, includeInstantApps);
7833        ComponentName comp = intent.getComponent();
7834        if (comp == null) {
7835            if (intent.getSelector() != null) {
7836                intent = intent.getSelector();
7837                comp = intent.getComponent();
7838            }
7839        }
7840        if (comp != null) {
7841            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
7842            final ServiceInfo si = getServiceInfo(comp, flags, userId);
7843            if (si != null) {
7844                // When specifying an explicit component, we prevent the service from being
7845                // used when either 1) the service is in an instant application and the
7846                // caller is not the same instant application or 2) the calling package is
7847                // ephemeral and the activity is not visible to ephemeral applications.
7848                final boolean matchInstantApp =
7849                        (flags & PackageManager.MATCH_INSTANT) != 0;
7850                final boolean matchVisibleToInstantAppOnly =
7851                        (flags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
7852                final boolean isCallerInstantApp =
7853                        instantAppPkgName != null;
7854                final boolean isTargetSameInstantApp =
7855                        comp.getPackageName().equals(instantAppPkgName);
7856                final boolean isTargetInstantApp =
7857                        (si.applicationInfo.privateFlags
7858                                & ApplicationInfo.PRIVATE_FLAG_INSTANT) != 0;
7859                final boolean isTargetHiddenFromInstantApp =
7860                        (si.flags & ServiceInfo.FLAG_VISIBLE_TO_INSTANT_APP) == 0;
7861                final boolean blockResolution =
7862                        !isTargetSameInstantApp
7863                        && ((!matchInstantApp && !isCallerInstantApp && isTargetInstantApp)
7864                                || (matchVisibleToInstantAppOnly && isCallerInstantApp
7865                                        && isTargetHiddenFromInstantApp));
7866                if (!blockResolution) {
7867                    final ResolveInfo ri = new ResolveInfo();
7868                    ri.serviceInfo = si;
7869                    list.add(ri);
7870                }
7871            }
7872            return list;
7873        }
7874
7875        // reader
7876        synchronized (mPackages) {
7877            String pkgName = intent.getPackage();
7878            if (pkgName == null) {
7879                return applyPostServiceResolutionFilter(
7880                        mServices.queryIntent(intent, resolvedType, flags, userId),
7881                        instantAppPkgName);
7882            }
7883            final PackageParser.Package pkg = mPackages.get(pkgName);
7884            if (pkg != null) {
7885                return applyPostServiceResolutionFilter(
7886                        mServices.queryIntentForPackage(intent, resolvedType, flags, pkg.services,
7887                                userId),
7888                        instantAppPkgName);
7889            }
7890            return Collections.emptyList();
7891        }
7892    }
7893
7894    private List<ResolveInfo> applyPostServiceResolutionFilter(List<ResolveInfo> resolveInfos,
7895            String instantAppPkgName) {
7896        // TODO: When adding on-demand split support for non-instant apps, remove this check
7897        // and always apply post filtering
7898        if (instantAppPkgName == null) {
7899            return resolveInfos;
7900        }
7901        for (int i = resolveInfos.size() - 1; i >= 0; i--) {
7902            final ResolveInfo info = resolveInfos.get(i);
7903            final boolean isEphemeralApp = info.serviceInfo.applicationInfo.isInstantApp();
7904            // allow services that are defined in the provided package
7905            if (isEphemeralApp && instantAppPkgName.equals(info.serviceInfo.packageName)) {
7906                if (info.serviceInfo.splitName != null
7907                        && !ArrayUtils.contains(info.serviceInfo.applicationInfo.splitNames,
7908                                info.serviceInfo.splitName)) {
7909                    // requested service is defined in a split that hasn't been installed yet.
7910                    // add the installer to the resolve list
7911                    if (DEBUG_EPHEMERAL) {
7912                        Slog.v(TAG, "Adding ephemeral installer to the ResolveInfo list");
7913                    }
7914                    final ResolveInfo installerInfo = new ResolveInfo(mInstantAppInstallerInfo);
7915                    installerInfo.auxiliaryInfo = new AuxiliaryResolveInfo(
7916                            info.serviceInfo.packageName, info.serviceInfo.splitName,
7917                            info.serviceInfo.applicationInfo.versionCode, null /*failureIntent*/);
7918                    // make sure this resolver is the default
7919                    installerInfo.isDefault = true;
7920                    installerInfo.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART
7921                            | IntentFilter.MATCH_ADJUSTMENT_NORMAL;
7922                    // add a non-generic filter
7923                    installerInfo.filter = new IntentFilter();
7924                    // load resources from the correct package
7925                    installerInfo.resolvePackageName = info.getComponentInfo().packageName;
7926                    resolveInfos.set(i, installerInfo);
7927                }
7928                continue;
7929            }
7930            // allow services that have been explicitly exposed to ephemeral apps
7931            if (!isEphemeralApp
7932                    && ((info.serviceInfo.flags & ServiceInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0)) {
7933                continue;
7934            }
7935            resolveInfos.remove(i);
7936        }
7937        return resolveInfos;
7938    }
7939
7940    @Override
7941    public @NonNull ParceledListSlice<ResolveInfo> queryIntentContentProviders(Intent intent,
7942            String resolvedType, int flags, int userId) {
7943        return new ParceledListSlice<>(
7944                queryIntentContentProvidersInternal(intent, resolvedType, flags, userId));
7945    }
7946
7947    private @NonNull List<ResolveInfo> queryIntentContentProvidersInternal(
7948            Intent intent, String resolvedType, int flags, int userId) {
7949        if (!sUserManager.exists(userId)) return Collections.emptyList();
7950        final int callingUid = Binder.getCallingUid();
7951        final String instantAppPkgName = getInstantAppPackageName(callingUid);
7952        flags = updateFlagsForResolve(flags, userId, intent, callingUid,
7953                false /*includeInstantApps*/);
7954        ComponentName comp = intent.getComponent();
7955        if (comp == null) {
7956            if (intent.getSelector() != null) {
7957                intent = intent.getSelector();
7958                comp = intent.getComponent();
7959            }
7960        }
7961        if (comp != null) {
7962            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
7963            final ProviderInfo pi = getProviderInfo(comp, flags, userId);
7964            if (pi != null) {
7965                // When specifying an explicit component, we prevent the provider from being
7966                // used when either 1) the provider is in an instant application and the
7967                // caller is not the same instant application or 2) the calling package is an
7968                // instant application and the provider is not visible to instant applications.
7969                final boolean matchInstantApp =
7970                        (flags & PackageManager.MATCH_INSTANT) != 0;
7971                final boolean matchVisibleToInstantAppOnly =
7972                        (flags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
7973                final boolean isCallerInstantApp =
7974                        instantAppPkgName != null;
7975                final boolean isTargetSameInstantApp =
7976                        comp.getPackageName().equals(instantAppPkgName);
7977                final boolean isTargetInstantApp =
7978                        (pi.applicationInfo.privateFlags
7979                                & ApplicationInfo.PRIVATE_FLAG_INSTANT) != 0;
7980                final boolean isTargetHiddenFromInstantApp =
7981                        (pi.flags & ProviderInfo.FLAG_VISIBLE_TO_INSTANT_APP) == 0;
7982                final boolean blockResolution =
7983                        !isTargetSameInstantApp
7984                        && ((!matchInstantApp && !isCallerInstantApp && isTargetInstantApp)
7985                                || (matchVisibleToInstantAppOnly && isCallerInstantApp
7986                                        && isTargetHiddenFromInstantApp));
7987                if (!blockResolution) {
7988                    final ResolveInfo ri = new ResolveInfo();
7989                    ri.providerInfo = pi;
7990                    list.add(ri);
7991                }
7992            }
7993            return list;
7994        }
7995
7996        // reader
7997        synchronized (mPackages) {
7998            String pkgName = intent.getPackage();
7999            if (pkgName == null) {
8000                return applyPostContentProviderResolutionFilter(
8001                        mProviders.queryIntent(intent, resolvedType, flags, userId),
8002                        instantAppPkgName);
8003            }
8004            final PackageParser.Package pkg = mPackages.get(pkgName);
8005            if (pkg != null) {
8006                return applyPostContentProviderResolutionFilter(
8007                        mProviders.queryIntentForPackage(
8008                        intent, resolvedType, flags, pkg.providers, userId),
8009                        instantAppPkgName);
8010            }
8011            return Collections.emptyList();
8012        }
8013    }
8014
8015    private List<ResolveInfo> applyPostContentProviderResolutionFilter(
8016            List<ResolveInfo> resolveInfos, String instantAppPkgName) {
8017        // TODO: When adding on-demand split support for non-instant applications, remove
8018        // this check and always apply post filtering
8019        if (instantAppPkgName == null) {
8020            return resolveInfos;
8021        }
8022        for (int i = resolveInfos.size() - 1; i >= 0; i--) {
8023            final ResolveInfo info = resolveInfos.get(i);
8024            final boolean isEphemeralApp = info.providerInfo.applicationInfo.isInstantApp();
8025            // allow providers that are defined in the provided package
8026            if (isEphemeralApp && instantAppPkgName.equals(info.providerInfo.packageName)) {
8027                if (info.providerInfo.splitName != null
8028                        && !ArrayUtils.contains(info.providerInfo.applicationInfo.splitNames,
8029                                info.providerInfo.splitName)) {
8030                    // requested provider is defined in a split that hasn't been installed yet.
8031                    // add the installer to the resolve list
8032                    if (DEBUG_EPHEMERAL) {
8033                        Slog.v(TAG, "Adding ephemeral installer to the ResolveInfo list");
8034                    }
8035                    final ResolveInfo installerInfo = new ResolveInfo(mInstantAppInstallerInfo);
8036                    installerInfo.auxiliaryInfo = new AuxiliaryResolveInfo(
8037                            info.providerInfo.packageName, info.providerInfo.splitName,
8038                            info.providerInfo.applicationInfo.versionCode, null /*failureIntent*/);
8039                    // make sure this resolver is the default
8040                    installerInfo.isDefault = true;
8041                    installerInfo.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART
8042                            | IntentFilter.MATCH_ADJUSTMENT_NORMAL;
8043                    // add a non-generic filter
8044                    installerInfo.filter = new IntentFilter();
8045                    // load resources from the correct package
8046                    installerInfo.resolvePackageName = info.getComponentInfo().packageName;
8047                    resolveInfos.set(i, installerInfo);
8048                }
8049                continue;
8050            }
8051            // allow providers that have been explicitly exposed to instant applications
8052            if (!isEphemeralApp
8053                    && ((info.providerInfo.flags & ProviderInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0)) {
8054                continue;
8055            }
8056            resolveInfos.remove(i);
8057        }
8058        return resolveInfos;
8059    }
8060
8061    @Override
8062    public ParceledListSlice<PackageInfo> getInstalledPackages(int flags, int userId) {
8063        final int callingUid = Binder.getCallingUid();
8064        if (getInstantAppPackageName(callingUid) != null) {
8065            return ParceledListSlice.emptyList();
8066        }
8067        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
8068        flags = updateFlagsForPackage(flags, userId, null);
8069        final boolean listUninstalled = (flags & MATCH_KNOWN_PACKAGES) != 0;
8070        enforceCrossUserPermission(callingUid, userId,
8071                true /* requireFullPermission */, false /* checkShell */,
8072                "get installed packages");
8073
8074        // writer
8075        synchronized (mPackages) {
8076            ArrayList<PackageInfo> list;
8077            if (listUninstalled) {
8078                list = new ArrayList<>(mSettings.mPackages.size());
8079                for (PackageSetting ps : mSettings.mPackages.values()) {
8080                    if (filterSharedLibPackageLPr(ps, callingUid, userId, flags)) {
8081                        continue;
8082                    }
8083                    if (filterAppAccessLPr(ps, callingUid, userId)) {
8084                        return null;
8085                    }
8086                    final PackageInfo pi = generatePackageInfo(ps, flags, userId);
8087                    if (pi != null) {
8088                        list.add(pi);
8089                    }
8090                }
8091            } else {
8092                list = new ArrayList<>(mPackages.size());
8093                for (PackageParser.Package p : mPackages.values()) {
8094                    final PackageSetting ps = (PackageSetting) p.mExtras;
8095                    if (filterSharedLibPackageLPr(ps, callingUid, userId, flags)) {
8096                        continue;
8097                    }
8098                    if (filterAppAccessLPr(ps, callingUid, userId)) {
8099                        return null;
8100                    }
8101                    final PackageInfo pi = generatePackageInfo((PackageSetting)
8102                            p.mExtras, flags, userId);
8103                    if (pi != null) {
8104                        list.add(pi);
8105                    }
8106                }
8107            }
8108
8109            return new ParceledListSlice<>(list);
8110        }
8111    }
8112
8113    private void addPackageHoldingPermissions(ArrayList<PackageInfo> list, PackageSetting ps,
8114            String[] permissions, boolean[] tmp, int flags, int userId) {
8115        int numMatch = 0;
8116        final PermissionsState permissionsState = ps.getPermissionsState();
8117        for (int i=0; i<permissions.length; i++) {
8118            final String permission = permissions[i];
8119            if (permissionsState.hasPermission(permission, userId)) {
8120                tmp[i] = true;
8121                numMatch++;
8122            } else {
8123                tmp[i] = false;
8124            }
8125        }
8126        if (numMatch == 0) {
8127            return;
8128        }
8129        final PackageInfo pi = generatePackageInfo(ps, flags, userId);
8130
8131        // The above might return null in cases of uninstalled apps or install-state
8132        // skew across users/profiles.
8133        if (pi != null) {
8134            if ((flags&PackageManager.GET_PERMISSIONS) == 0) {
8135                if (numMatch == permissions.length) {
8136                    pi.requestedPermissions = permissions;
8137                } else {
8138                    pi.requestedPermissions = new String[numMatch];
8139                    numMatch = 0;
8140                    for (int i=0; i<permissions.length; i++) {
8141                        if (tmp[i]) {
8142                            pi.requestedPermissions[numMatch] = permissions[i];
8143                            numMatch++;
8144                        }
8145                    }
8146                }
8147            }
8148            list.add(pi);
8149        }
8150    }
8151
8152    @Override
8153    public ParceledListSlice<PackageInfo> getPackagesHoldingPermissions(
8154            String[] permissions, int flags, int userId) {
8155        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
8156        flags = updateFlagsForPackage(flags, userId, permissions);
8157        enforceCrossUserPermission(Binder.getCallingUid(), userId,
8158                true /* requireFullPermission */, false /* checkShell */,
8159                "get packages holding permissions");
8160        final boolean listUninstalled = (flags & MATCH_KNOWN_PACKAGES) != 0;
8161
8162        // writer
8163        synchronized (mPackages) {
8164            ArrayList<PackageInfo> list = new ArrayList<PackageInfo>();
8165            boolean[] tmpBools = new boolean[permissions.length];
8166            if (listUninstalled) {
8167                for (PackageSetting ps : mSettings.mPackages.values()) {
8168                    addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags,
8169                            userId);
8170                }
8171            } else {
8172                for (PackageParser.Package pkg : mPackages.values()) {
8173                    PackageSetting ps = (PackageSetting)pkg.mExtras;
8174                    if (ps != null) {
8175                        addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags,
8176                                userId);
8177                    }
8178                }
8179            }
8180
8181            return new ParceledListSlice<PackageInfo>(list);
8182        }
8183    }
8184
8185    @Override
8186    public ParceledListSlice<ApplicationInfo> getInstalledApplications(int flags, int userId) {
8187        final int callingUid = Binder.getCallingUid();
8188        if (getInstantAppPackageName(callingUid) != null) {
8189            return ParceledListSlice.emptyList();
8190        }
8191        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
8192        flags = updateFlagsForApplication(flags, userId, null);
8193        final boolean listUninstalled = (flags & MATCH_KNOWN_PACKAGES) != 0;
8194
8195        // writer
8196        synchronized (mPackages) {
8197            ArrayList<ApplicationInfo> list;
8198            if (listUninstalled) {
8199                list = new ArrayList<>(mSettings.mPackages.size());
8200                for (PackageSetting ps : mSettings.mPackages.values()) {
8201                    ApplicationInfo ai;
8202                    int effectiveFlags = flags;
8203                    if (ps.isSystem()) {
8204                        effectiveFlags |= PackageManager.MATCH_ANY_USER;
8205                    }
8206                    if (ps.pkg != null) {
8207                        if (filterSharedLibPackageLPr(ps, callingUid, userId, flags)) {
8208                            continue;
8209                        }
8210                        if (filterAppAccessLPr(ps, callingUid, userId)) {
8211                            return null;
8212                        }
8213                        ai = PackageParser.generateApplicationInfo(ps.pkg, effectiveFlags,
8214                                ps.readUserState(userId), userId);
8215                        if (ai != null) {
8216                            ai.packageName = resolveExternalPackageNameLPr(ps.pkg);
8217                        }
8218                    } else {
8219                        // Shared lib filtering done in generateApplicationInfoFromSettingsLPw
8220                        // and already converts to externally visible package name
8221                        ai = generateApplicationInfoFromSettingsLPw(ps.name,
8222                                callingUid, effectiveFlags, userId);
8223                    }
8224                    if (ai != null) {
8225                        list.add(ai);
8226                    }
8227                }
8228            } else {
8229                list = new ArrayList<>(mPackages.size());
8230                for (PackageParser.Package p : mPackages.values()) {
8231                    if (p.mExtras != null) {
8232                        PackageSetting ps = (PackageSetting) p.mExtras;
8233                        if (filterSharedLibPackageLPr(ps, Binder.getCallingUid(), userId, flags)) {
8234                            continue;
8235                        }
8236                        if (filterAppAccessLPr(ps, callingUid, userId)) {
8237                            return null;
8238                        }
8239                        ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags,
8240                                ps.readUserState(userId), userId);
8241                        if (ai != null) {
8242                            ai.packageName = resolveExternalPackageNameLPr(p);
8243                            list.add(ai);
8244                        }
8245                    }
8246                }
8247            }
8248
8249            return new ParceledListSlice<>(list);
8250        }
8251    }
8252
8253    @Override
8254    public ParceledListSlice<InstantAppInfo> getInstantApps(int userId) {
8255        if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) {
8256            return null;
8257        }
8258        mContext.enforceCallingOrSelfPermission(Manifest.permission.ACCESS_INSTANT_APPS,
8259                "getEphemeralApplications");
8260        enforceCrossUserPermission(Binder.getCallingUid(), userId,
8261                true /* requireFullPermission */, false /* checkShell */,
8262                "getEphemeralApplications");
8263        synchronized (mPackages) {
8264            List<InstantAppInfo> instantApps = mInstantAppRegistry
8265                    .getInstantAppsLPr(userId);
8266            if (instantApps != null) {
8267                return new ParceledListSlice<>(instantApps);
8268            }
8269        }
8270        return null;
8271    }
8272
8273    @Override
8274    public boolean isInstantApp(String packageName, int userId) {
8275        enforceCrossUserPermission(Binder.getCallingUid(), userId,
8276                true /* requireFullPermission */, false /* checkShell */,
8277                "isInstantApp");
8278        if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) {
8279            return false;
8280        }
8281
8282        synchronized (mPackages) {
8283            int callingUid = Binder.getCallingUid();
8284            if (Process.isIsolated(callingUid)) {
8285                callingUid = mIsolatedOwners.get(callingUid);
8286            }
8287            final PackageSetting ps = mSettings.mPackages.get(packageName);
8288            PackageParser.Package pkg = mPackages.get(packageName);
8289            final boolean returnAllowed =
8290                    ps != null
8291                    && (isCallerSameApp(packageName, callingUid)
8292                            || canViewInstantApps(callingUid, userId)
8293                            || mInstantAppRegistry.isInstantAccessGranted(
8294                                    userId, UserHandle.getAppId(callingUid), ps.appId));
8295            if (returnAllowed) {
8296                return ps.getInstantApp(userId);
8297            }
8298        }
8299        return false;
8300    }
8301
8302    @Override
8303    public byte[] getInstantAppCookie(String packageName, int userId) {
8304        if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) {
8305            return null;
8306        }
8307
8308        enforceCrossUserPermission(Binder.getCallingUid(), userId,
8309                true /* requireFullPermission */, false /* checkShell */,
8310                "getInstantAppCookie");
8311        if (!isCallerSameApp(packageName, Binder.getCallingUid())) {
8312            return null;
8313        }
8314        synchronized (mPackages) {
8315            return mInstantAppRegistry.getInstantAppCookieLPw(
8316                    packageName, userId);
8317        }
8318    }
8319
8320    @Override
8321    public boolean setInstantAppCookie(String packageName, byte[] cookie, int userId) {
8322        if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) {
8323            return true;
8324        }
8325
8326        enforceCrossUserPermission(Binder.getCallingUid(), userId,
8327                true /* requireFullPermission */, true /* checkShell */,
8328                "setInstantAppCookie");
8329        if (!isCallerSameApp(packageName, Binder.getCallingUid())) {
8330            return false;
8331        }
8332        synchronized (mPackages) {
8333            return mInstantAppRegistry.setInstantAppCookieLPw(
8334                    packageName, cookie, userId);
8335        }
8336    }
8337
8338    @Override
8339    public Bitmap getInstantAppIcon(String packageName, int userId) {
8340        if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) {
8341            return null;
8342        }
8343
8344        mContext.enforceCallingOrSelfPermission(Manifest.permission.ACCESS_INSTANT_APPS,
8345                "getInstantAppIcon");
8346
8347        enforceCrossUserPermission(Binder.getCallingUid(), userId,
8348                true /* requireFullPermission */, false /* checkShell */,
8349                "getInstantAppIcon");
8350
8351        synchronized (mPackages) {
8352            return mInstantAppRegistry.getInstantAppIconLPw(
8353                    packageName, userId);
8354        }
8355    }
8356
8357    private boolean isCallerSameApp(String packageName, int uid) {
8358        PackageParser.Package pkg = mPackages.get(packageName);
8359        return pkg != null
8360                && UserHandle.getAppId(uid) == pkg.applicationInfo.uid;
8361    }
8362
8363    @Override
8364    public @NonNull ParceledListSlice<ApplicationInfo> getPersistentApplications(int flags) {
8365        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
8366            return ParceledListSlice.emptyList();
8367        }
8368        return new ParceledListSlice<>(getPersistentApplicationsInternal(flags));
8369    }
8370
8371    private @NonNull List<ApplicationInfo> getPersistentApplicationsInternal(int flags) {
8372        final ArrayList<ApplicationInfo> finalList = new ArrayList<ApplicationInfo>();
8373
8374        // reader
8375        synchronized (mPackages) {
8376            final Iterator<PackageParser.Package> i = mPackages.values().iterator();
8377            final int userId = UserHandle.getCallingUserId();
8378            while (i.hasNext()) {
8379                final PackageParser.Package p = i.next();
8380                if (p.applicationInfo == null) continue;
8381
8382                final boolean matchesUnaware = ((flags & MATCH_DIRECT_BOOT_UNAWARE) != 0)
8383                        && !p.applicationInfo.isDirectBootAware();
8384                final boolean matchesAware = ((flags & MATCH_DIRECT_BOOT_AWARE) != 0)
8385                        && p.applicationInfo.isDirectBootAware();
8386
8387                if ((p.applicationInfo.flags & ApplicationInfo.FLAG_PERSISTENT) != 0
8388                        && (!mSafeMode || isSystemApp(p))
8389                        && (matchesUnaware || matchesAware)) {
8390                    PackageSetting ps = mSettings.mPackages.get(p.packageName);
8391                    if (ps != null) {
8392                        ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags,
8393                                ps.readUserState(userId), userId);
8394                        if (ai != null) {
8395                            finalList.add(ai);
8396                        }
8397                    }
8398                }
8399            }
8400        }
8401
8402        return finalList;
8403    }
8404
8405    @Override
8406    public ProviderInfo resolveContentProvider(String name, int flags, int userId) {
8407        if (!sUserManager.exists(userId)) return null;
8408        flags = updateFlagsForComponent(flags, userId, name);
8409        final String instantAppPkgName = getInstantAppPackageName(Binder.getCallingUid());
8410        // reader
8411        synchronized (mPackages) {
8412            final PackageParser.Provider provider = mProvidersByAuthority.get(name);
8413            PackageSetting ps = provider != null
8414                    ? mSettings.mPackages.get(provider.owner.packageName)
8415                    : null;
8416            if (ps != null) {
8417                final boolean isInstantApp = ps.getInstantApp(userId);
8418                // normal application; filter out instant application provider
8419                if (instantAppPkgName == null && isInstantApp) {
8420                    return null;
8421                }
8422                // instant application; filter out other instant applications
8423                if (instantAppPkgName != null
8424                        && isInstantApp
8425                        && !provider.owner.packageName.equals(instantAppPkgName)) {
8426                    return null;
8427                }
8428                // instant application; filter out non-exposed provider
8429                if (instantAppPkgName != null
8430                        && !isInstantApp
8431                        && (provider.info.flags & ProviderInfo.FLAG_VISIBLE_TO_INSTANT_APP) == 0) {
8432                    return null;
8433                }
8434                // provider not enabled
8435                if (!mSettings.isEnabledAndMatchLPr(provider.info, flags, userId)) {
8436                    return null;
8437                }
8438                return PackageParser.generateProviderInfo(
8439                        provider, flags, ps.readUserState(userId), userId);
8440            }
8441            return null;
8442        }
8443    }
8444
8445    /**
8446     * @deprecated
8447     */
8448    @Deprecated
8449    public void querySyncProviders(List<String> outNames, List<ProviderInfo> outInfo) {
8450        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
8451            return;
8452        }
8453        // reader
8454        synchronized (mPackages) {
8455            final Iterator<Map.Entry<String, PackageParser.Provider>> i = mProvidersByAuthority
8456                    .entrySet().iterator();
8457            final int userId = UserHandle.getCallingUserId();
8458            while (i.hasNext()) {
8459                Map.Entry<String, PackageParser.Provider> entry = i.next();
8460                PackageParser.Provider p = entry.getValue();
8461                PackageSetting ps = mSettings.mPackages.get(p.owner.packageName);
8462
8463                if (ps != null && p.syncable
8464                        && (!mSafeMode || (p.info.applicationInfo.flags
8465                                &ApplicationInfo.FLAG_SYSTEM) != 0)) {
8466                    ProviderInfo info = PackageParser.generateProviderInfo(p, 0,
8467                            ps.readUserState(userId), userId);
8468                    if (info != null) {
8469                        outNames.add(entry.getKey());
8470                        outInfo.add(info);
8471                    }
8472                }
8473            }
8474        }
8475    }
8476
8477    @Override
8478    public @NonNull ParceledListSlice<ProviderInfo> queryContentProviders(String processName,
8479            int uid, int flags, String metaDataKey) {
8480        final int callingUid = Binder.getCallingUid();
8481        final int userId = processName != null ? UserHandle.getUserId(uid)
8482                : UserHandle.getCallingUserId();
8483        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
8484        flags = updateFlagsForComponent(flags, userId, processName);
8485        ArrayList<ProviderInfo> finalList = null;
8486        // reader
8487        synchronized (mPackages) {
8488            final Iterator<PackageParser.Provider> i = mProviders.mProviders.values().iterator();
8489            while (i.hasNext()) {
8490                final PackageParser.Provider p = i.next();
8491                PackageSetting ps = mSettings.mPackages.get(p.owner.packageName);
8492                if (ps != null && p.info.authority != null
8493                        && (processName == null
8494                                || (p.info.processName.equals(processName)
8495                                        && UserHandle.isSameApp(p.info.applicationInfo.uid, uid)))
8496                        && mSettings.isEnabledAndMatchLPr(p.info, flags, userId)) {
8497
8498                    // See PM.queryContentProviders()'s javadoc for why we have the metaData
8499                    // parameter.
8500                    if (metaDataKey != null
8501                            && (p.metaData == null || !p.metaData.containsKey(metaDataKey))) {
8502                        continue;
8503                    }
8504                    final ComponentName component =
8505                            new ComponentName(p.info.packageName, p.info.name);
8506                    if (filterAppAccessLPr(ps, callingUid, component, TYPE_PROVIDER, userId)) {
8507                        continue;
8508                    }
8509                    if (finalList == null) {
8510                        finalList = new ArrayList<ProviderInfo>(3);
8511                    }
8512                    ProviderInfo info = PackageParser.generateProviderInfo(p, flags,
8513                            ps.readUserState(userId), userId);
8514                    if (info != null) {
8515                        finalList.add(info);
8516                    }
8517                }
8518            }
8519        }
8520
8521        if (finalList != null) {
8522            Collections.sort(finalList, mProviderInitOrderSorter);
8523            return new ParceledListSlice<ProviderInfo>(finalList);
8524        }
8525
8526        return ParceledListSlice.emptyList();
8527    }
8528
8529    @Override
8530    public InstrumentationInfo getInstrumentationInfo(ComponentName component, int flags) {
8531        // reader
8532        synchronized (mPackages) {
8533            final int callingUid = Binder.getCallingUid();
8534            final int callingUserId = UserHandle.getUserId(callingUid);
8535            final PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
8536            if (ps == null) return null;
8537            if (filterAppAccessLPr(ps, callingUid, component, TYPE_UNKNOWN, callingUserId)) {
8538                return null;
8539            }
8540            final PackageParser.Instrumentation i = mInstrumentation.get(component);
8541            return PackageParser.generateInstrumentationInfo(i, flags);
8542        }
8543    }
8544
8545    @Override
8546    public @NonNull ParceledListSlice<InstrumentationInfo> queryInstrumentation(
8547            String targetPackage, int flags) {
8548        final int callingUid = Binder.getCallingUid();
8549        final int callingUserId = UserHandle.getUserId(callingUid);
8550        final PackageSetting ps = mSettings.mPackages.get(targetPackage);
8551        if (filterAppAccessLPr(ps, callingUid, callingUserId)) {
8552            return ParceledListSlice.emptyList();
8553        }
8554        return new ParceledListSlice<>(queryInstrumentationInternal(targetPackage, flags));
8555    }
8556
8557    private @NonNull List<InstrumentationInfo> queryInstrumentationInternal(String targetPackage,
8558            int flags) {
8559        ArrayList<InstrumentationInfo> finalList = new ArrayList<InstrumentationInfo>();
8560
8561        // reader
8562        synchronized (mPackages) {
8563            final Iterator<PackageParser.Instrumentation> i = mInstrumentation.values().iterator();
8564            while (i.hasNext()) {
8565                final PackageParser.Instrumentation p = i.next();
8566                if (targetPackage == null
8567                        || targetPackage.equals(p.info.targetPackage)) {
8568                    InstrumentationInfo ii = PackageParser.generateInstrumentationInfo(p,
8569                            flags);
8570                    if (ii != null) {
8571                        finalList.add(ii);
8572                    }
8573                }
8574            }
8575        }
8576
8577        return finalList;
8578    }
8579
8580    private void scanDirTracedLI(File dir, final int parseFlags, int scanFlags, long currentTime) {
8581        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanDir [" + dir.getAbsolutePath() + "]");
8582        try {
8583            scanDirLI(dir, parseFlags, scanFlags, currentTime);
8584        } finally {
8585            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
8586        }
8587    }
8588
8589    private void scanDirLI(File dir, int parseFlags, int scanFlags, long currentTime) {
8590        final File[] files = dir.listFiles();
8591        if (ArrayUtils.isEmpty(files)) {
8592            Log.d(TAG, "No files in app dir " + dir);
8593            return;
8594        }
8595
8596        if (DEBUG_PACKAGE_SCANNING) {
8597            Log.d(TAG, "Scanning app dir " + dir + " scanFlags=" + scanFlags
8598                    + " flags=0x" + Integer.toHexString(parseFlags));
8599        }
8600        ParallelPackageParser parallelPackageParser = new ParallelPackageParser(
8601                mSeparateProcesses, mOnlyCore, mMetrics, mCacheDir,
8602                mParallelPackageParserCallback);
8603
8604        // Submit files for parsing in parallel
8605        int fileCount = 0;
8606        for (File file : files) {
8607            final boolean isPackage = (isApkFile(file) || file.isDirectory())
8608                    && !PackageInstallerService.isStageName(file.getName());
8609            if (!isPackage) {
8610                // Ignore entries which are not packages
8611                continue;
8612            }
8613            parallelPackageParser.submit(file, parseFlags);
8614            fileCount++;
8615        }
8616
8617        // Process results one by one
8618        for (; fileCount > 0; fileCount--) {
8619            ParallelPackageParser.ParseResult parseResult = parallelPackageParser.take();
8620            Throwable throwable = parseResult.throwable;
8621            int errorCode = PackageManager.INSTALL_SUCCEEDED;
8622
8623            if (throwable == null) {
8624                // Static shared libraries have synthetic package names
8625                if (parseResult.pkg.applicationInfo.isStaticSharedLibrary()) {
8626                    renameStaticSharedLibraryPackage(parseResult.pkg);
8627                }
8628                try {
8629                    if (errorCode == PackageManager.INSTALL_SUCCEEDED) {
8630                        scanPackageLI(parseResult.pkg, parseResult.scanFile, parseFlags, scanFlags,
8631                                currentTime, null);
8632                    }
8633                } catch (PackageManagerException e) {
8634                    errorCode = e.error;
8635                    Slog.w(TAG, "Failed to scan " + parseResult.scanFile + ": " + e.getMessage());
8636                }
8637            } else if (throwable instanceof PackageParser.PackageParserException) {
8638                PackageParser.PackageParserException e = (PackageParser.PackageParserException)
8639                        throwable;
8640                errorCode = e.error;
8641                Slog.w(TAG, "Failed to parse " + parseResult.scanFile + ": " + e.getMessage());
8642            } else {
8643                throw new IllegalStateException("Unexpected exception occurred while parsing "
8644                        + parseResult.scanFile, throwable);
8645            }
8646
8647            // Delete invalid userdata apps
8648            if ((parseFlags & PackageParser.PARSE_IS_SYSTEM) == 0 &&
8649                    errorCode == PackageManager.INSTALL_FAILED_INVALID_APK) {
8650                logCriticalInfo(Log.WARN,
8651                        "Deleting invalid package at " + parseResult.scanFile);
8652                removeCodePathLI(parseResult.scanFile);
8653            }
8654        }
8655        parallelPackageParser.close();
8656    }
8657
8658    private static File getSettingsProblemFile() {
8659        File dataDir = Environment.getDataDirectory();
8660        File systemDir = new File(dataDir, "system");
8661        File fname = new File(systemDir, "uiderrors.txt");
8662        return fname;
8663    }
8664
8665    static void reportSettingsProblem(int priority, String msg) {
8666        logCriticalInfo(priority, msg);
8667    }
8668
8669    public static void logCriticalInfo(int priority, String msg) {
8670        Slog.println(priority, TAG, msg);
8671        EventLogTags.writePmCriticalInfo(msg);
8672        try {
8673            File fname = getSettingsProblemFile();
8674            FileOutputStream out = new FileOutputStream(fname, true);
8675            PrintWriter pw = new FastPrintWriter(out);
8676            SimpleDateFormat formatter = new SimpleDateFormat();
8677            String dateString = formatter.format(new Date(System.currentTimeMillis()));
8678            pw.println(dateString + ": " + msg);
8679            pw.close();
8680            FileUtils.setPermissions(
8681                    fname.toString(),
8682                    FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IROTH,
8683                    -1, -1);
8684        } catch (java.io.IOException e) {
8685        }
8686    }
8687
8688    private long getLastModifiedTime(PackageParser.Package pkg, File srcFile) {
8689        if (srcFile.isDirectory()) {
8690            final File baseFile = new File(pkg.baseCodePath);
8691            long maxModifiedTime = baseFile.lastModified();
8692            if (pkg.splitCodePaths != null) {
8693                for (int i = pkg.splitCodePaths.length - 1; i >=0; --i) {
8694                    final File splitFile = new File(pkg.splitCodePaths[i]);
8695                    maxModifiedTime = Math.max(maxModifiedTime, splitFile.lastModified());
8696                }
8697            }
8698            return maxModifiedTime;
8699        }
8700        return srcFile.lastModified();
8701    }
8702
8703    private void collectCertificatesLI(PackageSetting ps, PackageParser.Package pkg, File srcFile,
8704            final int policyFlags) throws PackageManagerException {
8705        // When upgrading from pre-N MR1, verify the package time stamp using the package
8706        // directory and not the APK file.
8707        final long lastModifiedTime = mIsPreNMR1Upgrade
8708                ? new File(pkg.codePath).lastModified() : getLastModifiedTime(pkg, srcFile);
8709        if (ps != null
8710                && ps.codePath.equals(srcFile)
8711                && ps.timeStamp == lastModifiedTime
8712                && !isCompatSignatureUpdateNeeded(pkg)
8713                && !isRecoverSignatureUpdateNeeded(pkg)) {
8714            long mSigningKeySetId = ps.keySetData.getProperSigningKeySet();
8715            KeySetManagerService ksms = mSettings.mKeySetManagerService;
8716            ArraySet<PublicKey> signingKs;
8717            synchronized (mPackages) {
8718                signingKs = ksms.getPublicKeysFromKeySetLPr(mSigningKeySetId);
8719            }
8720            if (ps.signatures.mSignatures != null
8721                    && ps.signatures.mSignatures.length != 0
8722                    && signingKs != null) {
8723                // Optimization: reuse the existing cached certificates
8724                // if the package appears to be unchanged.
8725                pkg.mSignatures = ps.signatures.mSignatures;
8726                pkg.mSigningKeys = signingKs;
8727                return;
8728            }
8729
8730            Slog.w(TAG, "PackageSetting for " + ps.name
8731                    + " is missing signatures.  Collecting certs again to recover them.");
8732        } else {
8733            Slog.i(TAG, srcFile.toString() + " changed; collecting certs");
8734        }
8735
8736        try {
8737            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "collectCertificates");
8738            PackageParser.collectCertificates(pkg, policyFlags);
8739        } catch (PackageParserException e) {
8740            throw PackageManagerException.from(e);
8741        } finally {
8742            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
8743        }
8744    }
8745
8746    /**
8747     *  Traces a package scan.
8748     *  @see #scanPackageLI(File, int, int, long, UserHandle)
8749     */
8750    private PackageParser.Package scanPackageTracedLI(File scanFile, final int parseFlags,
8751            int scanFlags, long currentTime, UserHandle user) throws PackageManagerException {
8752        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage [" + scanFile.toString() + "]");
8753        try {
8754            return scanPackageLI(scanFile, parseFlags, scanFlags, currentTime, user);
8755        } finally {
8756            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
8757        }
8758    }
8759
8760    /**
8761     *  Scans a package and returns the newly parsed package.
8762     *  Returns {@code null} in case of errors and the error code is stored in mLastScanError
8763     */
8764    private PackageParser.Package scanPackageLI(File scanFile, int parseFlags, int scanFlags,
8765            long currentTime, UserHandle user) throws PackageManagerException {
8766        if (DEBUG_INSTALL) Slog.d(TAG, "Parsing: " + scanFile);
8767        PackageParser pp = new PackageParser();
8768        pp.setSeparateProcesses(mSeparateProcesses);
8769        pp.setOnlyCoreApps(mOnlyCore);
8770        pp.setDisplayMetrics(mMetrics);
8771        pp.setCallback(mPackageParserCallback);
8772
8773        if ((scanFlags & SCAN_TRUSTED_OVERLAY) != 0) {
8774            parseFlags |= PackageParser.PARSE_TRUSTED_OVERLAY;
8775        }
8776
8777        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "parsePackage");
8778        final PackageParser.Package pkg;
8779        try {
8780            pkg = pp.parsePackage(scanFile, parseFlags);
8781        } catch (PackageParserException e) {
8782            throw PackageManagerException.from(e);
8783        } finally {
8784            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
8785        }
8786
8787        // Static shared libraries have synthetic package names
8788        if (pkg.applicationInfo.isStaticSharedLibrary()) {
8789            renameStaticSharedLibraryPackage(pkg);
8790        }
8791
8792        return scanPackageLI(pkg, scanFile, parseFlags, scanFlags, currentTime, user);
8793    }
8794
8795    /**
8796     *  Scans a package and returns the newly parsed package.
8797     *  @throws PackageManagerException on a parse error.
8798     */
8799    private PackageParser.Package scanPackageLI(PackageParser.Package pkg, File scanFile,
8800            final int policyFlags, int scanFlags, long currentTime, @Nullable UserHandle user)
8801            throws PackageManagerException {
8802        // If the package has children and this is the first dive in the function
8803        // we scan the package with the SCAN_CHECK_ONLY flag set to see whether all
8804        // packages (parent and children) would be successfully scanned before the
8805        // actual scan since scanning mutates internal state and we want to atomically
8806        // install the package and its children.
8807        if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
8808            if (pkg.childPackages != null && pkg.childPackages.size() > 0) {
8809                scanFlags |= SCAN_CHECK_ONLY;
8810            }
8811        } else {
8812            scanFlags &= ~SCAN_CHECK_ONLY;
8813        }
8814
8815        // Scan the parent
8816        PackageParser.Package scannedPkg = scanPackageInternalLI(pkg, scanFile, policyFlags,
8817                scanFlags, currentTime, user);
8818
8819        // Scan the children
8820        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
8821        for (int i = 0; i < childCount; i++) {
8822            PackageParser.Package childPackage = pkg.childPackages.get(i);
8823            scanPackageInternalLI(childPackage, scanFile, policyFlags, scanFlags,
8824                    currentTime, user);
8825        }
8826
8827
8828        if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
8829            return scanPackageLI(pkg, scanFile, policyFlags, scanFlags, currentTime, user);
8830        }
8831
8832        return scannedPkg;
8833    }
8834
8835    /**
8836     *  Scans a package and returns the newly parsed package.
8837     *  @throws PackageManagerException on a parse error.
8838     */
8839    private PackageParser.Package scanPackageInternalLI(PackageParser.Package pkg, File scanFile,
8840            int policyFlags, int scanFlags, long currentTime, @Nullable UserHandle user)
8841            throws PackageManagerException {
8842        PackageSetting ps = null;
8843        PackageSetting updatedPkg;
8844        // reader
8845        synchronized (mPackages) {
8846            // Look to see if we already know about this package.
8847            String oldName = mSettings.getRenamedPackageLPr(pkg.packageName);
8848            if (pkg.mOriginalPackages != null && pkg.mOriginalPackages.contains(oldName)) {
8849                // This package has been renamed to its original name.  Let's
8850                // use that.
8851                ps = mSettings.getPackageLPr(oldName);
8852            }
8853            // If there was no original package, see one for the real package name.
8854            if (ps == null) {
8855                ps = mSettings.getPackageLPr(pkg.packageName);
8856            }
8857            // Check to see if this package could be hiding/updating a system
8858            // package.  Must look for it either under the original or real
8859            // package name depending on our state.
8860            updatedPkg = mSettings.getDisabledSystemPkgLPr(ps != null ? ps.name : pkg.packageName);
8861            if (DEBUG_INSTALL && updatedPkg != null) Slog.d(TAG, "updatedPkg = " + updatedPkg);
8862
8863            // If this is a package we don't know about on the system partition, we
8864            // may need to remove disabled child packages on the system partition
8865            // or may need to not add child packages if the parent apk is updated
8866            // on the data partition and no longer defines this child package.
8867            if ((policyFlags & PackageParser.PARSE_IS_SYSTEM) != 0) {
8868                // If this is a parent package for an updated system app and this system
8869                // app got an OTA update which no longer defines some of the child packages
8870                // we have to prune them from the disabled system packages.
8871                PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(pkg.packageName);
8872                if (disabledPs != null) {
8873                    final int scannedChildCount = (pkg.childPackages != null)
8874                            ? pkg.childPackages.size() : 0;
8875                    final int disabledChildCount = disabledPs.childPackageNames != null
8876                            ? disabledPs.childPackageNames.size() : 0;
8877                    for (int i = 0; i < disabledChildCount; i++) {
8878                        String disabledChildPackageName = disabledPs.childPackageNames.get(i);
8879                        boolean disabledPackageAvailable = false;
8880                        for (int j = 0; j < scannedChildCount; j++) {
8881                            PackageParser.Package childPkg = pkg.childPackages.get(j);
8882                            if (childPkg.packageName.equals(disabledChildPackageName)) {
8883                                disabledPackageAvailable = true;
8884                                break;
8885                            }
8886                         }
8887                         if (!disabledPackageAvailable) {
8888                             mSettings.removeDisabledSystemPackageLPw(disabledChildPackageName);
8889                         }
8890                    }
8891                }
8892            }
8893        }
8894
8895        boolean updatedPkgBetter = false;
8896        // First check if this is a system package that may involve an update
8897        if (updatedPkg != null && (policyFlags & PackageParser.PARSE_IS_SYSTEM) != 0) {
8898            // If new package is not located in "/system/priv-app" (e.g. due to an OTA),
8899            // it needs to drop FLAG_PRIVILEGED.
8900            if (locationIsPrivileged(scanFile)) {
8901                updatedPkg.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
8902            } else {
8903                updatedPkg.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
8904            }
8905
8906            if (ps != null && !ps.codePath.equals(scanFile)) {
8907                // The path has changed from what was last scanned...  check the
8908                // version of the new path against what we have stored to determine
8909                // what to do.
8910                if (DEBUG_INSTALL) Slog.d(TAG, "Path changing from " + ps.codePath);
8911                if (pkg.mVersionCode <= ps.versionCode) {
8912                    // The system package has been updated and the code path does not match
8913                    // Ignore entry. Skip it.
8914                    if (DEBUG_INSTALL) Slog.i(TAG, "Package " + ps.name + " at " + scanFile
8915                            + " ignored: updated version " + ps.versionCode
8916                            + " better than this " + pkg.mVersionCode);
8917                    if (!updatedPkg.codePath.equals(scanFile)) {
8918                        Slog.w(PackageManagerService.TAG, "Code path for hidden system pkg "
8919                                + ps.name + " changing from " + updatedPkg.codePathString
8920                                + " to " + scanFile);
8921                        updatedPkg.codePath = scanFile;
8922                        updatedPkg.codePathString = scanFile.toString();
8923                        updatedPkg.resourcePath = scanFile;
8924                        updatedPkg.resourcePathString = scanFile.toString();
8925                    }
8926                    updatedPkg.pkg = pkg;
8927                    updatedPkg.versionCode = pkg.mVersionCode;
8928
8929                    // Update the disabled system child packages to point to the package too.
8930                    final int childCount = updatedPkg.childPackageNames != null
8931                            ? updatedPkg.childPackageNames.size() : 0;
8932                    for (int i = 0; i < childCount; i++) {
8933                        String childPackageName = updatedPkg.childPackageNames.get(i);
8934                        PackageSetting updatedChildPkg = mSettings.getDisabledSystemPkgLPr(
8935                                childPackageName);
8936                        if (updatedChildPkg != null) {
8937                            updatedChildPkg.pkg = pkg;
8938                            updatedChildPkg.versionCode = pkg.mVersionCode;
8939                        }
8940                    }
8941
8942                    throw new PackageManagerException(Log.WARN, "Package " + ps.name + " at "
8943                            + scanFile + " ignored: updated version " + ps.versionCode
8944                            + " better than this " + pkg.mVersionCode);
8945                } else {
8946                    // The current app on the system partition is better than
8947                    // what we have updated to on the data partition; switch
8948                    // back to the system partition version.
8949                    // At this point, its safely assumed that package installation for
8950                    // apps in system partition will go through. If not there won't be a working
8951                    // version of the app
8952                    // writer
8953                    synchronized (mPackages) {
8954                        // Just remove the loaded entries from package lists.
8955                        mPackages.remove(ps.name);
8956                    }
8957
8958                    logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile
8959                            + " reverting from " + ps.codePathString
8960                            + ": new version " + pkg.mVersionCode
8961                            + " better than installed " + ps.versionCode);
8962
8963                    InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
8964                            ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
8965                    synchronized (mInstallLock) {
8966                        args.cleanUpResourcesLI();
8967                    }
8968                    synchronized (mPackages) {
8969                        mSettings.enableSystemPackageLPw(ps.name);
8970                    }
8971                    updatedPkgBetter = true;
8972                }
8973            }
8974        }
8975
8976        if (updatedPkg != null) {
8977            // An updated system app will not have the PARSE_IS_SYSTEM flag set
8978            // initially
8979            policyFlags |= PackageParser.PARSE_IS_SYSTEM;
8980
8981            // An updated privileged app will not have the PARSE_IS_PRIVILEGED
8982            // flag set initially
8983            if ((updatedPkg.pkgPrivateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0) {
8984                policyFlags |= PackageParser.PARSE_IS_PRIVILEGED;
8985            }
8986        }
8987
8988        // Verify certificates against what was last scanned
8989        collectCertificatesLI(ps, pkg, scanFile, policyFlags);
8990
8991        /*
8992         * A new system app appeared, but we already had a non-system one of the
8993         * same name installed earlier.
8994         */
8995        boolean shouldHideSystemApp = false;
8996        if (updatedPkg == null && ps != null
8997                && (policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0 && !isSystemApp(ps)) {
8998            /*
8999             * Check to make sure the signatures match first. If they don't,
9000             * wipe the installed application and its data.
9001             */
9002            if (compareSignatures(ps.signatures.mSignatures, pkg.mSignatures)
9003                    != PackageManager.SIGNATURE_MATCH) {
9004                logCriticalInfo(Log.WARN, "Package " + ps.name + " appeared on system, but"
9005                        + " signatures don't match existing userdata copy; removing");
9006                try (PackageFreezer freezer = freezePackage(pkg.packageName,
9007                        "scanPackageInternalLI")) {
9008                    deletePackageLIF(pkg.packageName, null, true, null, 0, null, false, null);
9009                }
9010                ps = null;
9011            } else {
9012                /*
9013                 * If the newly-added system app is an older version than the
9014                 * already installed version, hide it. It will be scanned later
9015                 * and re-added like an update.
9016                 */
9017                if (pkg.mVersionCode <= ps.versionCode) {
9018                    shouldHideSystemApp = true;
9019                    logCriticalInfo(Log.INFO, "Package " + ps.name + " appeared at " + scanFile
9020                            + " but new version " + pkg.mVersionCode + " better than installed "
9021                            + ps.versionCode + "; hiding system");
9022                } else {
9023                    /*
9024                     * The newly found system app is a newer version that the
9025                     * one previously installed. Simply remove the
9026                     * already-installed application and replace it with our own
9027                     * while keeping the application data.
9028                     */
9029                    logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile
9030                            + " reverting from " + ps.codePathString + ": new version "
9031                            + pkg.mVersionCode + " better than installed " + ps.versionCode);
9032                    InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
9033                            ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
9034                    synchronized (mInstallLock) {
9035                        args.cleanUpResourcesLI();
9036                    }
9037                }
9038            }
9039        }
9040
9041        // The apk is forward locked (not public) if its code and resources
9042        // are kept in different files. (except for app in either system or
9043        // vendor path).
9044        // TODO grab this value from PackageSettings
9045        if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
9046            if (ps != null && !ps.codePath.equals(ps.resourcePath)) {
9047                policyFlags |= PackageParser.PARSE_FORWARD_LOCK;
9048            }
9049        }
9050
9051        // TODO: extend to support forward-locked splits
9052        String resourcePath = null;
9053        String baseResourcePath = null;
9054        if ((policyFlags & PackageParser.PARSE_FORWARD_LOCK) != 0 && !updatedPkgBetter) {
9055            if (ps != null && ps.resourcePathString != null) {
9056                resourcePath = ps.resourcePathString;
9057                baseResourcePath = ps.resourcePathString;
9058            } else {
9059                // Should not happen at all. Just log an error.
9060                Slog.e(TAG, "Resource path not set for package " + pkg.packageName);
9061            }
9062        } else {
9063            resourcePath = pkg.codePath;
9064            baseResourcePath = pkg.baseCodePath;
9065        }
9066
9067        // Set application objects path explicitly.
9068        pkg.setApplicationVolumeUuid(pkg.volumeUuid);
9069        pkg.setApplicationInfoCodePath(pkg.codePath);
9070        pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
9071        pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
9072        pkg.setApplicationInfoResourcePath(resourcePath);
9073        pkg.setApplicationInfoBaseResourcePath(baseResourcePath);
9074        pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
9075
9076        final int userId = ((user == null) ? 0 : user.getIdentifier());
9077        if (ps != null && ps.getInstantApp(userId)) {
9078            scanFlags |= SCAN_AS_INSTANT_APP;
9079        }
9080
9081        // Note that we invoke the following method only if we are about to unpack an application
9082        PackageParser.Package scannedPkg = scanPackageLI(pkg, policyFlags, scanFlags
9083                | SCAN_UPDATE_SIGNATURE, currentTime, user);
9084
9085        /*
9086         * If the system app should be overridden by a previously installed
9087         * data, hide the system app now and let the /data/app scan pick it up
9088         * again.
9089         */
9090        if (shouldHideSystemApp) {
9091            synchronized (mPackages) {
9092                mSettings.disableSystemPackageLPw(pkg.packageName, true);
9093            }
9094        }
9095
9096        return scannedPkg;
9097    }
9098
9099    private void renameStaticSharedLibraryPackage(PackageParser.Package pkg) {
9100        // Derive the new package synthetic package name
9101        pkg.setPackageName(pkg.packageName + STATIC_SHARED_LIB_DELIMITER
9102                + pkg.staticSharedLibVersion);
9103    }
9104
9105    private static String fixProcessName(String defProcessName,
9106            String processName) {
9107        if (processName == null) {
9108            return defProcessName;
9109        }
9110        return processName;
9111    }
9112
9113    private void verifySignaturesLP(PackageSetting pkgSetting, PackageParser.Package pkg)
9114            throws PackageManagerException {
9115        if (pkgSetting.signatures.mSignatures != null) {
9116            // Already existing package. Make sure signatures match
9117            boolean match = compareSignatures(pkgSetting.signatures.mSignatures, pkg.mSignatures)
9118                    == PackageManager.SIGNATURE_MATCH;
9119            if (!match) {
9120                match = compareSignaturesCompat(pkgSetting.signatures, pkg)
9121                        == PackageManager.SIGNATURE_MATCH;
9122            }
9123            if (!match) {
9124                match = compareSignaturesRecover(pkgSetting.signatures, pkg)
9125                        == PackageManager.SIGNATURE_MATCH;
9126            }
9127            if (!match) {
9128                throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package "
9129                        + pkg.packageName + " signatures do not match the "
9130                        + "previously installed version; ignoring!");
9131            }
9132        }
9133
9134        // Check for shared user signatures
9135        if (pkgSetting.sharedUser != null && pkgSetting.sharedUser.signatures.mSignatures != null) {
9136            // Already existing package. Make sure signatures match
9137            boolean match = compareSignatures(pkgSetting.sharedUser.signatures.mSignatures,
9138                    pkg.mSignatures) == PackageManager.SIGNATURE_MATCH;
9139            if (!match) {
9140                match = compareSignaturesCompat(pkgSetting.sharedUser.signatures, pkg)
9141                        == PackageManager.SIGNATURE_MATCH;
9142            }
9143            if (!match) {
9144                match = compareSignaturesRecover(pkgSetting.sharedUser.signatures, pkg)
9145                        == PackageManager.SIGNATURE_MATCH;
9146            }
9147            if (!match) {
9148                throw new PackageManagerException(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE,
9149                        "Package " + pkg.packageName
9150                        + " has no signatures that match those in shared user "
9151                        + pkgSetting.sharedUser.name + "; ignoring!");
9152            }
9153        }
9154    }
9155
9156    /**
9157     * Enforces that only the system UID or root's UID can call a method exposed
9158     * via Binder.
9159     *
9160     * @param message used as message if SecurityException is thrown
9161     * @throws SecurityException if the caller is not system or root
9162     */
9163    private static final void enforceSystemOrRoot(String message) {
9164        final int uid = Binder.getCallingUid();
9165        if (uid != Process.SYSTEM_UID && uid != Process.ROOT_UID) {
9166            throw new SecurityException(message);
9167        }
9168    }
9169
9170    @Override
9171    public void performFstrimIfNeeded() {
9172        enforceSystemOrRoot("Only the system can request fstrim");
9173
9174        // Before everything else, see whether we need to fstrim.
9175        try {
9176            IStorageManager sm = PackageHelper.getStorageManager();
9177            if (sm != null) {
9178                boolean doTrim = false;
9179                final long interval = android.provider.Settings.Global.getLong(
9180                        mContext.getContentResolver(),
9181                        android.provider.Settings.Global.FSTRIM_MANDATORY_INTERVAL,
9182                        DEFAULT_MANDATORY_FSTRIM_INTERVAL);
9183                if (interval > 0) {
9184                    final long timeSinceLast = System.currentTimeMillis() - sm.lastMaintenance();
9185                    if (timeSinceLast > interval) {
9186                        doTrim = true;
9187                        Slog.w(TAG, "No disk maintenance in " + timeSinceLast
9188                                + "; running immediately");
9189                    }
9190                }
9191                if (doTrim) {
9192                    final boolean dexOptDialogShown;
9193                    synchronized (mPackages) {
9194                        dexOptDialogShown = mDexOptDialogShown;
9195                    }
9196                    if (!isFirstBoot() && dexOptDialogShown) {
9197                        try {
9198                            ActivityManager.getService().showBootMessage(
9199                                    mContext.getResources().getString(
9200                                            R.string.android_upgrading_fstrim), true);
9201                        } catch (RemoteException e) {
9202                        }
9203                    }
9204                    sm.runMaintenance();
9205                }
9206            } else {
9207                Slog.e(TAG, "storageManager service unavailable!");
9208            }
9209        } catch (RemoteException e) {
9210            // Can't happen; StorageManagerService is local
9211        }
9212    }
9213
9214    @Override
9215    public void updatePackagesIfNeeded() {
9216        enforceSystemOrRoot("Only the system can request package update");
9217
9218        // We need to re-extract after an OTA.
9219        boolean causeUpgrade = isUpgrade();
9220
9221        // First boot or factory reset.
9222        // Note: we also handle devices that are upgrading to N right now as if it is their
9223        //       first boot, as they do not have profile data.
9224        boolean causeFirstBoot = isFirstBoot() || mIsPreNUpgrade;
9225
9226        // We need to re-extract after a pruned cache, as AoT-ed files will be out of date.
9227        boolean causePrunedCache = VMRuntime.didPruneDalvikCache();
9228
9229        if (!causeUpgrade && !causeFirstBoot && !causePrunedCache) {
9230            return;
9231        }
9232
9233        List<PackageParser.Package> pkgs;
9234        synchronized (mPackages) {
9235            pkgs = PackageManagerServiceUtils.getPackagesForDexopt(mPackages.values(), this);
9236        }
9237
9238        final long startTime = System.nanoTime();
9239        final int[] stats = performDexOptUpgrade(pkgs, mIsPreNUpgrade /* showDialog */,
9240                    getCompilerFilterForReason(causeFirstBoot ? REASON_FIRST_BOOT : REASON_BOOT),
9241                    false /* bootComplete */);
9242
9243        final int elapsedTimeSeconds =
9244                (int) TimeUnit.NANOSECONDS.toSeconds(System.nanoTime() - startTime);
9245
9246        MetricsLogger.histogram(mContext, "opt_dialog_num_dexopted", stats[0]);
9247        MetricsLogger.histogram(mContext, "opt_dialog_num_skipped", stats[1]);
9248        MetricsLogger.histogram(mContext, "opt_dialog_num_failed", stats[2]);
9249        MetricsLogger.histogram(mContext, "opt_dialog_num_total", getOptimizablePackages().size());
9250        MetricsLogger.histogram(mContext, "opt_dialog_time_s", elapsedTimeSeconds);
9251    }
9252
9253    /*
9254     * Return the prebuilt profile path given a package base code path.
9255     */
9256    private static String getPrebuildProfilePath(PackageParser.Package pkg) {
9257        return pkg.baseCodePath + ".prof";
9258    }
9259
9260    /**
9261     * Performs dexopt on the set of packages in {@code packages} and returns an int array
9262     * containing statistics about the invocation. The array consists of three elements,
9263     * which are (in order) {@code numberOfPackagesOptimized}, {@code numberOfPackagesSkipped}
9264     * and {@code numberOfPackagesFailed}.
9265     */
9266    private int[] performDexOptUpgrade(List<PackageParser.Package> pkgs, boolean showDialog,
9267            String compilerFilter, boolean bootComplete) {
9268
9269        int numberOfPackagesVisited = 0;
9270        int numberOfPackagesOptimized = 0;
9271        int numberOfPackagesSkipped = 0;
9272        int numberOfPackagesFailed = 0;
9273        final int numberOfPackagesToDexopt = pkgs.size();
9274
9275        for (PackageParser.Package pkg : pkgs) {
9276            numberOfPackagesVisited++;
9277
9278            if ((isFirstBoot() || isUpgrade()) && isSystemApp(pkg)) {
9279                // Copy over initial preopt profiles since we won't get any JIT samples for methods
9280                // that are already compiled.
9281                File profileFile = new File(getPrebuildProfilePath(pkg));
9282                // Copy profile if it exists.
9283                if (profileFile.exists()) {
9284                    try {
9285                        // We could also do this lazily before calling dexopt in
9286                        // PackageDexOptimizer to prevent this happening on first boot. The issue
9287                        // is that we don't have a good way to say "do this only once".
9288                        if (!mInstaller.copySystemProfile(profileFile.getAbsolutePath(),
9289                                pkg.applicationInfo.uid, pkg.packageName)) {
9290                            Log.e(TAG, "Installer failed to copy system profile!");
9291                        }
9292                    } catch (Exception e) {
9293                        Log.e(TAG, "Failed to copy profile " + profileFile.getAbsolutePath() + " ",
9294                                e);
9295                    }
9296                }
9297            }
9298
9299            if (!PackageDexOptimizer.canOptimizePackage(pkg)) {
9300                if (DEBUG_DEXOPT) {
9301                    Log.i(TAG, "Skipping update of of non-optimizable app " + pkg.packageName);
9302                }
9303                numberOfPackagesSkipped++;
9304                continue;
9305            }
9306
9307            if (DEBUG_DEXOPT) {
9308                Log.i(TAG, "Updating app " + numberOfPackagesVisited + " of " +
9309                        numberOfPackagesToDexopt + ": " + pkg.packageName);
9310            }
9311
9312            if (showDialog) {
9313                try {
9314                    ActivityManager.getService().showBootMessage(
9315                            mContext.getResources().getString(R.string.android_upgrading_apk,
9316                                    numberOfPackagesVisited, numberOfPackagesToDexopt), true);
9317                } catch (RemoteException e) {
9318                }
9319                synchronized (mPackages) {
9320                    mDexOptDialogShown = true;
9321                }
9322            }
9323
9324            // If the OTA updates a system app which was previously preopted to a non-preopted state
9325            // the app might end up being verified at runtime. That's because by default the apps
9326            // are verify-profile but for preopted apps there's no profile.
9327            // Do a hacky check to ensure that if we have no profiles (a reasonable indication
9328            // that before the OTA the app was preopted) the app gets compiled with a non-profile
9329            // filter (by default 'quicken').
9330            // Note that at this stage unused apps are already filtered.
9331            if (isSystemApp(pkg) &&
9332                    DexFile.isProfileGuidedCompilerFilter(compilerFilter) &&
9333                    !Environment.getReferenceProfile(pkg.packageName).exists()) {
9334                compilerFilter = getNonProfileGuidedCompilerFilter(compilerFilter);
9335            }
9336
9337            // checkProfiles is false to avoid merging profiles during boot which
9338            // might interfere with background compilation (b/28612421).
9339            // Unfortunately this will also means that "pm.dexopt.boot=speed-profile" will
9340            // behave differently than "pm.dexopt.bg-dexopt=speed-profile" but that's a
9341            // trade-off worth doing to save boot time work.
9342            int dexOptStatus = performDexOptTraced(pkg.packageName,
9343                    false /* checkProfiles */,
9344                    compilerFilter,
9345                    false /* force */,
9346                    bootComplete);
9347            switch (dexOptStatus) {
9348                case PackageDexOptimizer.DEX_OPT_PERFORMED:
9349                    numberOfPackagesOptimized++;
9350                    break;
9351                case PackageDexOptimizer.DEX_OPT_SKIPPED:
9352                    numberOfPackagesSkipped++;
9353                    break;
9354                case PackageDexOptimizer.DEX_OPT_FAILED:
9355                    numberOfPackagesFailed++;
9356                    break;
9357                default:
9358                    Log.e(TAG, "Unexpected dexopt return code " + dexOptStatus);
9359                    break;
9360            }
9361        }
9362
9363        return new int[] { numberOfPackagesOptimized, numberOfPackagesSkipped,
9364                numberOfPackagesFailed };
9365    }
9366
9367    @Override
9368    public void notifyPackageUse(String packageName, int reason) {
9369        synchronized (mPackages) {
9370            final int callingUid = Binder.getCallingUid();
9371            final int callingUserId = UserHandle.getUserId(callingUid);
9372            if (getInstantAppPackageName(callingUid) != null) {
9373                if (!isCallerSameApp(packageName, callingUid)) {
9374                    return;
9375                }
9376            } else {
9377                if (isInstantApp(packageName, callingUserId)) {
9378                    return;
9379                }
9380            }
9381            final PackageParser.Package p = mPackages.get(packageName);
9382            if (p == null) {
9383                return;
9384            }
9385            p.mLastPackageUsageTimeInMills[reason] = System.currentTimeMillis();
9386        }
9387    }
9388
9389    @Override
9390    public void notifyDexLoad(String loadingPackageName, List<String> dexPaths, String loaderIsa) {
9391        int userId = UserHandle.getCallingUserId();
9392        ApplicationInfo ai = getApplicationInfo(loadingPackageName, /*flags*/ 0, userId);
9393        if (ai == null) {
9394            Slog.w(TAG, "Loading a package that does not exist for the calling user. package="
9395                + loadingPackageName + ", user=" + userId);
9396            return;
9397        }
9398        mDexManager.notifyDexLoad(ai, dexPaths, loaderIsa, userId);
9399    }
9400
9401    @Override
9402    public void registerDexModule(String packageName, String dexModulePath, boolean isSharedModule,
9403            IDexModuleRegisterCallback callback) {
9404        int userId = UserHandle.getCallingUserId();
9405        ApplicationInfo ai = getApplicationInfo(packageName, /*flags*/ 0, userId);
9406        DexManager.RegisterDexModuleResult result;
9407        if (ai == null) {
9408            Slog.w(TAG, "Registering a dex module for a package that does not exist for the" +
9409                     " calling user. package=" + packageName + ", user=" + userId);
9410            result = new DexManager.RegisterDexModuleResult(false, "Package not installed");
9411        } else {
9412            result = mDexManager.registerDexModule(ai, dexModulePath, isSharedModule, userId);
9413        }
9414
9415        if (callback != null) {
9416            mHandler.post(() -> {
9417                try {
9418                    callback.onDexModuleRegistered(dexModulePath, result.success, result.message);
9419                } catch (RemoteException e) {
9420                    Slog.w(TAG, "Failed to callback after module registration " + dexModulePath, e);
9421                }
9422            });
9423        }
9424    }
9425
9426    @Override
9427    public boolean performDexOpt(String packageName,
9428            boolean checkProfiles, int compileReason, boolean force, boolean bootComplete) {
9429        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
9430            return false;
9431        } else if (isInstantApp(packageName, UserHandle.getCallingUserId())) {
9432            return false;
9433        }
9434        int dexoptStatus = performDexOptWithStatus(
9435              packageName, checkProfiles, compileReason, force, bootComplete);
9436        return dexoptStatus != PackageDexOptimizer.DEX_OPT_FAILED;
9437    }
9438
9439    /**
9440     * Perform dexopt on the given package and return one of following result:
9441     *  {@link PackageDexOptimizer#DEX_OPT_SKIPPED}
9442     *  {@link PackageDexOptimizer#DEX_OPT_PERFORMED}
9443     *  {@link PackageDexOptimizer#DEX_OPT_FAILED}
9444     */
9445    /* package */ int performDexOptWithStatus(String packageName,
9446            boolean checkProfiles, int compileReason, boolean force, boolean bootComplete) {
9447        return performDexOptTraced(packageName, checkProfiles,
9448                getCompilerFilterForReason(compileReason), force, bootComplete);
9449    }
9450
9451    @Override
9452    public boolean performDexOptMode(String packageName,
9453            boolean checkProfiles, String targetCompilerFilter, boolean force,
9454            boolean bootComplete) {
9455        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
9456            return false;
9457        } else if (isInstantApp(packageName, UserHandle.getCallingUserId())) {
9458            return false;
9459        }
9460        int dexOptStatus = performDexOptTraced(packageName, checkProfiles,
9461                targetCompilerFilter, force, bootComplete);
9462        return dexOptStatus != PackageDexOptimizer.DEX_OPT_FAILED;
9463    }
9464
9465    private int performDexOptTraced(String packageName,
9466                boolean checkProfiles, String targetCompilerFilter, boolean force,
9467                boolean bootComplete) {
9468        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt");
9469        try {
9470            return performDexOptInternal(packageName, checkProfiles,
9471                    targetCompilerFilter, force, bootComplete);
9472        } finally {
9473            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
9474        }
9475    }
9476
9477    // Run dexopt on a given package. Returns true if dexopt did not fail, i.e.
9478    // if the package can now be considered up to date for the given filter.
9479    private int performDexOptInternal(String packageName,
9480                boolean checkProfiles, String targetCompilerFilter, boolean force,
9481                boolean bootComplete) {
9482        PackageParser.Package p;
9483        synchronized (mPackages) {
9484            p = mPackages.get(packageName);
9485            if (p == null) {
9486                // Package could not be found. Report failure.
9487                return PackageDexOptimizer.DEX_OPT_FAILED;
9488            }
9489            mPackageUsage.maybeWriteAsync(mPackages);
9490            mCompilerStats.maybeWriteAsync();
9491        }
9492        long callingId = Binder.clearCallingIdentity();
9493        try {
9494            synchronized (mInstallLock) {
9495                return performDexOptInternalWithDependenciesLI(p, checkProfiles,
9496                        targetCompilerFilter, force, bootComplete);
9497            }
9498        } finally {
9499            Binder.restoreCallingIdentity(callingId);
9500        }
9501    }
9502
9503    public ArraySet<String> getOptimizablePackages() {
9504        ArraySet<String> pkgs = new ArraySet<String>();
9505        synchronized (mPackages) {
9506            for (PackageParser.Package p : mPackages.values()) {
9507                if (PackageDexOptimizer.canOptimizePackage(p)) {
9508                    pkgs.add(p.packageName);
9509                }
9510            }
9511        }
9512        return pkgs;
9513    }
9514
9515    private int performDexOptInternalWithDependenciesLI(PackageParser.Package p,
9516            boolean checkProfiles, String targetCompilerFilter,
9517            boolean force, boolean bootComplete) {
9518        // Select the dex optimizer based on the force parameter.
9519        // Note: The force option is rarely used (cmdline input for testing, mostly), so it's OK to
9520        //       allocate an object here.
9521        PackageDexOptimizer pdo = force
9522                ? new PackageDexOptimizer.ForcedUpdatePackageDexOptimizer(mPackageDexOptimizer)
9523                : mPackageDexOptimizer;
9524
9525        // Dexopt all dependencies first. Note: we ignore the return value and march on
9526        // on errors.
9527        // Note that we are going to call performDexOpt on those libraries as many times as
9528        // they are referenced in packages. When we do a batch of performDexOpt (for example
9529        // at boot, or background job), the passed 'targetCompilerFilter' stays the same,
9530        // and the first package that uses the library will dexopt it. The
9531        // others will see that the compiled code for the library is up to date.
9532        Collection<PackageParser.Package> deps = findSharedNonSystemLibraries(p);
9533        final String[] instructionSets = getAppDexInstructionSets(p.applicationInfo);
9534        if (!deps.isEmpty()) {
9535            for (PackageParser.Package depPackage : deps) {
9536                // TODO: Analyze and investigate if we (should) profile libraries.
9537                pdo.performDexOpt(depPackage, null /* sharedLibraries */, instructionSets,
9538                        false /* checkProfiles */,
9539                        targetCompilerFilter,
9540                        getOrCreateCompilerPackageStats(depPackage),
9541                        true /* isUsedByOtherApps */,
9542                        bootComplete);
9543            }
9544        }
9545        return pdo.performDexOpt(p, p.usesLibraryFiles, instructionSets, checkProfiles,
9546                targetCompilerFilter, getOrCreateCompilerPackageStats(p),
9547                mDexManager.isUsedByOtherApps(p.packageName), bootComplete);
9548    }
9549
9550    // Performs dexopt on the used secondary dex files belonging to the given package.
9551    // Returns true if all dex files were process successfully (which could mean either dexopt or
9552    // skip). Returns false if any of the files caused errors.
9553    @Override
9554    public boolean performDexOptSecondary(String packageName, String compilerFilter,
9555            boolean force) {
9556        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
9557            return false;
9558        } else if (isInstantApp(packageName, UserHandle.getCallingUserId())) {
9559            return false;
9560        }
9561        mDexManager.reconcileSecondaryDexFiles(packageName);
9562        return mDexManager.dexoptSecondaryDex(packageName, compilerFilter, force);
9563    }
9564
9565    public boolean performDexOptSecondary(String packageName, int compileReason,
9566            boolean force) {
9567        return mDexManager.dexoptSecondaryDex(packageName, compileReason, force);
9568    }
9569
9570    /**
9571     * Reconcile the information we have about the secondary dex files belonging to
9572     * {@code packagName} and the actual dex files. For all dex files that were
9573     * deleted, update the internal records and delete the generated oat files.
9574     */
9575    @Override
9576    public void reconcileSecondaryDexFiles(String packageName) {
9577        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
9578            return;
9579        } else if (isInstantApp(packageName, UserHandle.getCallingUserId())) {
9580            return;
9581        }
9582        mDexManager.reconcileSecondaryDexFiles(packageName);
9583    }
9584
9585    // TODO(calin): this is only needed for BackgroundDexOptService. Find a cleaner way to inject
9586    // a reference there.
9587    /*package*/ DexManager getDexManager() {
9588        return mDexManager;
9589    }
9590
9591    /**
9592     * Execute the background dexopt job immediately.
9593     */
9594    @Override
9595    public boolean runBackgroundDexoptJob() {
9596        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
9597            return false;
9598        }
9599        return BackgroundDexOptService.runIdleOptimizationsNow(this, mContext);
9600    }
9601
9602    List<PackageParser.Package> findSharedNonSystemLibraries(PackageParser.Package p) {
9603        if (p.usesLibraries != null || p.usesOptionalLibraries != null
9604                || p.usesStaticLibraries != null) {
9605            ArrayList<PackageParser.Package> retValue = new ArrayList<>();
9606            Set<String> collectedNames = new HashSet<>();
9607            findSharedNonSystemLibrariesRecursive(p, retValue, collectedNames);
9608
9609            retValue.remove(p);
9610
9611            return retValue;
9612        } else {
9613            return Collections.emptyList();
9614        }
9615    }
9616
9617    private void findSharedNonSystemLibrariesRecursive(PackageParser.Package p,
9618            ArrayList<PackageParser.Package> collected, Set<String> collectedNames) {
9619        if (!collectedNames.contains(p.packageName)) {
9620            collectedNames.add(p.packageName);
9621            collected.add(p);
9622
9623            if (p.usesLibraries != null) {
9624                findSharedNonSystemLibrariesRecursive(p.usesLibraries,
9625                        null, collected, collectedNames);
9626            }
9627            if (p.usesOptionalLibraries != null) {
9628                findSharedNonSystemLibrariesRecursive(p.usesOptionalLibraries,
9629                        null, collected, collectedNames);
9630            }
9631            if (p.usesStaticLibraries != null) {
9632                findSharedNonSystemLibrariesRecursive(p.usesStaticLibraries,
9633                        p.usesStaticLibrariesVersions, collected, collectedNames);
9634            }
9635        }
9636    }
9637
9638    private void findSharedNonSystemLibrariesRecursive(ArrayList<String> libs, int[] versions,
9639            ArrayList<PackageParser.Package> collected, Set<String> collectedNames) {
9640        final int libNameCount = libs.size();
9641        for (int i = 0; i < libNameCount; i++) {
9642            String libName = libs.get(i);
9643            int version = (versions != null && versions.length == libNameCount)
9644                    ? versions[i] : PackageManager.VERSION_CODE_HIGHEST;
9645            PackageParser.Package libPkg = findSharedNonSystemLibrary(libName, version);
9646            if (libPkg != null) {
9647                findSharedNonSystemLibrariesRecursive(libPkg, collected, collectedNames);
9648            }
9649        }
9650    }
9651
9652    private PackageParser.Package findSharedNonSystemLibrary(String name, int version) {
9653        synchronized (mPackages) {
9654            SharedLibraryEntry libEntry = getSharedLibraryEntryLPr(name, version);
9655            if (libEntry != null) {
9656                return mPackages.get(libEntry.apk);
9657            }
9658            return null;
9659        }
9660    }
9661
9662    private SharedLibraryEntry getSharedLibraryEntryLPr(String name, int version) {
9663        SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(name);
9664        if (versionedLib == null) {
9665            return null;
9666        }
9667        return versionedLib.get(version);
9668    }
9669
9670    private SharedLibraryEntry getLatestSharedLibraVersionLPr(PackageParser.Package pkg) {
9671        SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(
9672                pkg.staticSharedLibName);
9673        if (versionedLib == null) {
9674            return null;
9675        }
9676        int previousLibVersion = -1;
9677        final int versionCount = versionedLib.size();
9678        for (int i = 0; i < versionCount; i++) {
9679            final int libVersion = versionedLib.keyAt(i);
9680            if (libVersion < pkg.staticSharedLibVersion) {
9681                previousLibVersion = Math.max(previousLibVersion, libVersion);
9682            }
9683        }
9684        if (previousLibVersion >= 0) {
9685            return versionedLib.get(previousLibVersion);
9686        }
9687        return null;
9688    }
9689
9690    public void shutdown() {
9691        mPackageUsage.writeNow(mPackages);
9692        mCompilerStats.writeNow();
9693    }
9694
9695    @Override
9696    public void dumpProfiles(String packageName) {
9697        PackageParser.Package pkg;
9698        synchronized (mPackages) {
9699            pkg = mPackages.get(packageName);
9700            if (pkg == null) {
9701                throw new IllegalArgumentException("Unknown package: " + packageName);
9702            }
9703        }
9704        /* Only the shell, root, or the app user should be able to dump profiles. */
9705        int callingUid = Binder.getCallingUid();
9706        if (callingUid != Process.SHELL_UID &&
9707            callingUid != Process.ROOT_UID &&
9708            callingUid != pkg.applicationInfo.uid) {
9709            throw new SecurityException("dumpProfiles");
9710        }
9711
9712        synchronized (mInstallLock) {
9713            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dump profiles");
9714            final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid);
9715            try {
9716                List<String> allCodePaths = pkg.getAllCodePathsExcludingResourceOnly();
9717                String codePaths = TextUtils.join(";", allCodePaths);
9718                mInstaller.dumpProfiles(sharedGid, packageName, codePaths);
9719            } catch (InstallerException e) {
9720                Slog.w(TAG, "Failed to dump profiles", e);
9721            }
9722            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
9723        }
9724    }
9725
9726    @Override
9727    public void forceDexOpt(String packageName) {
9728        enforceSystemOrRoot("forceDexOpt");
9729
9730        PackageParser.Package pkg;
9731        synchronized (mPackages) {
9732            pkg = mPackages.get(packageName);
9733            if (pkg == null) {
9734                throw new IllegalArgumentException("Unknown package: " + packageName);
9735            }
9736        }
9737
9738        synchronized (mInstallLock) {
9739            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt");
9740
9741            // Whoever is calling forceDexOpt wants a compiled package.
9742            // Don't use profiles since that may cause compilation to be skipped.
9743            final int res = performDexOptInternalWithDependenciesLI(pkg,
9744                    false /* checkProfiles */, getDefaultCompilerFilter(),
9745                    true /* force */,
9746                    true /* bootComplete */);
9747
9748            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
9749            if (res != PackageDexOptimizer.DEX_OPT_PERFORMED) {
9750                throw new IllegalStateException("Failed to dexopt: " + res);
9751            }
9752        }
9753    }
9754
9755    private boolean verifyPackageUpdateLPr(PackageSetting oldPkg, PackageParser.Package newPkg) {
9756        if ((oldPkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) {
9757            Slog.w(TAG, "Unable to update from " + oldPkg.name
9758                    + " to " + newPkg.packageName
9759                    + ": old package not in system partition");
9760            return false;
9761        } else if (mPackages.get(oldPkg.name) != null) {
9762            Slog.w(TAG, "Unable to update from " + oldPkg.name
9763                    + " to " + newPkg.packageName
9764                    + ": old package still exists");
9765            return false;
9766        }
9767        return true;
9768    }
9769
9770    void removeCodePathLI(File codePath) {
9771        if (codePath.isDirectory()) {
9772            try {
9773                mInstaller.rmPackageDir(codePath.getAbsolutePath());
9774            } catch (InstallerException e) {
9775                Slog.w(TAG, "Failed to remove code path", e);
9776            }
9777        } else {
9778            codePath.delete();
9779        }
9780    }
9781
9782    private int[] resolveUserIds(int userId) {
9783        return (userId == UserHandle.USER_ALL) ? sUserManager.getUserIds() : new int[] { userId };
9784    }
9785
9786    private void clearAppDataLIF(PackageParser.Package pkg, int userId, int flags) {
9787        if (pkg == null) {
9788            Slog.wtf(TAG, "Package was null!", new Throwable());
9789            return;
9790        }
9791        clearAppDataLeafLIF(pkg, userId, flags);
9792        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
9793        for (int i = 0; i < childCount; i++) {
9794            clearAppDataLeafLIF(pkg.childPackages.get(i), userId, flags);
9795        }
9796    }
9797
9798    private void clearAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) {
9799        final PackageSetting ps;
9800        synchronized (mPackages) {
9801            ps = mSettings.mPackages.get(pkg.packageName);
9802        }
9803        for (int realUserId : resolveUserIds(userId)) {
9804            final long ceDataInode = (ps != null) ? ps.getCeDataInode(realUserId) : 0;
9805            try {
9806                mInstaller.clearAppData(pkg.volumeUuid, pkg.packageName, realUserId, flags,
9807                        ceDataInode);
9808            } catch (InstallerException e) {
9809                Slog.w(TAG, String.valueOf(e));
9810            }
9811        }
9812    }
9813
9814    private void destroyAppDataLIF(PackageParser.Package pkg, int userId, int flags) {
9815        if (pkg == null) {
9816            Slog.wtf(TAG, "Package was null!", new Throwable());
9817            return;
9818        }
9819        destroyAppDataLeafLIF(pkg, userId, flags);
9820        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
9821        for (int i = 0; i < childCount; i++) {
9822            destroyAppDataLeafLIF(pkg.childPackages.get(i), userId, flags);
9823        }
9824    }
9825
9826    private void destroyAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) {
9827        final PackageSetting ps;
9828        synchronized (mPackages) {
9829            ps = mSettings.mPackages.get(pkg.packageName);
9830        }
9831        for (int realUserId : resolveUserIds(userId)) {
9832            final long ceDataInode = (ps != null) ? ps.getCeDataInode(realUserId) : 0;
9833            try {
9834                mInstaller.destroyAppData(pkg.volumeUuid, pkg.packageName, realUserId, flags,
9835                        ceDataInode);
9836            } catch (InstallerException e) {
9837                Slog.w(TAG, String.valueOf(e));
9838            }
9839            mDexManager.notifyPackageDataDestroyed(pkg.packageName, userId);
9840        }
9841    }
9842
9843    private void destroyAppProfilesLIF(PackageParser.Package pkg, int userId) {
9844        if (pkg == null) {
9845            Slog.wtf(TAG, "Package was null!", new Throwable());
9846            return;
9847        }
9848        destroyAppProfilesLeafLIF(pkg);
9849        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
9850        for (int i = 0; i < childCount; i++) {
9851            destroyAppProfilesLeafLIF(pkg.childPackages.get(i));
9852        }
9853    }
9854
9855    private void destroyAppProfilesLeafLIF(PackageParser.Package pkg) {
9856        try {
9857            mInstaller.destroyAppProfiles(pkg.packageName);
9858        } catch (InstallerException e) {
9859            Slog.w(TAG, String.valueOf(e));
9860        }
9861    }
9862
9863    private void clearAppProfilesLIF(PackageParser.Package pkg, int userId) {
9864        if (pkg == null) {
9865            Slog.wtf(TAG, "Package was null!", new Throwable());
9866            return;
9867        }
9868        clearAppProfilesLeafLIF(pkg);
9869        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
9870        for (int i = 0; i < childCount; i++) {
9871            clearAppProfilesLeafLIF(pkg.childPackages.get(i));
9872        }
9873    }
9874
9875    private void clearAppProfilesLeafLIF(PackageParser.Package pkg) {
9876        try {
9877            mInstaller.clearAppProfiles(pkg.packageName);
9878        } catch (InstallerException e) {
9879            Slog.w(TAG, String.valueOf(e));
9880        }
9881    }
9882
9883    private void setInstallAndUpdateTime(PackageParser.Package pkg, long firstInstallTime,
9884            long lastUpdateTime) {
9885        // Set parent install/update time
9886        PackageSetting ps = (PackageSetting) pkg.mExtras;
9887        if (ps != null) {
9888            ps.firstInstallTime = firstInstallTime;
9889            ps.lastUpdateTime = lastUpdateTime;
9890        }
9891        // Set children install/update time
9892        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
9893        for (int i = 0; i < childCount; i++) {
9894            PackageParser.Package childPkg = pkg.childPackages.get(i);
9895            ps = (PackageSetting) childPkg.mExtras;
9896            if (ps != null) {
9897                ps.firstInstallTime = firstInstallTime;
9898                ps.lastUpdateTime = lastUpdateTime;
9899            }
9900        }
9901    }
9902
9903    private void addSharedLibraryLPr(ArraySet<String> usesLibraryFiles, SharedLibraryEntry file,
9904            PackageParser.Package changingLib) {
9905        if (file.path != null) {
9906            usesLibraryFiles.add(file.path);
9907            return;
9908        }
9909        PackageParser.Package p = mPackages.get(file.apk);
9910        if (changingLib != null && changingLib.packageName.equals(file.apk)) {
9911            // If we are doing this while in the middle of updating a library apk,
9912            // then we need to make sure to use that new apk for determining the
9913            // dependencies here.  (We haven't yet finished committing the new apk
9914            // to the package manager state.)
9915            if (p == null || p.packageName.equals(changingLib.packageName)) {
9916                p = changingLib;
9917            }
9918        }
9919        if (p != null) {
9920            usesLibraryFiles.addAll(p.getAllCodePaths());
9921            if (p.usesLibraryFiles != null) {
9922                Collections.addAll(usesLibraryFiles, p.usesLibraryFiles);
9923            }
9924        }
9925    }
9926
9927    private void updateSharedLibrariesLPr(PackageParser.Package pkg,
9928            PackageParser.Package changingLib) throws PackageManagerException {
9929        if (pkg == null) {
9930            return;
9931        }
9932        ArraySet<String> usesLibraryFiles = null;
9933        if (pkg.usesLibraries != null) {
9934            usesLibraryFiles = addSharedLibrariesLPw(pkg.usesLibraries,
9935                    null, null, pkg.packageName, changingLib, true, null);
9936        }
9937        if (pkg.usesStaticLibraries != null) {
9938            usesLibraryFiles = addSharedLibrariesLPw(pkg.usesStaticLibraries,
9939                    pkg.usesStaticLibrariesVersions, pkg.usesStaticLibrariesCertDigests,
9940                    pkg.packageName, changingLib, true, usesLibraryFiles);
9941        }
9942        if (pkg.usesOptionalLibraries != null) {
9943            usesLibraryFiles = addSharedLibrariesLPw(pkg.usesOptionalLibraries,
9944                    null, null, pkg.packageName, changingLib, false, usesLibraryFiles);
9945        }
9946        if (!ArrayUtils.isEmpty(usesLibraryFiles)) {
9947            pkg.usesLibraryFiles = usesLibraryFiles.toArray(new String[usesLibraryFiles.size()]);
9948        } else {
9949            pkg.usesLibraryFiles = null;
9950        }
9951    }
9952
9953    private ArraySet<String> addSharedLibrariesLPw(@NonNull List<String> requestedLibraries,
9954            @Nullable int[] requiredVersions, @Nullable String[] requiredCertDigests,
9955            @NonNull String packageName, @Nullable PackageParser.Package changingLib,
9956            boolean required, @Nullable ArraySet<String> outUsedLibraries)
9957            throws PackageManagerException {
9958        final int libCount = requestedLibraries.size();
9959        for (int i = 0; i < libCount; i++) {
9960            final String libName = requestedLibraries.get(i);
9961            final int libVersion = requiredVersions != null ? requiredVersions[i]
9962                    : SharedLibraryInfo.VERSION_UNDEFINED;
9963            final SharedLibraryEntry libEntry = getSharedLibraryEntryLPr(libName, libVersion);
9964            if (libEntry == null) {
9965                if (required) {
9966                    throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY,
9967                            "Package " + packageName + " requires unavailable shared library "
9968                                    + libName + "; failing!");
9969                } else if (DEBUG_SHARED_LIBRARIES) {
9970                    Slog.i(TAG, "Package " + packageName
9971                            + " desires unavailable shared library "
9972                            + libName + "; ignoring!");
9973                }
9974            } else {
9975                if (requiredVersions != null && requiredCertDigests != null) {
9976                    if (libEntry.info.getVersion() != requiredVersions[i]) {
9977                        throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY,
9978                            "Package " + packageName + " requires unavailable static shared"
9979                                    + " library " + libName + " version "
9980                                    + libEntry.info.getVersion() + "; failing!");
9981                    }
9982
9983                    PackageParser.Package libPkg = mPackages.get(libEntry.apk);
9984                    if (libPkg == null) {
9985                        throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY,
9986                                "Package " + packageName + " requires unavailable static shared"
9987                                        + " library; failing!");
9988                    }
9989
9990                    String expectedCertDigest = requiredCertDigests[i];
9991                    String libCertDigest = PackageUtils.computeCertSha256Digest(
9992                                libPkg.mSignatures[0]);
9993                    if (!libCertDigest.equalsIgnoreCase(expectedCertDigest)) {
9994                        throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY,
9995                                "Package " + packageName + " requires differently signed" +
9996                                        " static shared library; failing!");
9997                    }
9998                }
9999
10000                if (outUsedLibraries == null) {
10001                    outUsedLibraries = new ArraySet<>();
10002                }
10003                addSharedLibraryLPr(outUsedLibraries, libEntry, changingLib);
10004            }
10005        }
10006        return outUsedLibraries;
10007    }
10008
10009    private static boolean hasString(List<String> list, List<String> which) {
10010        if (list == null) {
10011            return false;
10012        }
10013        for (int i=list.size()-1; i>=0; i--) {
10014            for (int j=which.size()-1; j>=0; j--) {
10015                if (which.get(j).equals(list.get(i))) {
10016                    return true;
10017                }
10018            }
10019        }
10020        return false;
10021    }
10022
10023    private ArrayList<PackageParser.Package> updateAllSharedLibrariesLPw(
10024            PackageParser.Package changingPkg) {
10025        ArrayList<PackageParser.Package> res = null;
10026        for (PackageParser.Package pkg : mPackages.values()) {
10027            if (changingPkg != null
10028                    && !hasString(pkg.usesLibraries, changingPkg.libraryNames)
10029                    && !hasString(pkg.usesOptionalLibraries, changingPkg.libraryNames)
10030                    && !ArrayUtils.contains(pkg.usesStaticLibraries,
10031                            changingPkg.staticSharedLibName)) {
10032                return null;
10033            }
10034            if (res == null) {
10035                res = new ArrayList<>();
10036            }
10037            res.add(pkg);
10038            try {
10039                updateSharedLibrariesLPr(pkg, changingPkg);
10040            } catch (PackageManagerException e) {
10041                // If a system app update or an app and a required lib missing we
10042                // delete the package and for updated system apps keep the data as
10043                // it is better for the user to reinstall than to be in an limbo
10044                // state. Also libs disappearing under an app should never happen
10045                // - just in case.
10046                if (!pkg.isSystemApp() || pkg.isUpdatedSystemApp()) {
10047                    final int flags = pkg.isUpdatedSystemApp()
10048                            ? PackageManager.DELETE_KEEP_DATA : 0;
10049                    deletePackageLIF(pkg.packageName, null, true, sUserManager.getUserIds(),
10050                            flags , null, true, null);
10051                }
10052                Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
10053            }
10054        }
10055        return res;
10056    }
10057
10058    /**
10059     * Derive the value of the {@code cpuAbiOverride} based on the provided
10060     * value and an optional stored value from the package settings.
10061     */
10062    private static String deriveAbiOverride(String abiOverride, PackageSetting settings) {
10063        String cpuAbiOverride = null;
10064
10065        if (NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(abiOverride)) {
10066            cpuAbiOverride = null;
10067        } else if (abiOverride != null) {
10068            cpuAbiOverride = abiOverride;
10069        } else if (settings != null) {
10070            cpuAbiOverride = settings.cpuAbiOverrideString;
10071        }
10072
10073        return cpuAbiOverride;
10074    }
10075
10076    private PackageParser.Package scanPackageTracedLI(PackageParser.Package pkg,
10077            final int policyFlags, int scanFlags, long currentTime, @Nullable UserHandle user)
10078                    throws PackageManagerException {
10079        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage");
10080        // If the package has children and this is the first dive in the function
10081        // we recursively scan the package with the SCAN_CHECK_ONLY flag set to see
10082        // whether all packages (parent and children) would be successfully scanned
10083        // before the actual scan since scanning mutates internal state and we want
10084        // to atomically install the package and its children.
10085        if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
10086            if (pkg.childPackages != null && pkg.childPackages.size() > 0) {
10087                scanFlags |= SCAN_CHECK_ONLY;
10088            }
10089        } else {
10090            scanFlags &= ~SCAN_CHECK_ONLY;
10091        }
10092
10093        final PackageParser.Package scannedPkg;
10094        try {
10095            // Scan the parent
10096            scannedPkg = scanPackageLI(pkg, policyFlags, scanFlags, currentTime, user);
10097            // Scan the children
10098            final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
10099            for (int i = 0; i < childCount; i++) {
10100                PackageParser.Package childPkg = pkg.childPackages.get(i);
10101                scanPackageLI(childPkg, policyFlags,
10102                        scanFlags, currentTime, user);
10103            }
10104        } finally {
10105            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
10106        }
10107
10108        if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
10109            return scanPackageTracedLI(pkg, policyFlags, scanFlags, currentTime, user);
10110        }
10111
10112        return scannedPkg;
10113    }
10114
10115    private PackageParser.Package scanPackageLI(PackageParser.Package pkg, final int policyFlags,
10116            int scanFlags, long currentTime, @Nullable UserHandle user)
10117                    throws PackageManagerException {
10118        boolean success = false;
10119        try {
10120            final PackageParser.Package res = scanPackageDirtyLI(pkg, policyFlags, scanFlags,
10121                    currentTime, user);
10122            success = true;
10123            return res;
10124        } finally {
10125            if (!success && (scanFlags & SCAN_DELETE_DATA_ON_FAILURES) != 0) {
10126                // DELETE_DATA_ON_FAILURES is only used by frozen paths
10127                destroyAppDataLIF(pkg, UserHandle.USER_ALL,
10128                        StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
10129                destroyAppProfilesLIF(pkg, UserHandle.USER_ALL);
10130            }
10131        }
10132    }
10133
10134    /**
10135     * Returns {@code true} if the given file contains code. Otherwise {@code false}.
10136     */
10137    private static boolean apkHasCode(String fileName) {
10138        StrictJarFile jarFile = null;
10139        try {
10140            jarFile = new StrictJarFile(fileName,
10141                    false /*verify*/, false /*signatureSchemeRollbackProtectionsEnforced*/);
10142            return jarFile.findEntry("classes.dex") != null;
10143        } catch (IOException ignore) {
10144        } finally {
10145            try {
10146                if (jarFile != null) {
10147                    jarFile.close();
10148                }
10149            } catch (IOException ignore) {}
10150        }
10151        return false;
10152    }
10153
10154    /**
10155     * Enforces code policy for the package. This ensures that if an APK has
10156     * declared hasCode="true" in its manifest that the APK actually contains
10157     * code.
10158     *
10159     * @throws PackageManagerException If bytecode could not be found when it should exist
10160     */
10161    private static void assertCodePolicy(PackageParser.Package pkg)
10162            throws PackageManagerException {
10163        final boolean shouldHaveCode =
10164                (pkg.applicationInfo.flags & ApplicationInfo.FLAG_HAS_CODE) != 0;
10165        if (shouldHaveCode && !apkHasCode(pkg.baseCodePath)) {
10166            throw new PackageManagerException(INSTALL_FAILED_INVALID_APK,
10167                    "Package " + pkg.baseCodePath + " code is missing");
10168        }
10169
10170        if (!ArrayUtils.isEmpty(pkg.splitCodePaths)) {
10171            for (int i = 0; i < pkg.splitCodePaths.length; i++) {
10172                final boolean splitShouldHaveCode =
10173                        (pkg.splitFlags[i] & ApplicationInfo.FLAG_HAS_CODE) != 0;
10174                if (splitShouldHaveCode && !apkHasCode(pkg.splitCodePaths[i])) {
10175                    throw new PackageManagerException(INSTALL_FAILED_INVALID_APK,
10176                            "Package " + pkg.splitCodePaths[i] + " code is missing");
10177                }
10178            }
10179        }
10180    }
10181
10182    private PackageParser.Package scanPackageDirtyLI(PackageParser.Package pkg,
10183            final int policyFlags, final int scanFlags, long currentTime, @Nullable UserHandle user)
10184                    throws PackageManagerException {
10185        if (DEBUG_PACKAGE_SCANNING) {
10186            if ((policyFlags & PackageParser.PARSE_CHATTY) != 0)
10187                Log.d(TAG, "Scanning package " + pkg.packageName);
10188        }
10189
10190        applyPolicy(pkg, policyFlags);
10191
10192        assertPackageIsValid(pkg, policyFlags, scanFlags);
10193
10194        // Initialize package source and resource directories
10195        final File scanFile = new File(pkg.codePath);
10196        final File destCodeFile = new File(pkg.applicationInfo.getCodePath());
10197        final File destResourceFile = new File(pkg.applicationInfo.getResourcePath());
10198
10199        SharedUserSetting suid = null;
10200        PackageSetting pkgSetting = null;
10201
10202        // Getting the package setting may have a side-effect, so if we
10203        // are only checking if scan would succeed, stash a copy of the
10204        // old setting to restore at the end.
10205        PackageSetting nonMutatedPs = null;
10206
10207        // We keep references to the derived CPU Abis from settings in oder to reuse
10208        // them in the case where we're not upgrading or booting for the first time.
10209        String primaryCpuAbiFromSettings = null;
10210        String secondaryCpuAbiFromSettings = null;
10211
10212        // writer
10213        synchronized (mPackages) {
10214            if (pkg.mSharedUserId != null) {
10215                // SIDE EFFECTS; may potentially allocate a new shared user
10216                suid = mSettings.getSharedUserLPw(
10217                        pkg.mSharedUserId, 0 /*pkgFlags*/, 0 /*pkgPrivateFlags*/, true /*create*/);
10218                if (DEBUG_PACKAGE_SCANNING) {
10219                    if ((policyFlags & PackageParser.PARSE_CHATTY) != 0)
10220                        Log.d(TAG, "Shared UserID " + pkg.mSharedUserId + " (uid=" + suid.userId
10221                                + "): packages=" + suid.packages);
10222                }
10223            }
10224
10225            // Check if we are renaming from an original package name.
10226            PackageSetting origPackage = null;
10227            String realName = null;
10228            if (pkg.mOriginalPackages != null) {
10229                // This package may need to be renamed to a previously
10230                // installed name.  Let's check on that...
10231                final String renamed = mSettings.getRenamedPackageLPr(pkg.mRealPackage);
10232                if (pkg.mOriginalPackages.contains(renamed)) {
10233                    // This package had originally been installed as the
10234                    // original name, and we have already taken care of
10235                    // transitioning to the new one.  Just update the new
10236                    // one to continue using the old name.
10237                    realName = pkg.mRealPackage;
10238                    if (!pkg.packageName.equals(renamed)) {
10239                        // Callers into this function may have already taken
10240                        // care of renaming the package; only do it here if
10241                        // it is not already done.
10242                        pkg.setPackageName(renamed);
10243                    }
10244                } else {
10245                    for (int i=pkg.mOriginalPackages.size()-1; i>=0; i--) {
10246                        if ((origPackage = mSettings.getPackageLPr(
10247                                pkg.mOriginalPackages.get(i))) != null) {
10248                            // We do have the package already installed under its
10249                            // original name...  should we use it?
10250                            if (!verifyPackageUpdateLPr(origPackage, pkg)) {
10251                                // New package is not compatible with original.
10252                                origPackage = null;
10253                                continue;
10254                            } else if (origPackage.sharedUser != null) {
10255                                // Make sure uid is compatible between packages.
10256                                if (!origPackage.sharedUser.name.equals(pkg.mSharedUserId)) {
10257                                    Slog.w(TAG, "Unable to migrate data from " + origPackage.name
10258                                            + " to " + pkg.packageName + ": old uid "
10259                                            + origPackage.sharedUser.name
10260                                            + " differs from " + pkg.mSharedUserId);
10261                                    origPackage = null;
10262                                    continue;
10263                                }
10264                                // TODO: Add case when shared user id is added [b/28144775]
10265                            } else {
10266                                if (DEBUG_UPGRADE) Log.v(TAG, "Renaming new package "
10267                                        + pkg.packageName + " to old name " + origPackage.name);
10268                            }
10269                            break;
10270                        }
10271                    }
10272                }
10273            }
10274
10275            if (mTransferedPackages.contains(pkg.packageName)) {
10276                Slog.w(TAG, "Package " + pkg.packageName
10277                        + " was transferred to another, but its .apk remains");
10278            }
10279
10280            // See comments in nonMutatedPs declaration
10281            if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
10282                PackageSetting foundPs = mSettings.getPackageLPr(pkg.packageName);
10283                if (foundPs != null) {
10284                    nonMutatedPs = new PackageSetting(foundPs);
10285                }
10286            }
10287
10288            if ((scanFlags & SCAN_FIRST_BOOT_OR_UPGRADE) == 0) {
10289                PackageSetting foundPs = mSettings.getPackageLPr(pkg.packageName);
10290                if (foundPs != null) {
10291                    primaryCpuAbiFromSettings = foundPs.primaryCpuAbiString;
10292                    secondaryCpuAbiFromSettings = foundPs.secondaryCpuAbiString;
10293                }
10294            }
10295
10296            pkgSetting = mSettings.getPackageLPr(pkg.packageName);
10297            if (pkgSetting != null && pkgSetting.sharedUser != suid) {
10298                PackageManagerService.reportSettingsProblem(Log.WARN,
10299                        "Package " + pkg.packageName + " shared user changed from "
10300                                + (pkgSetting.sharedUser != null
10301                                        ? pkgSetting.sharedUser.name : "<nothing>")
10302                                + " to "
10303                                + (suid != null ? suid.name : "<nothing>")
10304                                + "; replacing with new");
10305                pkgSetting = null;
10306            }
10307            final PackageSetting oldPkgSetting =
10308                    pkgSetting == null ? null : new PackageSetting(pkgSetting);
10309            final PackageSetting disabledPkgSetting =
10310                    mSettings.getDisabledSystemPkgLPr(pkg.packageName);
10311
10312            String[] usesStaticLibraries = null;
10313            if (pkg.usesStaticLibraries != null) {
10314                usesStaticLibraries = new String[pkg.usesStaticLibraries.size()];
10315                pkg.usesStaticLibraries.toArray(usesStaticLibraries);
10316            }
10317
10318            if (pkgSetting == null) {
10319                final String parentPackageName = (pkg.parentPackage != null)
10320                        ? pkg.parentPackage.packageName : null;
10321                final boolean instantApp = (scanFlags & SCAN_AS_INSTANT_APP) != 0;
10322                // REMOVE SharedUserSetting from method; update in a separate call
10323                pkgSetting = Settings.createNewSetting(pkg.packageName, origPackage,
10324                        disabledPkgSetting, realName, suid, destCodeFile, destResourceFile,
10325                        pkg.applicationInfo.nativeLibraryRootDir, pkg.applicationInfo.primaryCpuAbi,
10326                        pkg.applicationInfo.secondaryCpuAbi, pkg.mVersionCode,
10327                        pkg.applicationInfo.flags, pkg.applicationInfo.privateFlags, user,
10328                        true /*allowInstall*/, instantApp, parentPackageName,
10329                        pkg.getChildPackageNames(), UserManagerService.getInstance(),
10330                        usesStaticLibraries, pkg.usesStaticLibrariesVersions);
10331                // SIDE EFFECTS; updates system state; move elsewhere
10332                if (origPackage != null) {
10333                    mSettings.addRenamedPackageLPw(pkg.packageName, origPackage.name);
10334                }
10335                mSettings.addUserToSettingLPw(pkgSetting);
10336            } else {
10337                // REMOVE SharedUserSetting from method; update in a separate call.
10338                //
10339                // TODO(narayan): This update is bogus. nativeLibraryDir & primaryCpuAbi,
10340                // secondaryCpuAbi are not known at this point so we always update them
10341                // to null here, only to reset them at a later point.
10342                Settings.updatePackageSetting(pkgSetting, disabledPkgSetting, suid, destCodeFile,
10343                        pkg.applicationInfo.nativeLibraryDir, pkg.applicationInfo.primaryCpuAbi,
10344                        pkg.applicationInfo.secondaryCpuAbi, pkg.applicationInfo.flags,
10345                        pkg.applicationInfo.privateFlags, pkg.getChildPackageNames(),
10346                        UserManagerService.getInstance(), usesStaticLibraries,
10347                        pkg.usesStaticLibrariesVersions);
10348            }
10349            // SIDE EFFECTS; persists system state to files on disk; move elsewhere
10350            mSettings.writeUserRestrictionsLPw(pkgSetting, oldPkgSetting);
10351
10352            // SIDE EFFECTS; modifies system state; move elsewhere
10353            if (pkgSetting.origPackage != null) {
10354                // If we are first transitioning from an original package,
10355                // fix up the new package's name now.  We need to do this after
10356                // looking up the package under its new name, so getPackageLP
10357                // can take care of fiddling things correctly.
10358                pkg.setPackageName(origPackage.name);
10359
10360                // File a report about this.
10361                String msg = "New package " + pkgSetting.realName
10362                        + " renamed to replace old package " + pkgSetting.name;
10363                reportSettingsProblem(Log.WARN, msg);
10364
10365                // Make a note of it.
10366                if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
10367                    mTransferedPackages.add(origPackage.name);
10368                }
10369
10370                // No longer need to retain this.
10371                pkgSetting.origPackage = null;
10372            }
10373
10374            // SIDE EFFECTS; modifies system state; move elsewhere
10375            if ((scanFlags & SCAN_CHECK_ONLY) == 0 && realName != null) {
10376                // Make a note of it.
10377                mTransferedPackages.add(pkg.packageName);
10378            }
10379
10380            if (mSettings.isDisabledSystemPackageLPr(pkg.packageName)) {
10381                pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
10382            }
10383
10384            if ((scanFlags & SCAN_BOOTING) == 0
10385                    && (policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
10386                // Check all shared libraries and map to their actual file path.
10387                // We only do this here for apps not on a system dir, because those
10388                // are the only ones that can fail an install due to this.  We
10389                // will take care of the system apps by updating all of their
10390                // library paths after the scan is done. Also during the initial
10391                // scan don't update any libs as we do this wholesale after all
10392                // apps are scanned to avoid dependency based scanning.
10393                updateSharedLibrariesLPr(pkg, null);
10394            }
10395
10396            if (mFoundPolicyFile) {
10397                SELinuxMMAC.assignSeInfoValue(pkg);
10398            }
10399            pkg.applicationInfo.uid = pkgSetting.appId;
10400            pkg.mExtras = pkgSetting;
10401
10402
10403            // Static shared libs have same package with different versions where
10404            // we internally use a synthetic package name to allow multiple versions
10405            // of the same package, therefore we need to compare signatures against
10406            // the package setting for the latest library version.
10407            PackageSetting signatureCheckPs = pkgSetting;
10408            if (pkg.applicationInfo.isStaticSharedLibrary()) {
10409                SharedLibraryEntry libraryEntry = getLatestSharedLibraVersionLPr(pkg);
10410                if (libraryEntry != null) {
10411                    signatureCheckPs = mSettings.getPackageLPr(libraryEntry.apk);
10412                }
10413            }
10414
10415            if (shouldCheckUpgradeKeySetLP(signatureCheckPs, scanFlags)) {
10416                if (checkUpgradeKeySetLP(signatureCheckPs, pkg)) {
10417                    // We just determined the app is signed correctly, so bring
10418                    // over the latest parsed certs.
10419                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
10420                } else {
10421                    if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
10422                        throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
10423                                "Package " + pkg.packageName + " upgrade keys do not match the "
10424                                + "previously installed version");
10425                    } else {
10426                        pkgSetting.signatures.mSignatures = pkg.mSignatures;
10427                        String msg = "System package " + pkg.packageName
10428                                + " signature changed; retaining data.";
10429                        reportSettingsProblem(Log.WARN, msg);
10430                    }
10431                }
10432            } else {
10433                try {
10434                    // SIDE EFFECTS; compareSignaturesCompat() changes KeysetManagerService
10435                    verifySignaturesLP(signatureCheckPs, pkg);
10436                    // We just determined the app is signed correctly, so bring
10437                    // over the latest parsed certs.
10438                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
10439                } catch (PackageManagerException e) {
10440                    if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
10441                        throw e;
10442                    }
10443                    // The signature has changed, but this package is in the system
10444                    // image...  let's recover!
10445                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
10446                    // However...  if this package is part of a shared user, but it
10447                    // doesn't match the signature of the shared user, let's fail.
10448                    // What this means is that you can't change the signatures
10449                    // associated with an overall shared user, which doesn't seem all
10450                    // that unreasonable.
10451                    if (signatureCheckPs.sharedUser != null) {
10452                        if (compareSignatures(signatureCheckPs.sharedUser.signatures.mSignatures,
10453                                pkg.mSignatures) != PackageManager.SIGNATURE_MATCH) {
10454                            throw new PackageManagerException(
10455                                    INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES,
10456                                    "Signature mismatch for shared user: "
10457                                            + pkgSetting.sharedUser);
10458                        }
10459                    }
10460                    // File a report about this.
10461                    String msg = "System package " + pkg.packageName
10462                            + " signature changed; retaining data.";
10463                    reportSettingsProblem(Log.WARN, msg);
10464                }
10465            }
10466
10467            if ((scanFlags & SCAN_CHECK_ONLY) == 0 && pkg.mAdoptPermissions != null) {
10468                // This package wants to adopt ownership of permissions from
10469                // another package.
10470                for (int i = pkg.mAdoptPermissions.size() - 1; i >= 0; i--) {
10471                    final String origName = pkg.mAdoptPermissions.get(i);
10472                    final PackageSetting orig = mSettings.getPackageLPr(origName);
10473                    if (orig != null) {
10474                        if (verifyPackageUpdateLPr(orig, pkg)) {
10475                            Slog.i(TAG, "Adopting permissions from " + origName + " to "
10476                                    + pkg.packageName);
10477                            // SIDE EFFECTS; updates permissions system state; move elsewhere
10478                            mSettings.transferPermissionsLPw(origName, pkg.packageName);
10479                        }
10480                    }
10481                }
10482            }
10483        }
10484
10485        pkg.applicationInfo.processName = fixProcessName(
10486                pkg.applicationInfo.packageName,
10487                pkg.applicationInfo.processName);
10488
10489        if (pkg != mPlatformPackage) {
10490            // Get all of our default paths setup
10491            pkg.applicationInfo.initForUser(UserHandle.USER_SYSTEM);
10492        }
10493
10494        final String cpuAbiOverride = deriveAbiOverride(pkg.cpuAbiOverride, pkgSetting);
10495
10496        if ((scanFlags & SCAN_NEW_INSTALL) == 0) {
10497            if ((scanFlags & SCAN_FIRST_BOOT_OR_UPGRADE) != 0) {
10498                Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "derivePackageAbi");
10499                final boolean extractNativeLibs = !pkg.isLibrary();
10500                derivePackageAbi(pkg, scanFile, cpuAbiOverride, extractNativeLibs,
10501                        mAppLib32InstallDir);
10502                Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
10503
10504                // Some system apps still use directory structure for native libraries
10505                // in which case we might end up not detecting abi solely based on apk
10506                // structure. Try to detect abi based on directory structure.
10507                if (isSystemApp(pkg) && !pkg.isUpdatedSystemApp() &&
10508                        pkg.applicationInfo.primaryCpuAbi == null) {
10509                    setBundledAppAbisAndRoots(pkg, pkgSetting);
10510                    setNativeLibraryPaths(pkg, mAppLib32InstallDir);
10511                }
10512            } else {
10513                // This is not a first boot or an upgrade, don't bother deriving the
10514                // ABI during the scan. Instead, trust the value that was stored in the
10515                // package setting.
10516                pkg.applicationInfo.primaryCpuAbi = primaryCpuAbiFromSettings;
10517                pkg.applicationInfo.secondaryCpuAbi = secondaryCpuAbiFromSettings;
10518
10519                setNativeLibraryPaths(pkg, mAppLib32InstallDir);
10520
10521                if (DEBUG_ABI_SELECTION) {
10522                    Slog.i(TAG, "Using ABIS and native lib paths from settings : " +
10523                        pkg.packageName + " " + pkg.applicationInfo.primaryCpuAbi + ", " +
10524                        pkg.applicationInfo.secondaryCpuAbi);
10525                }
10526            }
10527        } else {
10528            if ((scanFlags & SCAN_MOVE) != 0) {
10529                // We haven't run dex-opt for this move (since we've moved the compiled output too)
10530                // but we already have this packages package info in the PackageSetting. We just
10531                // use that and derive the native library path based on the new codepath.
10532                pkg.applicationInfo.primaryCpuAbi = pkgSetting.primaryCpuAbiString;
10533                pkg.applicationInfo.secondaryCpuAbi = pkgSetting.secondaryCpuAbiString;
10534            }
10535
10536            // Set native library paths again. For moves, the path will be updated based on the
10537            // ABIs we've determined above. For non-moves, the path will be updated based on the
10538            // ABIs we determined during compilation, but the path will depend on the final
10539            // package path (after the rename away from the stage path).
10540            setNativeLibraryPaths(pkg, mAppLib32InstallDir);
10541        }
10542
10543        // This is a special case for the "system" package, where the ABI is
10544        // dictated by the zygote configuration (and init.rc). We should keep track
10545        // of this ABI so that we can deal with "normal" applications that run under
10546        // the same UID correctly.
10547        if (mPlatformPackage == pkg) {
10548            pkg.applicationInfo.primaryCpuAbi = VMRuntime.getRuntime().is64Bit() ?
10549                    Build.SUPPORTED_64_BIT_ABIS[0] : Build.SUPPORTED_32_BIT_ABIS[0];
10550        }
10551
10552        // If there's a mismatch between the abi-override in the package setting
10553        // and the abiOverride specified for the install. Warn about this because we
10554        // would've already compiled the app without taking the package setting into
10555        // account.
10556        if ((scanFlags & SCAN_NO_DEX) == 0 && (scanFlags & SCAN_NEW_INSTALL) != 0) {
10557            if (cpuAbiOverride == null && pkgSetting.cpuAbiOverrideString != null) {
10558                Slog.w(TAG, "Ignoring persisted ABI override " + cpuAbiOverride +
10559                        " for package " + pkg.packageName);
10560            }
10561        }
10562
10563        pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi;
10564        pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi;
10565        pkgSetting.cpuAbiOverrideString = cpuAbiOverride;
10566
10567        // Copy the derived override back to the parsed package, so that we can
10568        // update the package settings accordingly.
10569        pkg.cpuAbiOverride = cpuAbiOverride;
10570
10571        if (DEBUG_ABI_SELECTION) {
10572            Slog.d(TAG, "Resolved nativeLibraryRoot for " + pkg.applicationInfo.packageName
10573                    + " to root=" + pkg.applicationInfo.nativeLibraryRootDir + ", isa="
10574                    + pkg.applicationInfo.nativeLibraryRootRequiresIsa);
10575        }
10576
10577        // Push the derived path down into PackageSettings so we know what to
10578        // clean up at uninstall time.
10579        pkgSetting.legacyNativeLibraryPathString = pkg.applicationInfo.nativeLibraryRootDir;
10580
10581        if (DEBUG_ABI_SELECTION) {
10582            Log.d(TAG, "Abis for package[" + pkg.packageName + "] are" +
10583                    " primary=" + pkg.applicationInfo.primaryCpuAbi +
10584                    " secondary=" + pkg.applicationInfo.secondaryCpuAbi);
10585        }
10586
10587        // SIDE EFFECTS; removes DEX files from disk; move elsewhere
10588        if ((scanFlags & SCAN_BOOTING) == 0 && pkgSetting.sharedUser != null) {
10589            // We don't do this here during boot because we can do it all
10590            // at once after scanning all existing packages.
10591            //
10592            // We also do this *before* we perform dexopt on this package, so that
10593            // we can avoid redundant dexopts, and also to make sure we've got the
10594            // code and package path correct.
10595            adjustCpuAbisForSharedUserLPw(pkgSetting.sharedUser.packages, pkg);
10596        }
10597
10598        if (mFactoryTest && pkg.requestedPermissions.contains(
10599                android.Manifest.permission.FACTORY_TEST)) {
10600            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_FACTORY_TEST;
10601        }
10602
10603        if (isSystemApp(pkg)) {
10604            pkgSetting.isOrphaned = true;
10605        }
10606
10607        // Take care of first install / last update times.
10608        final long scanFileTime = getLastModifiedTime(pkg, scanFile);
10609        if (currentTime != 0) {
10610            if (pkgSetting.firstInstallTime == 0) {
10611                pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = currentTime;
10612            } else if ((scanFlags & SCAN_UPDATE_TIME) != 0) {
10613                pkgSetting.lastUpdateTime = currentTime;
10614            }
10615        } else if (pkgSetting.firstInstallTime == 0) {
10616            // We need *something*.  Take time time stamp of the file.
10617            pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = scanFileTime;
10618        } else if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0) {
10619            if (scanFileTime != pkgSetting.timeStamp) {
10620                // A package on the system image has changed; consider this
10621                // to be an update.
10622                pkgSetting.lastUpdateTime = scanFileTime;
10623            }
10624        }
10625        pkgSetting.setTimeStamp(scanFileTime);
10626
10627        if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
10628            if (nonMutatedPs != null) {
10629                synchronized (mPackages) {
10630                    mSettings.mPackages.put(nonMutatedPs.name, nonMutatedPs);
10631                }
10632            }
10633        } else {
10634            final int userId = user == null ? 0 : user.getIdentifier();
10635            // Modify state for the given package setting
10636            commitPackageSettings(pkg, pkgSetting, user, scanFlags,
10637                    (policyFlags & PackageParser.PARSE_CHATTY) != 0 /*chatty*/);
10638            if (pkgSetting.getInstantApp(userId)) {
10639                mInstantAppRegistry.addInstantAppLPw(userId, pkgSetting.appId);
10640            }
10641        }
10642        return pkg;
10643    }
10644
10645    /**
10646     * Applies policy to the parsed package based upon the given policy flags.
10647     * Ensures the package is in a good state.
10648     * <p>
10649     * Implementation detail: This method must NOT have any side effect. It would
10650     * ideally be static, but, it requires locks to read system state.
10651     */
10652    private void applyPolicy(PackageParser.Package pkg, int policyFlags) {
10653        if ((policyFlags&PackageParser.PARSE_IS_SYSTEM) != 0) {
10654            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_SYSTEM;
10655            if (pkg.applicationInfo.isDirectBootAware()) {
10656                // we're direct boot aware; set for all components
10657                for (PackageParser.Service s : pkg.services) {
10658                    s.info.encryptionAware = s.info.directBootAware = true;
10659                }
10660                for (PackageParser.Provider p : pkg.providers) {
10661                    p.info.encryptionAware = p.info.directBootAware = true;
10662                }
10663                for (PackageParser.Activity a : pkg.activities) {
10664                    a.info.encryptionAware = a.info.directBootAware = true;
10665                }
10666                for (PackageParser.Activity r : pkg.receivers) {
10667                    r.info.encryptionAware = r.info.directBootAware = true;
10668                }
10669            }
10670        } else {
10671            // Only allow system apps to be flagged as core apps.
10672            pkg.coreApp = false;
10673            // clear flags not applicable to regular apps
10674            pkg.applicationInfo.privateFlags &=
10675                    ~ApplicationInfo.PRIVATE_FLAG_DEFAULT_TO_DEVICE_PROTECTED_STORAGE;
10676            pkg.applicationInfo.privateFlags &=
10677                    ~ApplicationInfo.PRIVATE_FLAG_DIRECT_BOOT_AWARE;
10678        }
10679        pkg.mTrustedOverlay = (policyFlags&PackageParser.PARSE_TRUSTED_OVERLAY) != 0;
10680
10681        if ((policyFlags&PackageParser.PARSE_IS_PRIVILEGED) != 0) {
10682            pkg.applicationInfo.privateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
10683        }
10684
10685        if (!isSystemApp(pkg)) {
10686            // Only system apps can use these features.
10687            pkg.mOriginalPackages = null;
10688            pkg.mRealPackage = null;
10689            pkg.mAdoptPermissions = null;
10690        }
10691    }
10692
10693    /**
10694     * Asserts the parsed package is valid according to the given policy. If the
10695     * package is invalid, for whatever reason, throws {@link PackageManagerException}.
10696     * <p>
10697     * Implementation detail: This method must NOT have any side effects. It would
10698     * ideally be static, but, it requires locks to read system state.
10699     *
10700     * @throws PackageManagerException If the package fails any of the validation checks
10701     */
10702    private void assertPackageIsValid(PackageParser.Package pkg, int policyFlags, int scanFlags)
10703            throws PackageManagerException {
10704        if ((policyFlags & PackageParser.PARSE_ENFORCE_CODE) != 0) {
10705            assertCodePolicy(pkg);
10706        }
10707
10708        if (pkg.applicationInfo.getCodePath() == null ||
10709                pkg.applicationInfo.getResourcePath() == null) {
10710            // Bail out. The resource and code paths haven't been set.
10711            throw new PackageManagerException(INSTALL_FAILED_INVALID_APK,
10712                    "Code and resource paths haven't been set correctly");
10713        }
10714
10715        // Make sure we're not adding any bogus keyset info
10716        KeySetManagerService ksms = mSettings.mKeySetManagerService;
10717        ksms.assertScannedPackageValid(pkg);
10718
10719        synchronized (mPackages) {
10720            // The special "android" package can only be defined once
10721            if (pkg.packageName.equals("android")) {
10722                if (mAndroidApplication != null) {
10723                    Slog.w(TAG, "*************************************************");
10724                    Slog.w(TAG, "Core android package being redefined.  Skipping.");
10725                    Slog.w(TAG, " codePath=" + pkg.codePath);
10726                    Slog.w(TAG, "*************************************************");
10727                    throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE,
10728                            "Core android package being redefined.  Skipping.");
10729                }
10730            }
10731
10732            // A package name must be unique; don't allow duplicates
10733            if (mPackages.containsKey(pkg.packageName)) {
10734                throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE,
10735                        "Application package " + pkg.packageName
10736                        + " already installed.  Skipping duplicate.");
10737            }
10738
10739            if (pkg.applicationInfo.isStaticSharedLibrary()) {
10740                // Static libs have a synthetic package name containing the version
10741                // but we still want the base name to be unique.
10742                if (mPackages.containsKey(pkg.manifestPackageName)) {
10743                    throw new PackageManagerException(
10744                            "Duplicate static shared lib provider package");
10745                }
10746
10747                // Static shared libraries should have at least O target SDK
10748                if (pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.O) {
10749                    throw new PackageManagerException(
10750                            "Packages declaring static-shared libs must target O SDK or higher");
10751                }
10752
10753                // Package declaring static a shared lib cannot be instant apps
10754                if ((scanFlags & SCAN_AS_INSTANT_APP) != 0) {
10755                    throw new PackageManagerException(
10756                            "Packages declaring static-shared libs cannot be instant apps");
10757                }
10758
10759                // Package declaring static a shared lib cannot be renamed since the package
10760                // name is synthetic and apps can't code around package manager internals.
10761                if (!ArrayUtils.isEmpty(pkg.mOriginalPackages)) {
10762                    throw new PackageManagerException(
10763                            "Packages declaring static-shared libs cannot be renamed");
10764                }
10765
10766                // Package declaring static a shared lib cannot declare child packages
10767                if (!ArrayUtils.isEmpty(pkg.childPackages)) {
10768                    throw new PackageManagerException(
10769                            "Packages declaring static-shared libs cannot have child packages");
10770                }
10771
10772                // Package declaring static a shared lib cannot declare dynamic libs
10773                if (!ArrayUtils.isEmpty(pkg.libraryNames)) {
10774                    throw new PackageManagerException(
10775                            "Packages declaring static-shared libs cannot declare dynamic libs");
10776                }
10777
10778                // Package declaring static a shared lib cannot declare shared users
10779                if (pkg.mSharedUserId != null) {
10780                    throw new PackageManagerException(
10781                            "Packages declaring static-shared libs cannot declare shared users");
10782                }
10783
10784                // Static shared libs cannot declare activities
10785                if (!pkg.activities.isEmpty()) {
10786                    throw new PackageManagerException(
10787                            "Static shared libs cannot declare activities");
10788                }
10789
10790                // Static shared libs cannot declare services
10791                if (!pkg.services.isEmpty()) {
10792                    throw new PackageManagerException(
10793                            "Static shared libs cannot declare services");
10794                }
10795
10796                // Static shared libs cannot declare providers
10797                if (!pkg.providers.isEmpty()) {
10798                    throw new PackageManagerException(
10799                            "Static shared libs cannot declare content providers");
10800                }
10801
10802                // Static shared libs cannot declare receivers
10803                if (!pkg.receivers.isEmpty()) {
10804                    throw new PackageManagerException(
10805                            "Static shared libs cannot declare broadcast receivers");
10806                }
10807
10808                // Static shared libs cannot declare permission groups
10809                if (!pkg.permissionGroups.isEmpty()) {
10810                    throw new PackageManagerException(
10811                            "Static shared libs cannot declare permission groups");
10812                }
10813
10814                // Static shared libs cannot declare permissions
10815                if (!pkg.permissions.isEmpty()) {
10816                    throw new PackageManagerException(
10817                            "Static shared libs cannot declare permissions");
10818                }
10819
10820                // Static shared libs cannot declare protected broadcasts
10821                if (pkg.protectedBroadcasts != null) {
10822                    throw new PackageManagerException(
10823                            "Static shared libs cannot declare protected broadcasts");
10824                }
10825
10826                // Static shared libs cannot be overlay targets
10827                if (pkg.mOverlayTarget != null) {
10828                    throw new PackageManagerException(
10829                            "Static shared libs cannot be overlay targets");
10830                }
10831
10832                // The version codes must be ordered as lib versions
10833                int minVersionCode = Integer.MIN_VALUE;
10834                int maxVersionCode = Integer.MAX_VALUE;
10835
10836                SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(
10837                        pkg.staticSharedLibName);
10838                if (versionedLib != null) {
10839                    final int versionCount = versionedLib.size();
10840                    for (int i = 0; i < versionCount; i++) {
10841                        SharedLibraryInfo libInfo = versionedLib.valueAt(i).info;
10842                        final int libVersionCode = libInfo.getDeclaringPackage()
10843                                .getVersionCode();
10844                        if (libInfo.getVersion() <  pkg.staticSharedLibVersion) {
10845                            minVersionCode = Math.max(minVersionCode, libVersionCode + 1);
10846                        } else if (libInfo.getVersion() >  pkg.staticSharedLibVersion) {
10847                            maxVersionCode = Math.min(maxVersionCode, libVersionCode - 1);
10848                        } else {
10849                            minVersionCode = maxVersionCode = libVersionCode;
10850                            break;
10851                        }
10852                    }
10853                }
10854                if (pkg.mVersionCode < minVersionCode || pkg.mVersionCode > maxVersionCode) {
10855                    throw new PackageManagerException("Static shared"
10856                            + " lib version codes must be ordered as lib versions");
10857                }
10858            }
10859
10860            // Only privileged apps and updated privileged apps can add child packages.
10861            if (pkg.childPackages != null && !pkg.childPackages.isEmpty()) {
10862                if ((policyFlags & PARSE_IS_PRIVILEGED) == 0) {
10863                    throw new PackageManagerException("Only privileged apps can add child "
10864                            + "packages. Ignoring package " + pkg.packageName);
10865                }
10866                final int childCount = pkg.childPackages.size();
10867                for (int i = 0; i < childCount; i++) {
10868                    PackageParser.Package childPkg = pkg.childPackages.get(i);
10869                    if (mSettings.hasOtherDisabledSystemPkgWithChildLPr(pkg.packageName,
10870                            childPkg.packageName)) {
10871                        throw new PackageManagerException("Can't override child of "
10872                                + "another disabled app. Ignoring package " + pkg.packageName);
10873                    }
10874                }
10875            }
10876
10877            // If we're only installing presumed-existing packages, require that the
10878            // scanned APK is both already known and at the path previously established
10879            // for it.  Previously unknown packages we pick up normally, but if we have an
10880            // a priori expectation about this package's install presence, enforce it.
10881            // With a singular exception for new system packages. When an OTA contains
10882            // a new system package, we allow the codepath to change from a system location
10883            // to the user-installed location. If we don't allow this change, any newer,
10884            // user-installed version of the application will be ignored.
10885            if ((scanFlags & SCAN_REQUIRE_KNOWN) != 0) {
10886                if (mExpectingBetter.containsKey(pkg.packageName)) {
10887                    logCriticalInfo(Log.WARN,
10888                            "Relax SCAN_REQUIRE_KNOWN requirement for package " + pkg.packageName);
10889                } else {
10890                    PackageSetting known = mSettings.getPackageLPr(pkg.packageName);
10891                    if (known != null) {
10892                        if (DEBUG_PACKAGE_SCANNING) {
10893                            Log.d(TAG, "Examining " + pkg.codePath
10894                                    + " and requiring known paths " + known.codePathString
10895                                    + " & " + known.resourcePathString);
10896                        }
10897                        if (!pkg.applicationInfo.getCodePath().equals(known.codePathString)
10898                                || !pkg.applicationInfo.getResourcePath().equals(
10899                                        known.resourcePathString)) {
10900                            throw new PackageManagerException(INSTALL_FAILED_PACKAGE_CHANGED,
10901                                    "Application package " + pkg.packageName
10902                                    + " found at " + pkg.applicationInfo.getCodePath()
10903                                    + " but expected at " + known.codePathString
10904                                    + "; ignoring.");
10905                        }
10906                    }
10907                }
10908            }
10909
10910            // Verify that this new package doesn't have any content providers
10911            // that conflict with existing packages.  Only do this if the
10912            // package isn't already installed, since we don't want to break
10913            // things that are installed.
10914            if ((scanFlags & SCAN_NEW_INSTALL) != 0) {
10915                final int N = pkg.providers.size();
10916                int i;
10917                for (i=0; i<N; i++) {
10918                    PackageParser.Provider p = pkg.providers.get(i);
10919                    if (p.info.authority != null) {
10920                        String names[] = p.info.authority.split(";");
10921                        for (int j = 0; j < names.length; j++) {
10922                            if (mProvidersByAuthority.containsKey(names[j])) {
10923                                PackageParser.Provider other = mProvidersByAuthority.get(names[j]);
10924                                final String otherPackageName =
10925                                        ((other != null && other.getComponentName() != null) ?
10926                                                other.getComponentName().getPackageName() : "?");
10927                                throw new PackageManagerException(
10928                                        INSTALL_FAILED_CONFLICTING_PROVIDER,
10929                                        "Can't install because provider name " + names[j]
10930                                                + " (in package " + pkg.applicationInfo.packageName
10931                                                + ") is already used by " + otherPackageName);
10932                            }
10933                        }
10934                    }
10935                }
10936            }
10937        }
10938    }
10939
10940    private boolean addSharedLibraryLPw(String path, String apk, String name, int version,
10941            int type, String declaringPackageName, int declaringVersionCode) {
10942        SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(name);
10943        if (versionedLib == null) {
10944            versionedLib = new SparseArray<>();
10945            mSharedLibraries.put(name, versionedLib);
10946            if (type == SharedLibraryInfo.TYPE_STATIC) {
10947                mStaticLibsByDeclaringPackage.put(declaringPackageName, versionedLib);
10948            }
10949        } else if (versionedLib.indexOfKey(version) >= 0) {
10950            return false;
10951        }
10952        SharedLibraryEntry libEntry = new SharedLibraryEntry(path, apk, name,
10953                version, type, declaringPackageName, declaringVersionCode);
10954        versionedLib.put(version, libEntry);
10955        return true;
10956    }
10957
10958    private boolean removeSharedLibraryLPw(String name, int version) {
10959        SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(name);
10960        if (versionedLib == null) {
10961            return false;
10962        }
10963        final int libIdx = versionedLib.indexOfKey(version);
10964        if (libIdx < 0) {
10965            return false;
10966        }
10967        SharedLibraryEntry libEntry = versionedLib.valueAt(libIdx);
10968        versionedLib.remove(version);
10969        if (versionedLib.size() <= 0) {
10970            mSharedLibraries.remove(name);
10971            if (libEntry.info.getType() == SharedLibraryInfo.TYPE_STATIC) {
10972                mStaticLibsByDeclaringPackage.remove(libEntry.info.getDeclaringPackage()
10973                        .getPackageName());
10974            }
10975        }
10976        return true;
10977    }
10978
10979    /**
10980     * Adds a scanned package to the system. When this method is finished, the package will
10981     * be available for query, resolution, etc...
10982     */
10983    private void commitPackageSettings(PackageParser.Package pkg, PackageSetting pkgSetting,
10984            UserHandle user, int scanFlags, boolean chatty) throws PackageManagerException {
10985        final String pkgName = pkg.packageName;
10986        if (mCustomResolverComponentName != null &&
10987                mCustomResolverComponentName.getPackageName().equals(pkg.packageName)) {
10988            setUpCustomResolverActivity(pkg);
10989        }
10990
10991        if (pkg.packageName.equals("android")) {
10992            synchronized (mPackages) {
10993                if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
10994                    // Set up information for our fall-back user intent resolution activity.
10995                    mPlatformPackage = pkg;
10996                    pkg.mVersionCode = mSdkVersion;
10997                    mAndroidApplication = pkg.applicationInfo;
10998                    if (!mResolverReplaced) {
10999                        mResolveActivity.applicationInfo = mAndroidApplication;
11000                        mResolveActivity.name = ResolverActivity.class.getName();
11001                        mResolveActivity.packageName = mAndroidApplication.packageName;
11002                        mResolveActivity.processName = "system:ui";
11003                        mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
11004                        mResolveActivity.documentLaunchMode = ActivityInfo.DOCUMENT_LAUNCH_NEVER;
11005                        mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS;
11006                        mResolveActivity.theme = R.style.Theme_Material_Dialog_Alert;
11007                        mResolveActivity.exported = true;
11008                        mResolveActivity.enabled = true;
11009                        mResolveActivity.resizeMode = ActivityInfo.RESIZE_MODE_RESIZEABLE;
11010                        mResolveActivity.configChanges = ActivityInfo.CONFIG_SCREEN_SIZE
11011                                | ActivityInfo.CONFIG_SMALLEST_SCREEN_SIZE
11012                                | ActivityInfo.CONFIG_SCREEN_LAYOUT
11013                                | ActivityInfo.CONFIG_ORIENTATION
11014                                | ActivityInfo.CONFIG_KEYBOARD
11015                                | ActivityInfo.CONFIG_KEYBOARD_HIDDEN;
11016                        mResolveInfo.activityInfo = mResolveActivity;
11017                        mResolveInfo.priority = 0;
11018                        mResolveInfo.preferredOrder = 0;
11019                        mResolveInfo.match = 0;
11020                        mResolveComponentName = new ComponentName(
11021                                mAndroidApplication.packageName, mResolveActivity.name);
11022                    }
11023                }
11024            }
11025        }
11026
11027        ArrayList<PackageParser.Package> clientLibPkgs = null;
11028        // writer
11029        synchronized (mPackages) {
11030            boolean hasStaticSharedLibs = false;
11031
11032            // Any app can add new static shared libraries
11033            if (pkg.staticSharedLibName != null) {
11034                // Static shared libs don't allow renaming as they have synthetic package
11035                // names to allow install of multiple versions, so use name from manifest.
11036                if (addSharedLibraryLPw(null, pkg.packageName, pkg.staticSharedLibName,
11037                        pkg.staticSharedLibVersion, SharedLibraryInfo.TYPE_STATIC,
11038                        pkg.manifestPackageName, pkg.mVersionCode)) {
11039                    hasStaticSharedLibs = true;
11040                } else {
11041                    Slog.w(TAG, "Package " + pkg.packageName + " library "
11042                                + pkg.staticSharedLibName + " already exists; skipping");
11043                }
11044                // Static shared libs cannot be updated once installed since they
11045                // use synthetic package name which includes the version code, so
11046                // not need to update other packages's shared lib dependencies.
11047            }
11048
11049            if (!hasStaticSharedLibs
11050                    && (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
11051                // Only system apps can add new dynamic shared libraries.
11052                if (pkg.libraryNames != null) {
11053                    for (int i = 0; i < pkg.libraryNames.size(); i++) {
11054                        String name = pkg.libraryNames.get(i);
11055                        boolean allowed = false;
11056                        if (pkg.isUpdatedSystemApp()) {
11057                            // New library entries can only be added through the
11058                            // system image.  This is important to get rid of a lot
11059                            // of nasty edge cases: for example if we allowed a non-
11060                            // system update of the app to add a library, then uninstalling
11061                            // the update would make the library go away, and assumptions
11062                            // we made such as through app install filtering would now
11063                            // have allowed apps on the device which aren't compatible
11064                            // with it.  Better to just have the restriction here, be
11065                            // conservative, and create many fewer cases that can negatively
11066                            // impact the user experience.
11067                            final PackageSetting sysPs = mSettings
11068                                    .getDisabledSystemPkgLPr(pkg.packageName);
11069                            if (sysPs.pkg != null && sysPs.pkg.libraryNames != null) {
11070                                for (int j = 0; j < sysPs.pkg.libraryNames.size(); j++) {
11071                                    if (name.equals(sysPs.pkg.libraryNames.get(j))) {
11072                                        allowed = true;
11073                                        break;
11074                                    }
11075                                }
11076                            }
11077                        } else {
11078                            allowed = true;
11079                        }
11080                        if (allowed) {
11081                            if (!addSharedLibraryLPw(null, pkg.packageName, name,
11082                                    SharedLibraryInfo.VERSION_UNDEFINED,
11083                                    SharedLibraryInfo.TYPE_DYNAMIC,
11084                                    pkg.packageName, pkg.mVersionCode)) {
11085                                Slog.w(TAG, "Package " + pkg.packageName + " library "
11086                                        + name + " already exists; skipping");
11087                            }
11088                        } else {
11089                            Slog.w(TAG, "Package " + pkg.packageName + " declares lib "
11090                                    + name + " that is not declared on system image; skipping");
11091                        }
11092                    }
11093
11094                    if ((scanFlags & SCAN_BOOTING) == 0) {
11095                        // If we are not booting, we need to update any applications
11096                        // that are clients of our shared library.  If we are booting,
11097                        // this will all be done once the scan is complete.
11098                        clientLibPkgs = updateAllSharedLibrariesLPw(pkg);
11099                    }
11100                }
11101            }
11102        }
11103
11104        if ((scanFlags & SCAN_BOOTING) != 0) {
11105            // No apps can run during boot scan, so they don't need to be frozen
11106        } else if ((scanFlags & SCAN_DONT_KILL_APP) != 0) {
11107            // Caller asked to not kill app, so it's probably not frozen
11108        } else if ((scanFlags & SCAN_IGNORE_FROZEN) != 0) {
11109            // Caller asked us to ignore frozen check for some reason; they
11110            // probably didn't know the package name
11111        } else {
11112            // We're doing major surgery on this package, so it better be frozen
11113            // right now to keep it from launching
11114            checkPackageFrozen(pkgName);
11115        }
11116
11117        // Also need to kill any apps that are dependent on the library.
11118        if (clientLibPkgs != null) {
11119            for (int i=0; i<clientLibPkgs.size(); i++) {
11120                PackageParser.Package clientPkg = clientLibPkgs.get(i);
11121                killApplication(clientPkg.applicationInfo.packageName,
11122                        clientPkg.applicationInfo.uid, "update lib");
11123            }
11124        }
11125
11126        // writer
11127        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings");
11128
11129        synchronized (mPackages) {
11130            // We don't expect installation to fail beyond this point
11131
11132            // Add the new setting to mSettings
11133            mSettings.insertPackageSettingLPw(pkgSetting, pkg);
11134            // Add the new setting to mPackages
11135            mPackages.put(pkg.applicationInfo.packageName, pkg);
11136            // Make sure we don't accidentally delete its data.
11137            final Iterator<PackageCleanItem> iter = mSettings.mPackagesToBeCleaned.iterator();
11138            while (iter.hasNext()) {
11139                PackageCleanItem item = iter.next();
11140                if (pkgName.equals(item.packageName)) {
11141                    iter.remove();
11142                }
11143            }
11144
11145            // Add the package's KeySets to the global KeySetManagerService
11146            KeySetManagerService ksms = mSettings.mKeySetManagerService;
11147            ksms.addScannedPackageLPw(pkg);
11148
11149            int N = pkg.providers.size();
11150            StringBuilder r = null;
11151            int i;
11152            for (i=0; i<N; i++) {
11153                PackageParser.Provider p = pkg.providers.get(i);
11154                p.info.processName = fixProcessName(pkg.applicationInfo.processName,
11155                        p.info.processName);
11156                mProviders.addProvider(p);
11157                p.syncable = p.info.isSyncable;
11158                if (p.info.authority != null) {
11159                    String names[] = p.info.authority.split(";");
11160                    p.info.authority = null;
11161                    for (int j = 0; j < names.length; j++) {
11162                        if (j == 1 && p.syncable) {
11163                            // We only want the first authority for a provider to possibly be
11164                            // syncable, so if we already added this provider using a different
11165                            // authority clear the syncable flag. We copy the provider before
11166                            // changing it because the mProviders object contains a reference
11167                            // to a provider that we don't want to change.
11168                            // Only do this for the second authority since the resulting provider
11169                            // object can be the same for all future authorities for this provider.
11170                            p = new PackageParser.Provider(p);
11171                            p.syncable = false;
11172                        }
11173                        if (!mProvidersByAuthority.containsKey(names[j])) {
11174                            mProvidersByAuthority.put(names[j], p);
11175                            if (p.info.authority == null) {
11176                                p.info.authority = names[j];
11177                            } else {
11178                                p.info.authority = p.info.authority + ";" + names[j];
11179                            }
11180                            if (DEBUG_PACKAGE_SCANNING) {
11181                                if (chatty)
11182                                    Log.d(TAG, "Registered content provider: " + names[j]
11183                                            + ", className = " + p.info.name + ", isSyncable = "
11184                                            + p.info.isSyncable);
11185                            }
11186                        } else {
11187                            PackageParser.Provider other = mProvidersByAuthority.get(names[j]);
11188                            Slog.w(TAG, "Skipping provider name " + names[j] +
11189                                    " (in package " + pkg.applicationInfo.packageName +
11190                                    "): name already used by "
11191                                    + ((other != null && other.getComponentName() != null)
11192                                            ? other.getComponentName().getPackageName() : "?"));
11193                        }
11194                    }
11195                }
11196                if (chatty) {
11197                    if (r == null) {
11198                        r = new StringBuilder(256);
11199                    } else {
11200                        r.append(' ');
11201                    }
11202                    r.append(p.info.name);
11203                }
11204            }
11205            if (r != null) {
11206                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Providers: " + r);
11207            }
11208
11209            N = pkg.services.size();
11210            r = null;
11211            for (i=0; i<N; i++) {
11212                PackageParser.Service s = pkg.services.get(i);
11213                s.info.processName = fixProcessName(pkg.applicationInfo.processName,
11214                        s.info.processName);
11215                mServices.addService(s);
11216                if (chatty) {
11217                    if (r == null) {
11218                        r = new StringBuilder(256);
11219                    } else {
11220                        r.append(' ');
11221                    }
11222                    r.append(s.info.name);
11223                }
11224            }
11225            if (r != null) {
11226                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Services: " + r);
11227            }
11228
11229            N = pkg.receivers.size();
11230            r = null;
11231            for (i=0; i<N; i++) {
11232                PackageParser.Activity a = pkg.receivers.get(i);
11233                a.info.processName = fixProcessName(pkg.applicationInfo.processName,
11234                        a.info.processName);
11235                mReceivers.addActivity(a, "receiver");
11236                if (chatty) {
11237                    if (r == null) {
11238                        r = new StringBuilder(256);
11239                    } else {
11240                        r.append(' ');
11241                    }
11242                    r.append(a.info.name);
11243                }
11244            }
11245            if (r != null) {
11246                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Receivers: " + r);
11247            }
11248
11249            N = pkg.activities.size();
11250            r = null;
11251            for (i=0; i<N; i++) {
11252                PackageParser.Activity a = pkg.activities.get(i);
11253                a.info.processName = fixProcessName(pkg.applicationInfo.processName,
11254                        a.info.processName);
11255                mActivities.addActivity(a, "activity");
11256                if (chatty) {
11257                    if (r == null) {
11258                        r = new StringBuilder(256);
11259                    } else {
11260                        r.append(' ');
11261                    }
11262                    r.append(a.info.name);
11263                }
11264            }
11265            if (r != null) {
11266                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Activities: " + r);
11267            }
11268
11269            N = pkg.permissionGroups.size();
11270            r = null;
11271            for (i=0; i<N; i++) {
11272                PackageParser.PermissionGroup pg = pkg.permissionGroups.get(i);
11273                PackageParser.PermissionGroup cur = mPermissionGroups.get(pg.info.name);
11274                final String curPackageName = cur == null ? null : cur.info.packageName;
11275                // Dont allow ephemeral apps to define new permission groups.
11276                if ((scanFlags & SCAN_AS_INSTANT_APP) != 0) {
11277                    Slog.w(TAG, "Permission group " + pg.info.name + " from package "
11278                            + pg.info.packageName
11279                            + " ignored: instant apps cannot define new permission groups.");
11280                    continue;
11281                }
11282                final boolean isPackageUpdate = pg.info.packageName.equals(curPackageName);
11283                if (cur == null || isPackageUpdate) {
11284                    mPermissionGroups.put(pg.info.name, pg);
11285                    if (chatty) {
11286                        if (r == null) {
11287                            r = new StringBuilder(256);
11288                        } else {
11289                            r.append(' ');
11290                        }
11291                        if (isPackageUpdate) {
11292                            r.append("UPD:");
11293                        }
11294                        r.append(pg.info.name);
11295                    }
11296                } else {
11297                    Slog.w(TAG, "Permission group " + pg.info.name + " from package "
11298                            + pg.info.packageName + " ignored: original from "
11299                            + cur.info.packageName);
11300                    if (chatty) {
11301                        if (r == null) {
11302                            r = new StringBuilder(256);
11303                        } else {
11304                            r.append(' ');
11305                        }
11306                        r.append("DUP:");
11307                        r.append(pg.info.name);
11308                    }
11309                }
11310            }
11311            if (r != null) {
11312                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Permission Groups: " + r);
11313            }
11314
11315            N = pkg.permissions.size();
11316            r = null;
11317            for (i=0; i<N; i++) {
11318                PackageParser.Permission p = pkg.permissions.get(i);
11319
11320                // Dont allow ephemeral apps to define new permissions.
11321                if ((scanFlags & SCAN_AS_INSTANT_APP) != 0) {
11322                    Slog.w(TAG, "Permission " + p.info.name + " from package "
11323                            + p.info.packageName
11324                            + " ignored: instant apps cannot define new permissions.");
11325                    continue;
11326                }
11327
11328                // Assume by default that we did not install this permission into the system.
11329                p.info.flags &= ~PermissionInfo.FLAG_INSTALLED;
11330
11331                // Now that permission groups have a special meaning, we ignore permission
11332                // groups for legacy apps to prevent unexpected behavior. In particular,
11333                // permissions for one app being granted to someone just because they happen
11334                // to be in a group defined by another app (before this had no implications).
11335                if (pkg.applicationInfo.targetSdkVersion > Build.VERSION_CODES.LOLLIPOP_MR1) {
11336                    p.group = mPermissionGroups.get(p.info.group);
11337                    // Warn for a permission in an unknown group.
11338                    if (DEBUG_PERMISSIONS && p.info.group != null && p.group == null) {
11339                        Slog.i(TAG, "Permission " + p.info.name + " from package "
11340                                + p.info.packageName + " in an unknown group " + p.info.group);
11341                    }
11342                }
11343
11344                ArrayMap<String, BasePermission> permissionMap =
11345                        p.tree ? mSettings.mPermissionTrees
11346                                : mSettings.mPermissions;
11347                BasePermission bp = permissionMap.get(p.info.name);
11348
11349                // Allow system apps to redefine non-system permissions
11350                if (bp != null && !Objects.equals(bp.sourcePackage, p.info.packageName)) {
11351                    final boolean currentOwnerIsSystem = (bp.perm != null
11352                            && isSystemApp(bp.perm.owner));
11353                    if (isSystemApp(p.owner)) {
11354                        if (bp.type == BasePermission.TYPE_BUILTIN && bp.perm == null) {
11355                            // It's a built-in permission and no owner, take ownership now
11356                            bp.packageSetting = pkgSetting;
11357                            bp.perm = p;
11358                            bp.uid = pkg.applicationInfo.uid;
11359                            bp.sourcePackage = p.info.packageName;
11360                            p.info.flags |= PermissionInfo.FLAG_INSTALLED;
11361                        } else if (!currentOwnerIsSystem) {
11362                            String msg = "New decl " + p.owner + " of permission  "
11363                                    + p.info.name + " is system; overriding " + bp.sourcePackage;
11364                            reportSettingsProblem(Log.WARN, msg);
11365                            bp = null;
11366                        }
11367                    }
11368                }
11369
11370                if (bp == null) {
11371                    bp = new BasePermission(p.info.name, p.info.packageName,
11372                            BasePermission.TYPE_NORMAL);
11373                    permissionMap.put(p.info.name, bp);
11374                }
11375
11376                if (bp.perm == null) {
11377                    if (bp.sourcePackage == null
11378                            || bp.sourcePackage.equals(p.info.packageName)) {
11379                        BasePermission tree = findPermissionTreeLP(p.info.name);
11380                        if (tree == null
11381                                || tree.sourcePackage.equals(p.info.packageName)) {
11382                            bp.packageSetting = pkgSetting;
11383                            bp.perm = p;
11384                            bp.uid = pkg.applicationInfo.uid;
11385                            bp.sourcePackage = p.info.packageName;
11386                            p.info.flags |= PermissionInfo.FLAG_INSTALLED;
11387                            if (chatty) {
11388                                if (r == null) {
11389                                    r = new StringBuilder(256);
11390                                } else {
11391                                    r.append(' ');
11392                                }
11393                                r.append(p.info.name);
11394                            }
11395                        } else {
11396                            Slog.w(TAG, "Permission " + p.info.name + " from package "
11397                                    + p.info.packageName + " ignored: base tree "
11398                                    + tree.name + " is from package "
11399                                    + tree.sourcePackage);
11400                        }
11401                    } else {
11402                        Slog.w(TAG, "Permission " + p.info.name + " from package "
11403                                + p.info.packageName + " ignored: original from "
11404                                + bp.sourcePackage);
11405                    }
11406                } else if (chatty) {
11407                    if (r == null) {
11408                        r = new StringBuilder(256);
11409                    } else {
11410                        r.append(' ');
11411                    }
11412                    r.append("DUP:");
11413                    r.append(p.info.name);
11414                }
11415                if (bp.perm == p) {
11416                    bp.protectionLevel = p.info.protectionLevel;
11417                }
11418            }
11419
11420            if (r != null) {
11421                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Permissions: " + r);
11422            }
11423
11424            N = pkg.instrumentation.size();
11425            r = null;
11426            for (i=0; i<N; i++) {
11427                PackageParser.Instrumentation a = pkg.instrumentation.get(i);
11428                a.info.packageName = pkg.applicationInfo.packageName;
11429                a.info.sourceDir = pkg.applicationInfo.sourceDir;
11430                a.info.publicSourceDir = pkg.applicationInfo.publicSourceDir;
11431                a.info.splitNames = pkg.splitNames;
11432                a.info.splitSourceDirs = pkg.applicationInfo.splitSourceDirs;
11433                a.info.splitPublicSourceDirs = pkg.applicationInfo.splitPublicSourceDirs;
11434                a.info.splitDependencies = pkg.applicationInfo.splitDependencies;
11435                a.info.dataDir = pkg.applicationInfo.dataDir;
11436                a.info.deviceProtectedDataDir = pkg.applicationInfo.deviceProtectedDataDir;
11437                a.info.credentialProtectedDataDir = pkg.applicationInfo.credentialProtectedDataDir;
11438                a.info.nativeLibraryDir = pkg.applicationInfo.nativeLibraryDir;
11439                a.info.secondaryNativeLibraryDir = pkg.applicationInfo.secondaryNativeLibraryDir;
11440                mInstrumentation.put(a.getComponentName(), a);
11441                if (chatty) {
11442                    if (r == null) {
11443                        r = new StringBuilder(256);
11444                    } else {
11445                        r.append(' ');
11446                    }
11447                    r.append(a.info.name);
11448                }
11449            }
11450            if (r != null) {
11451                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Instrumentation: " + r);
11452            }
11453
11454            if (pkg.protectedBroadcasts != null) {
11455                N = pkg.protectedBroadcasts.size();
11456                synchronized (mProtectedBroadcasts) {
11457                    for (i = 0; i < N; i++) {
11458                        mProtectedBroadcasts.add(pkg.protectedBroadcasts.get(i));
11459                    }
11460                }
11461            }
11462        }
11463
11464        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
11465    }
11466
11467    /**
11468     * Derive the ABI of a non-system package located at {@code scanFile}. This information
11469     * is derived purely on the basis of the contents of {@code scanFile} and
11470     * {@code cpuAbiOverride}.
11471     *
11472     * If {@code extractLibs} is true, native libraries are extracted from the app if required.
11473     */
11474    private static void derivePackageAbi(PackageParser.Package pkg, File scanFile,
11475                                 String cpuAbiOverride, boolean extractLibs,
11476                                 File appLib32InstallDir)
11477            throws PackageManagerException {
11478        // Give ourselves some initial paths; we'll come back for another
11479        // pass once we've determined ABI below.
11480        setNativeLibraryPaths(pkg, appLib32InstallDir);
11481
11482        // We would never need to extract libs for forward-locked and external packages,
11483        // since the container service will do it for us. We shouldn't attempt to
11484        // extract libs from system app when it was not updated.
11485        if (pkg.isForwardLocked() || pkg.applicationInfo.isExternalAsec() ||
11486                (isSystemApp(pkg) && !pkg.isUpdatedSystemApp())) {
11487            extractLibs = false;
11488        }
11489
11490        final String nativeLibraryRootStr = pkg.applicationInfo.nativeLibraryRootDir;
11491        final boolean useIsaSpecificSubdirs = pkg.applicationInfo.nativeLibraryRootRequiresIsa;
11492
11493        NativeLibraryHelper.Handle handle = null;
11494        try {
11495            handle = NativeLibraryHelper.Handle.create(pkg);
11496            // TODO(multiArch): This can be null for apps that didn't go through the
11497            // usual installation process. We can calculate it again, like we
11498            // do during install time.
11499            //
11500            // TODO(multiArch): Why do we need to rescan ASEC apps again ? It seems totally
11501            // unnecessary.
11502            final File nativeLibraryRoot = new File(nativeLibraryRootStr);
11503
11504            // Null out the abis so that they can be recalculated.
11505            pkg.applicationInfo.primaryCpuAbi = null;
11506            pkg.applicationInfo.secondaryCpuAbi = null;
11507            if (isMultiArch(pkg.applicationInfo)) {
11508                // Warn if we've set an abiOverride for multi-lib packages..
11509                // By definition, we need to copy both 32 and 64 bit libraries for
11510                // such packages.
11511                if (pkg.cpuAbiOverride != null
11512                        && !NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(pkg.cpuAbiOverride)) {
11513                    Slog.w(TAG, "Ignoring abiOverride for multi arch application.");
11514                }
11515
11516                int abi32 = PackageManager.NO_NATIVE_LIBRARIES;
11517                int abi64 = PackageManager.NO_NATIVE_LIBRARIES;
11518                if (Build.SUPPORTED_32_BIT_ABIS.length > 0) {
11519                    if (extractLibs) {
11520                        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyNativeBinaries");
11521                        abi32 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
11522                                nativeLibraryRoot, Build.SUPPORTED_32_BIT_ABIS,
11523                                useIsaSpecificSubdirs);
11524                    } else {
11525                        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "findSupportedAbi");
11526                        abi32 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_32_BIT_ABIS);
11527                    }
11528                    Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
11529                }
11530
11531                // Shared library native code should be in the APK zip aligned
11532                if (abi32 >= 0 && pkg.isLibrary() && extractLibs) {
11533                    throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR,
11534                            "Shared library native lib extraction not supported");
11535                }
11536
11537                maybeThrowExceptionForMultiArchCopy(
11538                        "Error unpackaging 32 bit native libs for multiarch app.", abi32);
11539
11540                if (Build.SUPPORTED_64_BIT_ABIS.length > 0) {
11541                    if (extractLibs) {
11542                        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyNativeBinaries");
11543                        abi64 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
11544                                nativeLibraryRoot, Build.SUPPORTED_64_BIT_ABIS,
11545                                useIsaSpecificSubdirs);
11546                    } else {
11547                        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "findSupportedAbi");
11548                        abi64 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_64_BIT_ABIS);
11549                    }
11550                    Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
11551                }
11552
11553                maybeThrowExceptionForMultiArchCopy(
11554                        "Error unpackaging 64 bit native libs for multiarch app.", abi64);
11555
11556                if (abi64 >= 0) {
11557                    // Shared library native libs should be in the APK zip aligned
11558                    if (extractLibs && pkg.isLibrary()) {
11559                        throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR,
11560                                "Shared library native lib extraction not supported");
11561                    }
11562                    pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[abi64];
11563                }
11564
11565                if (abi32 >= 0) {
11566                    final String abi = Build.SUPPORTED_32_BIT_ABIS[abi32];
11567                    if (abi64 >= 0) {
11568                        if (pkg.use32bitAbi) {
11569                            pkg.applicationInfo.secondaryCpuAbi = pkg.applicationInfo.primaryCpuAbi;
11570                            pkg.applicationInfo.primaryCpuAbi = abi;
11571                        } else {
11572                            pkg.applicationInfo.secondaryCpuAbi = abi;
11573                        }
11574                    } else {
11575                        pkg.applicationInfo.primaryCpuAbi = abi;
11576                    }
11577                }
11578            } else {
11579                String[] abiList = (cpuAbiOverride != null) ?
11580                        new String[] { cpuAbiOverride } : Build.SUPPORTED_ABIS;
11581
11582                // Enable gross and lame hacks for apps that are built with old
11583                // SDK tools. We must scan their APKs for renderscript bitcode and
11584                // not launch them if it's present. Don't bother checking on devices
11585                // that don't have 64 bit support.
11586                boolean needsRenderScriptOverride = false;
11587                if (Build.SUPPORTED_64_BIT_ABIS.length > 0 && cpuAbiOverride == null &&
11588                        NativeLibraryHelper.hasRenderscriptBitcode(handle)) {
11589                    abiList = Build.SUPPORTED_32_BIT_ABIS;
11590                    needsRenderScriptOverride = true;
11591                }
11592
11593                final int copyRet;
11594                if (extractLibs) {
11595                    Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyNativeBinaries");
11596                    copyRet = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
11597                            nativeLibraryRoot, abiList, useIsaSpecificSubdirs);
11598                } else {
11599                    Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "findSupportedAbi");
11600                    copyRet = NativeLibraryHelper.findSupportedAbi(handle, abiList);
11601                }
11602                Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
11603
11604                if (copyRet < 0 && copyRet != PackageManager.NO_NATIVE_LIBRARIES) {
11605                    throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR,
11606                            "Error unpackaging native libs for app, errorCode=" + copyRet);
11607                }
11608
11609                if (copyRet >= 0) {
11610                    // Shared libraries that have native libs must be multi-architecture
11611                    if (pkg.isLibrary()) {
11612                        throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR,
11613                                "Shared library with native libs must be multiarch");
11614                    }
11615                    pkg.applicationInfo.primaryCpuAbi = abiList[copyRet];
11616                } else if (copyRet == PackageManager.NO_NATIVE_LIBRARIES && cpuAbiOverride != null) {
11617                    pkg.applicationInfo.primaryCpuAbi = cpuAbiOverride;
11618                } else if (needsRenderScriptOverride) {
11619                    pkg.applicationInfo.primaryCpuAbi = abiList[0];
11620                }
11621            }
11622        } catch (IOException ioe) {
11623            Slog.e(TAG, "Unable to get canonical file " + ioe.toString());
11624        } finally {
11625            IoUtils.closeQuietly(handle);
11626        }
11627
11628        // Now that we've calculated the ABIs and determined if it's an internal app,
11629        // we will go ahead and populate the nativeLibraryPath.
11630        setNativeLibraryPaths(pkg, appLib32InstallDir);
11631    }
11632
11633    /**
11634     * Adjusts ABIs for a set of packages belonging to a shared user so that they all match.
11635     * i.e, so that all packages can be run inside a single process if required.
11636     *
11637     * Optionally, callers can pass in a parsed package via {@code newPackage} in which case
11638     * this function will either try and make the ABI for all packages in {@code packagesForUser}
11639     * match {@code scannedPackage} or will update the ABI of {@code scannedPackage} to match
11640     * the ABI selected for {@code packagesForUser}. This variant is used when installing or
11641     * updating a package that belongs to a shared user.
11642     *
11643     * NOTE: We currently only match for the primary CPU abi string. Matching the secondary
11644     * adds unnecessary complexity.
11645     */
11646    private void adjustCpuAbisForSharedUserLPw(Set<PackageSetting> packagesForUser,
11647            PackageParser.Package scannedPackage) {
11648        String requiredInstructionSet = null;
11649        if (scannedPackage != null && scannedPackage.applicationInfo.primaryCpuAbi != null) {
11650            requiredInstructionSet = VMRuntime.getInstructionSet(
11651                     scannedPackage.applicationInfo.primaryCpuAbi);
11652        }
11653
11654        PackageSetting requirer = null;
11655        for (PackageSetting ps : packagesForUser) {
11656            // If packagesForUser contains scannedPackage, we skip it. This will happen
11657            // when scannedPackage is an update of an existing package. Without this check,
11658            // we will never be able to change the ABI of any package belonging to a shared
11659            // user, even if it's compatible with other packages.
11660            if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) {
11661                if (ps.primaryCpuAbiString == null) {
11662                    continue;
11663                }
11664
11665                final String instructionSet = VMRuntime.getInstructionSet(ps.primaryCpuAbiString);
11666                if (requiredInstructionSet != null && !instructionSet.equals(requiredInstructionSet)) {
11667                    // We have a mismatch between instruction sets (say arm vs arm64) warn about
11668                    // this but there's not much we can do.
11669                    String errorMessage = "Instruction set mismatch, "
11670                            + ((requirer == null) ? "[caller]" : requirer)
11671                            + " requires " + requiredInstructionSet + " whereas " + ps
11672                            + " requires " + instructionSet;
11673                    Slog.w(TAG, errorMessage);
11674                }
11675
11676                if (requiredInstructionSet == null) {
11677                    requiredInstructionSet = instructionSet;
11678                    requirer = ps;
11679                }
11680            }
11681        }
11682
11683        if (requiredInstructionSet != null) {
11684            String adjustedAbi;
11685            if (requirer != null) {
11686                // requirer != null implies that either scannedPackage was null or that scannedPackage
11687                // did not require an ABI, in which case we have to adjust scannedPackage to match
11688                // the ABI of the set (which is the same as requirer's ABI)
11689                adjustedAbi = requirer.primaryCpuAbiString;
11690                if (scannedPackage != null) {
11691                    scannedPackage.applicationInfo.primaryCpuAbi = adjustedAbi;
11692                }
11693            } else {
11694                // requirer == null implies that we're updating all ABIs in the set to
11695                // match scannedPackage.
11696                adjustedAbi =  scannedPackage.applicationInfo.primaryCpuAbi;
11697            }
11698
11699            for (PackageSetting ps : packagesForUser) {
11700                if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) {
11701                    if (ps.primaryCpuAbiString != null) {
11702                        continue;
11703                    }
11704
11705                    ps.primaryCpuAbiString = adjustedAbi;
11706                    if (ps.pkg != null && ps.pkg.applicationInfo != null &&
11707                            !TextUtils.equals(adjustedAbi, ps.pkg.applicationInfo.primaryCpuAbi)) {
11708                        ps.pkg.applicationInfo.primaryCpuAbi = adjustedAbi;
11709                        if (DEBUG_ABI_SELECTION) {
11710                            Slog.i(TAG, "Adjusting ABI for " + ps.name + " to " + adjustedAbi
11711                                    + " (requirer="
11712                                    + (requirer != null ? requirer.pkg : "null")
11713                                    + ", scannedPackage="
11714                                    + (scannedPackage != null ? scannedPackage : "null")
11715                                    + ")");
11716                        }
11717                        try {
11718                            mInstaller.rmdex(ps.codePathString,
11719                                    getDexCodeInstructionSet(getPreferredInstructionSet()));
11720                        } catch (InstallerException ignored) {
11721                        }
11722                    }
11723                }
11724            }
11725        }
11726    }
11727
11728    private void setUpCustomResolverActivity(PackageParser.Package pkg) {
11729        synchronized (mPackages) {
11730            mResolverReplaced = true;
11731            // Set up information for custom user intent resolution activity.
11732            mResolveActivity.applicationInfo = pkg.applicationInfo;
11733            mResolveActivity.name = mCustomResolverComponentName.getClassName();
11734            mResolveActivity.packageName = pkg.applicationInfo.packageName;
11735            mResolveActivity.processName = pkg.applicationInfo.packageName;
11736            mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
11737            mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS |
11738                    ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS;
11739            mResolveActivity.theme = 0;
11740            mResolveActivity.exported = true;
11741            mResolveActivity.enabled = true;
11742            mResolveInfo.activityInfo = mResolveActivity;
11743            mResolveInfo.priority = 0;
11744            mResolveInfo.preferredOrder = 0;
11745            mResolveInfo.match = 0;
11746            mResolveComponentName = mCustomResolverComponentName;
11747            Slog.i(TAG, "Replacing default ResolverActivity with custom activity: " +
11748                    mResolveComponentName);
11749        }
11750    }
11751
11752    private void setUpInstantAppInstallerActivityLP(ActivityInfo installerActivity) {
11753        if (installerActivity == null) {
11754            if (DEBUG_EPHEMERAL) {
11755                Slog.d(TAG, "Clear ephemeral installer activity");
11756            }
11757            mInstantAppInstallerActivity = null;
11758            return;
11759        }
11760
11761        if (DEBUG_EPHEMERAL) {
11762            Slog.d(TAG, "Set ephemeral installer activity: "
11763                    + installerActivity.getComponentName());
11764        }
11765        // Set up information for ephemeral installer activity
11766        mInstantAppInstallerActivity = installerActivity;
11767        mInstantAppInstallerActivity.flags |= ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS
11768                | ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS;
11769        mInstantAppInstallerActivity.exported = true;
11770        mInstantAppInstallerActivity.enabled = true;
11771        mInstantAppInstallerInfo.activityInfo = mInstantAppInstallerActivity;
11772        mInstantAppInstallerInfo.priority = 0;
11773        mInstantAppInstallerInfo.preferredOrder = 1;
11774        mInstantAppInstallerInfo.isDefault = true;
11775        mInstantAppInstallerInfo.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART
11776                | IntentFilter.MATCH_ADJUSTMENT_NORMAL;
11777    }
11778
11779    private static String calculateBundledApkRoot(final String codePathString) {
11780        final File codePath = new File(codePathString);
11781        final File codeRoot;
11782        if (FileUtils.contains(Environment.getRootDirectory(), codePath)) {
11783            codeRoot = Environment.getRootDirectory();
11784        } else if (FileUtils.contains(Environment.getOemDirectory(), codePath)) {
11785            codeRoot = Environment.getOemDirectory();
11786        } else if (FileUtils.contains(Environment.getVendorDirectory(), codePath)) {
11787            codeRoot = Environment.getVendorDirectory();
11788        } else {
11789            // Unrecognized code path; take its top real segment as the apk root:
11790            // e.g. /something/app/blah.apk => /something
11791            try {
11792                File f = codePath.getCanonicalFile();
11793                File parent = f.getParentFile();    // non-null because codePath is a file
11794                File tmp;
11795                while ((tmp = parent.getParentFile()) != null) {
11796                    f = parent;
11797                    parent = tmp;
11798                }
11799                codeRoot = f;
11800                Slog.w(TAG, "Unrecognized code path "
11801                        + codePath + " - using " + codeRoot);
11802            } catch (IOException e) {
11803                // Can't canonicalize the code path -- shenanigans?
11804                Slog.w(TAG, "Can't canonicalize code path " + codePath);
11805                return Environment.getRootDirectory().getPath();
11806            }
11807        }
11808        return codeRoot.getPath();
11809    }
11810
11811    /**
11812     * Derive and set the location of native libraries for the given package,
11813     * which varies depending on where and how the package was installed.
11814     */
11815    private static void setNativeLibraryPaths(PackageParser.Package pkg, File appLib32InstallDir) {
11816        final ApplicationInfo info = pkg.applicationInfo;
11817        final String codePath = pkg.codePath;
11818        final File codeFile = new File(codePath);
11819        final boolean bundledApp = info.isSystemApp() && !info.isUpdatedSystemApp();
11820        final boolean asecApp = info.isForwardLocked() || info.isExternalAsec();
11821
11822        info.nativeLibraryRootDir = null;
11823        info.nativeLibraryRootRequiresIsa = false;
11824        info.nativeLibraryDir = null;
11825        info.secondaryNativeLibraryDir = null;
11826
11827        if (isApkFile(codeFile)) {
11828            // Monolithic install
11829            if (bundledApp) {
11830                // If "/system/lib64/apkname" exists, assume that is the per-package
11831                // native library directory to use; otherwise use "/system/lib/apkname".
11832                final String apkRoot = calculateBundledApkRoot(info.sourceDir);
11833                final boolean is64Bit = VMRuntime.is64BitInstructionSet(
11834                        getPrimaryInstructionSet(info));
11835
11836                // This is a bundled system app so choose the path based on the ABI.
11837                // if it's a 64 bit abi, use lib64 otherwise use lib32. Note that this
11838                // is just the default path.
11839                final String apkName = deriveCodePathName(codePath);
11840                final String libDir = is64Bit ? LIB64_DIR_NAME : LIB_DIR_NAME;
11841                info.nativeLibraryRootDir = Environment.buildPath(new File(apkRoot), libDir,
11842                        apkName).getAbsolutePath();
11843
11844                if (info.secondaryCpuAbi != null) {
11845                    final String secondaryLibDir = is64Bit ? LIB_DIR_NAME : LIB64_DIR_NAME;
11846                    info.secondaryNativeLibraryDir = Environment.buildPath(new File(apkRoot),
11847                            secondaryLibDir, apkName).getAbsolutePath();
11848                }
11849            } else if (asecApp) {
11850                info.nativeLibraryRootDir = new File(codeFile.getParentFile(), LIB_DIR_NAME)
11851                        .getAbsolutePath();
11852            } else {
11853                final String apkName = deriveCodePathName(codePath);
11854                info.nativeLibraryRootDir = new File(appLib32InstallDir, apkName)
11855                        .getAbsolutePath();
11856            }
11857
11858            info.nativeLibraryRootRequiresIsa = false;
11859            info.nativeLibraryDir = info.nativeLibraryRootDir;
11860        } else {
11861            // Cluster install
11862            info.nativeLibraryRootDir = new File(codeFile, LIB_DIR_NAME).getAbsolutePath();
11863            info.nativeLibraryRootRequiresIsa = true;
11864
11865            info.nativeLibraryDir = new File(info.nativeLibraryRootDir,
11866                    getPrimaryInstructionSet(info)).getAbsolutePath();
11867
11868            if (info.secondaryCpuAbi != null) {
11869                info.secondaryNativeLibraryDir = new File(info.nativeLibraryRootDir,
11870                        VMRuntime.getInstructionSet(info.secondaryCpuAbi)).getAbsolutePath();
11871            }
11872        }
11873    }
11874
11875    /**
11876     * Calculate the abis and roots for a bundled app. These can uniquely
11877     * be determined from the contents of the system partition, i.e whether
11878     * it contains 64 or 32 bit shared libraries etc. We do not validate any
11879     * of this information, and instead assume that the system was built
11880     * sensibly.
11881     */
11882    private static void setBundledAppAbisAndRoots(PackageParser.Package pkg,
11883                                           PackageSetting pkgSetting) {
11884        final String apkName = deriveCodePathName(pkg.applicationInfo.getCodePath());
11885
11886        // If "/system/lib64/apkname" exists, assume that is the per-package
11887        // native library directory to use; otherwise use "/system/lib/apkname".
11888        final String apkRoot = calculateBundledApkRoot(pkg.applicationInfo.sourceDir);
11889        setBundledAppAbi(pkg, apkRoot, apkName);
11890        // pkgSetting might be null during rescan following uninstall of updates
11891        // to a bundled app, so accommodate that possibility.  The settings in
11892        // that case will be established later from the parsed package.
11893        //
11894        // If the settings aren't null, sync them up with what we've just derived.
11895        // note that apkRoot isn't stored in the package settings.
11896        if (pkgSetting != null) {
11897            pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi;
11898            pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi;
11899        }
11900    }
11901
11902    /**
11903     * Deduces the ABI of a bundled app and sets the relevant fields on the
11904     * parsed pkg object.
11905     *
11906     * @param apkRoot the root of the installed apk, something like {@code /system} or {@code /oem}
11907     *        under which system libraries are installed.
11908     * @param apkName the name of the installed package.
11909     */
11910    private static void setBundledAppAbi(PackageParser.Package pkg, String apkRoot, String apkName) {
11911        final File codeFile = new File(pkg.codePath);
11912
11913        final boolean has64BitLibs;
11914        final boolean has32BitLibs;
11915        if (isApkFile(codeFile)) {
11916            // Monolithic install
11917            has64BitLibs = (new File(apkRoot, new File(LIB64_DIR_NAME, apkName).getPath())).exists();
11918            has32BitLibs = (new File(apkRoot, new File(LIB_DIR_NAME, apkName).getPath())).exists();
11919        } else {
11920            // Cluster install
11921            final File rootDir = new File(codeFile, LIB_DIR_NAME);
11922            if (!ArrayUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS)
11923                    && !TextUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS[0])) {
11924                final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_64_BIT_ABIS[0]);
11925                has64BitLibs = (new File(rootDir, isa)).exists();
11926            } else {
11927                has64BitLibs = false;
11928            }
11929            if (!ArrayUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS)
11930                    && !TextUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS[0])) {
11931                final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_32_BIT_ABIS[0]);
11932                has32BitLibs = (new File(rootDir, isa)).exists();
11933            } else {
11934                has32BitLibs = false;
11935            }
11936        }
11937
11938        if (has64BitLibs && !has32BitLibs) {
11939            // The package has 64 bit libs, but not 32 bit libs. Its primary
11940            // ABI should be 64 bit. We can safely assume here that the bundled
11941            // native libraries correspond to the most preferred ABI in the list.
11942
11943            pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
11944            pkg.applicationInfo.secondaryCpuAbi = null;
11945        } else if (has32BitLibs && !has64BitLibs) {
11946            // The package has 32 bit libs but not 64 bit libs. Its primary
11947            // ABI should be 32 bit.
11948
11949            pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
11950            pkg.applicationInfo.secondaryCpuAbi = null;
11951        } else if (has32BitLibs && has64BitLibs) {
11952            // The application has both 64 and 32 bit bundled libraries. We check
11953            // here that the app declares multiArch support, and warn if it doesn't.
11954            //
11955            // We will be lenient here and record both ABIs. The primary will be the
11956            // ABI that's higher on the list, i.e, a device that's configured to prefer
11957            // 64 bit apps will see a 64 bit primary ABI,
11958
11959            if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_MULTIARCH) == 0) {
11960                Slog.e(TAG, "Package " + pkg + " has multiple bundled libs, but is not multiarch.");
11961            }
11962
11963            if (VMRuntime.is64BitInstructionSet(getPreferredInstructionSet())) {
11964                pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
11965                pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
11966            } else {
11967                pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
11968                pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
11969            }
11970        } else {
11971            pkg.applicationInfo.primaryCpuAbi = null;
11972            pkg.applicationInfo.secondaryCpuAbi = null;
11973        }
11974    }
11975
11976    private void killApplication(String pkgName, int appId, String reason) {
11977        killApplication(pkgName, appId, UserHandle.USER_ALL, reason);
11978    }
11979
11980    private void killApplication(String pkgName, int appId, int userId, String reason) {
11981        // Request the ActivityManager to kill the process(only for existing packages)
11982        // so that we do not end up in a confused state while the user is still using the older
11983        // version of the application while the new one gets installed.
11984        final long token = Binder.clearCallingIdentity();
11985        try {
11986            IActivityManager am = ActivityManager.getService();
11987            if (am != null) {
11988                try {
11989                    am.killApplication(pkgName, appId, userId, reason);
11990                } catch (RemoteException e) {
11991                }
11992            }
11993        } finally {
11994            Binder.restoreCallingIdentity(token);
11995        }
11996    }
11997
11998    private void removePackageLI(PackageParser.Package pkg, boolean chatty) {
11999        // Remove the parent package setting
12000        PackageSetting ps = (PackageSetting) pkg.mExtras;
12001        if (ps != null) {
12002            removePackageLI(ps, chatty);
12003        }
12004        // Remove the child package setting
12005        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
12006        for (int i = 0; i < childCount; i++) {
12007            PackageParser.Package childPkg = pkg.childPackages.get(i);
12008            ps = (PackageSetting) childPkg.mExtras;
12009            if (ps != null) {
12010                removePackageLI(ps, chatty);
12011            }
12012        }
12013    }
12014
12015    void removePackageLI(PackageSetting ps, boolean chatty) {
12016        if (DEBUG_INSTALL) {
12017            if (chatty)
12018                Log.d(TAG, "Removing package " + ps.name);
12019        }
12020
12021        // writer
12022        synchronized (mPackages) {
12023            mPackages.remove(ps.name);
12024            final PackageParser.Package pkg = ps.pkg;
12025            if (pkg != null) {
12026                cleanPackageDataStructuresLILPw(pkg, chatty);
12027            }
12028        }
12029    }
12030
12031    void removeInstalledPackageLI(PackageParser.Package pkg, boolean chatty) {
12032        if (DEBUG_INSTALL) {
12033            if (chatty)
12034                Log.d(TAG, "Removing package " + pkg.applicationInfo.packageName);
12035        }
12036
12037        // writer
12038        synchronized (mPackages) {
12039            // Remove the parent package
12040            mPackages.remove(pkg.applicationInfo.packageName);
12041            cleanPackageDataStructuresLILPw(pkg, chatty);
12042
12043            // Remove the child packages
12044            final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
12045            for (int i = 0; i < childCount; i++) {
12046                PackageParser.Package childPkg = pkg.childPackages.get(i);
12047                mPackages.remove(childPkg.applicationInfo.packageName);
12048                cleanPackageDataStructuresLILPw(childPkg, chatty);
12049            }
12050        }
12051    }
12052
12053    void cleanPackageDataStructuresLILPw(PackageParser.Package pkg, boolean chatty) {
12054        int N = pkg.providers.size();
12055        StringBuilder r = null;
12056        int i;
12057        for (i=0; i<N; i++) {
12058            PackageParser.Provider p = pkg.providers.get(i);
12059            mProviders.removeProvider(p);
12060            if (p.info.authority == null) {
12061
12062                /* There was another ContentProvider with this authority when
12063                 * this app was installed so this authority is null,
12064                 * Ignore it as we don't have to unregister the provider.
12065                 */
12066                continue;
12067            }
12068            String names[] = p.info.authority.split(";");
12069            for (int j = 0; j < names.length; j++) {
12070                if (mProvidersByAuthority.get(names[j]) == p) {
12071                    mProvidersByAuthority.remove(names[j]);
12072                    if (DEBUG_REMOVE) {
12073                        if (chatty)
12074                            Log.d(TAG, "Unregistered content provider: " + names[j]
12075                                    + ", className = " + p.info.name + ", isSyncable = "
12076                                    + p.info.isSyncable);
12077                    }
12078                }
12079            }
12080            if (DEBUG_REMOVE && chatty) {
12081                if (r == null) {
12082                    r = new StringBuilder(256);
12083                } else {
12084                    r.append(' ');
12085                }
12086                r.append(p.info.name);
12087            }
12088        }
12089        if (r != null) {
12090            if (DEBUG_REMOVE) Log.d(TAG, "  Providers: " + r);
12091        }
12092
12093        N = pkg.services.size();
12094        r = null;
12095        for (i=0; i<N; i++) {
12096            PackageParser.Service s = pkg.services.get(i);
12097            mServices.removeService(s);
12098            if (chatty) {
12099                if (r == null) {
12100                    r = new StringBuilder(256);
12101                } else {
12102                    r.append(' ');
12103                }
12104                r.append(s.info.name);
12105            }
12106        }
12107        if (r != null) {
12108            if (DEBUG_REMOVE) Log.d(TAG, "  Services: " + r);
12109        }
12110
12111        N = pkg.receivers.size();
12112        r = null;
12113        for (i=0; i<N; i++) {
12114            PackageParser.Activity a = pkg.receivers.get(i);
12115            mReceivers.removeActivity(a, "receiver");
12116            if (DEBUG_REMOVE && chatty) {
12117                if (r == null) {
12118                    r = new StringBuilder(256);
12119                } else {
12120                    r.append(' ');
12121                }
12122                r.append(a.info.name);
12123            }
12124        }
12125        if (r != null) {
12126            if (DEBUG_REMOVE) Log.d(TAG, "  Receivers: " + r);
12127        }
12128
12129        N = pkg.activities.size();
12130        r = null;
12131        for (i=0; i<N; i++) {
12132            PackageParser.Activity a = pkg.activities.get(i);
12133            mActivities.removeActivity(a, "activity");
12134            if (DEBUG_REMOVE && chatty) {
12135                if (r == null) {
12136                    r = new StringBuilder(256);
12137                } else {
12138                    r.append(' ');
12139                }
12140                r.append(a.info.name);
12141            }
12142        }
12143        if (r != null) {
12144            if (DEBUG_REMOVE) Log.d(TAG, "  Activities: " + r);
12145        }
12146
12147        N = pkg.permissions.size();
12148        r = null;
12149        for (i=0; i<N; i++) {
12150            PackageParser.Permission p = pkg.permissions.get(i);
12151            BasePermission bp = mSettings.mPermissions.get(p.info.name);
12152            if (bp == null) {
12153                bp = mSettings.mPermissionTrees.get(p.info.name);
12154            }
12155            if (bp != null && bp.perm == p) {
12156                bp.perm = null;
12157                if (DEBUG_REMOVE && chatty) {
12158                    if (r == null) {
12159                        r = new StringBuilder(256);
12160                    } else {
12161                        r.append(' ');
12162                    }
12163                    r.append(p.info.name);
12164                }
12165            }
12166            if ((p.info.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
12167                ArraySet<String> appOpPkgs = mAppOpPermissionPackages.get(p.info.name);
12168                if (appOpPkgs != null) {
12169                    appOpPkgs.remove(pkg.packageName);
12170                }
12171            }
12172        }
12173        if (r != null) {
12174            if (DEBUG_REMOVE) Log.d(TAG, "  Permissions: " + r);
12175        }
12176
12177        N = pkg.requestedPermissions.size();
12178        r = null;
12179        for (i=0; i<N; i++) {
12180            String perm = pkg.requestedPermissions.get(i);
12181            BasePermission bp = mSettings.mPermissions.get(perm);
12182            if (bp != null && (bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
12183                ArraySet<String> appOpPkgs = mAppOpPermissionPackages.get(perm);
12184                if (appOpPkgs != null) {
12185                    appOpPkgs.remove(pkg.packageName);
12186                    if (appOpPkgs.isEmpty()) {
12187                        mAppOpPermissionPackages.remove(perm);
12188                    }
12189                }
12190            }
12191        }
12192        if (r != null) {
12193            if (DEBUG_REMOVE) Log.d(TAG, "  Permissions: " + r);
12194        }
12195
12196        N = pkg.instrumentation.size();
12197        r = null;
12198        for (i=0; i<N; i++) {
12199            PackageParser.Instrumentation a = pkg.instrumentation.get(i);
12200            mInstrumentation.remove(a.getComponentName());
12201            if (DEBUG_REMOVE && chatty) {
12202                if (r == null) {
12203                    r = new StringBuilder(256);
12204                } else {
12205                    r.append(' ');
12206                }
12207                r.append(a.info.name);
12208            }
12209        }
12210        if (r != null) {
12211            if (DEBUG_REMOVE) Log.d(TAG, "  Instrumentation: " + r);
12212        }
12213
12214        r = null;
12215        if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) {
12216            // Only system apps can hold shared libraries.
12217            if (pkg.libraryNames != null) {
12218                for (i = 0; i < pkg.libraryNames.size(); i++) {
12219                    String name = pkg.libraryNames.get(i);
12220                    if (removeSharedLibraryLPw(name, 0)) {
12221                        if (DEBUG_REMOVE && chatty) {
12222                            if (r == null) {
12223                                r = new StringBuilder(256);
12224                            } else {
12225                                r.append(' ');
12226                            }
12227                            r.append(name);
12228                        }
12229                    }
12230                }
12231            }
12232        }
12233
12234        r = null;
12235
12236        // Any package can hold static shared libraries.
12237        if (pkg.staticSharedLibName != null) {
12238            if (removeSharedLibraryLPw(pkg.staticSharedLibName, pkg.staticSharedLibVersion)) {
12239                if (DEBUG_REMOVE && chatty) {
12240                    if (r == null) {
12241                        r = new StringBuilder(256);
12242                    } else {
12243                        r.append(' ');
12244                    }
12245                    r.append(pkg.staticSharedLibName);
12246                }
12247            }
12248        }
12249
12250        if (r != null) {
12251            if (DEBUG_REMOVE) Log.d(TAG, "  Libraries: " + r);
12252        }
12253    }
12254
12255    private static boolean hasPermission(PackageParser.Package pkgInfo, String perm) {
12256        for (int i=pkgInfo.permissions.size()-1; i>=0; i--) {
12257            if (pkgInfo.permissions.get(i).info.name.equals(perm)) {
12258                return true;
12259            }
12260        }
12261        return false;
12262    }
12263
12264    static final int UPDATE_PERMISSIONS_ALL = 1<<0;
12265    static final int UPDATE_PERMISSIONS_REPLACE_PKG = 1<<1;
12266    static final int UPDATE_PERMISSIONS_REPLACE_ALL = 1<<2;
12267
12268    private void updatePermissionsLPw(PackageParser.Package pkg, int flags) {
12269        // Update the parent permissions
12270        updatePermissionsLPw(pkg.packageName, pkg, flags);
12271        // Update the child permissions
12272        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
12273        for (int i = 0; i < childCount; i++) {
12274            PackageParser.Package childPkg = pkg.childPackages.get(i);
12275            updatePermissionsLPw(childPkg.packageName, childPkg, flags);
12276        }
12277    }
12278
12279    private void updatePermissionsLPw(String changingPkg, PackageParser.Package pkgInfo,
12280            int flags) {
12281        final String volumeUuid = (pkgInfo != null) ? getVolumeUuidForPackage(pkgInfo) : null;
12282        updatePermissionsLPw(changingPkg, pkgInfo, volumeUuid, flags);
12283    }
12284
12285    private void updatePermissionsLPw(String changingPkg,
12286            PackageParser.Package pkgInfo, String replaceVolumeUuid, int flags) {
12287        // Make sure there are no dangling permission trees.
12288        Iterator<BasePermission> it = mSettings.mPermissionTrees.values().iterator();
12289        while (it.hasNext()) {
12290            final BasePermission bp = it.next();
12291            if (bp.packageSetting == null) {
12292                // We may not yet have parsed the package, so just see if
12293                // we still know about its settings.
12294                bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage);
12295            }
12296            if (bp.packageSetting == null) {
12297                Slog.w(TAG, "Removing dangling permission tree: " + bp.name
12298                        + " from package " + bp.sourcePackage);
12299                it.remove();
12300            } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) {
12301                if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) {
12302                    Slog.i(TAG, "Removing old permission tree: " + bp.name
12303                            + " from package " + bp.sourcePackage);
12304                    flags |= UPDATE_PERMISSIONS_ALL;
12305                    it.remove();
12306                }
12307            }
12308        }
12309
12310        // Make sure all dynamic permissions have been assigned to a package,
12311        // and make sure there are no dangling permissions.
12312        it = mSettings.mPermissions.values().iterator();
12313        while (it.hasNext()) {
12314            final BasePermission bp = it.next();
12315            if (bp.type == BasePermission.TYPE_DYNAMIC) {
12316                if (DEBUG_SETTINGS) Log.v(TAG, "Dynamic permission: name="
12317                        + bp.name + " pkg=" + bp.sourcePackage
12318                        + " info=" + bp.pendingInfo);
12319                if (bp.packageSetting == null && bp.pendingInfo != null) {
12320                    final BasePermission tree = findPermissionTreeLP(bp.name);
12321                    if (tree != null && tree.perm != null) {
12322                        bp.packageSetting = tree.packageSetting;
12323                        bp.perm = new PackageParser.Permission(tree.perm.owner,
12324                                new PermissionInfo(bp.pendingInfo));
12325                        bp.perm.info.packageName = tree.perm.info.packageName;
12326                        bp.perm.info.name = bp.name;
12327                        bp.uid = tree.uid;
12328                    }
12329                }
12330            }
12331            if (bp.packageSetting == null) {
12332                // We may not yet have parsed the package, so just see if
12333                // we still know about its settings.
12334                bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage);
12335            }
12336            if (bp.packageSetting == null) {
12337                Slog.w(TAG, "Removing dangling permission: " + bp.name
12338                        + " from package " + bp.sourcePackage);
12339                it.remove();
12340            } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) {
12341                if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) {
12342                    Slog.i(TAG, "Removing old permission: " + bp.name
12343                            + " from package " + bp.sourcePackage);
12344                    flags |= UPDATE_PERMISSIONS_ALL;
12345                    it.remove();
12346                }
12347            }
12348        }
12349
12350        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "grantPermissions");
12351        // Now update the permissions for all packages, in particular
12352        // replace the granted permissions of the system packages.
12353        if ((flags&UPDATE_PERMISSIONS_ALL) != 0) {
12354            for (PackageParser.Package pkg : mPackages.values()) {
12355                if (pkg != pkgInfo) {
12356                    // Only replace for packages on requested volume
12357                    final String volumeUuid = getVolumeUuidForPackage(pkg);
12358                    final boolean replace = ((flags & UPDATE_PERMISSIONS_REPLACE_ALL) != 0)
12359                            && Objects.equals(replaceVolumeUuid, volumeUuid);
12360                    grantPermissionsLPw(pkg, replace, changingPkg);
12361                }
12362            }
12363        }
12364
12365        if (pkgInfo != null) {
12366            // Only replace for packages on requested volume
12367            final String volumeUuid = getVolumeUuidForPackage(pkgInfo);
12368            final boolean replace = ((flags & UPDATE_PERMISSIONS_REPLACE_PKG) != 0)
12369                    && Objects.equals(replaceVolumeUuid, volumeUuid);
12370            grantPermissionsLPw(pkgInfo, replace, changingPkg);
12371        }
12372        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
12373    }
12374
12375    private void grantPermissionsLPw(PackageParser.Package pkg, boolean replace,
12376            String packageOfInterest) {
12377        // IMPORTANT: There are two types of permissions: install and runtime.
12378        // Install time permissions are granted when the app is installed to
12379        // all device users and users added in the future. Runtime permissions
12380        // are granted at runtime explicitly to specific users. Normal and signature
12381        // protected permissions are install time permissions. Dangerous permissions
12382        // are install permissions if the app's target SDK is Lollipop MR1 or older,
12383        // otherwise they are runtime permissions. This function does not manage
12384        // runtime permissions except for the case an app targeting Lollipop MR1
12385        // being upgraded to target a newer SDK, in which case dangerous permissions
12386        // are transformed from install time to runtime ones.
12387
12388        final PackageSetting ps = (PackageSetting) pkg.mExtras;
12389        if (ps == null) {
12390            return;
12391        }
12392
12393        PermissionsState permissionsState = ps.getPermissionsState();
12394        PermissionsState origPermissions = permissionsState;
12395
12396        final int[] currentUserIds = UserManagerService.getInstance().getUserIds();
12397
12398        boolean runtimePermissionsRevoked = false;
12399        int[] changedRuntimePermissionUserIds = EMPTY_INT_ARRAY;
12400
12401        boolean changedInstallPermission = false;
12402
12403        if (replace) {
12404            ps.installPermissionsFixed = false;
12405            if (!ps.isSharedUser()) {
12406                origPermissions = new PermissionsState(permissionsState);
12407                permissionsState.reset();
12408            } else {
12409                // We need to know only about runtime permission changes since the
12410                // calling code always writes the install permissions state but
12411                // the runtime ones are written only if changed. The only cases of
12412                // changed runtime permissions here are promotion of an install to
12413                // runtime and revocation of a runtime from a shared user.
12414                changedRuntimePermissionUserIds = revokeUnusedSharedUserPermissionsLPw(
12415                        ps.sharedUser, UserManagerService.getInstance().getUserIds());
12416                if (!ArrayUtils.isEmpty(changedRuntimePermissionUserIds)) {
12417                    runtimePermissionsRevoked = true;
12418                }
12419            }
12420        }
12421
12422        permissionsState.setGlobalGids(mGlobalGids);
12423
12424        final int N = pkg.requestedPermissions.size();
12425        for (int i=0; i<N; i++) {
12426            final String name = pkg.requestedPermissions.get(i);
12427            final BasePermission bp = mSettings.mPermissions.get(name);
12428            final boolean appSupportsRuntimePermissions = pkg.applicationInfo.targetSdkVersion
12429                    >= Build.VERSION_CODES.M;
12430
12431            if (DEBUG_INSTALL) {
12432                Log.i(TAG, "Package " + pkg.packageName + " checking " + name + ": " + bp);
12433            }
12434
12435            if (bp == null || bp.packageSetting == null) {
12436                if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) {
12437                    if (DEBUG_PERMISSIONS) {
12438                        Slog.i(TAG, "Unknown permission " + name
12439                                + " in package " + pkg.packageName);
12440                    }
12441                }
12442                continue;
12443            }
12444
12445
12446            // Limit ephemeral apps to ephemeral allowed permissions.
12447            if (pkg.applicationInfo.isInstantApp() && !bp.isInstant()) {
12448                if (DEBUG_PERMISSIONS) {
12449                    Log.i(TAG, "Denying non-ephemeral permission " + bp.name + " for package "
12450                            + pkg.packageName);
12451                }
12452                continue;
12453            }
12454
12455            if (bp.isRuntimeOnly() && !appSupportsRuntimePermissions) {
12456                if (DEBUG_PERMISSIONS) {
12457                    Log.i(TAG, "Denying runtime-only permission " + bp.name + " for package "
12458                            + pkg.packageName);
12459                }
12460                continue;
12461            }
12462
12463            final String perm = bp.name;
12464            boolean allowedSig = false;
12465            int grant = GRANT_DENIED;
12466
12467            // Keep track of app op permissions.
12468            if ((bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
12469                ArraySet<String> pkgs = mAppOpPermissionPackages.get(bp.name);
12470                if (pkgs == null) {
12471                    pkgs = new ArraySet<>();
12472                    mAppOpPermissionPackages.put(bp.name, pkgs);
12473                }
12474                pkgs.add(pkg.packageName);
12475            }
12476
12477            final int level = bp.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE;
12478            switch (level) {
12479                case PermissionInfo.PROTECTION_NORMAL: {
12480                    // For all apps normal permissions are install time ones.
12481                    grant = GRANT_INSTALL;
12482                } break;
12483
12484                case PermissionInfo.PROTECTION_DANGEROUS: {
12485                    // If a permission review is required for legacy apps we represent
12486                    // their permissions as always granted runtime ones since we need
12487                    // to keep the review required permission flag per user while an
12488                    // install permission's state is shared across all users.
12489                    if (!appSupportsRuntimePermissions && !mPermissionReviewRequired) {
12490                        // For legacy apps dangerous permissions are install time ones.
12491                        grant = GRANT_INSTALL;
12492                    } else if (origPermissions.hasInstallPermission(bp.name)) {
12493                        // For legacy apps that became modern, install becomes runtime.
12494                        grant = GRANT_UPGRADE;
12495                    } else if (mPromoteSystemApps
12496                            && isSystemApp(ps)
12497                            && mExistingSystemPackages.contains(ps.name)) {
12498                        // For legacy system apps, install becomes runtime.
12499                        // We cannot check hasInstallPermission() for system apps since those
12500                        // permissions were granted implicitly and not persisted pre-M.
12501                        grant = GRANT_UPGRADE;
12502                    } else {
12503                        // For modern apps keep runtime permissions unchanged.
12504                        grant = GRANT_RUNTIME;
12505                    }
12506                } break;
12507
12508                case PermissionInfo.PROTECTION_SIGNATURE: {
12509                    // For all apps signature permissions are install time ones.
12510                    allowedSig = grantSignaturePermission(perm, pkg, bp, origPermissions);
12511                    if (allowedSig) {
12512                        grant = GRANT_INSTALL;
12513                    }
12514                } break;
12515            }
12516
12517            if (DEBUG_PERMISSIONS) {
12518                Slog.i(TAG, "Granting permission " + perm + " to package " + pkg.packageName);
12519            }
12520
12521            if (grant != GRANT_DENIED) {
12522                if (!isSystemApp(ps) && ps.installPermissionsFixed) {
12523                    // If this is an existing, non-system package, then
12524                    // we can't add any new permissions to it.
12525                    if (!allowedSig && !origPermissions.hasInstallPermission(perm)) {
12526                        // Except...  if this is a permission that was added
12527                        // to the platform (note: need to only do this when
12528                        // updating the platform).
12529                        if (!isNewPlatformPermissionForPackage(perm, pkg)) {
12530                            grant = GRANT_DENIED;
12531                        }
12532                    }
12533                }
12534
12535                switch (grant) {
12536                    case GRANT_INSTALL: {
12537                        // Revoke this as runtime permission to handle the case of
12538                        // a runtime permission being downgraded to an install one.
12539                        // Also in permission review mode we keep dangerous permissions
12540                        // for legacy apps
12541                        for (int userId : UserManagerService.getInstance().getUserIds()) {
12542                            if (origPermissions.getRuntimePermissionState(
12543                                    bp.name, userId) != null) {
12544                                // Revoke the runtime permission and clear the flags.
12545                                origPermissions.revokeRuntimePermission(bp, userId);
12546                                origPermissions.updatePermissionFlags(bp, userId,
12547                                      PackageManager.MASK_PERMISSION_FLAGS, 0);
12548                                // If we revoked a permission permission, we have to write.
12549                                changedRuntimePermissionUserIds = ArrayUtils.appendInt(
12550                                        changedRuntimePermissionUserIds, userId);
12551                            }
12552                        }
12553                        // Grant an install permission.
12554                        if (permissionsState.grantInstallPermission(bp) !=
12555                                PermissionsState.PERMISSION_OPERATION_FAILURE) {
12556                            changedInstallPermission = true;
12557                        }
12558                    } break;
12559
12560                    case GRANT_RUNTIME: {
12561                        // Grant previously granted runtime permissions.
12562                        for (int userId : UserManagerService.getInstance().getUserIds()) {
12563                            PermissionState permissionState = origPermissions
12564                                    .getRuntimePermissionState(bp.name, userId);
12565                            int flags = permissionState != null
12566                                    ? permissionState.getFlags() : 0;
12567                            if (origPermissions.hasRuntimePermission(bp.name, userId)) {
12568                                // Don't propagate the permission in a permission review mode if
12569                                // the former was revoked, i.e. marked to not propagate on upgrade.
12570                                // Note that in a permission review mode install permissions are
12571                                // represented as constantly granted runtime ones since we need to
12572                                // keep a per user state associated with the permission. Also the
12573                                // revoke on upgrade flag is no longer applicable and is reset.
12574                                final boolean revokeOnUpgrade = (flags & PackageManager
12575                                        .FLAG_PERMISSION_REVOKE_ON_UPGRADE) != 0;
12576                                if (revokeOnUpgrade) {
12577                                    flags &= ~PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE;
12578                                    // Since we changed the flags, we have to write.
12579                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
12580                                            changedRuntimePermissionUserIds, userId);
12581                                }
12582                                if (!mPermissionReviewRequired || !revokeOnUpgrade) {
12583                                    if (permissionsState.grantRuntimePermission(bp, userId) ==
12584                                            PermissionsState.PERMISSION_OPERATION_FAILURE) {
12585                                        // If we cannot put the permission as it was,
12586                                        // we have to write.
12587                                        changedRuntimePermissionUserIds = ArrayUtils.appendInt(
12588                                                changedRuntimePermissionUserIds, userId);
12589                                    }
12590                                }
12591
12592                                // If the app supports runtime permissions no need for a review.
12593                                if (mPermissionReviewRequired
12594                                        && appSupportsRuntimePermissions
12595                                        && (flags & PackageManager
12596                                                .FLAG_PERMISSION_REVIEW_REQUIRED) != 0) {
12597                                    flags &= ~PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED;
12598                                    // Since we changed the flags, we have to write.
12599                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
12600                                            changedRuntimePermissionUserIds, userId);
12601                                }
12602                            } else if (mPermissionReviewRequired
12603                                    && !appSupportsRuntimePermissions) {
12604                                // For legacy apps that need a permission review, every new
12605                                // runtime permission is granted but it is pending a review.
12606                                // We also need to review only platform defined runtime
12607                                // permissions as these are the only ones the platform knows
12608                                // how to disable the API to simulate revocation as legacy
12609                                // apps don't expect to run with revoked permissions.
12610                                if (PLATFORM_PACKAGE_NAME.equals(bp.sourcePackage)) {
12611                                    if ((flags & FLAG_PERMISSION_REVIEW_REQUIRED) == 0) {
12612                                        flags |= FLAG_PERMISSION_REVIEW_REQUIRED;
12613                                        // We changed the flags, hence have to write.
12614                                        changedRuntimePermissionUserIds = ArrayUtils.appendInt(
12615                                                changedRuntimePermissionUserIds, userId);
12616                                    }
12617                                }
12618                                if (permissionsState.grantRuntimePermission(bp, userId)
12619                                        != PermissionsState.PERMISSION_OPERATION_FAILURE) {
12620                                    // We changed the permission, hence have to write.
12621                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
12622                                            changedRuntimePermissionUserIds, userId);
12623                                }
12624                            }
12625                            // Propagate the permission flags.
12626                            permissionsState.updatePermissionFlags(bp, userId, flags, flags);
12627                        }
12628                    } break;
12629
12630                    case GRANT_UPGRADE: {
12631                        // Grant runtime permissions for a previously held install permission.
12632                        PermissionState permissionState = origPermissions
12633                                .getInstallPermissionState(bp.name);
12634                        final int flags = permissionState != null ? permissionState.getFlags() : 0;
12635
12636                        if (origPermissions.revokeInstallPermission(bp)
12637                                != PermissionsState.PERMISSION_OPERATION_FAILURE) {
12638                            // We will be transferring the permission flags, so clear them.
12639                            origPermissions.updatePermissionFlags(bp, UserHandle.USER_ALL,
12640                                    PackageManager.MASK_PERMISSION_FLAGS, 0);
12641                            changedInstallPermission = true;
12642                        }
12643
12644                        // If the permission is not to be promoted to runtime we ignore it and
12645                        // also its other flags as they are not applicable to install permissions.
12646                        if ((flags & PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE) == 0) {
12647                            for (int userId : currentUserIds) {
12648                                if (permissionsState.grantRuntimePermission(bp, userId) !=
12649                                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
12650                                    // Transfer the permission flags.
12651                                    permissionsState.updatePermissionFlags(bp, userId,
12652                                            flags, flags);
12653                                    // If we granted the permission, we have to write.
12654                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
12655                                            changedRuntimePermissionUserIds, userId);
12656                                }
12657                            }
12658                        }
12659                    } break;
12660
12661                    default: {
12662                        if (packageOfInterest == null
12663                                || packageOfInterest.equals(pkg.packageName)) {
12664                            if (DEBUG_PERMISSIONS) {
12665                                Slog.i(TAG, "Not granting permission " + perm
12666                                        + " to package " + pkg.packageName
12667                                        + " because it was previously installed without");
12668                            }
12669                        }
12670                    } break;
12671                }
12672            } else {
12673                if (permissionsState.revokeInstallPermission(bp) !=
12674                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
12675                    // Also drop the permission flags.
12676                    permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL,
12677                            PackageManager.MASK_PERMISSION_FLAGS, 0);
12678                    changedInstallPermission = true;
12679                    Slog.i(TAG, "Un-granting permission " + perm
12680                            + " from package " + pkg.packageName
12681                            + " (protectionLevel=" + bp.protectionLevel
12682                            + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
12683                            + ")");
12684                } else if ((bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) == 0) {
12685                    // Don't print warning for app op permissions, since it is fine for them
12686                    // not to be granted, there is a UI for the user to decide.
12687                    if (DEBUG_PERMISSIONS
12688                            && (packageOfInterest == null
12689                                    || packageOfInterest.equals(pkg.packageName))) {
12690                        Slog.i(TAG, "Not granting permission " + perm
12691                                + " to package " + pkg.packageName
12692                                + " (protectionLevel=" + bp.protectionLevel
12693                                + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
12694                                + ")");
12695                    }
12696                }
12697            }
12698        }
12699
12700        if ((changedInstallPermission || replace) && !ps.installPermissionsFixed &&
12701                !isSystemApp(ps) || isUpdatedSystemApp(ps)){
12702            // This is the first that we have heard about this package, so the
12703            // permissions we have now selected are fixed until explicitly
12704            // changed.
12705            ps.installPermissionsFixed = true;
12706        }
12707
12708        // Persist the runtime permissions state for users with changes. If permissions
12709        // were revoked because no app in the shared user declares them we have to
12710        // write synchronously to avoid losing runtime permissions state.
12711        for (int userId : changedRuntimePermissionUserIds) {
12712            mSettings.writeRuntimePermissionsForUserLPr(userId, runtimePermissionsRevoked);
12713        }
12714    }
12715
12716    private boolean isNewPlatformPermissionForPackage(String perm, PackageParser.Package pkg) {
12717        boolean allowed = false;
12718        final int NP = PackageParser.NEW_PERMISSIONS.length;
12719        for (int ip=0; ip<NP; ip++) {
12720            final PackageParser.NewPermissionInfo npi
12721                    = PackageParser.NEW_PERMISSIONS[ip];
12722            if (npi.name.equals(perm)
12723                    && pkg.applicationInfo.targetSdkVersion < npi.sdkVersion) {
12724                allowed = true;
12725                Log.i(TAG, "Auto-granting " + perm + " to old pkg "
12726                        + pkg.packageName);
12727                break;
12728            }
12729        }
12730        return allowed;
12731    }
12732
12733    private boolean grantSignaturePermission(String perm, PackageParser.Package pkg,
12734            BasePermission bp, PermissionsState origPermissions) {
12735        boolean privilegedPermission = (bp.protectionLevel
12736                & PermissionInfo.PROTECTION_FLAG_PRIVILEGED) != 0;
12737        boolean privappPermissionsDisable =
12738                RoSystemProperties.CONTROL_PRIVAPP_PERMISSIONS_DISABLE;
12739        boolean platformPermission = PLATFORM_PACKAGE_NAME.equals(bp.sourcePackage);
12740        boolean platformPackage = PLATFORM_PACKAGE_NAME.equals(pkg.packageName);
12741        if (!privappPermissionsDisable && privilegedPermission && pkg.isPrivilegedApp()
12742                && !platformPackage && platformPermission) {
12743            ArraySet<String> wlPermissions = SystemConfig.getInstance()
12744                    .getPrivAppPermissions(pkg.packageName);
12745            boolean whitelisted = wlPermissions != null && wlPermissions.contains(perm);
12746            if (!whitelisted) {
12747                Slog.w(TAG, "Privileged permission " + perm + " for package "
12748                        + pkg.packageName + " - not in privapp-permissions whitelist");
12749                // Only report violations for apps on system image
12750                if (!mSystemReady && !pkg.isUpdatedSystemApp()) {
12751                    if (mPrivappPermissionsViolations == null) {
12752                        mPrivappPermissionsViolations = new ArraySet<>();
12753                    }
12754                    mPrivappPermissionsViolations.add(pkg.packageName + ": " + perm);
12755                }
12756                if (RoSystemProperties.CONTROL_PRIVAPP_PERMISSIONS_ENFORCE) {
12757                    return false;
12758                }
12759            }
12760        }
12761        boolean allowed = (compareSignatures(
12762                bp.packageSetting.signatures.mSignatures, pkg.mSignatures)
12763                        == PackageManager.SIGNATURE_MATCH)
12764                || (compareSignatures(mPlatformPackage.mSignatures, pkg.mSignatures)
12765                        == PackageManager.SIGNATURE_MATCH);
12766        if (!allowed && privilegedPermission) {
12767            if (isSystemApp(pkg)) {
12768                // For updated system applications, a system permission
12769                // is granted only if it had been defined by the original application.
12770                if (pkg.isUpdatedSystemApp()) {
12771                    final PackageSetting sysPs = mSettings
12772                            .getDisabledSystemPkgLPr(pkg.packageName);
12773                    if (sysPs != null && sysPs.getPermissionsState().hasInstallPermission(perm)) {
12774                        // If the original was granted this permission, we take
12775                        // that grant decision as read and propagate it to the
12776                        // update.
12777                        if (sysPs.isPrivileged()) {
12778                            allowed = true;
12779                        }
12780                    } else {
12781                        // The system apk may have been updated with an older
12782                        // version of the one on the data partition, but which
12783                        // granted a new system permission that it didn't have
12784                        // before.  In this case we do want to allow the app to
12785                        // now get the new permission if the ancestral apk is
12786                        // privileged to get it.
12787                        if (sysPs != null && sysPs.pkg != null && sysPs.isPrivileged()) {
12788                            for (int j = 0; j < sysPs.pkg.requestedPermissions.size(); j++) {
12789                                if (perm.equals(sysPs.pkg.requestedPermissions.get(j))) {
12790                                    allowed = true;
12791                                    break;
12792                                }
12793                            }
12794                        }
12795                        // Also if a privileged parent package on the system image or any of
12796                        // its children requested a privileged permission, the updated child
12797                        // packages can also get the permission.
12798                        if (pkg.parentPackage != null) {
12799                            final PackageSetting disabledSysParentPs = mSettings
12800                                    .getDisabledSystemPkgLPr(pkg.parentPackage.packageName);
12801                            if (disabledSysParentPs != null && disabledSysParentPs.pkg != null
12802                                    && disabledSysParentPs.isPrivileged()) {
12803                                if (isPackageRequestingPermission(disabledSysParentPs.pkg, perm)) {
12804                                    allowed = true;
12805                                } else if (disabledSysParentPs.pkg.childPackages != null) {
12806                                    final int count = disabledSysParentPs.pkg.childPackages.size();
12807                                    for (int i = 0; i < count; i++) {
12808                                        PackageParser.Package disabledSysChildPkg =
12809                                                disabledSysParentPs.pkg.childPackages.get(i);
12810                                        if (isPackageRequestingPermission(disabledSysChildPkg,
12811                                                perm)) {
12812                                            allowed = true;
12813                                            break;
12814                                        }
12815                                    }
12816                                }
12817                            }
12818                        }
12819                    }
12820                } else {
12821                    allowed = isPrivilegedApp(pkg);
12822                }
12823            }
12824        }
12825        if (!allowed) {
12826            if (!allowed && (bp.protectionLevel
12827                    & PermissionInfo.PROTECTION_FLAG_PRE23) != 0
12828                    && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) {
12829                // If this was a previously normal/dangerous permission that got moved
12830                // to a system permission as part of the runtime permission redesign, then
12831                // we still want to blindly grant it to old apps.
12832                allowed = true;
12833            }
12834            if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_INSTALLER) != 0
12835                    && pkg.packageName.equals(mRequiredInstallerPackage)) {
12836                // If this permission is to be granted to the system installer and
12837                // this app is an installer, then it gets the permission.
12838                allowed = true;
12839            }
12840            if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_VERIFIER) != 0
12841                    && pkg.packageName.equals(mRequiredVerifierPackage)) {
12842                // If this permission is to be granted to the system verifier and
12843                // this app is a verifier, then it gets the permission.
12844                allowed = true;
12845            }
12846            if (!allowed && (bp.protectionLevel
12847                    & PermissionInfo.PROTECTION_FLAG_PREINSTALLED) != 0
12848                    && isSystemApp(pkg)) {
12849                // Any pre-installed system app is allowed to get this permission.
12850                allowed = true;
12851            }
12852            if (!allowed && (bp.protectionLevel
12853                    & PermissionInfo.PROTECTION_FLAG_DEVELOPMENT) != 0) {
12854                // For development permissions, a development permission
12855                // is granted only if it was already granted.
12856                allowed = origPermissions.hasInstallPermission(perm);
12857            }
12858            if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_SETUP) != 0
12859                    && pkg.packageName.equals(mSetupWizardPackage)) {
12860                // If this permission is to be granted to the system setup wizard and
12861                // this app is a setup wizard, then it gets the permission.
12862                allowed = true;
12863            }
12864        }
12865        return allowed;
12866    }
12867
12868    private boolean isPackageRequestingPermission(PackageParser.Package pkg, String permission) {
12869        final int permCount = pkg.requestedPermissions.size();
12870        for (int j = 0; j < permCount; j++) {
12871            String requestedPermission = pkg.requestedPermissions.get(j);
12872            if (permission.equals(requestedPermission)) {
12873                return true;
12874            }
12875        }
12876        return false;
12877    }
12878
12879    final class ActivityIntentResolver
12880            extends IntentResolver<PackageParser.ActivityIntentInfo, ResolveInfo> {
12881        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
12882                boolean defaultOnly, int userId) {
12883            if (!sUserManager.exists(userId)) return null;
12884            mFlags = (defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0);
12885            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
12886        }
12887
12888        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
12889                int userId) {
12890            if (!sUserManager.exists(userId)) return null;
12891            mFlags = flags;
12892            return super.queryIntent(intent, resolvedType,
12893                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0,
12894                    userId);
12895        }
12896
12897        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
12898                int flags, ArrayList<PackageParser.Activity> packageActivities, int userId) {
12899            if (!sUserManager.exists(userId)) return null;
12900            if (packageActivities == null) {
12901                return null;
12902            }
12903            mFlags = flags;
12904            final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0;
12905            final int N = packageActivities.size();
12906            ArrayList<PackageParser.ActivityIntentInfo[]> listCut =
12907                new ArrayList<PackageParser.ActivityIntentInfo[]>(N);
12908
12909            ArrayList<PackageParser.ActivityIntentInfo> intentFilters;
12910            for (int i = 0; i < N; ++i) {
12911                intentFilters = packageActivities.get(i).intents;
12912                if (intentFilters != null && intentFilters.size() > 0) {
12913                    PackageParser.ActivityIntentInfo[] array =
12914                            new PackageParser.ActivityIntentInfo[intentFilters.size()];
12915                    intentFilters.toArray(array);
12916                    listCut.add(array);
12917                }
12918            }
12919            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
12920        }
12921
12922        /**
12923         * Finds a privileged activity that matches the specified activity names.
12924         */
12925        private PackageParser.Activity findMatchingActivity(
12926                List<PackageParser.Activity> activityList, ActivityInfo activityInfo) {
12927            for (PackageParser.Activity sysActivity : activityList) {
12928                if (sysActivity.info.name.equals(activityInfo.name)) {
12929                    return sysActivity;
12930                }
12931                if (sysActivity.info.name.equals(activityInfo.targetActivity)) {
12932                    return sysActivity;
12933                }
12934                if (sysActivity.info.targetActivity != null) {
12935                    if (sysActivity.info.targetActivity.equals(activityInfo.name)) {
12936                        return sysActivity;
12937                    }
12938                    if (sysActivity.info.targetActivity.equals(activityInfo.targetActivity)) {
12939                        return sysActivity;
12940                    }
12941                }
12942            }
12943            return null;
12944        }
12945
12946        public class IterGenerator<E> {
12947            public Iterator<E> generate(ActivityIntentInfo info) {
12948                return null;
12949            }
12950        }
12951
12952        public class ActionIterGenerator extends IterGenerator<String> {
12953            @Override
12954            public Iterator<String> generate(ActivityIntentInfo info) {
12955                return info.actionsIterator();
12956            }
12957        }
12958
12959        public class CategoriesIterGenerator extends IterGenerator<String> {
12960            @Override
12961            public Iterator<String> generate(ActivityIntentInfo info) {
12962                return info.categoriesIterator();
12963            }
12964        }
12965
12966        public class SchemesIterGenerator extends IterGenerator<String> {
12967            @Override
12968            public Iterator<String> generate(ActivityIntentInfo info) {
12969                return info.schemesIterator();
12970            }
12971        }
12972
12973        public class AuthoritiesIterGenerator extends IterGenerator<IntentFilter.AuthorityEntry> {
12974            @Override
12975            public Iterator<IntentFilter.AuthorityEntry> generate(ActivityIntentInfo info) {
12976                return info.authoritiesIterator();
12977            }
12978        }
12979
12980        /**
12981         * <em>WARNING</em> for performance reasons, the passed in intentList WILL BE
12982         * MODIFIED. Do not pass in a list that should not be changed.
12983         */
12984        private <T> void getIntentListSubset(List<ActivityIntentInfo> intentList,
12985                IterGenerator<T> generator, Iterator<T> searchIterator) {
12986            // loop through the set of actions; every one must be found in the intent filter
12987            while (searchIterator.hasNext()) {
12988                // we must have at least one filter in the list to consider a match
12989                if (intentList.size() == 0) {
12990                    break;
12991                }
12992
12993                final T searchAction = searchIterator.next();
12994
12995                // loop through the set of intent filters
12996                final Iterator<ActivityIntentInfo> intentIter = intentList.iterator();
12997                while (intentIter.hasNext()) {
12998                    final ActivityIntentInfo intentInfo = intentIter.next();
12999                    boolean selectionFound = false;
13000
13001                    // loop through the intent filter's selection criteria; at least one
13002                    // of them must match the searched criteria
13003                    final Iterator<T> intentSelectionIter = generator.generate(intentInfo);
13004                    while (intentSelectionIter != null && intentSelectionIter.hasNext()) {
13005                        final T intentSelection = intentSelectionIter.next();
13006                        if (intentSelection != null && intentSelection.equals(searchAction)) {
13007                            selectionFound = true;
13008                            break;
13009                        }
13010                    }
13011
13012                    // the selection criteria wasn't found in this filter's set; this filter
13013                    // is not a potential match
13014                    if (!selectionFound) {
13015                        intentIter.remove();
13016                    }
13017                }
13018            }
13019        }
13020
13021        private boolean isProtectedAction(ActivityIntentInfo filter) {
13022            final Iterator<String> actionsIter = filter.actionsIterator();
13023            while (actionsIter != null && actionsIter.hasNext()) {
13024                final String filterAction = actionsIter.next();
13025                if (PROTECTED_ACTIONS.contains(filterAction)) {
13026                    return true;
13027                }
13028            }
13029            return false;
13030        }
13031
13032        /**
13033         * Adjusts the priority of the given intent filter according to policy.
13034         * <p>
13035         * <ul>
13036         * <li>The priority for non privileged applications is capped to '0'</li>
13037         * <li>The priority for protected actions on privileged applications is capped to '0'</li>
13038         * <li>The priority for unbundled updates to privileged applications is capped to the
13039         *      priority defined on the system partition</li>
13040         * </ul>
13041         * <p>
13042         * <em>NOTE:</em> There is one exception. For security reasons, the setup wizard is
13043         * allowed to obtain any priority on any action.
13044         */
13045        private void adjustPriority(
13046                List<PackageParser.Activity> systemActivities, ActivityIntentInfo intent) {
13047            // nothing to do; priority is fine as-is
13048            if (intent.getPriority() <= 0) {
13049                return;
13050            }
13051
13052            final ActivityInfo activityInfo = intent.activity.info;
13053            final ApplicationInfo applicationInfo = activityInfo.applicationInfo;
13054
13055            final boolean privilegedApp =
13056                    ((applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0);
13057            if (!privilegedApp) {
13058                // non-privileged applications can never define a priority >0
13059                if (DEBUG_FILTERS) {
13060                    Slog.i(TAG, "Non-privileged app; cap priority to 0;"
13061                            + " package: " + applicationInfo.packageName
13062                            + " activity: " + intent.activity.className
13063                            + " origPrio: " + intent.getPriority());
13064                }
13065                intent.setPriority(0);
13066                return;
13067            }
13068
13069            if (systemActivities == null) {
13070                // the system package is not disabled; we're parsing the system partition
13071                if (isProtectedAction(intent)) {
13072                    if (mDeferProtectedFilters) {
13073                        // We can't deal with these just yet. No component should ever obtain a
13074                        // >0 priority for a protected actions, with ONE exception -- the setup
13075                        // wizard. The setup wizard, however, cannot be known until we're able to
13076                        // query it for the category CATEGORY_SETUP_WIZARD. Which we can't do
13077                        // until all intent filters have been processed. Chicken, meet egg.
13078                        // Let the filter temporarily have a high priority and rectify the
13079                        // priorities after all system packages have been scanned.
13080                        mProtectedFilters.add(intent);
13081                        if (DEBUG_FILTERS) {
13082                            Slog.i(TAG, "Protected action; save for later;"
13083                                    + " package: " + applicationInfo.packageName
13084                                    + " activity: " + intent.activity.className
13085                                    + " origPrio: " + intent.getPriority());
13086                        }
13087                        return;
13088                    } else {
13089                        if (DEBUG_FILTERS && mSetupWizardPackage == null) {
13090                            Slog.i(TAG, "No setup wizard;"
13091                                + " All protected intents capped to priority 0");
13092                        }
13093                        if (intent.activity.info.packageName.equals(mSetupWizardPackage)) {
13094                            if (DEBUG_FILTERS) {
13095                                Slog.i(TAG, "Found setup wizard;"
13096                                    + " allow priority " + intent.getPriority() + ";"
13097                                    + " package: " + intent.activity.info.packageName
13098                                    + " activity: " + intent.activity.className
13099                                    + " priority: " + intent.getPriority());
13100                            }
13101                            // setup wizard gets whatever it wants
13102                            return;
13103                        }
13104                        if (DEBUG_FILTERS) {
13105                            Slog.i(TAG, "Protected action; cap priority to 0;"
13106                                    + " package: " + intent.activity.info.packageName
13107                                    + " activity: " + intent.activity.className
13108                                    + " origPrio: " + intent.getPriority());
13109                        }
13110                        intent.setPriority(0);
13111                        return;
13112                    }
13113                }
13114                // privileged apps on the system image get whatever priority they request
13115                return;
13116            }
13117
13118            // privileged app unbundled update ... try to find the same activity
13119            final PackageParser.Activity foundActivity =
13120                    findMatchingActivity(systemActivities, activityInfo);
13121            if (foundActivity == null) {
13122                // this is a new activity; it cannot obtain >0 priority
13123                if (DEBUG_FILTERS) {
13124                    Slog.i(TAG, "New activity; cap priority to 0;"
13125                            + " package: " + applicationInfo.packageName
13126                            + " activity: " + intent.activity.className
13127                            + " origPrio: " + intent.getPriority());
13128                }
13129                intent.setPriority(0);
13130                return;
13131            }
13132
13133            // found activity, now check for filter equivalence
13134
13135            // a shallow copy is enough; we modify the list, not its contents
13136            final List<ActivityIntentInfo> intentListCopy =
13137                    new ArrayList<>(foundActivity.intents);
13138            final List<ActivityIntentInfo> foundFilters = findFilters(intent);
13139
13140            // find matching action subsets
13141            final Iterator<String> actionsIterator = intent.actionsIterator();
13142            if (actionsIterator != null) {
13143                getIntentListSubset(
13144                        intentListCopy, new ActionIterGenerator(), actionsIterator);
13145                if (intentListCopy.size() == 0) {
13146                    // no more intents to match; we're not equivalent
13147                    if (DEBUG_FILTERS) {
13148                        Slog.i(TAG, "Mismatched action; cap priority to 0;"
13149                                + " package: " + applicationInfo.packageName
13150                                + " activity: " + intent.activity.className
13151                                + " origPrio: " + intent.getPriority());
13152                    }
13153                    intent.setPriority(0);
13154                    return;
13155                }
13156            }
13157
13158            // find matching category subsets
13159            final Iterator<String> categoriesIterator = intent.categoriesIterator();
13160            if (categoriesIterator != null) {
13161                getIntentListSubset(intentListCopy, new CategoriesIterGenerator(),
13162                        categoriesIterator);
13163                if (intentListCopy.size() == 0) {
13164                    // no more intents to match; we're not equivalent
13165                    if (DEBUG_FILTERS) {
13166                        Slog.i(TAG, "Mismatched category; cap priority to 0;"
13167                                + " package: " + applicationInfo.packageName
13168                                + " activity: " + intent.activity.className
13169                                + " origPrio: " + intent.getPriority());
13170                    }
13171                    intent.setPriority(0);
13172                    return;
13173                }
13174            }
13175
13176            // find matching schemes subsets
13177            final Iterator<String> schemesIterator = intent.schemesIterator();
13178            if (schemesIterator != null) {
13179                getIntentListSubset(intentListCopy, new SchemesIterGenerator(),
13180                        schemesIterator);
13181                if (intentListCopy.size() == 0) {
13182                    // no more intents to match; we're not equivalent
13183                    if (DEBUG_FILTERS) {
13184                        Slog.i(TAG, "Mismatched scheme; cap priority to 0;"
13185                                + " package: " + applicationInfo.packageName
13186                                + " activity: " + intent.activity.className
13187                                + " origPrio: " + intent.getPriority());
13188                    }
13189                    intent.setPriority(0);
13190                    return;
13191                }
13192            }
13193
13194            // find matching authorities subsets
13195            final Iterator<IntentFilter.AuthorityEntry>
13196                    authoritiesIterator = intent.authoritiesIterator();
13197            if (authoritiesIterator != null) {
13198                getIntentListSubset(intentListCopy,
13199                        new AuthoritiesIterGenerator(),
13200                        authoritiesIterator);
13201                if (intentListCopy.size() == 0) {
13202                    // no more intents to match; we're not equivalent
13203                    if (DEBUG_FILTERS) {
13204                        Slog.i(TAG, "Mismatched authority; cap priority to 0;"
13205                                + " package: " + applicationInfo.packageName
13206                                + " activity: " + intent.activity.className
13207                                + " origPrio: " + intent.getPriority());
13208                    }
13209                    intent.setPriority(0);
13210                    return;
13211                }
13212            }
13213
13214            // we found matching filter(s); app gets the max priority of all intents
13215            int cappedPriority = 0;
13216            for (int i = intentListCopy.size() - 1; i >= 0; --i) {
13217                cappedPriority = Math.max(cappedPriority, intentListCopy.get(i).getPriority());
13218            }
13219            if (intent.getPriority() > cappedPriority) {
13220                if (DEBUG_FILTERS) {
13221                    Slog.i(TAG, "Found matching filter(s);"
13222                            + " cap priority to " + cappedPriority + ";"
13223                            + " package: " + applicationInfo.packageName
13224                            + " activity: " + intent.activity.className
13225                            + " origPrio: " + intent.getPriority());
13226                }
13227                intent.setPriority(cappedPriority);
13228                return;
13229            }
13230            // all this for nothing; the requested priority was <= what was on the system
13231        }
13232
13233        public final void addActivity(PackageParser.Activity a, String type) {
13234            mActivities.put(a.getComponentName(), a);
13235            if (DEBUG_SHOW_INFO)
13236                Log.v(
13237                TAG, "  " + type + " " +
13238                (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":");
13239            if (DEBUG_SHOW_INFO)
13240                Log.v(TAG, "    Class=" + a.info.name);
13241            final int NI = a.intents.size();
13242            for (int j=0; j<NI; j++) {
13243                PackageParser.ActivityIntentInfo intent = a.intents.get(j);
13244                if ("activity".equals(type)) {
13245                    final PackageSetting ps =
13246                            mSettings.getDisabledSystemPkgLPr(intent.activity.info.packageName);
13247                    final List<PackageParser.Activity> systemActivities =
13248                            ps != null && ps.pkg != null ? ps.pkg.activities : null;
13249                    adjustPriority(systemActivities, intent);
13250                }
13251                if (DEBUG_SHOW_INFO) {
13252                    Log.v(TAG, "    IntentFilter:");
13253                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
13254                }
13255                if (!intent.debugCheck()) {
13256                    Log.w(TAG, "==> For Activity " + a.info.name);
13257                }
13258                addFilter(intent);
13259            }
13260        }
13261
13262        public final void removeActivity(PackageParser.Activity a, String type) {
13263            mActivities.remove(a.getComponentName());
13264            if (DEBUG_SHOW_INFO) {
13265                Log.v(TAG, "  " + type + " "
13266                        + (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel
13267                                : a.info.name) + ":");
13268                Log.v(TAG, "    Class=" + a.info.name);
13269            }
13270            final int NI = a.intents.size();
13271            for (int j=0; j<NI; j++) {
13272                PackageParser.ActivityIntentInfo intent = a.intents.get(j);
13273                if (DEBUG_SHOW_INFO) {
13274                    Log.v(TAG, "    IntentFilter:");
13275                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
13276                }
13277                removeFilter(intent);
13278            }
13279        }
13280
13281        @Override
13282        protected boolean allowFilterResult(
13283                PackageParser.ActivityIntentInfo filter, List<ResolveInfo> dest) {
13284            ActivityInfo filterAi = filter.activity.info;
13285            for (int i=dest.size()-1; i>=0; i--) {
13286                ActivityInfo destAi = dest.get(i).activityInfo;
13287                if (destAi.name == filterAi.name
13288                        && destAi.packageName == filterAi.packageName) {
13289                    return false;
13290                }
13291            }
13292            return true;
13293        }
13294
13295        @Override
13296        protected ActivityIntentInfo[] newArray(int size) {
13297            return new ActivityIntentInfo[size];
13298        }
13299
13300        @Override
13301        protected boolean isFilterStopped(PackageParser.ActivityIntentInfo filter, int userId) {
13302            if (!sUserManager.exists(userId)) return true;
13303            PackageParser.Package p = filter.activity.owner;
13304            if (p != null) {
13305                PackageSetting ps = (PackageSetting)p.mExtras;
13306                if (ps != null) {
13307                    // System apps are never considered stopped for purposes of
13308                    // filtering, because there may be no way for the user to
13309                    // actually re-launch them.
13310                    return (ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0
13311                            && ps.getStopped(userId);
13312                }
13313            }
13314            return false;
13315        }
13316
13317        @Override
13318        protected boolean isPackageForFilter(String packageName,
13319                PackageParser.ActivityIntentInfo info) {
13320            return packageName.equals(info.activity.owner.packageName);
13321        }
13322
13323        @Override
13324        protected ResolveInfo newResult(PackageParser.ActivityIntentInfo info,
13325                int match, int userId) {
13326            if (!sUserManager.exists(userId)) return null;
13327            if (!mSettings.isEnabledAndMatchLPr(info.activity.info, mFlags, userId)) {
13328                return null;
13329            }
13330            final PackageParser.Activity activity = info.activity;
13331            PackageSetting ps = (PackageSetting) activity.owner.mExtras;
13332            if (ps == null) {
13333                return null;
13334            }
13335            final PackageUserState userState = ps.readUserState(userId);
13336            ActivityInfo ai =
13337                    PackageParser.generateActivityInfo(activity, mFlags, userState, userId);
13338            if (ai == null) {
13339                return null;
13340            }
13341            final boolean matchExplicitlyVisibleOnly =
13342                    (mFlags & PackageManager.MATCH_EXPLICITLY_VISIBLE_ONLY) != 0;
13343            final boolean matchVisibleToInstantApp =
13344                    (mFlags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
13345            final boolean componentVisible =
13346                    matchVisibleToInstantApp
13347                    && info.isVisibleToInstantApp()
13348                    && (!matchExplicitlyVisibleOnly || info.isExplicitlyVisibleToInstantApp());
13349            final boolean matchInstantApp = (mFlags & PackageManager.MATCH_INSTANT) != 0;
13350            // throw out filters that aren't visible to ephemeral apps
13351            if (matchVisibleToInstantApp && !(componentVisible || userState.instantApp)) {
13352                return null;
13353            }
13354            // throw out instant app filters if we're not explicitly requesting them
13355            if (!matchInstantApp && userState.instantApp) {
13356                return null;
13357            }
13358            // throw out instant app filters if updates are available; will trigger
13359            // instant app resolution
13360            if (userState.instantApp && ps.isUpdateAvailable()) {
13361                return null;
13362            }
13363            final ResolveInfo res = new ResolveInfo();
13364            res.activityInfo = ai;
13365            if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
13366                res.filter = info;
13367            }
13368            if (info != null) {
13369                res.handleAllWebDataURI = info.handleAllWebDataURI();
13370            }
13371            res.priority = info.getPriority();
13372            res.preferredOrder = activity.owner.mPreferredOrder;
13373            //System.out.println("Result: " + res.activityInfo.className +
13374            //                   " = " + res.priority);
13375            res.match = match;
13376            res.isDefault = info.hasDefault;
13377            res.labelRes = info.labelRes;
13378            res.nonLocalizedLabel = info.nonLocalizedLabel;
13379            if (userNeedsBadging(userId)) {
13380                res.noResourceId = true;
13381            } else {
13382                res.icon = info.icon;
13383            }
13384            res.iconResourceId = info.icon;
13385            res.system = res.activityInfo.applicationInfo.isSystemApp();
13386            res.isInstantAppAvailable = userState.instantApp;
13387            return res;
13388        }
13389
13390        @Override
13391        protected void sortResults(List<ResolveInfo> results) {
13392            Collections.sort(results, mResolvePrioritySorter);
13393        }
13394
13395        @Override
13396        protected void dumpFilter(PrintWriter out, String prefix,
13397                PackageParser.ActivityIntentInfo filter) {
13398            out.print(prefix); out.print(
13399                    Integer.toHexString(System.identityHashCode(filter.activity)));
13400                    out.print(' ');
13401                    filter.activity.printComponentShortName(out);
13402                    out.print(" filter ");
13403                    out.println(Integer.toHexString(System.identityHashCode(filter)));
13404        }
13405
13406        @Override
13407        protected Object filterToLabel(PackageParser.ActivityIntentInfo filter) {
13408            return filter.activity;
13409        }
13410
13411        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
13412            PackageParser.Activity activity = (PackageParser.Activity)label;
13413            out.print(prefix); out.print(
13414                    Integer.toHexString(System.identityHashCode(activity)));
13415                    out.print(' ');
13416                    activity.printComponentShortName(out);
13417            if (count > 1) {
13418                out.print(" ("); out.print(count); out.print(" filters)");
13419            }
13420            out.println();
13421        }
13422
13423        // Keys are String (activity class name), values are Activity.
13424        private final ArrayMap<ComponentName, PackageParser.Activity> mActivities
13425                = new ArrayMap<ComponentName, PackageParser.Activity>();
13426        private int mFlags;
13427    }
13428
13429    private final class ServiceIntentResolver
13430            extends IntentResolver<PackageParser.ServiceIntentInfo, ResolveInfo> {
13431        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
13432                boolean defaultOnly, int userId) {
13433            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
13434            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
13435        }
13436
13437        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
13438                int userId) {
13439            if (!sUserManager.exists(userId)) return null;
13440            mFlags = flags;
13441            return super.queryIntent(intent, resolvedType,
13442                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0,
13443                    userId);
13444        }
13445
13446        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
13447                int flags, ArrayList<PackageParser.Service> packageServices, int userId) {
13448            if (!sUserManager.exists(userId)) return null;
13449            if (packageServices == null) {
13450                return null;
13451            }
13452            mFlags = flags;
13453            final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0;
13454            final int N = packageServices.size();
13455            ArrayList<PackageParser.ServiceIntentInfo[]> listCut =
13456                new ArrayList<PackageParser.ServiceIntentInfo[]>(N);
13457
13458            ArrayList<PackageParser.ServiceIntentInfo> intentFilters;
13459            for (int i = 0; i < N; ++i) {
13460                intentFilters = packageServices.get(i).intents;
13461                if (intentFilters != null && intentFilters.size() > 0) {
13462                    PackageParser.ServiceIntentInfo[] array =
13463                            new PackageParser.ServiceIntentInfo[intentFilters.size()];
13464                    intentFilters.toArray(array);
13465                    listCut.add(array);
13466                }
13467            }
13468            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
13469        }
13470
13471        public final void addService(PackageParser.Service s) {
13472            mServices.put(s.getComponentName(), s);
13473            if (DEBUG_SHOW_INFO) {
13474                Log.v(TAG, "  "
13475                        + (s.info.nonLocalizedLabel != null
13476                        ? s.info.nonLocalizedLabel : s.info.name) + ":");
13477                Log.v(TAG, "    Class=" + s.info.name);
13478            }
13479            final int NI = s.intents.size();
13480            int j;
13481            for (j=0; j<NI; j++) {
13482                PackageParser.ServiceIntentInfo intent = s.intents.get(j);
13483                if (DEBUG_SHOW_INFO) {
13484                    Log.v(TAG, "    IntentFilter:");
13485                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
13486                }
13487                if (!intent.debugCheck()) {
13488                    Log.w(TAG, "==> For Service " + s.info.name);
13489                }
13490                addFilter(intent);
13491            }
13492        }
13493
13494        public final void removeService(PackageParser.Service s) {
13495            mServices.remove(s.getComponentName());
13496            if (DEBUG_SHOW_INFO) {
13497                Log.v(TAG, "  " + (s.info.nonLocalizedLabel != null
13498                        ? s.info.nonLocalizedLabel : s.info.name) + ":");
13499                Log.v(TAG, "    Class=" + s.info.name);
13500            }
13501            final int NI = s.intents.size();
13502            int j;
13503            for (j=0; j<NI; j++) {
13504                PackageParser.ServiceIntentInfo intent = s.intents.get(j);
13505                if (DEBUG_SHOW_INFO) {
13506                    Log.v(TAG, "    IntentFilter:");
13507                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
13508                }
13509                removeFilter(intent);
13510            }
13511        }
13512
13513        @Override
13514        protected boolean allowFilterResult(
13515                PackageParser.ServiceIntentInfo filter, List<ResolveInfo> dest) {
13516            ServiceInfo filterSi = filter.service.info;
13517            for (int i=dest.size()-1; i>=0; i--) {
13518                ServiceInfo destAi = dest.get(i).serviceInfo;
13519                if (destAi.name == filterSi.name
13520                        && destAi.packageName == filterSi.packageName) {
13521                    return false;
13522                }
13523            }
13524            return true;
13525        }
13526
13527        @Override
13528        protected PackageParser.ServiceIntentInfo[] newArray(int size) {
13529            return new PackageParser.ServiceIntentInfo[size];
13530        }
13531
13532        @Override
13533        protected boolean isFilterStopped(PackageParser.ServiceIntentInfo filter, int userId) {
13534            if (!sUserManager.exists(userId)) return true;
13535            PackageParser.Package p = filter.service.owner;
13536            if (p != null) {
13537                PackageSetting ps = (PackageSetting)p.mExtras;
13538                if (ps != null) {
13539                    // System apps are never considered stopped for purposes of
13540                    // filtering, because there may be no way for the user to
13541                    // actually re-launch them.
13542                    return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0
13543                            && ps.getStopped(userId);
13544                }
13545            }
13546            return false;
13547        }
13548
13549        @Override
13550        protected boolean isPackageForFilter(String packageName,
13551                PackageParser.ServiceIntentInfo info) {
13552            return packageName.equals(info.service.owner.packageName);
13553        }
13554
13555        @Override
13556        protected ResolveInfo newResult(PackageParser.ServiceIntentInfo filter,
13557                int match, int userId) {
13558            if (!sUserManager.exists(userId)) return null;
13559            final PackageParser.ServiceIntentInfo info = (PackageParser.ServiceIntentInfo)filter;
13560            if (!mSettings.isEnabledAndMatchLPr(info.service.info, mFlags, userId)) {
13561                return null;
13562            }
13563            final PackageParser.Service service = info.service;
13564            PackageSetting ps = (PackageSetting) service.owner.mExtras;
13565            if (ps == null) {
13566                return null;
13567            }
13568            final PackageUserState userState = ps.readUserState(userId);
13569            ServiceInfo si = PackageParser.generateServiceInfo(service, mFlags,
13570                    userState, userId);
13571            if (si == null) {
13572                return null;
13573            }
13574            final boolean matchVisibleToInstantApp =
13575                    (mFlags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
13576            final boolean isInstantApp = (mFlags & PackageManager.MATCH_INSTANT) != 0;
13577            // throw out filters that aren't visible to ephemeral apps
13578            if (matchVisibleToInstantApp
13579                    && !(info.isVisibleToInstantApp() || userState.instantApp)) {
13580                return null;
13581            }
13582            // throw out ephemeral filters if we're not explicitly requesting them
13583            if (!isInstantApp && userState.instantApp) {
13584                return null;
13585            }
13586            // throw out instant app filters if updates are available; will trigger
13587            // instant app resolution
13588            if (userState.instantApp && ps.isUpdateAvailable()) {
13589                return null;
13590            }
13591            final ResolveInfo res = new ResolveInfo();
13592            res.serviceInfo = si;
13593            if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
13594                res.filter = filter;
13595            }
13596            res.priority = info.getPriority();
13597            res.preferredOrder = service.owner.mPreferredOrder;
13598            res.match = match;
13599            res.isDefault = info.hasDefault;
13600            res.labelRes = info.labelRes;
13601            res.nonLocalizedLabel = info.nonLocalizedLabel;
13602            res.icon = info.icon;
13603            res.system = res.serviceInfo.applicationInfo.isSystemApp();
13604            return res;
13605        }
13606
13607        @Override
13608        protected void sortResults(List<ResolveInfo> results) {
13609            Collections.sort(results, mResolvePrioritySorter);
13610        }
13611
13612        @Override
13613        protected void dumpFilter(PrintWriter out, String prefix,
13614                PackageParser.ServiceIntentInfo filter) {
13615            out.print(prefix); out.print(
13616                    Integer.toHexString(System.identityHashCode(filter.service)));
13617                    out.print(' ');
13618                    filter.service.printComponentShortName(out);
13619                    out.print(" filter ");
13620                    out.println(Integer.toHexString(System.identityHashCode(filter)));
13621        }
13622
13623        @Override
13624        protected Object filterToLabel(PackageParser.ServiceIntentInfo filter) {
13625            return filter.service;
13626        }
13627
13628        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
13629            PackageParser.Service service = (PackageParser.Service)label;
13630            out.print(prefix); out.print(
13631                    Integer.toHexString(System.identityHashCode(service)));
13632                    out.print(' ');
13633                    service.printComponentShortName(out);
13634            if (count > 1) {
13635                out.print(" ("); out.print(count); out.print(" filters)");
13636            }
13637            out.println();
13638        }
13639
13640//        List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) {
13641//            final Iterator<ResolveInfo> i = resolveInfoList.iterator();
13642//            final List<ResolveInfo> retList = Lists.newArrayList();
13643//            while (i.hasNext()) {
13644//                final ResolveInfo resolveInfo = (ResolveInfo) i;
13645//                if (isEnabledLP(resolveInfo.serviceInfo)) {
13646//                    retList.add(resolveInfo);
13647//                }
13648//            }
13649//            return retList;
13650//        }
13651
13652        // Keys are String (activity class name), values are Activity.
13653        private final ArrayMap<ComponentName, PackageParser.Service> mServices
13654                = new ArrayMap<ComponentName, PackageParser.Service>();
13655        private int mFlags;
13656    }
13657
13658    private final class ProviderIntentResolver
13659            extends IntentResolver<PackageParser.ProviderIntentInfo, ResolveInfo> {
13660        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
13661                boolean defaultOnly, int userId) {
13662            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
13663            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
13664        }
13665
13666        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
13667                int userId) {
13668            if (!sUserManager.exists(userId))
13669                return null;
13670            mFlags = flags;
13671            return super.queryIntent(intent, resolvedType,
13672                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0,
13673                    userId);
13674        }
13675
13676        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
13677                int flags, ArrayList<PackageParser.Provider> packageProviders, int userId) {
13678            if (!sUserManager.exists(userId))
13679                return null;
13680            if (packageProviders == null) {
13681                return null;
13682            }
13683            mFlags = flags;
13684            final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0;
13685            final int N = packageProviders.size();
13686            ArrayList<PackageParser.ProviderIntentInfo[]> listCut =
13687                    new ArrayList<PackageParser.ProviderIntentInfo[]>(N);
13688
13689            ArrayList<PackageParser.ProviderIntentInfo> intentFilters;
13690            for (int i = 0; i < N; ++i) {
13691                intentFilters = packageProviders.get(i).intents;
13692                if (intentFilters != null && intentFilters.size() > 0) {
13693                    PackageParser.ProviderIntentInfo[] array =
13694                            new PackageParser.ProviderIntentInfo[intentFilters.size()];
13695                    intentFilters.toArray(array);
13696                    listCut.add(array);
13697                }
13698            }
13699            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
13700        }
13701
13702        public final void addProvider(PackageParser.Provider p) {
13703            if (mProviders.containsKey(p.getComponentName())) {
13704                Slog.w(TAG, "Provider " + p.getComponentName() + " already defined; ignoring");
13705                return;
13706            }
13707
13708            mProviders.put(p.getComponentName(), p);
13709            if (DEBUG_SHOW_INFO) {
13710                Log.v(TAG, "  "
13711                        + (p.info.nonLocalizedLabel != null
13712                                ? p.info.nonLocalizedLabel : p.info.name) + ":");
13713                Log.v(TAG, "    Class=" + p.info.name);
13714            }
13715            final int NI = p.intents.size();
13716            int j;
13717            for (j = 0; j < NI; j++) {
13718                PackageParser.ProviderIntentInfo intent = p.intents.get(j);
13719                if (DEBUG_SHOW_INFO) {
13720                    Log.v(TAG, "    IntentFilter:");
13721                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
13722                }
13723                if (!intent.debugCheck()) {
13724                    Log.w(TAG, "==> For Provider " + p.info.name);
13725                }
13726                addFilter(intent);
13727            }
13728        }
13729
13730        public final void removeProvider(PackageParser.Provider p) {
13731            mProviders.remove(p.getComponentName());
13732            if (DEBUG_SHOW_INFO) {
13733                Log.v(TAG, "  " + (p.info.nonLocalizedLabel != null
13734                        ? p.info.nonLocalizedLabel : p.info.name) + ":");
13735                Log.v(TAG, "    Class=" + p.info.name);
13736            }
13737            final int NI = p.intents.size();
13738            int j;
13739            for (j = 0; j < NI; j++) {
13740                PackageParser.ProviderIntentInfo intent = p.intents.get(j);
13741                if (DEBUG_SHOW_INFO) {
13742                    Log.v(TAG, "    IntentFilter:");
13743                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
13744                }
13745                removeFilter(intent);
13746            }
13747        }
13748
13749        @Override
13750        protected boolean allowFilterResult(
13751                PackageParser.ProviderIntentInfo filter, List<ResolveInfo> dest) {
13752            ProviderInfo filterPi = filter.provider.info;
13753            for (int i = dest.size() - 1; i >= 0; i--) {
13754                ProviderInfo destPi = dest.get(i).providerInfo;
13755                if (destPi.name == filterPi.name
13756                        && destPi.packageName == filterPi.packageName) {
13757                    return false;
13758                }
13759            }
13760            return true;
13761        }
13762
13763        @Override
13764        protected PackageParser.ProviderIntentInfo[] newArray(int size) {
13765            return new PackageParser.ProviderIntentInfo[size];
13766        }
13767
13768        @Override
13769        protected boolean isFilterStopped(PackageParser.ProviderIntentInfo filter, int userId) {
13770            if (!sUserManager.exists(userId))
13771                return true;
13772            PackageParser.Package p = filter.provider.owner;
13773            if (p != null) {
13774                PackageSetting ps = (PackageSetting) p.mExtras;
13775                if (ps != null) {
13776                    // System apps are never considered stopped for purposes of
13777                    // filtering, because there may be no way for the user to
13778                    // actually re-launch them.
13779                    return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0
13780                            && ps.getStopped(userId);
13781                }
13782            }
13783            return false;
13784        }
13785
13786        @Override
13787        protected boolean isPackageForFilter(String packageName,
13788                PackageParser.ProviderIntentInfo info) {
13789            return packageName.equals(info.provider.owner.packageName);
13790        }
13791
13792        @Override
13793        protected ResolveInfo newResult(PackageParser.ProviderIntentInfo filter,
13794                int match, int userId) {
13795            if (!sUserManager.exists(userId))
13796                return null;
13797            final PackageParser.ProviderIntentInfo info = filter;
13798            if (!mSettings.isEnabledAndMatchLPr(info.provider.info, mFlags, userId)) {
13799                return null;
13800            }
13801            final PackageParser.Provider provider = info.provider;
13802            PackageSetting ps = (PackageSetting) provider.owner.mExtras;
13803            if (ps == null) {
13804                return null;
13805            }
13806            final PackageUserState userState = ps.readUserState(userId);
13807            final boolean matchVisibleToInstantApp =
13808                    (mFlags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
13809            final boolean isInstantApp = (mFlags & PackageManager.MATCH_INSTANT) != 0;
13810            // throw out filters that aren't visible to instant applications
13811            if (matchVisibleToInstantApp
13812                    && !(info.isVisibleToInstantApp() || userState.instantApp)) {
13813                return null;
13814            }
13815            // throw out instant application filters if we're not explicitly requesting them
13816            if (!isInstantApp && userState.instantApp) {
13817                return null;
13818            }
13819            // throw out instant application filters if updates are available; will trigger
13820            // instant application resolution
13821            if (userState.instantApp && ps.isUpdateAvailable()) {
13822                return null;
13823            }
13824            ProviderInfo pi = PackageParser.generateProviderInfo(provider, mFlags,
13825                    userState, userId);
13826            if (pi == null) {
13827                return null;
13828            }
13829            final ResolveInfo res = new ResolveInfo();
13830            res.providerInfo = pi;
13831            if ((mFlags & PackageManager.GET_RESOLVED_FILTER) != 0) {
13832                res.filter = filter;
13833            }
13834            res.priority = info.getPriority();
13835            res.preferredOrder = provider.owner.mPreferredOrder;
13836            res.match = match;
13837            res.isDefault = info.hasDefault;
13838            res.labelRes = info.labelRes;
13839            res.nonLocalizedLabel = info.nonLocalizedLabel;
13840            res.icon = info.icon;
13841            res.system = res.providerInfo.applicationInfo.isSystemApp();
13842            return res;
13843        }
13844
13845        @Override
13846        protected void sortResults(List<ResolveInfo> results) {
13847            Collections.sort(results, mResolvePrioritySorter);
13848        }
13849
13850        @Override
13851        protected void dumpFilter(PrintWriter out, String prefix,
13852                PackageParser.ProviderIntentInfo filter) {
13853            out.print(prefix);
13854            out.print(
13855                    Integer.toHexString(System.identityHashCode(filter.provider)));
13856            out.print(' ');
13857            filter.provider.printComponentShortName(out);
13858            out.print(" filter ");
13859            out.println(Integer.toHexString(System.identityHashCode(filter)));
13860        }
13861
13862        @Override
13863        protected Object filterToLabel(PackageParser.ProviderIntentInfo filter) {
13864            return filter.provider;
13865        }
13866
13867        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
13868            PackageParser.Provider provider = (PackageParser.Provider)label;
13869            out.print(prefix); out.print(
13870                    Integer.toHexString(System.identityHashCode(provider)));
13871                    out.print(' ');
13872                    provider.printComponentShortName(out);
13873            if (count > 1) {
13874                out.print(" ("); out.print(count); out.print(" filters)");
13875            }
13876            out.println();
13877        }
13878
13879        private final ArrayMap<ComponentName, PackageParser.Provider> mProviders
13880                = new ArrayMap<ComponentName, PackageParser.Provider>();
13881        private int mFlags;
13882    }
13883
13884    static final class EphemeralIntentResolver
13885            extends IntentResolver<AuxiliaryResolveInfo, AuxiliaryResolveInfo> {
13886        /**
13887         * The result that has the highest defined order. Ordering applies on a
13888         * per-package basis. Mapping is from package name to Pair of order and
13889         * EphemeralResolveInfo.
13890         * <p>
13891         * NOTE: This is implemented as a field variable for convenience and efficiency.
13892         * By having a field variable, we're able to track filter ordering as soon as
13893         * a non-zero order is defined. Otherwise, multiple loops across the result set
13894         * would be needed to apply ordering. If the intent resolver becomes re-entrant,
13895         * this needs to be contained entirely within {@link #filterResults}.
13896         */
13897        final ArrayMap<String, Pair<Integer, InstantAppResolveInfo>> mOrderResult = new ArrayMap<>();
13898
13899        @Override
13900        protected AuxiliaryResolveInfo[] newArray(int size) {
13901            return new AuxiliaryResolveInfo[size];
13902        }
13903
13904        @Override
13905        protected boolean isPackageForFilter(String packageName, AuxiliaryResolveInfo responseObj) {
13906            return true;
13907        }
13908
13909        @Override
13910        protected AuxiliaryResolveInfo newResult(AuxiliaryResolveInfo responseObj, int match,
13911                int userId) {
13912            if (!sUserManager.exists(userId)) {
13913                return null;
13914            }
13915            final String packageName = responseObj.resolveInfo.getPackageName();
13916            final Integer order = responseObj.getOrder();
13917            final Pair<Integer, InstantAppResolveInfo> lastOrderResult =
13918                    mOrderResult.get(packageName);
13919            // ordering is enabled and this item's order isn't high enough
13920            if (lastOrderResult != null && lastOrderResult.first >= order) {
13921                return null;
13922            }
13923            final InstantAppResolveInfo res = responseObj.resolveInfo;
13924            if (order > 0) {
13925                // non-zero order, enable ordering
13926                mOrderResult.put(packageName, new Pair<>(order, res));
13927            }
13928            return responseObj;
13929        }
13930
13931        @Override
13932        protected void filterResults(List<AuxiliaryResolveInfo> results) {
13933            // only do work if ordering is enabled [most of the time it won't be]
13934            if (mOrderResult.size() == 0) {
13935                return;
13936            }
13937            int resultSize = results.size();
13938            for (int i = 0; i < resultSize; i++) {
13939                final InstantAppResolveInfo info = results.get(i).resolveInfo;
13940                final String packageName = info.getPackageName();
13941                final Pair<Integer, InstantAppResolveInfo> savedInfo = mOrderResult.get(packageName);
13942                if (savedInfo == null) {
13943                    // package doesn't having ordering
13944                    continue;
13945                }
13946                if (savedInfo.second == info) {
13947                    // circled back to the highest ordered item; remove from order list
13948                    mOrderResult.remove(savedInfo);
13949                    if (mOrderResult.size() == 0) {
13950                        // no more ordered items
13951                        break;
13952                    }
13953                    continue;
13954                }
13955                // item has a worse order, remove it from the result list
13956                results.remove(i);
13957                resultSize--;
13958                i--;
13959            }
13960        }
13961    }
13962
13963    private static final Comparator<ResolveInfo> mResolvePrioritySorter =
13964            new Comparator<ResolveInfo>() {
13965        public int compare(ResolveInfo r1, ResolveInfo r2) {
13966            int v1 = r1.priority;
13967            int v2 = r2.priority;
13968            //System.out.println("Comparing: q1=" + q1 + " q2=" + q2);
13969            if (v1 != v2) {
13970                return (v1 > v2) ? -1 : 1;
13971            }
13972            v1 = r1.preferredOrder;
13973            v2 = r2.preferredOrder;
13974            if (v1 != v2) {
13975                return (v1 > v2) ? -1 : 1;
13976            }
13977            if (r1.isDefault != r2.isDefault) {
13978                return r1.isDefault ? -1 : 1;
13979            }
13980            v1 = r1.match;
13981            v2 = r2.match;
13982            //System.out.println("Comparing: m1=" + m1 + " m2=" + m2);
13983            if (v1 != v2) {
13984                return (v1 > v2) ? -1 : 1;
13985            }
13986            if (r1.system != r2.system) {
13987                return r1.system ? -1 : 1;
13988            }
13989            if (r1.activityInfo != null) {
13990                return r1.activityInfo.packageName.compareTo(r2.activityInfo.packageName);
13991            }
13992            if (r1.serviceInfo != null) {
13993                return r1.serviceInfo.packageName.compareTo(r2.serviceInfo.packageName);
13994            }
13995            if (r1.providerInfo != null) {
13996                return r1.providerInfo.packageName.compareTo(r2.providerInfo.packageName);
13997            }
13998            return 0;
13999        }
14000    };
14001
14002    private static final Comparator<ProviderInfo> mProviderInitOrderSorter =
14003            new Comparator<ProviderInfo>() {
14004        public int compare(ProviderInfo p1, ProviderInfo p2) {
14005            final int v1 = p1.initOrder;
14006            final int v2 = p2.initOrder;
14007            return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0);
14008        }
14009    };
14010
14011    public void sendPackageBroadcast(final String action, final String pkg, final Bundle extras,
14012            final int flags, final String targetPkg, final IIntentReceiver finishedReceiver,
14013            final int[] userIds) {
14014        mHandler.post(new Runnable() {
14015            @Override
14016            public void run() {
14017                try {
14018                    final IActivityManager am = ActivityManager.getService();
14019                    if (am == null) return;
14020                    final int[] resolvedUserIds;
14021                    if (userIds == null) {
14022                        resolvedUserIds = am.getRunningUserIds();
14023                    } else {
14024                        resolvedUserIds = userIds;
14025                    }
14026                    for (int id : resolvedUserIds) {
14027                        final Intent intent = new Intent(action,
14028                                pkg != null ? Uri.fromParts(PACKAGE_SCHEME, pkg, null) : null);
14029                        if (extras != null) {
14030                            intent.putExtras(extras);
14031                        }
14032                        if (targetPkg != null) {
14033                            intent.setPackage(targetPkg);
14034                        }
14035                        // Modify the UID when posting to other users
14036                        int uid = intent.getIntExtra(Intent.EXTRA_UID, -1);
14037                        if (uid > 0 && UserHandle.getUserId(uid) != id) {
14038                            uid = UserHandle.getUid(id, UserHandle.getAppId(uid));
14039                            intent.putExtra(Intent.EXTRA_UID, uid);
14040                        }
14041                        intent.putExtra(Intent.EXTRA_USER_HANDLE, id);
14042                        intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT | flags);
14043                        if (DEBUG_BROADCASTS) {
14044                            RuntimeException here = new RuntimeException("here");
14045                            here.fillInStackTrace();
14046                            Slog.d(TAG, "Sending to user " + id + ": "
14047                                    + intent.toShortString(false, true, false, false)
14048                                    + " " + intent.getExtras(), here);
14049                        }
14050                        am.broadcastIntent(null, intent, null, finishedReceiver,
14051                                0, null, null, null, android.app.AppOpsManager.OP_NONE,
14052                                null, finishedReceiver != null, false, id);
14053                    }
14054                } catch (RemoteException ex) {
14055                }
14056            }
14057        });
14058    }
14059
14060    /**
14061     * Check if the external storage media is available. This is true if there
14062     * is a mounted external storage medium or if the external storage is
14063     * emulated.
14064     */
14065    private boolean isExternalMediaAvailable() {
14066        return mMediaMounted || Environment.isExternalStorageEmulated();
14067    }
14068
14069    @Override
14070    public PackageCleanItem nextPackageToClean(PackageCleanItem lastPackage) {
14071        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
14072            return null;
14073        }
14074        // writer
14075        synchronized (mPackages) {
14076            if (!isExternalMediaAvailable()) {
14077                // If the external storage is no longer mounted at this point,
14078                // the caller may not have been able to delete all of this
14079                // packages files and can not delete any more.  Bail.
14080                return null;
14081            }
14082            final ArrayList<PackageCleanItem> pkgs = mSettings.mPackagesToBeCleaned;
14083            if (lastPackage != null) {
14084                pkgs.remove(lastPackage);
14085            }
14086            if (pkgs.size() > 0) {
14087                return pkgs.get(0);
14088            }
14089        }
14090        return null;
14091    }
14092
14093    void schedulePackageCleaning(String packageName, int userId, boolean andCode) {
14094        final Message msg = mHandler.obtainMessage(START_CLEANING_PACKAGE,
14095                userId, andCode ? 1 : 0, packageName);
14096        if (mSystemReady) {
14097            msg.sendToTarget();
14098        } else {
14099            if (mPostSystemReadyMessages == null) {
14100                mPostSystemReadyMessages = new ArrayList<>();
14101            }
14102            mPostSystemReadyMessages.add(msg);
14103        }
14104    }
14105
14106    void startCleaningPackages() {
14107        // reader
14108        if (!isExternalMediaAvailable()) {
14109            return;
14110        }
14111        synchronized (mPackages) {
14112            if (mSettings.mPackagesToBeCleaned.isEmpty()) {
14113                return;
14114            }
14115        }
14116        Intent intent = new Intent(PackageManager.ACTION_CLEAN_EXTERNAL_STORAGE);
14117        intent.setComponent(DEFAULT_CONTAINER_COMPONENT);
14118        IActivityManager am = ActivityManager.getService();
14119        if (am != null) {
14120            int dcsUid = -1;
14121            synchronized (mPackages) {
14122                if (!mDefaultContainerWhitelisted) {
14123                    mDefaultContainerWhitelisted = true;
14124                    PackageSetting ps = mSettings.mPackages.get(DEFAULT_CONTAINER_PACKAGE);
14125                    dcsUid = UserHandle.getUid(UserHandle.USER_SYSTEM, ps.appId);
14126                }
14127            }
14128            try {
14129                if (dcsUid > 0) {
14130                    am.backgroundWhitelistUid(dcsUid);
14131                }
14132                am.startService(null, intent, null, false, mContext.getOpPackageName(),
14133                        UserHandle.USER_SYSTEM);
14134            } catch (RemoteException e) {
14135            }
14136        }
14137    }
14138
14139    @Override
14140    public void installPackageAsUser(String originPath, IPackageInstallObserver2 observer,
14141            int installFlags, String installerPackageName, int userId) {
14142        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, null);
14143
14144        final int callingUid = Binder.getCallingUid();
14145        enforceCrossUserPermission(callingUid, userId,
14146                true /* requireFullPermission */, true /* checkShell */, "installPackageAsUser");
14147
14148        if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) {
14149            try {
14150                if (observer != null) {
14151                    observer.onPackageInstalled("", INSTALL_FAILED_USER_RESTRICTED, null, null);
14152                }
14153            } catch (RemoteException re) {
14154            }
14155            return;
14156        }
14157
14158        if ((callingUid == Process.SHELL_UID) || (callingUid == Process.ROOT_UID)) {
14159            installFlags |= PackageManager.INSTALL_FROM_ADB;
14160
14161        } else {
14162            // Caller holds INSTALL_PACKAGES permission, so we're less strict
14163            // about installerPackageName.
14164
14165            installFlags &= ~PackageManager.INSTALL_FROM_ADB;
14166            installFlags &= ~PackageManager.INSTALL_ALL_USERS;
14167        }
14168
14169        UserHandle user;
14170        if ((installFlags & PackageManager.INSTALL_ALL_USERS) != 0) {
14171            user = UserHandle.ALL;
14172        } else {
14173            user = new UserHandle(userId);
14174        }
14175
14176        // Only system components can circumvent runtime permissions when installing.
14177        if ((installFlags & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0
14178                && mContext.checkCallingOrSelfPermission(Manifest.permission
14179                .INSTALL_GRANT_RUNTIME_PERMISSIONS) == PackageManager.PERMISSION_DENIED) {
14180            throw new SecurityException("You need the "
14181                    + "android.permission.INSTALL_GRANT_RUNTIME_PERMISSIONS permission "
14182                    + "to use the PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS flag");
14183        }
14184
14185        if ((installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0
14186                || (installFlags & PackageManager.INSTALL_EXTERNAL) != 0) {
14187            throw new IllegalArgumentException(
14188                    "New installs into ASEC containers no longer supported");
14189        }
14190
14191        final File originFile = new File(originPath);
14192        final OriginInfo origin = OriginInfo.fromUntrustedFile(originFile);
14193
14194        final Message msg = mHandler.obtainMessage(INIT_COPY);
14195        final VerificationInfo verificationInfo = new VerificationInfo(
14196                null /*originatingUri*/, null /*referrer*/, -1 /*originatingUid*/, callingUid);
14197        final InstallParams params = new InstallParams(origin, null /*moveInfo*/, observer,
14198                installFlags, installerPackageName, null /*volumeUuid*/, verificationInfo, user,
14199                null /*packageAbiOverride*/, null /*grantedPermissions*/,
14200                null /*certificates*/, PackageManager.INSTALL_REASON_UNKNOWN);
14201        params.setTraceMethod("installAsUser").setTraceCookie(System.identityHashCode(params));
14202        msg.obj = params;
14203
14204        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "installAsUser",
14205                System.identityHashCode(msg.obj));
14206        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
14207                System.identityHashCode(msg.obj));
14208
14209        mHandler.sendMessage(msg);
14210    }
14211
14212
14213    /**
14214     * Ensure that the install reason matches what we know about the package installer (e.g. whether
14215     * it is acting on behalf on an enterprise or the user).
14216     *
14217     * Note that the ordering of the conditionals in this method is important. The checks we perform
14218     * are as follows, in this order:
14219     *
14220     * 1) If the install is being performed by a system app, we can trust the app to have set the
14221     *    install reason correctly. Thus, we pass through the install reason unchanged, no matter
14222     *    what it is.
14223     * 2) If the install is being performed by a device or profile owner app, the install reason
14224     *    should be enterprise policy. However, we cannot be sure that the device or profile owner
14225     *    set the install reason correctly. If the app targets an older SDK version where install
14226     *    reasons did not exist yet, or if the app author simply forgot, the install reason may be
14227     *    unset or wrong. Thus, we force the install reason to be enterprise policy.
14228     * 3) In all other cases, the install is being performed by a regular app that is neither part
14229     *    of the system nor a device or profile owner. We have no reason to believe that this app is
14230     *    acting on behalf of the enterprise admin. Thus, we check whether the install reason was
14231     *    set to enterprise policy and if so, change it to unknown instead.
14232     */
14233    private int fixUpInstallReason(String installerPackageName, int installerUid,
14234            int installReason) {
14235        if (checkUidPermission(android.Manifest.permission.INSTALL_PACKAGES, installerUid)
14236                == PERMISSION_GRANTED) {
14237            // If the install is being performed by a system app, we trust that app to have set the
14238            // install reason correctly.
14239            return installReason;
14240        }
14241
14242        final IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface(
14243            ServiceManager.getService(Context.DEVICE_POLICY_SERVICE));
14244        if (dpm != null) {
14245            ComponentName owner = null;
14246            try {
14247                owner = dpm.getDeviceOwnerComponent(true /* callingUserOnly */);
14248                if (owner == null) {
14249                    owner = dpm.getProfileOwner(UserHandle.getUserId(installerUid));
14250                }
14251            } catch (RemoteException e) {
14252            }
14253            if (owner != null && owner.getPackageName().equals(installerPackageName)) {
14254                // If the install is being performed by a device or profile owner, the install
14255                // reason should be enterprise policy.
14256                return PackageManager.INSTALL_REASON_POLICY;
14257            }
14258        }
14259
14260        if (installReason == PackageManager.INSTALL_REASON_POLICY) {
14261            // If the install is being performed by a regular app (i.e. neither system app nor
14262            // device or profile owner), we have no reason to believe that the app is acting on
14263            // behalf of an enterprise. If the app set the install reason to enterprise policy,
14264            // change it to unknown instead.
14265            return PackageManager.INSTALL_REASON_UNKNOWN;
14266        }
14267
14268        // If the install is being performed by a regular app and the install reason was set to any
14269        // value but enterprise policy, leave the install reason unchanged.
14270        return installReason;
14271    }
14272
14273    void installStage(String packageName, File stagedDir, String stagedCid,
14274            IPackageInstallObserver2 observer, PackageInstaller.SessionParams sessionParams,
14275            String installerPackageName, int installerUid, UserHandle user,
14276            Certificate[][] certificates) {
14277        if (DEBUG_EPHEMERAL) {
14278            if ((sessionParams.installFlags & PackageManager.INSTALL_INSTANT_APP) != 0) {
14279                Slog.d(TAG, "Ephemeral install of " + packageName);
14280            }
14281        }
14282        final VerificationInfo verificationInfo = new VerificationInfo(
14283                sessionParams.originatingUri, sessionParams.referrerUri,
14284                sessionParams.originatingUid, installerUid);
14285
14286        final OriginInfo origin;
14287        if (stagedDir != null) {
14288            origin = OriginInfo.fromStagedFile(stagedDir);
14289        } else {
14290            origin = OriginInfo.fromStagedContainer(stagedCid);
14291        }
14292
14293        final Message msg = mHandler.obtainMessage(INIT_COPY);
14294        final int installReason = fixUpInstallReason(installerPackageName, installerUid,
14295                sessionParams.installReason);
14296        final InstallParams params = new InstallParams(origin, null, observer,
14297                sessionParams.installFlags, installerPackageName, sessionParams.volumeUuid,
14298                verificationInfo, user, sessionParams.abiOverride,
14299                sessionParams.grantedRuntimePermissions, certificates, installReason);
14300        params.setTraceMethod("installStage").setTraceCookie(System.identityHashCode(params));
14301        msg.obj = params;
14302
14303        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "installStage",
14304                System.identityHashCode(msg.obj));
14305        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
14306                System.identityHashCode(msg.obj));
14307
14308        mHandler.sendMessage(msg);
14309    }
14310
14311    private void sendPackageAddedForUser(String packageName, PackageSetting pkgSetting,
14312            int userId) {
14313        final boolean isSystem = isSystemApp(pkgSetting) || isUpdatedSystemApp(pkgSetting);
14314        sendPackageAddedForNewUsers(packageName, isSystem, pkgSetting.appId, userId);
14315
14316        // Send a session commit broadcast
14317        final PackageInstaller.SessionInfo info = new PackageInstaller.SessionInfo();
14318        info.installReason = pkgSetting.getInstallReason(userId);
14319        info.appPackageName = packageName;
14320        sendSessionCommitBroadcast(info, userId);
14321    }
14322
14323    public void sendPackageAddedForNewUsers(String packageName, boolean isSystem, int appId, int... userIds) {
14324        if (ArrayUtils.isEmpty(userIds)) {
14325            return;
14326        }
14327        Bundle extras = new Bundle(1);
14328        // Set to UID of the first user, EXTRA_UID is automatically updated in sendPackageBroadcast
14329        extras.putInt(Intent.EXTRA_UID, UserHandle.getUid(userIds[0], appId));
14330
14331        sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
14332                packageName, extras, 0, null, null, userIds);
14333        if (isSystem) {
14334            mHandler.post(() -> {
14335                        for (int userId : userIds) {
14336                            sendBootCompletedBroadcastToSystemApp(packageName, userId);
14337                        }
14338                    }
14339            );
14340        }
14341    }
14342
14343    /**
14344     * The just-installed/enabled app is bundled on the system, so presumed to be able to run
14345     * automatically without needing an explicit launch.
14346     * Send it a LOCKED_BOOT_COMPLETED/BOOT_COMPLETED if it would ordinarily have gotten ones.
14347     */
14348    private void sendBootCompletedBroadcastToSystemApp(String packageName, int userId) {
14349        // If user is not running, the app didn't miss any broadcast
14350        if (!mUserManagerInternal.isUserRunning(userId)) {
14351            return;
14352        }
14353        final IActivityManager am = ActivityManager.getService();
14354        try {
14355            // Deliver LOCKED_BOOT_COMPLETED first
14356            Intent lockedBcIntent = new Intent(Intent.ACTION_LOCKED_BOOT_COMPLETED)
14357                    .setPackage(packageName);
14358            final String[] requiredPermissions = {Manifest.permission.RECEIVE_BOOT_COMPLETED};
14359            am.broadcastIntent(null, lockedBcIntent, null, null, 0, null, null, requiredPermissions,
14360                    android.app.AppOpsManager.OP_NONE, null, false, false, userId);
14361
14362            // Deliver BOOT_COMPLETED only if user is unlocked
14363            if (mUserManagerInternal.isUserUnlockingOrUnlocked(userId)) {
14364                Intent bcIntent = new Intent(Intent.ACTION_BOOT_COMPLETED).setPackage(packageName);
14365                am.broadcastIntent(null, bcIntent, null, null, 0, null, null, requiredPermissions,
14366                        android.app.AppOpsManager.OP_NONE, null, false, false, userId);
14367            }
14368        } catch (RemoteException e) {
14369            throw e.rethrowFromSystemServer();
14370        }
14371    }
14372
14373    @Override
14374    public boolean setApplicationHiddenSettingAsUser(String packageName, boolean hidden,
14375            int userId) {
14376        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
14377        PackageSetting pkgSetting;
14378        final int callingUid = Binder.getCallingUid();
14379        enforceCrossUserPermission(callingUid, userId,
14380                true /* requireFullPermission */, true /* checkShell */,
14381                "setApplicationHiddenSetting for user " + userId);
14382
14383        if (hidden && isPackageDeviceAdmin(packageName, userId)) {
14384            Slog.w(TAG, "Not hiding package " + packageName + ": has active device admin");
14385            return false;
14386        }
14387
14388        long callingId = Binder.clearCallingIdentity();
14389        try {
14390            boolean sendAdded = false;
14391            boolean sendRemoved = false;
14392            // writer
14393            synchronized (mPackages) {
14394                pkgSetting = mSettings.mPackages.get(packageName);
14395                if (pkgSetting == null) {
14396                    return false;
14397                }
14398                if (filterAppAccessLPr(pkgSetting, callingUid, userId)) {
14399                    return false;
14400                }
14401                // Do not allow "android" is being disabled
14402                if ("android".equals(packageName)) {
14403                    Slog.w(TAG, "Cannot hide package: android");
14404                    return false;
14405                }
14406                // Cannot hide static shared libs as they are considered
14407                // a part of the using app (emulating static linking). Also
14408                // static libs are installed always on internal storage.
14409                PackageParser.Package pkg = mPackages.get(packageName);
14410                if (pkg != null && pkg.staticSharedLibName != null) {
14411                    Slog.w(TAG, "Cannot hide package: " + packageName
14412                            + " providing static shared library: "
14413                            + pkg.staticSharedLibName);
14414                    return false;
14415                }
14416                // Only allow protected packages to hide themselves.
14417                if (hidden && !UserHandle.isSameApp(callingUid, pkgSetting.appId)
14418                        && mProtectedPackages.isPackageStateProtected(userId, packageName)) {
14419                    Slog.w(TAG, "Not hiding protected package: " + packageName);
14420                    return false;
14421                }
14422
14423                if (pkgSetting.getHidden(userId) != hidden) {
14424                    pkgSetting.setHidden(hidden, userId);
14425                    mSettings.writePackageRestrictionsLPr(userId);
14426                    if (hidden) {
14427                        sendRemoved = true;
14428                    } else {
14429                        sendAdded = true;
14430                    }
14431                }
14432            }
14433            if (sendAdded) {
14434                sendPackageAddedForUser(packageName, pkgSetting, userId);
14435                return true;
14436            }
14437            if (sendRemoved) {
14438                killApplication(packageName, UserHandle.getUid(userId, pkgSetting.appId),
14439                        "hiding pkg");
14440                sendApplicationHiddenForUser(packageName, pkgSetting, userId);
14441                return true;
14442            }
14443        } finally {
14444            Binder.restoreCallingIdentity(callingId);
14445        }
14446        return false;
14447    }
14448
14449    private void sendApplicationHiddenForUser(String packageName, PackageSetting pkgSetting,
14450            int userId) {
14451        final PackageRemovedInfo info = new PackageRemovedInfo(this);
14452        info.removedPackage = packageName;
14453        info.installerPackageName = pkgSetting.installerPackageName;
14454        info.removedUsers = new int[] {userId};
14455        info.broadcastUsers = new int[] {userId};
14456        info.uid = UserHandle.getUid(userId, pkgSetting.appId);
14457        info.sendPackageRemovedBroadcasts(true /*killApp*/);
14458    }
14459
14460    private void sendPackagesSuspendedForUser(String[] pkgList, int userId, boolean suspended) {
14461        if (pkgList.length > 0) {
14462            Bundle extras = new Bundle(1);
14463            extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList);
14464
14465            sendPackageBroadcast(
14466                    suspended ? Intent.ACTION_PACKAGES_SUSPENDED
14467                            : Intent.ACTION_PACKAGES_UNSUSPENDED,
14468                    null, extras, Intent.FLAG_RECEIVER_REGISTERED_ONLY, null, null,
14469                    new int[] {userId});
14470        }
14471    }
14472
14473    /**
14474     * Returns true if application is not found or there was an error. Otherwise it returns
14475     * the hidden state of the package for the given user.
14476     */
14477    @Override
14478    public boolean getApplicationHiddenSettingAsUser(String packageName, int userId) {
14479        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
14480        final int callingUid = Binder.getCallingUid();
14481        enforceCrossUserPermission(callingUid, userId,
14482                true /* requireFullPermission */, false /* checkShell */,
14483                "getApplicationHidden for user " + userId);
14484        PackageSetting ps;
14485        long callingId = Binder.clearCallingIdentity();
14486        try {
14487            // writer
14488            synchronized (mPackages) {
14489                ps = mSettings.mPackages.get(packageName);
14490                if (ps == null) {
14491                    return true;
14492                }
14493                if (filterAppAccessLPr(ps, callingUid, userId)) {
14494                    return true;
14495                }
14496                return ps.getHidden(userId);
14497            }
14498        } finally {
14499            Binder.restoreCallingIdentity(callingId);
14500        }
14501    }
14502
14503    /**
14504     * @hide
14505     */
14506    @Override
14507    public int installExistingPackageAsUser(String packageName, int userId, int installFlags,
14508            int installReason) {
14509        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES,
14510                null);
14511        PackageSetting pkgSetting;
14512        final int callingUid = Binder.getCallingUid();
14513        enforceCrossUserPermission(callingUid, userId,
14514                true /* requireFullPermission */, true /* checkShell */,
14515                "installExistingPackage for user " + userId);
14516        if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) {
14517            return PackageManager.INSTALL_FAILED_USER_RESTRICTED;
14518        }
14519
14520        long callingId = Binder.clearCallingIdentity();
14521        try {
14522            boolean installed = false;
14523            final boolean instantApp =
14524                    (installFlags & PackageManager.INSTALL_INSTANT_APP) != 0;
14525            final boolean fullApp =
14526                    (installFlags & PackageManager.INSTALL_FULL_APP) != 0;
14527
14528            // writer
14529            synchronized (mPackages) {
14530                pkgSetting = mSettings.mPackages.get(packageName);
14531                if (pkgSetting == null) {
14532                    return PackageManager.INSTALL_FAILED_INVALID_URI;
14533                }
14534                if (!canViewInstantApps(callingUid, UserHandle.getUserId(callingUid))) {
14535                    // only allow the existing package to be used if it's installed as a full
14536                    // application for at least one user
14537                    boolean installAllowed = false;
14538                    for (int checkUserId : sUserManager.getUserIds()) {
14539                        installAllowed = !pkgSetting.getInstantApp(checkUserId);
14540                        if (installAllowed) {
14541                            break;
14542                        }
14543                    }
14544                    if (!installAllowed) {
14545                        return PackageManager.INSTALL_FAILED_INVALID_URI;
14546                    }
14547                }
14548                if (!pkgSetting.getInstalled(userId)) {
14549                    pkgSetting.setInstalled(true, userId);
14550                    pkgSetting.setHidden(false, userId);
14551                    pkgSetting.setInstallReason(installReason, userId);
14552                    mSettings.writePackageRestrictionsLPr(userId);
14553                    mSettings.writeKernelMappingLPr(pkgSetting);
14554                    installed = true;
14555                } else if (fullApp && pkgSetting.getInstantApp(userId)) {
14556                    // upgrade app from instant to full; we don't allow app downgrade
14557                    installed = true;
14558                }
14559                setInstantAppForUser(pkgSetting, userId, instantApp, fullApp);
14560            }
14561
14562            if (installed) {
14563                if (pkgSetting.pkg != null) {
14564                    synchronized (mInstallLock) {
14565                        // We don't need to freeze for a brand new install
14566                        prepareAppDataAfterInstallLIF(pkgSetting.pkg);
14567                    }
14568                }
14569                sendPackageAddedForUser(packageName, pkgSetting, userId);
14570                synchronized (mPackages) {
14571                    updateSequenceNumberLP(pkgSetting, new int[]{ userId });
14572                }
14573            }
14574        } finally {
14575            Binder.restoreCallingIdentity(callingId);
14576        }
14577
14578        return PackageManager.INSTALL_SUCCEEDED;
14579    }
14580
14581    void setInstantAppForUser(PackageSetting pkgSetting, int userId,
14582            boolean instantApp, boolean fullApp) {
14583        // no state specified; do nothing
14584        if (!instantApp && !fullApp) {
14585            return;
14586        }
14587        if (userId != UserHandle.USER_ALL) {
14588            if (instantApp && !pkgSetting.getInstantApp(userId)) {
14589                pkgSetting.setInstantApp(true /*instantApp*/, userId);
14590            } else if (fullApp && pkgSetting.getInstantApp(userId)) {
14591                pkgSetting.setInstantApp(false /*instantApp*/, userId);
14592            }
14593        } else {
14594            for (int currentUserId : sUserManager.getUserIds()) {
14595                if (instantApp && !pkgSetting.getInstantApp(currentUserId)) {
14596                    pkgSetting.setInstantApp(true /*instantApp*/, currentUserId);
14597                } else if (fullApp && pkgSetting.getInstantApp(currentUserId)) {
14598                    pkgSetting.setInstantApp(false /*instantApp*/, currentUserId);
14599                }
14600            }
14601        }
14602    }
14603
14604    boolean isUserRestricted(int userId, String restrictionKey) {
14605        Bundle restrictions = sUserManager.getUserRestrictions(userId);
14606        if (restrictions.getBoolean(restrictionKey, false)) {
14607            Log.w(TAG, "User is restricted: " + restrictionKey);
14608            return true;
14609        }
14610        return false;
14611    }
14612
14613    @Override
14614    public String[] setPackagesSuspendedAsUser(String[] packageNames, boolean suspended,
14615            int userId) {
14616        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
14617        final int callingUid = Binder.getCallingUid();
14618        enforceCrossUserPermission(callingUid, userId,
14619                true /* requireFullPermission */, true /* checkShell */,
14620                "setPackagesSuspended for user " + userId);
14621
14622        if (ArrayUtils.isEmpty(packageNames)) {
14623            return packageNames;
14624        }
14625
14626        // List of package names for whom the suspended state has changed.
14627        List<String> changedPackages = new ArrayList<>(packageNames.length);
14628        // List of package names for whom the suspended state is not set as requested in this
14629        // method.
14630        List<String> unactionedPackages = new ArrayList<>(packageNames.length);
14631        long callingId = Binder.clearCallingIdentity();
14632        try {
14633            for (int i = 0; i < packageNames.length; i++) {
14634                String packageName = packageNames[i];
14635                boolean changed = false;
14636                final int appId;
14637                synchronized (mPackages) {
14638                    final PackageSetting pkgSetting = mSettings.mPackages.get(packageName);
14639                    if (pkgSetting == null
14640                            || filterAppAccessLPr(pkgSetting, callingUid, userId)) {
14641                        Slog.w(TAG, "Could not find package setting for package \"" + packageName
14642                                + "\". Skipping suspending/un-suspending.");
14643                        unactionedPackages.add(packageName);
14644                        continue;
14645                    }
14646                    appId = pkgSetting.appId;
14647                    if (pkgSetting.getSuspended(userId) != suspended) {
14648                        if (!canSuspendPackageForUserLocked(packageName, userId)) {
14649                            unactionedPackages.add(packageName);
14650                            continue;
14651                        }
14652                        pkgSetting.setSuspended(suspended, userId);
14653                        mSettings.writePackageRestrictionsLPr(userId);
14654                        changed = true;
14655                        changedPackages.add(packageName);
14656                    }
14657                }
14658
14659                if (changed && suspended) {
14660                    killApplication(packageName, UserHandle.getUid(userId, appId),
14661                            "suspending package");
14662                }
14663            }
14664        } finally {
14665            Binder.restoreCallingIdentity(callingId);
14666        }
14667
14668        if (!changedPackages.isEmpty()) {
14669            sendPackagesSuspendedForUser(changedPackages.toArray(
14670                    new String[changedPackages.size()]), userId, suspended);
14671        }
14672
14673        return unactionedPackages.toArray(new String[unactionedPackages.size()]);
14674    }
14675
14676    @Override
14677    public boolean isPackageSuspendedForUser(String packageName, int userId) {
14678        final int callingUid = Binder.getCallingUid();
14679        enforceCrossUserPermission(callingUid, userId,
14680                true /* requireFullPermission */, false /* checkShell */,
14681                "isPackageSuspendedForUser for user " + userId);
14682        synchronized (mPackages) {
14683            final PackageSetting ps = mSettings.mPackages.get(packageName);
14684            if (ps == null || filterAppAccessLPr(ps, callingUid, userId)) {
14685                throw new IllegalArgumentException("Unknown target package: " + packageName);
14686            }
14687            return ps.getSuspended(userId);
14688        }
14689    }
14690
14691    private boolean canSuspendPackageForUserLocked(String packageName, int userId) {
14692        if (isPackageDeviceAdmin(packageName, userId)) {
14693            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
14694                    + "\": has an active device admin");
14695            return false;
14696        }
14697
14698        String activeLauncherPackageName = getActiveLauncherPackageName(userId);
14699        if (packageName.equals(activeLauncherPackageName)) {
14700            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
14701                    + "\": contains the active launcher");
14702            return false;
14703        }
14704
14705        if (packageName.equals(mRequiredInstallerPackage)) {
14706            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
14707                    + "\": required for package installation");
14708            return false;
14709        }
14710
14711        if (packageName.equals(mRequiredUninstallerPackage)) {
14712            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
14713                    + "\": required for package uninstallation");
14714            return false;
14715        }
14716
14717        if (packageName.equals(mRequiredVerifierPackage)) {
14718            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
14719                    + "\": required for package verification");
14720            return false;
14721        }
14722
14723        if (packageName.equals(getDefaultDialerPackageName(userId))) {
14724            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
14725                    + "\": is the default dialer");
14726            return false;
14727        }
14728
14729        if (mProtectedPackages.isPackageStateProtected(userId, packageName)) {
14730            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
14731                    + "\": protected package");
14732            return false;
14733        }
14734
14735        // Cannot suspend static shared libs as they are considered
14736        // a part of the using app (emulating static linking). Also
14737        // static libs are installed always on internal storage.
14738        PackageParser.Package pkg = mPackages.get(packageName);
14739        if (pkg != null && pkg.applicationInfo.isStaticSharedLibrary()) {
14740            Slog.w(TAG, "Cannot suspend package: " + packageName
14741                    + " providing static shared library: "
14742                    + pkg.staticSharedLibName);
14743            return false;
14744        }
14745
14746        return true;
14747    }
14748
14749    private String getActiveLauncherPackageName(int userId) {
14750        Intent intent = new Intent(Intent.ACTION_MAIN);
14751        intent.addCategory(Intent.CATEGORY_HOME);
14752        ResolveInfo resolveInfo = resolveIntent(
14753                intent,
14754                intent.resolveTypeIfNeeded(mContext.getContentResolver()),
14755                PackageManager.MATCH_DEFAULT_ONLY,
14756                userId);
14757
14758        return resolveInfo == null ? null : resolveInfo.activityInfo.packageName;
14759    }
14760
14761    private String getDefaultDialerPackageName(int userId) {
14762        synchronized (mPackages) {
14763            return mSettings.getDefaultDialerPackageNameLPw(userId);
14764        }
14765    }
14766
14767    @Override
14768    public void verifyPendingInstall(int id, int verificationCode) throws RemoteException {
14769        mContext.enforceCallingOrSelfPermission(
14770                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
14771                "Only package verification agents can verify applications");
14772
14773        final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED);
14774        final PackageVerificationResponse response = new PackageVerificationResponse(
14775                verificationCode, Binder.getCallingUid());
14776        msg.arg1 = id;
14777        msg.obj = response;
14778        mHandler.sendMessage(msg);
14779    }
14780
14781    @Override
14782    public void extendVerificationTimeout(int id, int verificationCodeAtTimeout,
14783            long millisecondsToDelay) {
14784        mContext.enforceCallingOrSelfPermission(
14785                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
14786                "Only package verification agents can extend verification timeouts");
14787
14788        final PackageVerificationState state = mPendingVerification.get(id);
14789        final PackageVerificationResponse response = new PackageVerificationResponse(
14790                verificationCodeAtTimeout, Binder.getCallingUid());
14791
14792        if (millisecondsToDelay > PackageManager.MAXIMUM_VERIFICATION_TIMEOUT) {
14793            millisecondsToDelay = PackageManager.MAXIMUM_VERIFICATION_TIMEOUT;
14794        }
14795        if (millisecondsToDelay < 0) {
14796            millisecondsToDelay = 0;
14797        }
14798        if ((verificationCodeAtTimeout != PackageManager.VERIFICATION_ALLOW)
14799                && (verificationCodeAtTimeout != PackageManager.VERIFICATION_REJECT)) {
14800            verificationCodeAtTimeout = PackageManager.VERIFICATION_REJECT;
14801        }
14802
14803        if ((state != null) && !state.timeoutExtended()) {
14804            state.extendTimeout();
14805
14806            final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED);
14807            msg.arg1 = id;
14808            msg.obj = response;
14809            mHandler.sendMessageDelayed(msg, millisecondsToDelay);
14810        }
14811    }
14812
14813    private void broadcastPackageVerified(int verificationId, Uri packageUri,
14814            int verificationCode, UserHandle user) {
14815        final Intent intent = new Intent(Intent.ACTION_PACKAGE_VERIFIED);
14816        intent.setDataAndType(packageUri, PACKAGE_MIME_TYPE);
14817        intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
14818        intent.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId);
14819        intent.putExtra(PackageManager.EXTRA_VERIFICATION_RESULT, verificationCode);
14820
14821        mContext.sendBroadcastAsUser(intent, user,
14822                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT);
14823    }
14824
14825    private ComponentName matchComponentForVerifier(String packageName,
14826            List<ResolveInfo> receivers) {
14827        ActivityInfo targetReceiver = null;
14828
14829        final int NR = receivers.size();
14830        for (int i = 0; i < NR; i++) {
14831            final ResolveInfo info = receivers.get(i);
14832            if (info.activityInfo == null) {
14833                continue;
14834            }
14835
14836            if (packageName.equals(info.activityInfo.packageName)) {
14837                targetReceiver = info.activityInfo;
14838                break;
14839            }
14840        }
14841
14842        if (targetReceiver == null) {
14843            return null;
14844        }
14845
14846        return new ComponentName(targetReceiver.packageName, targetReceiver.name);
14847    }
14848
14849    private List<ComponentName> matchVerifiers(PackageInfoLite pkgInfo,
14850            List<ResolveInfo> receivers, final PackageVerificationState verificationState) {
14851        if (pkgInfo.verifiers.length == 0) {
14852            return null;
14853        }
14854
14855        final int N = pkgInfo.verifiers.length;
14856        final List<ComponentName> sufficientVerifiers = new ArrayList<ComponentName>(N + 1);
14857        for (int i = 0; i < N; i++) {
14858            final VerifierInfo verifierInfo = pkgInfo.verifiers[i];
14859
14860            final ComponentName comp = matchComponentForVerifier(verifierInfo.packageName,
14861                    receivers);
14862            if (comp == null) {
14863                continue;
14864            }
14865
14866            final int verifierUid = getUidForVerifier(verifierInfo);
14867            if (verifierUid == -1) {
14868                continue;
14869            }
14870
14871            if (DEBUG_VERIFY) {
14872                Slog.d(TAG, "Added sufficient verifier " + verifierInfo.packageName
14873                        + " with the correct signature");
14874            }
14875            sufficientVerifiers.add(comp);
14876            verificationState.addSufficientVerifier(verifierUid);
14877        }
14878
14879        return sufficientVerifiers;
14880    }
14881
14882    private int getUidForVerifier(VerifierInfo verifierInfo) {
14883        synchronized (mPackages) {
14884            final PackageParser.Package pkg = mPackages.get(verifierInfo.packageName);
14885            if (pkg == null) {
14886                return -1;
14887            } else if (pkg.mSignatures.length != 1) {
14888                Slog.i(TAG, "Verifier package " + verifierInfo.packageName
14889                        + " has more than one signature; ignoring");
14890                return -1;
14891            }
14892
14893            /*
14894             * If the public key of the package's signature does not match
14895             * our expected public key, then this is a different package and
14896             * we should skip.
14897             */
14898
14899            final byte[] expectedPublicKey;
14900            try {
14901                final Signature verifierSig = pkg.mSignatures[0];
14902                final PublicKey publicKey = verifierSig.getPublicKey();
14903                expectedPublicKey = publicKey.getEncoded();
14904            } catch (CertificateException e) {
14905                return -1;
14906            }
14907
14908            final byte[] actualPublicKey = verifierInfo.publicKey.getEncoded();
14909
14910            if (!Arrays.equals(actualPublicKey, expectedPublicKey)) {
14911                Slog.i(TAG, "Verifier package " + verifierInfo.packageName
14912                        + " does not have the expected public key; ignoring");
14913                return -1;
14914            }
14915
14916            return pkg.applicationInfo.uid;
14917        }
14918    }
14919
14920    @Override
14921    public void finishPackageInstall(int token, boolean didLaunch) {
14922        enforceSystemOrRoot("Only the system is allowed to finish installs");
14923
14924        if (DEBUG_INSTALL) {
14925            Slog.v(TAG, "BM finishing package install for " + token);
14926        }
14927        Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "restore", token);
14928
14929        final Message msg = mHandler.obtainMessage(POST_INSTALL, token, didLaunch ? 1 : 0);
14930        mHandler.sendMessage(msg);
14931    }
14932
14933    /**
14934     * Get the verification agent timeout.  Used for both the APK verifier and the
14935     * intent filter verifier.
14936     *
14937     * @return verification timeout in milliseconds
14938     */
14939    private long getVerificationTimeout() {
14940        return android.provider.Settings.Global.getLong(mContext.getContentResolver(),
14941                android.provider.Settings.Global.PACKAGE_VERIFIER_TIMEOUT,
14942                DEFAULT_VERIFICATION_TIMEOUT);
14943    }
14944
14945    /**
14946     * Get the default verification agent response code.
14947     *
14948     * @return default verification response code
14949     */
14950    private int getDefaultVerificationResponse(UserHandle user) {
14951        if (sUserManager.hasUserRestriction(UserManager.ENSURE_VERIFY_APPS, user.getIdentifier())) {
14952            return PackageManager.VERIFICATION_REJECT;
14953        }
14954        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
14955                android.provider.Settings.Global.PACKAGE_VERIFIER_DEFAULT_RESPONSE,
14956                DEFAULT_VERIFICATION_RESPONSE);
14957    }
14958
14959    /**
14960     * Check whether or not package verification has been enabled.
14961     *
14962     * @return true if verification should be performed
14963     */
14964    private boolean isVerificationEnabled(int userId, int installFlags, int installerUid) {
14965        if (!DEFAULT_VERIFY_ENABLE) {
14966            return false;
14967        }
14968
14969        boolean ensureVerifyAppsEnabled = isUserRestricted(userId, UserManager.ENSURE_VERIFY_APPS);
14970
14971        // Check if installing from ADB
14972        if ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0) {
14973            // Do not run verification in a test harness environment
14974            if (ActivityManager.isRunningInTestHarness()) {
14975                return false;
14976            }
14977            if (ensureVerifyAppsEnabled) {
14978                return true;
14979            }
14980            // Check if the developer does not want package verification for ADB installs
14981            if (android.provider.Settings.Global.getInt(mContext.getContentResolver(),
14982                    android.provider.Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB, 1) == 0) {
14983                return false;
14984            }
14985        } else {
14986            // only when not installed from ADB, skip verification for instant apps when
14987            // the installer and verifier are the same.
14988            if ((installFlags & PackageManager.INSTALL_INSTANT_APP) != 0) {
14989                if (mInstantAppInstallerActivity != null
14990                        && mInstantAppInstallerActivity.packageName.equals(
14991                                mRequiredVerifierPackage)) {
14992                    try {
14993                        mContext.getSystemService(AppOpsManager.class)
14994                                .checkPackage(installerUid, mRequiredVerifierPackage);
14995                        if (DEBUG_VERIFY) {
14996                            Slog.i(TAG, "disable verification for instant app");
14997                        }
14998                        return false;
14999                    } catch (SecurityException ignore) { }
15000                }
15001            }
15002        }
15003
15004        if (ensureVerifyAppsEnabled) {
15005            return true;
15006        }
15007
15008        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
15009                android.provider.Settings.Global.PACKAGE_VERIFIER_ENABLE, 1) == 1;
15010    }
15011
15012    @Override
15013    public void verifyIntentFilter(int id, int verificationCode, List<String> failedDomains)
15014            throws RemoteException {
15015        mContext.enforceCallingOrSelfPermission(
15016                Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT,
15017                "Only intentfilter verification agents can verify applications");
15018
15019        final Message msg = mHandler.obtainMessage(INTENT_FILTER_VERIFIED);
15020        final IntentFilterVerificationResponse response = new IntentFilterVerificationResponse(
15021                Binder.getCallingUid(), verificationCode, failedDomains);
15022        msg.arg1 = id;
15023        msg.obj = response;
15024        mHandler.sendMessage(msg);
15025    }
15026
15027    @Override
15028    public int getIntentVerificationStatus(String packageName, int userId) {
15029        final int callingUid = Binder.getCallingUid();
15030        if (getInstantAppPackageName(callingUid) != null) {
15031            return INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED;
15032        }
15033        synchronized (mPackages) {
15034            final PackageSetting ps = mSettings.mPackages.get(packageName);
15035            if (ps == null
15036                    || filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
15037                return INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED;
15038            }
15039            return mSettings.getIntentFilterVerificationStatusLPr(packageName, userId);
15040        }
15041    }
15042
15043    @Override
15044    public boolean updateIntentVerificationStatus(String packageName, int status, int userId) {
15045        mContext.enforceCallingOrSelfPermission(
15046                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
15047
15048        boolean result = false;
15049        synchronized (mPackages) {
15050            final PackageSetting ps = mSettings.mPackages.get(packageName);
15051            if (filterAppAccessLPr(ps, Binder.getCallingUid(), UserHandle.getCallingUserId())) {
15052                return false;
15053            }
15054            result = mSettings.updateIntentFilterVerificationStatusLPw(packageName, status, userId);
15055        }
15056        if (result) {
15057            scheduleWritePackageRestrictionsLocked(userId);
15058        }
15059        return result;
15060    }
15061
15062    @Override
15063    public @NonNull ParceledListSlice<IntentFilterVerificationInfo> getIntentFilterVerifications(
15064            String packageName) {
15065        final int callingUid = Binder.getCallingUid();
15066        if (getInstantAppPackageName(callingUid) != null) {
15067            return ParceledListSlice.emptyList();
15068        }
15069        synchronized (mPackages) {
15070            final PackageSetting ps = mSettings.mPackages.get(packageName);
15071            if (filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
15072                return ParceledListSlice.emptyList();
15073            }
15074            return new ParceledListSlice<>(mSettings.getIntentFilterVerificationsLPr(packageName));
15075        }
15076    }
15077
15078    @Override
15079    public @NonNull ParceledListSlice<IntentFilter> getAllIntentFilters(String packageName) {
15080        if (TextUtils.isEmpty(packageName)) {
15081            return ParceledListSlice.emptyList();
15082        }
15083        final int callingUid = Binder.getCallingUid();
15084        final int callingUserId = UserHandle.getUserId(callingUid);
15085        synchronized (mPackages) {
15086            PackageParser.Package pkg = mPackages.get(packageName);
15087            if (pkg == null || pkg.activities == null) {
15088                return ParceledListSlice.emptyList();
15089            }
15090            if (pkg.mExtras == null) {
15091                return ParceledListSlice.emptyList();
15092            }
15093            final PackageSetting ps = (PackageSetting) pkg.mExtras;
15094            if (filterAppAccessLPr(ps, callingUid, callingUserId)) {
15095                return ParceledListSlice.emptyList();
15096            }
15097            final int count = pkg.activities.size();
15098            ArrayList<IntentFilter> result = new ArrayList<>();
15099            for (int n=0; n<count; n++) {
15100                PackageParser.Activity activity = pkg.activities.get(n);
15101                if (activity.intents != null && activity.intents.size() > 0) {
15102                    result.addAll(activity.intents);
15103                }
15104            }
15105            return new ParceledListSlice<>(result);
15106        }
15107    }
15108
15109    @Override
15110    public boolean setDefaultBrowserPackageName(String packageName, int userId) {
15111        mContext.enforceCallingOrSelfPermission(
15112                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
15113
15114        synchronized (mPackages) {
15115            boolean result = mSettings.setDefaultBrowserPackageNameLPw(packageName, userId);
15116            if (packageName != null) {
15117                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultBrowserLPr(
15118                        packageName, userId);
15119            }
15120            return result;
15121        }
15122    }
15123
15124    @Override
15125    public String getDefaultBrowserPackageName(int userId) {
15126        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
15127            return null;
15128        }
15129        synchronized (mPackages) {
15130            return mSettings.getDefaultBrowserPackageNameLPw(userId);
15131        }
15132    }
15133
15134    /**
15135     * Get the "allow unknown sources" setting.
15136     *
15137     * @return the current "allow unknown sources" setting
15138     */
15139    private int getUnknownSourcesSettings() {
15140        return android.provider.Settings.Secure.getInt(mContext.getContentResolver(),
15141                android.provider.Settings.Secure.INSTALL_NON_MARKET_APPS,
15142                -1);
15143    }
15144
15145    @Override
15146    public void setInstallerPackageName(String targetPackage, String installerPackageName) {
15147        final int callingUid = Binder.getCallingUid();
15148        if (getInstantAppPackageName(callingUid) != null) {
15149            return;
15150        }
15151        // writer
15152        synchronized (mPackages) {
15153            PackageSetting targetPackageSetting = mSettings.mPackages.get(targetPackage);
15154            if (targetPackageSetting == null
15155                    || filterAppAccessLPr(
15156                            targetPackageSetting, callingUid, UserHandle.getUserId(callingUid))) {
15157                throw new IllegalArgumentException("Unknown target package: " + targetPackage);
15158            }
15159
15160            PackageSetting installerPackageSetting;
15161            if (installerPackageName != null) {
15162                installerPackageSetting = mSettings.mPackages.get(installerPackageName);
15163                if (installerPackageSetting == null) {
15164                    throw new IllegalArgumentException("Unknown installer package: "
15165                            + installerPackageName);
15166                }
15167            } else {
15168                installerPackageSetting = null;
15169            }
15170
15171            Signature[] callerSignature;
15172            Object obj = mSettings.getUserIdLPr(callingUid);
15173            if (obj != null) {
15174                if (obj instanceof SharedUserSetting) {
15175                    callerSignature = ((SharedUserSetting)obj).signatures.mSignatures;
15176                } else if (obj instanceof PackageSetting) {
15177                    callerSignature = ((PackageSetting)obj).signatures.mSignatures;
15178                } else {
15179                    throw new SecurityException("Bad object " + obj + " for uid " + callingUid);
15180                }
15181            } else {
15182                throw new SecurityException("Unknown calling UID: " + callingUid);
15183            }
15184
15185            // Verify: can't set installerPackageName to a package that is
15186            // not signed with the same cert as the caller.
15187            if (installerPackageSetting != null) {
15188                if (compareSignatures(callerSignature,
15189                        installerPackageSetting.signatures.mSignatures)
15190                        != PackageManager.SIGNATURE_MATCH) {
15191                    throw new SecurityException(
15192                            "Caller does not have same cert as new installer package "
15193                            + installerPackageName);
15194                }
15195            }
15196
15197            // Verify: if target already has an installer package, it must
15198            // be signed with the same cert as the caller.
15199            if (targetPackageSetting.installerPackageName != null) {
15200                PackageSetting setting = mSettings.mPackages.get(
15201                        targetPackageSetting.installerPackageName);
15202                // If the currently set package isn't valid, then it's always
15203                // okay to change it.
15204                if (setting != null) {
15205                    if (compareSignatures(callerSignature,
15206                            setting.signatures.mSignatures)
15207                            != PackageManager.SIGNATURE_MATCH) {
15208                        throw new SecurityException(
15209                                "Caller does not have same cert as old installer package "
15210                                + targetPackageSetting.installerPackageName);
15211                    }
15212                }
15213            }
15214
15215            // Okay!
15216            targetPackageSetting.installerPackageName = installerPackageName;
15217            if (installerPackageName != null) {
15218                mSettings.mInstallerPackages.add(installerPackageName);
15219            }
15220            scheduleWriteSettingsLocked();
15221        }
15222    }
15223
15224    @Override
15225    public void setApplicationCategoryHint(String packageName, int categoryHint,
15226            String callerPackageName) {
15227        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
15228            throw new SecurityException("Instant applications don't have access to this method");
15229        }
15230        mContext.getSystemService(AppOpsManager.class).checkPackage(Binder.getCallingUid(),
15231                callerPackageName);
15232        synchronized (mPackages) {
15233            PackageSetting ps = mSettings.mPackages.get(packageName);
15234            if (ps == null) {
15235                throw new IllegalArgumentException("Unknown target package " + packageName);
15236            }
15237            if (filterAppAccessLPr(ps, Binder.getCallingUid(), UserHandle.getCallingUserId())) {
15238                throw new IllegalArgumentException("Unknown target package " + packageName);
15239            }
15240            if (!Objects.equals(callerPackageName, ps.installerPackageName)) {
15241                throw new IllegalArgumentException("Calling package " + callerPackageName
15242                        + " is not installer for " + packageName);
15243            }
15244
15245            if (ps.categoryHint != categoryHint) {
15246                ps.categoryHint = categoryHint;
15247                scheduleWriteSettingsLocked();
15248            }
15249        }
15250    }
15251
15252    private void processPendingInstall(final InstallArgs args, final int currentStatus) {
15253        // Queue up an async operation since the package installation may take a little while.
15254        mHandler.post(new Runnable() {
15255            public void run() {
15256                mHandler.removeCallbacks(this);
15257                 // Result object to be returned
15258                PackageInstalledInfo res = new PackageInstalledInfo();
15259                res.setReturnCode(currentStatus);
15260                res.uid = -1;
15261                res.pkg = null;
15262                res.removedInfo = null;
15263                if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
15264                    args.doPreInstall(res.returnCode);
15265                    synchronized (mInstallLock) {
15266                        installPackageTracedLI(args, res);
15267                    }
15268                    args.doPostInstall(res.returnCode, res.uid);
15269                }
15270
15271                // A restore should be performed at this point if (a) the install
15272                // succeeded, (b) the operation is not an update, and (c) the new
15273                // package has not opted out of backup participation.
15274                final boolean update = res.removedInfo != null
15275                        && res.removedInfo.removedPackage != null;
15276                final int flags = (res.pkg == null) ? 0 : res.pkg.applicationInfo.flags;
15277                boolean doRestore = !update
15278                        && ((flags & ApplicationInfo.FLAG_ALLOW_BACKUP) != 0);
15279
15280                // Set up the post-install work request bookkeeping.  This will be used
15281                // and cleaned up by the post-install event handling regardless of whether
15282                // there's a restore pass performed.  Token values are >= 1.
15283                int token;
15284                if (mNextInstallToken < 0) mNextInstallToken = 1;
15285                token = mNextInstallToken++;
15286
15287                PostInstallData data = new PostInstallData(args, res);
15288                mRunningInstalls.put(token, data);
15289                if (DEBUG_INSTALL) Log.v(TAG, "+ starting restore round-trip " + token);
15290
15291                if (res.returnCode == PackageManager.INSTALL_SUCCEEDED && doRestore) {
15292                    // Pass responsibility to the Backup Manager.  It will perform a
15293                    // restore if appropriate, then pass responsibility back to the
15294                    // Package Manager to run the post-install observer callbacks
15295                    // and broadcasts.
15296                    IBackupManager bm = IBackupManager.Stub.asInterface(
15297                            ServiceManager.getService(Context.BACKUP_SERVICE));
15298                    if (bm != null) {
15299                        if (DEBUG_INSTALL) Log.v(TAG, "token " + token
15300                                + " to BM for possible restore");
15301                        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "restore", token);
15302                        try {
15303                            // TODO: http://b/22388012
15304                            if (bm.isBackupServiceActive(UserHandle.USER_SYSTEM)) {
15305                                bm.restoreAtInstall(res.pkg.applicationInfo.packageName, token);
15306                            } else {
15307                                doRestore = false;
15308                            }
15309                        } catch (RemoteException e) {
15310                            // can't happen; the backup manager is local
15311                        } catch (Exception e) {
15312                            Slog.e(TAG, "Exception trying to enqueue restore", e);
15313                            doRestore = false;
15314                        }
15315                    } else {
15316                        Slog.e(TAG, "Backup Manager not found!");
15317                        doRestore = false;
15318                    }
15319                }
15320
15321                if (!doRestore) {
15322                    // No restore possible, or the Backup Manager was mysteriously not
15323                    // available -- just fire the post-install work request directly.
15324                    if (DEBUG_INSTALL) Log.v(TAG, "No restore - queue post-install for " + token);
15325
15326                    Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "postInstall", token);
15327
15328                    Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0);
15329                    mHandler.sendMessage(msg);
15330                }
15331            }
15332        });
15333    }
15334
15335    /**
15336     * Callback from PackageSettings whenever an app is first transitioned out of the
15337     * 'stopped' state.  Normally we just issue the broadcast, but we can't do that if
15338     * the app was "launched" for a restoreAtInstall operation.  Therefore we check
15339     * here whether the app is the target of an ongoing install, and only send the
15340     * broadcast immediately if it is not in that state.  If it *is* undergoing a restore,
15341     * the first-launch broadcast will be sent implicitly on that basis in POST_INSTALL
15342     * handling.
15343     */
15344    void notifyFirstLaunch(final String pkgName, final String installerPackage, final int userId) {
15345        // Serialize this with the rest of the install-process message chain.  In the
15346        // restore-at-install case, this Runnable will necessarily run before the
15347        // POST_INSTALL message is processed, so the contents of mRunningInstalls
15348        // are coherent.  In the non-restore case, the app has already completed install
15349        // and been launched through some other means, so it is not in a problematic
15350        // state for observers to see the FIRST_LAUNCH signal.
15351        mHandler.post(new Runnable() {
15352            @Override
15353            public void run() {
15354                for (int i = 0; i < mRunningInstalls.size(); i++) {
15355                    final PostInstallData data = mRunningInstalls.valueAt(i);
15356                    if (data.res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
15357                        continue;
15358                    }
15359                    if (pkgName.equals(data.res.pkg.applicationInfo.packageName)) {
15360                        // right package; but is it for the right user?
15361                        for (int uIndex = 0; uIndex < data.res.newUsers.length; uIndex++) {
15362                            if (userId == data.res.newUsers[uIndex]) {
15363                                if (DEBUG_BACKUP) {
15364                                    Slog.i(TAG, "Package " + pkgName
15365                                            + " being restored so deferring FIRST_LAUNCH");
15366                                }
15367                                return;
15368                            }
15369                        }
15370                    }
15371                }
15372                // didn't find it, so not being restored
15373                if (DEBUG_BACKUP) {
15374                    Slog.i(TAG, "Package " + pkgName + " sending normal FIRST_LAUNCH");
15375                }
15376                sendFirstLaunchBroadcast(pkgName, installerPackage, new int[] {userId});
15377            }
15378        });
15379    }
15380
15381    private void sendFirstLaunchBroadcast(String pkgName, String installerPkg, int[] userIds) {
15382        sendPackageBroadcast(Intent.ACTION_PACKAGE_FIRST_LAUNCH, pkgName, null, 0,
15383                installerPkg, null, userIds);
15384    }
15385
15386    private abstract class HandlerParams {
15387        private static final int MAX_RETRIES = 4;
15388
15389        /**
15390         * Number of times startCopy() has been attempted and had a non-fatal
15391         * error.
15392         */
15393        private int mRetries = 0;
15394
15395        /** User handle for the user requesting the information or installation. */
15396        private final UserHandle mUser;
15397        String traceMethod;
15398        int traceCookie;
15399
15400        HandlerParams(UserHandle user) {
15401            mUser = user;
15402        }
15403
15404        UserHandle getUser() {
15405            return mUser;
15406        }
15407
15408        HandlerParams setTraceMethod(String traceMethod) {
15409            this.traceMethod = traceMethod;
15410            return this;
15411        }
15412
15413        HandlerParams setTraceCookie(int traceCookie) {
15414            this.traceCookie = traceCookie;
15415            return this;
15416        }
15417
15418        final boolean startCopy() {
15419            boolean res;
15420            try {
15421                if (DEBUG_INSTALL) Slog.i(TAG, "startCopy " + mUser + ": " + this);
15422
15423                if (++mRetries > MAX_RETRIES) {
15424                    Slog.w(TAG, "Failed to invoke remote methods on default container service. Giving up");
15425                    mHandler.sendEmptyMessage(MCS_GIVE_UP);
15426                    handleServiceError();
15427                    return false;
15428                } else {
15429                    handleStartCopy();
15430                    res = true;
15431                }
15432            } catch (RemoteException e) {
15433                if (DEBUG_INSTALL) Slog.i(TAG, "Posting install MCS_RECONNECT");
15434                mHandler.sendEmptyMessage(MCS_RECONNECT);
15435                res = false;
15436            }
15437            handleReturnCode();
15438            return res;
15439        }
15440
15441        final void serviceError() {
15442            if (DEBUG_INSTALL) Slog.i(TAG, "serviceError");
15443            handleServiceError();
15444            handleReturnCode();
15445        }
15446
15447        abstract void handleStartCopy() throws RemoteException;
15448        abstract void handleServiceError();
15449        abstract void handleReturnCode();
15450    }
15451
15452    private static void clearDirectory(IMediaContainerService mcs, File[] paths) {
15453        for (File path : paths) {
15454            try {
15455                mcs.clearDirectory(path.getAbsolutePath());
15456            } catch (RemoteException e) {
15457            }
15458        }
15459    }
15460
15461    static class OriginInfo {
15462        /**
15463         * Location where install is coming from, before it has been
15464         * copied/renamed into place. This could be a single monolithic APK
15465         * file, or a cluster directory. This location may be untrusted.
15466         */
15467        final File file;
15468        final String cid;
15469
15470        /**
15471         * Flag indicating that {@link #file} or {@link #cid} has already been
15472         * staged, meaning downstream users don't need to defensively copy the
15473         * contents.
15474         */
15475        final boolean staged;
15476
15477        /**
15478         * Flag indicating that {@link #file} or {@link #cid} is an already
15479         * installed app that is being moved.
15480         */
15481        final boolean existing;
15482
15483        final String resolvedPath;
15484        final File resolvedFile;
15485
15486        static OriginInfo fromNothing() {
15487            return new OriginInfo(null, null, false, false);
15488        }
15489
15490        static OriginInfo fromUntrustedFile(File file) {
15491            return new OriginInfo(file, null, false, false);
15492        }
15493
15494        static OriginInfo fromExistingFile(File file) {
15495            return new OriginInfo(file, null, false, true);
15496        }
15497
15498        static OriginInfo fromStagedFile(File file) {
15499            return new OriginInfo(file, null, true, false);
15500        }
15501
15502        static OriginInfo fromStagedContainer(String cid) {
15503            return new OriginInfo(null, cid, true, false);
15504        }
15505
15506        private OriginInfo(File file, String cid, boolean staged, boolean existing) {
15507            this.file = file;
15508            this.cid = cid;
15509            this.staged = staged;
15510            this.existing = existing;
15511
15512            if (cid != null) {
15513                resolvedPath = PackageHelper.getSdDir(cid);
15514                resolvedFile = new File(resolvedPath);
15515            } else if (file != null) {
15516                resolvedPath = file.getAbsolutePath();
15517                resolvedFile = file;
15518            } else {
15519                resolvedPath = null;
15520                resolvedFile = null;
15521            }
15522        }
15523    }
15524
15525    static class MoveInfo {
15526        final int moveId;
15527        final String fromUuid;
15528        final String toUuid;
15529        final String packageName;
15530        final String dataAppName;
15531        final int appId;
15532        final String seinfo;
15533        final int targetSdkVersion;
15534
15535        public MoveInfo(int moveId, String fromUuid, String toUuid, String packageName,
15536                String dataAppName, int appId, String seinfo, int targetSdkVersion) {
15537            this.moveId = moveId;
15538            this.fromUuid = fromUuid;
15539            this.toUuid = toUuid;
15540            this.packageName = packageName;
15541            this.dataAppName = dataAppName;
15542            this.appId = appId;
15543            this.seinfo = seinfo;
15544            this.targetSdkVersion = targetSdkVersion;
15545        }
15546    }
15547
15548    static class VerificationInfo {
15549        /** A constant used to indicate that a uid value is not present. */
15550        public static final int NO_UID = -1;
15551
15552        /** URI referencing where the package was downloaded from. */
15553        final Uri originatingUri;
15554
15555        /** HTTP referrer URI associated with the originatingURI. */
15556        final Uri referrer;
15557
15558        /** UID of the application that the install request originated from. */
15559        final int originatingUid;
15560
15561        /** UID of application requesting the install */
15562        final int installerUid;
15563
15564        VerificationInfo(Uri originatingUri, Uri referrer, int originatingUid, int installerUid) {
15565            this.originatingUri = originatingUri;
15566            this.referrer = referrer;
15567            this.originatingUid = originatingUid;
15568            this.installerUid = installerUid;
15569        }
15570    }
15571
15572    class InstallParams extends HandlerParams {
15573        final OriginInfo origin;
15574        final MoveInfo move;
15575        final IPackageInstallObserver2 observer;
15576        int installFlags;
15577        final String installerPackageName;
15578        final String volumeUuid;
15579        private InstallArgs mArgs;
15580        private int mRet;
15581        final String packageAbiOverride;
15582        final String[] grantedRuntimePermissions;
15583        final VerificationInfo verificationInfo;
15584        final Certificate[][] certificates;
15585        final int installReason;
15586
15587        InstallParams(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer,
15588                int installFlags, String installerPackageName, String volumeUuid,
15589                VerificationInfo verificationInfo, UserHandle user, String packageAbiOverride,
15590                String[] grantedPermissions, Certificate[][] certificates, int installReason) {
15591            super(user);
15592            this.origin = origin;
15593            this.move = move;
15594            this.observer = observer;
15595            this.installFlags = installFlags;
15596            this.installerPackageName = installerPackageName;
15597            this.volumeUuid = volumeUuid;
15598            this.verificationInfo = verificationInfo;
15599            this.packageAbiOverride = packageAbiOverride;
15600            this.grantedRuntimePermissions = grantedPermissions;
15601            this.certificates = certificates;
15602            this.installReason = installReason;
15603        }
15604
15605        @Override
15606        public String toString() {
15607            return "InstallParams{" + Integer.toHexString(System.identityHashCode(this))
15608                    + " file=" + origin.file + " cid=" + origin.cid + "}";
15609        }
15610
15611        private int installLocationPolicy(PackageInfoLite pkgLite) {
15612            String packageName = pkgLite.packageName;
15613            int installLocation = pkgLite.installLocation;
15614            boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
15615            // reader
15616            synchronized (mPackages) {
15617                // Currently installed package which the new package is attempting to replace or
15618                // null if no such package is installed.
15619                PackageParser.Package installedPkg = mPackages.get(packageName);
15620                // Package which currently owns the data which the new package will own if installed.
15621                // If an app is unstalled while keeping data (e.g., adb uninstall -k), installedPkg
15622                // will be null whereas dataOwnerPkg will contain information about the package
15623                // which was uninstalled while keeping its data.
15624                PackageParser.Package dataOwnerPkg = installedPkg;
15625                if (dataOwnerPkg  == null) {
15626                    PackageSetting ps = mSettings.mPackages.get(packageName);
15627                    if (ps != null) {
15628                        dataOwnerPkg = ps.pkg;
15629                    }
15630                }
15631
15632                if (dataOwnerPkg != null) {
15633                    // If installed, the package will get access to data left on the device by its
15634                    // predecessor. As a security measure, this is permited only if this is not a
15635                    // version downgrade or if the predecessor package is marked as debuggable and
15636                    // a downgrade is explicitly requested.
15637                    //
15638                    // On debuggable platform builds, downgrades are permitted even for
15639                    // non-debuggable packages to make testing easier. Debuggable platform builds do
15640                    // not offer security guarantees and thus it's OK to disable some security
15641                    // mechanisms to make debugging/testing easier on those builds. However, even on
15642                    // debuggable builds downgrades of packages are permitted only if requested via
15643                    // installFlags. This is because we aim to keep the behavior of debuggable
15644                    // platform builds as close as possible to the behavior of non-debuggable
15645                    // platform builds.
15646                    final boolean downgradeRequested =
15647                            (installFlags & PackageManager.INSTALL_ALLOW_DOWNGRADE) != 0;
15648                    final boolean packageDebuggable =
15649                                (dataOwnerPkg.applicationInfo.flags
15650                                        & ApplicationInfo.FLAG_DEBUGGABLE) != 0;
15651                    final boolean downgradePermitted =
15652                            (downgradeRequested) && ((Build.IS_DEBUGGABLE) || (packageDebuggable));
15653                    if (!downgradePermitted) {
15654                        try {
15655                            checkDowngrade(dataOwnerPkg, pkgLite);
15656                        } catch (PackageManagerException e) {
15657                            Slog.w(TAG, "Downgrade detected: " + e.getMessage());
15658                            return PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE;
15659                        }
15660                    }
15661                }
15662
15663                if (installedPkg != null) {
15664                    if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
15665                        // Check for updated system application.
15666                        if ((installedPkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
15667                            if (onSd) {
15668                                Slog.w(TAG, "Cannot install update to system app on sdcard");
15669                                return PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION;
15670                            }
15671                            return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
15672                        } else {
15673                            if (onSd) {
15674                                // Install flag overrides everything.
15675                                return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
15676                            }
15677                            // If current upgrade specifies particular preference
15678                            if (installLocation == PackageInfo.INSTALL_LOCATION_INTERNAL_ONLY) {
15679                                // Application explicitly specified internal.
15680                                return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
15681                            } else if (installLocation == PackageInfo.INSTALL_LOCATION_PREFER_EXTERNAL) {
15682                                // App explictly prefers external. Let policy decide
15683                            } else {
15684                                // Prefer previous location
15685                                if (isExternal(installedPkg)) {
15686                                    return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
15687                                }
15688                                return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
15689                            }
15690                        }
15691                    } else {
15692                        // Invalid install. Return error code
15693                        return PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS;
15694                    }
15695                }
15696            }
15697            // All the special cases have been taken care of.
15698            // Return result based on recommended install location.
15699            if (onSd) {
15700                return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
15701            }
15702            return pkgLite.recommendedInstallLocation;
15703        }
15704
15705        /*
15706         * Invoke remote method to get package information and install
15707         * location values. Override install location based on default
15708         * policy if needed and then create install arguments based
15709         * on the install location.
15710         */
15711        public void handleStartCopy() throws RemoteException {
15712            int ret = PackageManager.INSTALL_SUCCEEDED;
15713
15714            // If we're already staged, we've firmly committed to an install location
15715            if (origin.staged) {
15716                if (origin.file != null) {
15717                    installFlags |= PackageManager.INSTALL_INTERNAL;
15718                    installFlags &= ~PackageManager.INSTALL_EXTERNAL;
15719                } else if (origin.cid != null) {
15720                    installFlags |= PackageManager.INSTALL_EXTERNAL;
15721                    installFlags &= ~PackageManager.INSTALL_INTERNAL;
15722                } else {
15723                    throw new IllegalStateException("Invalid stage location");
15724                }
15725            }
15726
15727            final boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
15728            final boolean onInt = (installFlags & PackageManager.INSTALL_INTERNAL) != 0;
15729            final boolean ephemeral = (installFlags & PackageManager.INSTALL_INSTANT_APP) != 0;
15730            PackageInfoLite pkgLite = null;
15731
15732            if (onInt && onSd) {
15733                // Check if both bits are set.
15734                Slog.w(TAG, "Conflicting flags specified for installing on both internal and external");
15735                ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
15736            } else if (onSd && ephemeral) {
15737                Slog.w(TAG,  "Conflicting flags specified for installing ephemeral on external");
15738                ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
15739            } else {
15740                pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, installFlags,
15741                        packageAbiOverride);
15742
15743                if (DEBUG_EPHEMERAL && ephemeral) {
15744                    Slog.v(TAG, "pkgLite for install: " + pkgLite);
15745                }
15746
15747                /*
15748                 * If we have too little free space, try to free cache
15749                 * before giving up.
15750                 */
15751                if (!origin.staged && pkgLite.recommendedInstallLocation
15752                        == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) {
15753                    // TODO: focus freeing disk space on the target device
15754                    final StorageManager storage = StorageManager.from(mContext);
15755                    final long lowThreshold = storage.getStorageLowBytes(
15756                            Environment.getDataDirectory());
15757
15758                    final long sizeBytes = mContainerService.calculateInstalledSize(
15759                            origin.resolvedPath, isForwardLocked(), packageAbiOverride);
15760
15761                    try {
15762                        mInstaller.freeCache(null, sizeBytes + lowThreshold, 0, 0);
15763                        pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath,
15764                                installFlags, packageAbiOverride);
15765                    } catch (InstallerException e) {
15766                        Slog.w(TAG, "Failed to free cache", e);
15767                    }
15768
15769                    /*
15770                     * The cache free must have deleted the file we
15771                     * downloaded to install.
15772                     *
15773                     * TODO: fix the "freeCache" call to not delete
15774                     *       the file we care about.
15775                     */
15776                    if (pkgLite.recommendedInstallLocation
15777                            == PackageHelper.RECOMMEND_FAILED_INVALID_URI) {
15778                        pkgLite.recommendedInstallLocation
15779                            = PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE;
15780                    }
15781                }
15782            }
15783
15784            if (ret == PackageManager.INSTALL_SUCCEEDED) {
15785                int loc = pkgLite.recommendedInstallLocation;
15786                if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION) {
15787                    ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
15788                } else if (loc == PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS) {
15789                    ret = PackageManager.INSTALL_FAILED_ALREADY_EXISTS;
15790                } else if (loc == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) {
15791                    ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
15792                } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_APK) {
15793                    ret = PackageManager.INSTALL_FAILED_INVALID_APK;
15794                } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_URI) {
15795                    ret = PackageManager.INSTALL_FAILED_INVALID_URI;
15796                } else if (loc == PackageHelper.RECOMMEND_MEDIA_UNAVAILABLE) {
15797                    ret = PackageManager.INSTALL_FAILED_MEDIA_UNAVAILABLE;
15798                } else {
15799                    // Override with defaults if needed.
15800                    loc = installLocationPolicy(pkgLite);
15801                    if (loc == PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE) {
15802                        ret = PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE;
15803                    } else if (!onSd && !onInt) {
15804                        // Override install location with flags
15805                        if (loc == PackageHelper.RECOMMEND_INSTALL_EXTERNAL) {
15806                            // Set the flag to install on external media.
15807                            installFlags |= PackageManager.INSTALL_EXTERNAL;
15808                            installFlags &= ~PackageManager.INSTALL_INTERNAL;
15809                        } else if (loc == PackageHelper.RECOMMEND_INSTALL_EPHEMERAL) {
15810                            if (DEBUG_EPHEMERAL) {
15811                                Slog.v(TAG, "...setting INSTALL_EPHEMERAL install flag");
15812                            }
15813                            installFlags |= PackageManager.INSTALL_INSTANT_APP;
15814                            installFlags &= ~(PackageManager.INSTALL_EXTERNAL
15815                                    |PackageManager.INSTALL_INTERNAL);
15816                        } else {
15817                            // Make sure the flag for installing on external
15818                            // media is unset
15819                            installFlags |= PackageManager.INSTALL_INTERNAL;
15820                            installFlags &= ~PackageManager.INSTALL_EXTERNAL;
15821                        }
15822                    }
15823                }
15824            }
15825
15826            final InstallArgs args = createInstallArgs(this);
15827            mArgs = args;
15828
15829            if (ret == PackageManager.INSTALL_SUCCEEDED) {
15830                // TODO: http://b/22976637
15831                // Apps installed for "all" users use the device owner to verify the app
15832                UserHandle verifierUser = getUser();
15833                if (verifierUser == UserHandle.ALL) {
15834                    verifierUser = UserHandle.SYSTEM;
15835                }
15836
15837                /*
15838                 * Determine if we have any installed package verifiers. If we
15839                 * do, then we'll defer to them to verify the packages.
15840                 */
15841                final int requiredUid = mRequiredVerifierPackage == null ? -1
15842                        : getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING,
15843                                verifierUser.getIdentifier());
15844                final int installerUid =
15845                        verificationInfo == null ? -1 : verificationInfo.installerUid;
15846                if (!origin.existing && requiredUid != -1
15847                        && isVerificationEnabled(
15848                                verifierUser.getIdentifier(), installFlags, installerUid)) {
15849                    final Intent verification = new Intent(
15850                            Intent.ACTION_PACKAGE_NEEDS_VERIFICATION);
15851                    verification.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
15852                    verification.setDataAndType(Uri.fromFile(new File(origin.resolvedPath)),
15853                            PACKAGE_MIME_TYPE);
15854                    verification.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
15855
15856                    // Query all live verifiers based on current user state
15857                    final List<ResolveInfo> receivers = queryIntentReceiversInternal(verification,
15858                            PACKAGE_MIME_TYPE, 0, verifierUser.getIdentifier());
15859
15860                    if (DEBUG_VERIFY) {
15861                        Slog.d(TAG, "Found " + receivers.size() + " verifiers for intent "
15862                                + verification.toString() + " with " + pkgLite.verifiers.length
15863                                + " optional verifiers");
15864                    }
15865
15866                    final int verificationId = mPendingVerificationToken++;
15867
15868                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId);
15869
15870                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_PACKAGE,
15871                            installerPackageName);
15872
15873                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALL_FLAGS,
15874                            installFlags);
15875
15876                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_PACKAGE_NAME,
15877                            pkgLite.packageName);
15878
15879                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_VERSION_CODE,
15880                            pkgLite.versionCode);
15881
15882                    if (verificationInfo != null) {
15883                        if (verificationInfo.originatingUri != null) {
15884                            verification.putExtra(Intent.EXTRA_ORIGINATING_URI,
15885                                    verificationInfo.originatingUri);
15886                        }
15887                        if (verificationInfo.referrer != null) {
15888                            verification.putExtra(Intent.EXTRA_REFERRER,
15889                                    verificationInfo.referrer);
15890                        }
15891                        if (verificationInfo.originatingUid >= 0) {
15892                            verification.putExtra(Intent.EXTRA_ORIGINATING_UID,
15893                                    verificationInfo.originatingUid);
15894                        }
15895                        if (verificationInfo.installerUid >= 0) {
15896                            verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_UID,
15897                                    verificationInfo.installerUid);
15898                        }
15899                    }
15900
15901                    final PackageVerificationState verificationState = new PackageVerificationState(
15902                            requiredUid, args);
15903
15904                    mPendingVerification.append(verificationId, verificationState);
15905
15906                    final List<ComponentName> sufficientVerifiers = matchVerifiers(pkgLite,
15907                            receivers, verificationState);
15908
15909                    DeviceIdleController.LocalService idleController = getDeviceIdleController();
15910                    final long idleDuration = getVerificationTimeout();
15911
15912                    /*
15913                     * If any sufficient verifiers were listed in the package
15914                     * manifest, attempt to ask them.
15915                     */
15916                    if (sufficientVerifiers != null) {
15917                        final int N = sufficientVerifiers.size();
15918                        if (N == 0) {
15919                            Slog.i(TAG, "Additional verifiers required, but none installed.");
15920                            ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
15921                        } else {
15922                            for (int i = 0; i < N; i++) {
15923                                final ComponentName verifierComponent = sufficientVerifiers.get(i);
15924                                idleController.addPowerSaveTempWhitelistApp(Process.myUid(),
15925                                        verifierComponent.getPackageName(), idleDuration,
15926                                        verifierUser.getIdentifier(), false, "package verifier");
15927
15928                                final Intent sufficientIntent = new Intent(verification);
15929                                sufficientIntent.setComponent(verifierComponent);
15930                                mContext.sendBroadcastAsUser(sufficientIntent, verifierUser);
15931                            }
15932                        }
15933                    }
15934
15935                    final ComponentName requiredVerifierComponent = matchComponentForVerifier(
15936                            mRequiredVerifierPackage, receivers);
15937                    if (ret == PackageManager.INSTALL_SUCCEEDED
15938                            && mRequiredVerifierPackage != null) {
15939                        Trace.asyncTraceBegin(
15940                                TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId);
15941                        /*
15942                         * Send the intent to the required verification agent,
15943                         * but only start the verification timeout after the
15944                         * target BroadcastReceivers have run.
15945                         */
15946                        verification.setComponent(requiredVerifierComponent);
15947                        idleController.addPowerSaveTempWhitelistApp(Process.myUid(),
15948                                mRequiredVerifierPackage, idleDuration,
15949                                verifierUser.getIdentifier(), false, "package verifier");
15950                        mContext.sendOrderedBroadcastAsUser(verification, verifierUser,
15951                                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
15952                                new BroadcastReceiver() {
15953                                    @Override
15954                                    public void onReceive(Context context, Intent intent) {
15955                                        final Message msg = mHandler
15956                                                .obtainMessage(CHECK_PENDING_VERIFICATION);
15957                                        msg.arg1 = verificationId;
15958                                        mHandler.sendMessageDelayed(msg, getVerificationTimeout());
15959                                    }
15960                                }, null, 0, null, null);
15961
15962                        /*
15963                         * We don't want the copy to proceed until verification
15964                         * succeeds, so null out this field.
15965                         */
15966                        mArgs = null;
15967                    }
15968                } else {
15969                    /*
15970                     * No package verification is enabled, so immediately start
15971                     * the remote call to initiate copy using temporary file.
15972                     */
15973                    ret = args.copyApk(mContainerService, true);
15974                }
15975            }
15976
15977            mRet = ret;
15978        }
15979
15980        @Override
15981        void handleReturnCode() {
15982            // If mArgs is null, then MCS couldn't be reached. When it
15983            // reconnects, it will try again to install. At that point, this
15984            // will succeed.
15985            if (mArgs != null) {
15986                processPendingInstall(mArgs, mRet);
15987            }
15988        }
15989
15990        @Override
15991        void handleServiceError() {
15992            mArgs = createInstallArgs(this);
15993            mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
15994        }
15995
15996        public boolean isForwardLocked() {
15997            return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
15998        }
15999    }
16000
16001    /**
16002     * Used during creation of InstallArgs
16003     *
16004     * @param installFlags package installation flags
16005     * @return true if should be installed on external storage
16006     */
16007    private static boolean installOnExternalAsec(int installFlags) {
16008        if ((installFlags & PackageManager.INSTALL_INTERNAL) != 0) {
16009            return false;
16010        }
16011        if ((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) {
16012            return true;
16013        }
16014        return false;
16015    }
16016
16017    /**
16018     * Used during creation of InstallArgs
16019     *
16020     * @param installFlags package installation flags
16021     * @return true if should be installed as forward locked
16022     */
16023    private static boolean installForwardLocked(int installFlags) {
16024        return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
16025    }
16026
16027    private InstallArgs createInstallArgs(InstallParams params) {
16028        if (params.move != null) {
16029            return new MoveInstallArgs(params);
16030        } else if (installOnExternalAsec(params.installFlags) || params.isForwardLocked()) {
16031            return new AsecInstallArgs(params);
16032        } else {
16033            return new FileInstallArgs(params);
16034        }
16035    }
16036
16037    /**
16038     * Create args that describe an existing installed package. Typically used
16039     * when cleaning up old installs, or used as a move source.
16040     */
16041    private InstallArgs createInstallArgsForExisting(int installFlags, String codePath,
16042            String resourcePath, String[] instructionSets) {
16043        final boolean isInAsec;
16044        if (installOnExternalAsec(installFlags)) {
16045            /* Apps on SD card are always in ASEC containers. */
16046            isInAsec = true;
16047        } else if (installForwardLocked(installFlags)
16048                && !codePath.startsWith(mDrmAppPrivateInstallDir.getAbsolutePath())) {
16049            /*
16050             * Forward-locked apps are only in ASEC containers if they're the
16051             * new style
16052             */
16053            isInAsec = true;
16054        } else {
16055            isInAsec = false;
16056        }
16057
16058        if (isInAsec) {
16059            return new AsecInstallArgs(codePath, instructionSets,
16060                    installOnExternalAsec(installFlags), installForwardLocked(installFlags));
16061        } else {
16062            return new FileInstallArgs(codePath, resourcePath, instructionSets);
16063        }
16064    }
16065
16066    static abstract class InstallArgs {
16067        /** @see InstallParams#origin */
16068        final OriginInfo origin;
16069        /** @see InstallParams#move */
16070        final MoveInfo move;
16071
16072        final IPackageInstallObserver2 observer;
16073        // Always refers to PackageManager flags only
16074        final int installFlags;
16075        final String installerPackageName;
16076        final String volumeUuid;
16077        final UserHandle user;
16078        final String abiOverride;
16079        final String[] installGrantPermissions;
16080        /** If non-null, drop an async trace when the install completes */
16081        final String traceMethod;
16082        final int traceCookie;
16083        final Certificate[][] certificates;
16084        final int installReason;
16085
16086        // The list of instruction sets supported by this app. This is currently
16087        // only used during the rmdex() phase to clean up resources. We can get rid of this
16088        // if we move dex files under the common app path.
16089        /* nullable */ String[] instructionSets;
16090
16091        InstallArgs(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer,
16092                int installFlags, String installerPackageName, String volumeUuid,
16093                UserHandle user, String[] instructionSets,
16094                String abiOverride, String[] installGrantPermissions,
16095                String traceMethod, int traceCookie, Certificate[][] certificates,
16096                int installReason) {
16097            this.origin = origin;
16098            this.move = move;
16099            this.installFlags = installFlags;
16100            this.observer = observer;
16101            this.installerPackageName = installerPackageName;
16102            this.volumeUuid = volumeUuid;
16103            this.user = user;
16104            this.instructionSets = instructionSets;
16105            this.abiOverride = abiOverride;
16106            this.installGrantPermissions = installGrantPermissions;
16107            this.traceMethod = traceMethod;
16108            this.traceCookie = traceCookie;
16109            this.certificates = certificates;
16110            this.installReason = installReason;
16111        }
16112
16113        abstract int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException;
16114        abstract int doPreInstall(int status);
16115
16116        /**
16117         * Rename package into final resting place. All paths on the given
16118         * scanned package should be updated to reflect the rename.
16119         */
16120        abstract boolean doRename(int status, PackageParser.Package pkg, String oldCodePath);
16121        abstract int doPostInstall(int status, int uid);
16122
16123        /** @see PackageSettingBase#codePathString */
16124        abstract String getCodePath();
16125        /** @see PackageSettingBase#resourcePathString */
16126        abstract String getResourcePath();
16127
16128        // Need installer lock especially for dex file removal.
16129        abstract void cleanUpResourcesLI();
16130        abstract boolean doPostDeleteLI(boolean delete);
16131
16132        /**
16133         * Called before the source arguments are copied. This is used mostly
16134         * for MoveParams when it needs to read the source file to put it in the
16135         * destination.
16136         */
16137        int doPreCopy() {
16138            return PackageManager.INSTALL_SUCCEEDED;
16139        }
16140
16141        /**
16142         * Called after the source arguments are copied. This is used mostly for
16143         * MoveParams when it needs to read the source file to put it in the
16144         * destination.
16145         */
16146        int doPostCopy(int uid) {
16147            return PackageManager.INSTALL_SUCCEEDED;
16148        }
16149
16150        protected boolean isFwdLocked() {
16151            return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
16152        }
16153
16154        protected boolean isExternalAsec() {
16155            return (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
16156        }
16157
16158        protected boolean isEphemeral() {
16159            return (installFlags & PackageManager.INSTALL_INSTANT_APP) != 0;
16160        }
16161
16162        UserHandle getUser() {
16163            return user;
16164        }
16165    }
16166
16167    private void removeDexFiles(List<String> allCodePaths, String[] instructionSets) {
16168        if (!allCodePaths.isEmpty()) {
16169            if (instructionSets == null) {
16170                throw new IllegalStateException("instructionSet == null");
16171            }
16172            String[] dexCodeInstructionSets = getDexCodeInstructionSets(instructionSets);
16173            for (String codePath : allCodePaths) {
16174                for (String dexCodeInstructionSet : dexCodeInstructionSets) {
16175                    try {
16176                        mInstaller.rmdex(codePath, dexCodeInstructionSet);
16177                    } catch (InstallerException ignored) {
16178                    }
16179                }
16180            }
16181        }
16182    }
16183
16184    /**
16185     * Logic to handle installation of non-ASEC applications, including copying
16186     * and renaming logic.
16187     */
16188    class FileInstallArgs extends InstallArgs {
16189        private File codeFile;
16190        private File resourceFile;
16191
16192        // Example topology:
16193        // /data/app/com.example/base.apk
16194        // /data/app/com.example/split_foo.apk
16195        // /data/app/com.example/lib/arm/libfoo.so
16196        // /data/app/com.example/lib/arm64/libfoo.so
16197        // /data/app/com.example/dalvik/arm/base.apk@classes.dex
16198
16199        /** New install */
16200        FileInstallArgs(InstallParams params) {
16201            super(params.origin, params.move, params.observer, params.installFlags,
16202                    params.installerPackageName, params.volumeUuid,
16203                    params.getUser(), null /*instructionSets*/, params.packageAbiOverride,
16204                    params.grantedRuntimePermissions,
16205                    params.traceMethod, params.traceCookie, params.certificates,
16206                    params.installReason);
16207            if (isFwdLocked()) {
16208                throw new IllegalArgumentException("Forward locking only supported in ASEC");
16209            }
16210        }
16211
16212        /** Existing install */
16213        FileInstallArgs(String codePath, String resourcePath, String[] instructionSets) {
16214            super(OriginInfo.fromNothing(), null, null, 0, null, null, null, instructionSets,
16215                    null, null, null, 0, null /*certificates*/,
16216                    PackageManager.INSTALL_REASON_UNKNOWN);
16217            this.codeFile = (codePath != null) ? new File(codePath) : null;
16218            this.resourceFile = (resourcePath != null) ? new File(resourcePath) : null;
16219        }
16220
16221        int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
16222            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyApk");
16223            try {
16224                return doCopyApk(imcs, temp);
16225            } finally {
16226                Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
16227            }
16228        }
16229
16230        private int doCopyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
16231            if (origin.staged) {
16232                if (DEBUG_INSTALL) Slog.d(TAG, origin.file + " already staged; skipping copy");
16233                codeFile = origin.file;
16234                resourceFile = origin.file;
16235                return PackageManager.INSTALL_SUCCEEDED;
16236            }
16237
16238            try {
16239                final boolean isEphemeral = (installFlags & PackageManager.INSTALL_INSTANT_APP) != 0;
16240                final File tempDir =
16241                        mInstallerService.allocateStageDirLegacy(volumeUuid, isEphemeral);
16242                codeFile = tempDir;
16243                resourceFile = tempDir;
16244            } catch (IOException e) {
16245                Slog.w(TAG, "Failed to create copy file: " + e);
16246                return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
16247            }
16248
16249            final IParcelFileDescriptorFactory target = new IParcelFileDescriptorFactory.Stub() {
16250                @Override
16251                public ParcelFileDescriptor open(String name, int mode) throws RemoteException {
16252                    if (!FileUtils.isValidExtFilename(name)) {
16253                        throw new IllegalArgumentException("Invalid filename: " + name);
16254                    }
16255                    try {
16256                        final File file = new File(codeFile, name);
16257                        final FileDescriptor fd = Os.open(file.getAbsolutePath(),
16258                                O_RDWR | O_CREAT, 0644);
16259                        Os.chmod(file.getAbsolutePath(), 0644);
16260                        return new ParcelFileDescriptor(fd);
16261                    } catch (ErrnoException e) {
16262                        throw new RemoteException("Failed to open: " + e.getMessage());
16263                    }
16264                }
16265            };
16266
16267            int ret = PackageManager.INSTALL_SUCCEEDED;
16268            ret = imcs.copyPackage(origin.file.getAbsolutePath(), target);
16269            if (ret != PackageManager.INSTALL_SUCCEEDED) {
16270                Slog.e(TAG, "Failed to copy package");
16271                return ret;
16272            }
16273
16274            final File libraryRoot = new File(codeFile, LIB_DIR_NAME);
16275            NativeLibraryHelper.Handle handle = null;
16276            try {
16277                handle = NativeLibraryHelper.Handle.create(codeFile);
16278                ret = NativeLibraryHelper.copyNativeBinariesWithOverride(handle, libraryRoot,
16279                        abiOverride);
16280            } catch (IOException e) {
16281                Slog.e(TAG, "Copying native libraries failed", e);
16282                ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
16283            } finally {
16284                IoUtils.closeQuietly(handle);
16285            }
16286
16287            return ret;
16288        }
16289
16290        int doPreInstall(int status) {
16291            if (status != PackageManager.INSTALL_SUCCEEDED) {
16292                cleanUp();
16293            }
16294            return status;
16295        }
16296
16297        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
16298            if (status != PackageManager.INSTALL_SUCCEEDED) {
16299                cleanUp();
16300                return false;
16301            }
16302
16303            final File targetDir = codeFile.getParentFile();
16304            final File beforeCodeFile = codeFile;
16305            final File afterCodeFile = getNextCodePath(targetDir, pkg.packageName);
16306
16307            if (DEBUG_INSTALL) Slog.d(TAG, "Renaming " + beforeCodeFile + " to " + afterCodeFile);
16308            try {
16309                Os.rename(beforeCodeFile.getAbsolutePath(), afterCodeFile.getAbsolutePath());
16310            } catch (ErrnoException e) {
16311                Slog.w(TAG, "Failed to rename", e);
16312                return false;
16313            }
16314
16315            if (!SELinux.restoreconRecursive(afterCodeFile)) {
16316                Slog.w(TAG, "Failed to restorecon");
16317                return false;
16318            }
16319
16320            // Reflect the rename internally
16321            codeFile = afterCodeFile;
16322            resourceFile = afterCodeFile;
16323
16324            // Reflect the rename in scanned details
16325            pkg.setCodePath(afterCodeFile.getAbsolutePath());
16326            pkg.setBaseCodePath(FileUtils.rewriteAfterRename(beforeCodeFile,
16327                    afterCodeFile, pkg.baseCodePath));
16328            pkg.setSplitCodePaths(FileUtils.rewriteAfterRename(beforeCodeFile,
16329                    afterCodeFile, pkg.splitCodePaths));
16330
16331            // Reflect the rename in app info
16332            pkg.setApplicationVolumeUuid(pkg.volumeUuid);
16333            pkg.setApplicationInfoCodePath(pkg.codePath);
16334            pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
16335            pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
16336            pkg.setApplicationInfoResourcePath(pkg.codePath);
16337            pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath);
16338            pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
16339
16340            return true;
16341        }
16342
16343        int doPostInstall(int status, int uid) {
16344            if (status != PackageManager.INSTALL_SUCCEEDED) {
16345                cleanUp();
16346            }
16347            return status;
16348        }
16349
16350        @Override
16351        String getCodePath() {
16352            return (codeFile != null) ? codeFile.getAbsolutePath() : null;
16353        }
16354
16355        @Override
16356        String getResourcePath() {
16357            return (resourceFile != null) ? resourceFile.getAbsolutePath() : null;
16358        }
16359
16360        private boolean cleanUp() {
16361            if (codeFile == null || !codeFile.exists()) {
16362                return false;
16363            }
16364
16365            removeCodePathLI(codeFile);
16366
16367            if (resourceFile != null && !FileUtils.contains(codeFile, resourceFile)) {
16368                resourceFile.delete();
16369            }
16370
16371            return true;
16372        }
16373
16374        void cleanUpResourcesLI() {
16375            // Try enumerating all code paths before deleting
16376            List<String> allCodePaths = Collections.EMPTY_LIST;
16377            if (codeFile != null && codeFile.exists()) {
16378                try {
16379                    final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0);
16380                    allCodePaths = pkg.getAllCodePaths();
16381                } catch (PackageParserException e) {
16382                    // Ignored; we tried our best
16383                }
16384            }
16385
16386            cleanUp();
16387            removeDexFiles(allCodePaths, instructionSets);
16388        }
16389
16390        boolean doPostDeleteLI(boolean delete) {
16391            // XXX err, shouldn't we respect the delete flag?
16392            cleanUpResourcesLI();
16393            return true;
16394        }
16395    }
16396
16397    private boolean isAsecExternal(String cid) {
16398        final String asecPath = PackageHelper.getSdFilesystem(cid);
16399        return !asecPath.startsWith(mAsecInternalPath);
16400    }
16401
16402    private static void maybeThrowExceptionForMultiArchCopy(String message, int copyRet) throws
16403            PackageManagerException {
16404        if (copyRet < 0) {
16405            if (copyRet != PackageManager.NO_NATIVE_LIBRARIES &&
16406                    copyRet != PackageManager.INSTALL_FAILED_NO_MATCHING_ABIS) {
16407                throw new PackageManagerException(copyRet, message);
16408            }
16409        }
16410    }
16411
16412    /**
16413     * Extract the StorageManagerService "container ID" from the full code path of an
16414     * .apk.
16415     */
16416    static String cidFromCodePath(String fullCodePath) {
16417        int eidx = fullCodePath.lastIndexOf("/");
16418        String subStr1 = fullCodePath.substring(0, eidx);
16419        int sidx = subStr1.lastIndexOf("/");
16420        return subStr1.substring(sidx+1, eidx);
16421    }
16422
16423    /**
16424     * Logic to handle installation of ASEC applications, including copying and
16425     * renaming logic.
16426     */
16427    class AsecInstallArgs extends InstallArgs {
16428        static final String RES_FILE_NAME = "pkg.apk";
16429        static final String PUBLIC_RES_FILE_NAME = "res.zip";
16430
16431        String cid;
16432        String packagePath;
16433        String resourcePath;
16434
16435        /** New install */
16436        AsecInstallArgs(InstallParams params) {
16437            super(params.origin, params.move, params.observer, params.installFlags,
16438                    params.installerPackageName, params.volumeUuid,
16439                    params.getUser(), null /* instruction sets */, params.packageAbiOverride,
16440                    params.grantedRuntimePermissions,
16441                    params.traceMethod, params.traceCookie, params.certificates,
16442                    params.installReason);
16443        }
16444
16445        /** Existing install */
16446        AsecInstallArgs(String fullCodePath, String[] instructionSets,
16447                        boolean isExternal, boolean isForwardLocked) {
16448            super(OriginInfo.fromNothing(), null, null, (isExternal ? INSTALL_EXTERNAL : 0)
16449                    | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null,
16450                    instructionSets, null, null, null, 0, null /*certificates*/,
16451                    PackageManager.INSTALL_REASON_UNKNOWN);
16452            // Hackily pretend we're still looking at a full code path
16453            if (!fullCodePath.endsWith(RES_FILE_NAME)) {
16454                fullCodePath = new File(fullCodePath, RES_FILE_NAME).getAbsolutePath();
16455            }
16456
16457            // Extract cid from fullCodePath
16458            int eidx = fullCodePath.lastIndexOf("/");
16459            String subStr1 = fullCodePath.substring(0, eidx);
16460            int sidx = subStr1.lastIndexOf("/");
16461            cid = subStr1.substring(sidx+1, eidx);
16462            setMountPath(subStr1);
16463        }
16464
16465        AsecInstallArgs(String cid, String[] instructionSets, boolean isForwardLocked) {
16466            super(OriginInfo.fromNothing(), null, null, (isAsecExternal(cid) ? INSTALL_EXTERNAL : 0)
16467                    | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null,
16468                    instructionSets, null, null, null, 0, null /*certificates*/,
16469                    PackageManager.INSTALL_REASON_UNKNOWN);
16470            this.cid = cid;
16471            setMountPath(PackageHelper.getSdDir(cid));
16472        }
16473
16474        void createCopyFile() {
16475            cid = mInstallerService.allocateExternalStageCidLegacy();
16476        }
16477
16478        int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
16479            if (origin.staged && origin.cid != null) {
16480                if (DEBUG_INSTALL) Slog.d(TAG, origin.cid + " already staged; skipping copy");
16481                cid = origin.cid;
16482                setMountPath(PackageHelper.getSdDir(cid));
16483                return PackageManager.INSTALL_SUCCEEDED;
16484            }
16485
16486            if (temp) {
16487                createCopyFile();
16488            } else {
16489                /*
16490                 * Pre-emptively destroy the container since it's destroyed if
16491                 * copying fails due to it existing anyway.
16492                 */
16493                PackageHelper.destroySdDir(cid);
16494            }
16495
16496            final String newMountPath = imcs.copyPackageToContainer(
16497                    origin.file.getAbsolutePath(), cid, getEncryptKey(), isExternalAsec(),
16498                    isFwdLocked(), deriveAbiOverride(abiOverride, null /* settings */));
16499
16500            if (newMountPath != null) {
16501                setMountPath(newMountPath);
16502                return PackageManager.INSTALL_SUCCEEDED;
16503            } else {
16504                return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
16505            }
16506        }
16507
16508        @Override
16509        String getCodePath() {
16510            return packagePath;
16511        }
16512
16513        @Override
16514        String getResourcePath() {
16515            return resourcePath;
16516        }
16517
16518        int doPreInstall(int status) {
16519            if (status != PackageManager.INSTALL_SUCCEEDED) {
16520                // Destroy container
16521                PackageHelper.destroySdDir(cid);
16522            } else {
16523                boolean mounted = PackageHelper.isContainerMounted(cid);
16524                if (!mounted) {
16525                    String newMountPath = PackageHelper.mountSdDir(cid, getEncryptKey(),
16526                            Process.SYSTEM_UID);
16527                    if (newMountPath != null) {
16528                        setMountPath(newMountPath);
16529                    } else {
16530                        return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
16531                    }
16532                }
16533            }
16534            return status;
16535        }
16536
16537        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
16538            String newCacheId = getNextCodePath(oldCodePath, pkg.packageName, "/" + RES_FILE_NAME);
16539            String newMountPath = null;
16540            if (PackageHelper.isContainerMounted(cid)) {
16541                // Unmount the container
16542                if (!PackageHelper.unMountSdDir(cid)) {
16543                    Slog.i(TAG, "Failed to unmount " + cid + " before renaming");
16544                    return false;
16545                }
16546            }
16547            if (!PackageHelper.renameSdDir(cid, newCacheId)) {
16548                Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId +
16549                        " which might be stale. Will try to clean up.");
16550                // Clean up the stale container and proceed to recreate.
16551                if (!PackageHelper.destroySdDir(newCacheId)) {
16552                    Slog.e(TAG, "Very strange. Cannot clean up stale container " + newCacheId);
16553                    return false;
16554                }
16555                // Successfully cleaned up stale container. Try to rename again.
16556                if (!PackageHelper.renameSdDir(cid, newCacheId)) {
16557                    Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId
16558                            + " inspite of cleaning it up.");
16559                    return false;
16560                }
16561            }
16562            if (!PackageHelper.isContainerMounted(newCacheId)) {
16563                Slog.w(TAG, "Mounting container " + newCacheId);
16564                newMountPath = PackageHelper.mountSdDir(newCacheId,
16565                        getEncryptKey(), Process.SYSTEM_UID);
16566            } else {
16567                newMountPath = PackageHelper.getSdDir(newCacheId);
16568            }
16569            if (newMountPath == null) {
16570                Slog.w(TAG, "Failed to get cache path for  " + newCacheId);
16571                return false;
16572            }
16573            Log.i(TAG, "Succesfully renamed " + cid +
16574                    " to " + newCacheId +
16575                    " at new path: " + newMountPath);
16576            cid = newCacheId;
16577
16578            final File beforeCodeFile = new File(packagePath);
16579            setMountPath(newMountPath);
16580            final File afterCodeFile = new File(packagePath);
16581
16582            // Reflect the rename in scanned details
16583            pkg.setCodePath(afterCodeFile.getAbsolutePath());
16584            pkg.setBaseCodePath(FileUtils.rewriteAfterRename(beforeCodeFile,
16585                    afterCodeFile, pkg.baseCodePath));
16586            pkg.setSplitCodePaths(FileUtils.rewriteAfterRename(beforeCodeFile,
16587                    afterCodeFile, pkg.splitCodePaths));
16588
16589            // Reflect the rename in app info
16590            pkg.setApplicationVolumeUuid(pkg.volumeUuid);
16591            pkg.setApplicationInfoCodePath(pkg.codePath);
16592            pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
16593            pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
16594            pkg.setApplicationInfoResourcePath(pkg.codePath);
16595            pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath);
16596            pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
16597
16598            return true;
16599        }
16600
16601        private void setMountPath(String mountPath) {
16602            final File mountFile = new File(mountPath);
16603
16604            final File monolithicFile = new File(mountFile, RES_FILE_NAME);
16605            if (monolithicFile.exists()) {
16606                packagePath = monolithicFile.getAbsolutePath();
16607                if (isFwdLocked()) {
16608                    resourcePath = new File(mountFile, PUBLIC_RES_FILE_NAME).getAbsolutePath();
16609                } else {
16610                    resourcePath = packagePath;
16611                }
16612            } else {
16613                packagePath = mountFile.getAbsolutePath();
16614                resourcePath = packagePath;
16615            }
16616        }
16617
16618        int doPostInstall(int status, int uid) {
16619            if (status != PackageManager.INSTALL_SUCCEEDED) {
16620                cleanUp();
16621            } else {
16622                final int groupOwner;
16623                final String protectedFile;
16624                if (isFwdLocked()) {
16625                    groupOwner = UserHandle.getSharedAppGid(uid);
16626                    protectedFile = RES_FILE_NAME;
16627                } else {
16628                    groupOwner = -1;
16629                    protectedFile = null;
16630                }
16631
16632                if (uid < Process.FIRST_APPLICATION_UID
16633                        || !PackageHelper.fixSdPermissions(cid, groupOwner, protectedFile)) {
16634                    Slog.e(TAG, "Failed to finalize " + cid);
16635                    PackageHelper.destroySdDir(cid);
16636                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
16637                }
16638
16639                boolean mounted = PackageHelper.isContainerMounted(cid);
16640                if (!mounted) {
16641                    PackageHelper.mountSdDir(cid, getEncryptKey(), Process.myUid());
16642                }
16643            }
16644            return status;
16645        }
16646
16647        private void cleanUp() {
16648            if (DEBUG_SD_INSTALL) Slog.i(TAG, "cleanUp");
16649
16650            // Destroy secure container
16651            PackageHelper.destroySdDir(cid);
16652        }
16653
16654        private List<String> getAllCodePaths() {
16655            final File codeFile = new File(getCodePath());
16656            if (codeFile != null && codeFile.exists()) {
16657                try {
16658                    final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0);
16659                    return pkg.getAllCodePaths();
16660                } catch (PackageParserException e) {
16661                    // Ignored; we tried our best
16662                }
16663            }
16664            return Collections.EMPTY_LIST;
16665        }
16666
16667        void cleanUpResourcesLI() {
16668            // Enumerate all code paths before deleting
16669            cleanUpResourcesLI(getAllCodePaths());
16670        }
16671
16672        private void cleanUpResourcesLI(List<String> allCodePaths) {
16673            cleanUp();
16674            removeDexFiles(allCodePaths, instructionSets);
16675        }
16676
16677        String getPackageName() {
16678            return getAsecPackageName(cid);
16679        }
16680
16681        boolean doPostDeleteLI(boolean delete) {
16682            if (DEBUG_SD_INSTALL) Slog.i(TAG, "doPostDeleteLI() del=" + delete);
16683            final List<String> allCodePaths = getAllCodePaths();
16684            boolean mounted = PackageHelper.isContainerMounted(cid);
16685            if (mounted) {
16686                // Unmount first
16687                if (PackageHelper.unMountSdDir(cid)) {
16688                    mounted = false;
16689                }
16690            }
16691            if (!mounted && delete) {
16692                cleanUpResourcesLI(allCodePaths);
16693            }
16694            return !mounted;
16695        }
16696
16697        @Override
16698        int doPreCopy() {
16699            if (isFwdLocked()) {
16700                if (!PackageHelper.fixSdPermissions(cid, getPackageUid(DEFAULT_CONTAINER_PACKAGE,
16701                        MATCH_SYSTEM_ONLY, UserHandle.USER_SYSTEM), RES_FILE_NAME)) {
16702                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
16703                }
16704            }
16705
16706            return PackageManager.INSTALL_SUCCEEDED;
16707        }
16708
16709        @Override
16710        int doPostCopy(int uid) {
16711            if (isFwdLocked()) {
16712                if (uid < Process.FIRST_APPLICATION_UID
16713                        || !PackageHelper.fixSdPermissions(cid, UserHandle.getSharedAppGid(uid),
16714                                RES_FILE_NAME)) {
16715                    Slog.e(TAG, "Failed to finalize " + cid);
16716                    PackageHelper.destroySdDir(cid);
16717                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
16718                }
16719            }
16720
16721            return PackageManager.INSTALL_SUCCEEDED;
16722        }
16723    }
16724
16725    /**
16726     * Logic to handle movement of existing installed applications.
16727     */
16728    class MoveInstallArgs extends InstallArgs {
16729        private File codeFile;
16730        private File resourceFile;
16731
16732        /** New install */
16733        MoveInstallArgs(InstallParams params) {
16734            super(params.origin, params.move, params.observer, params.installFlags,
16735                    params.installerPackageName, params.volumeUuid,
16736                    params.getUser(), null /* instruction sets */, params.packageAbiOverride,
16737                    params.grantedRuntimePermissions,
16738                    params.traceMethod, params.traceCookie, params.certificates,
16739                    params.installReason);
16740        }
16741
16742        int copyApk(IMediaContainerService imcs, boolean temp) {
16743            if (DEBUG_INSTALL) Slog.d(TAG, "Moving " + move.packageName + " from "
16744                    + move.fromUuid + " to " + move.toUuid);
16745            synchronized (mInstaller) {
16746                try {
16747                    mInstaller.moveCompleteApp(move.fromUuid, move.toUuid, move.packageName,
16748                            move.dataAppName, move.appId, move.seinfo, move.targetSdkVersion);
16749                } catch (InstallerException e) {
16750                    Slog.w(TAG, "Failed to move app", e);
16751                    return PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
16752                }
16753            }
16754
16755            codeFile = new File(Environment.getDataAppDirectory(move.toUuid), move.dataAppName);
16756            resourceFile = codeFile;
16757            if (DEBUG_INSTALL) Slog.d(TAG, "codeFile after move is " + codeFile);
16758
16759            return PackageManager.INSTALL_SUCCEEDED;
16760        }
16761
16762        int doPreInstall(int status) {
16763            if (status != PackageManager.INSTALL_SUCCEEDED) {
16764                cleanUp(move.toUuid);
16765            }
16766            return status;
16767        }
16768
16769        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
16770            if (status != PackageManager.INSTALL_SUCCEEDED) {
16771                cleanUp(move.toUuid);
16772                return false;
16773            }
16774
16775            // Reflect the move in app info
16776            pkg.setApplicationVolumeUuid(pkg.volumeUuid);
16777            pkg.setApplicationInfoCodePath(pkg.codePath);
16778            pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
16779            pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
16780            pkg.setApplicationInfoResourcePath(pkg.codePath);
16781            pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath);
16782            pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
16783
16784            return true;
16785        }
16786
16787        int doPostInstall(int status, int uid) {
16788            if (status == PackageManager.INSTALL_SUCCEEDED) {
16789                cleanUp(move.fromUuid);
16790            } else {
16791                cleanUp(move.toUuid);
16792            }
16793            return status;
16794        }
16795
16796        @Override
16797        String getCodePath() {
16798            return (codeFile != null) ? codeFile.getAbsolutePath() : null;
16799        }
16800
16801        @Override
16802        String getResourcePath() {
16803            return (resourceFile != null) ? resourceFile.getAbsolutePath() : null;
16804        }
16805
16806        private boolean cleanUp(String volumeUuid) {
16807            final File codeFile = new File(Environment.getDataAppDirectory(volumeUuid),
16808                    move.dataAppName);
16809            Slog.d(TAG, "Cleaning up " + move.packageName + " on " + volumeUuid);
16810            final int[] userIds = sUserManager.getUserIds();
16811            synchronized (mInstallLock) {
16812                // Clean up both app data and code
16813                // All package moves are frozen until finished
16814                for (int userId : userIds) {
16815                    try {
16816                        mInstaller.destroyAppData(volumeUuid, move.packageName, userId,
16817                                StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE, 0);
16818                    } catch (InstallerException e) {
16819                        Slog.w(TAG, String.valueOf(e));
16820                    }
16821                }
16822                removeCodePathLI(codeFile);
16823            }
16824            return true;
16825        }
16826
16827        void cleanUpResourcesLI() {
16828            throw new UnsupportedOperationException();
16829        }
16830
16831        boolean doPostDeleteLI(boolean delete) {
16832            throw new UnsupportedOperationException();
16833        }
16834    }
16835
16836    static String getAsecPackageName(String packageCid) {
16837        int idx = packageCid.lastIndexOf("-");
16838        if (idx == -1) {
16839            return packageCid;
16840        }
16841        return packageCid.substring(0, idx);
16842    }
16843
16844    // Utility method used to create code paths based on package name and available index.
16845    private static String getNextCodePath(String oldCodePath, String prefix, String suffix) {
16846        String idxStr = "";
16847        int idx = 1;
16848        // Fall back to default value of idx=1 if prefix is not
16849        // part of oldCodePath
16850        if (oldCodePath != null) {
16851            String subStr = oldCodePath;
16852            // Drop the suffix right away
16853            if (suffix != null && subStr.endsWith(suffix)) {
16854                subStr = subStr.substring(0, subStr.length() - suffix.length());
16855            }
16856            // If oldCodePath already contains prefix find out the
16857            // ending index to either increment or decrement.
16858            int sidx = subStr.lastIndexOf(prefix);
16859            if (sidx != -1) {
16860                subStr = subStr.substring(sidx + prefix.length());
16861                if (subStr != null) {
16862                    if (subStr.startsWith(INSTALL_PACKAGE_SUFFIX)) {
16863                        subStr = subStr.substring(INSTALL_PACKAGE_SUFFIX.length());
16864                    }
16865                    try {
16866                        idx = Integer.parseInt(subStr);
16867                        if (idx <= 1) {
16868                            idx++;
16869                        } else {
16870                            idx--;
16871                        }
16872                    } catch(NumberFormatException e) {
16873                    }
16874                }
16875            }
16876        }
16877        idxStr = INSTALL_PACKAGE_SUFFIX + Integer.toString(idx);
16878        return prefix + idxStr;
16879    }
16880
16881    private File getNextCodePath(File targetDir, String packageName) {
16882        File result;
16883        SecureRandom random = new SecureRandom();
16884        byte[] bytes = new byte[16];
16885        do {
16886            random.nextBytes(bytes);
16887            String suffix = Base64.encodeToString(bytes, Base64.URL_SAFE | Base64.NO_WRAP);
16888            result = new File(targetDir, packageName + "-" + suffix);
16889        } while (result.exists());
16890        return result;
16891    }
16892
16893    // Utility method that returns the relative package path with respect
16894    // to the installation directory. Like say for /data/data/com.test-1.apk
16895    // string com.test-1 is returned.
16896    static String deriveCodePathName(String codePath) {
16897        if (codePath == null) {
16898            return null;
16899        }
16900        final File codeFile = new File(codePath);
16901        final String name = codeFile.getName();
16902        if (codeFile.isDirectory()) {
16903            return name;
16904        } else if (name.endsWith(".apk") || name.endsWith(".tmp")) {
16905            final int lastDot = name.lastIndexOf('.');
16906            return name.substring(0, lastDot);
16907        } else {
16908            Slog.w(TAG, "Odd, " + codePath + " doesn't look like an APK");
16909            return null;
16910        }
16911    }
16912
16913    static class PackageInstalledInfo {
16914        String name;
16915        int uid;
16916        // The set of users that originally had this package installed.
16917        int[] origUsers;
16918        // The set of users that now have this package installed.
16919        int[] newUsers;
16920        PackageParser.Package pkg;
16921        int returnCode;
16922        String returnMsg;
16923        PackageRemovedInfo removedInfo;
16924        ArrayMap<String, PackageInstalledInfo> addedChildPackages;
16925
16926        public void setError(int code, String msg) {
16927            setReturnCode(code);
16928            setReturnMessage(msg);
16929            Slog.w(TAG, msg);
16930        }
16931
16932        public void setError(String msg, PackageParserException e) {
16933            setReturnCode(e.error);
16934            setReturnMessage(ExceptionUtils.getCompleteMessage(msg, e));
16935            Slog.w(TAG, msg, e);
16936        }
16937
16938        public void setError(String msg, PackageManagerException e) {
16939            returnCode = e.error;
16940            setReturnMessage(ExceptionUtils.getCompleteMessage(msg, e));
16941            Slog.w(TAG, msg, e);
16942        }
16943
16944        public void setReturnCode(int returnCode) {
16945            this.returnCode = returnCode;
16946            final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0;
16947            for (int i = 0; i < childCount; i++) {
16948                addedChildPackages.valueAt(i).returnCode = returnCode;
16949            }
16950        }
16951
16952        private void setReturnMessage(String returnMsg) {
16953            this.returnMsg = returnMsg;
16954            final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0;
16955            for (int i = 0; i < childCount; i++) {
16956                addedChildPackages.valueAt(i).returnMsg = returnMsg;
16957            }
16958        }
16959
16960        // In some error cases we want to convey more info back to the observer
16961        String origPackage;
16962        String origPermission;
16963    }
16964
16965    /*
16966     * Install a non-existing package.
16967     */
16968    private void installNewPackageLIF(PackageParser.Package pkg, final int policyFlags,
16969            int scanFlags, UserHandle user, String installerPackageName, String volumeUuid,
16970            PackageInstalledInfo res, int installReason) {
16971        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installNewPackage");
16972
16973        // Remember this for later, in case we need to rollback this install
16974        String pkgName = pkg.packageName;
16975
16976        if (DEBUG_INSTALL) Slog.d(TAG, "installNewPackageLI: " + pkg);
16977
16978        synchronized(mPackages) {
16979            final String renamedPackage = mSettings.getRenamedPackageLPr(pkgName);
16980            if (renamedPackage != null) {
16981                // A package with the same name is already installed, though
16982                // it has been renamed to an older name.  The package we
16983                // are trying to install should be installed as an update to
16984                // the existing one, but that has not been requested, so bail.
16985                res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName
16986                        + " without first uninstalling package running as "
16987                        + renamedPackage);
16988                return;
16989            }
16990            if (mPackages.containsKey(pkgName)) {
16991                // Don't allow installation over an existing package with the same name.
16992                res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName
16993                        + " without first uninstalling.");
16994                return;
16995            }
16996        }
16997
16998        try {
16999            PackageParser.Package newPackage = scanPackageTracedLI(pkg, policyFlags, scanFlags,
17000                    System.currentTimeMillis(), user);
17001
17002            updateSettingsLI(newPackage, installerPackageName, null, res, user, installReason);
17003
17004            if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
17005                prepareAppDataAfterInstallLIF(newPackage);
17006
17007            } else {
17008                // Remove package from internal structures, but keep around any
17009                // data that might have already existed
17010                deletePackageLIF(pkgName, UserHandle.ALL, false, null,
17011                        PackageManager.DELETE_KEEP_DATA, res.removedInfo, true, null);
17012            }
17013        } catch (PackageManagerException e) {
17014            res.setError("Package couldn't be installed in " + pkg.codePath, e);
17015        }
17016
17017        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
17018    }
17019
17020    private boolean shouldCheckUpgradeKeySetLP(PackageSetting oldPs, int scanFlags) {
17021        // Can't rotate keys during boot or if sharedUser.
17022        if (oldPs == null || (scanFlags&SCAN_INITIAL) != 0 || oldPs.sharedUser != null
17023                || !oldPs.keySetData.isUsingUpgradeKeySets()) {
17024            return false;
17025        }
17026        // app is using upgradeKeySets; make sure all are valid
17027        KeySetManagerService ksms = mSettings.mKeySetManagerService;
17028        long[] upgradeKeySets = oldPs.keySetData.getUpgradeKeySets();
17029        for (int i = 0; i < upgradeKeySets.length; i++) {
17030            if (!ksms.isIdValidKeySetId(upgradeKeySets[i])) {
17031                Slog.wtf(TAG, "Package "
17032                         + (oldPs.name != null ? oldPs.name : "<null>")
17033                         + " contains upgrade-key-set reference to unknown key-set: "
17034                         + upgradeKeySets[i]
17035                         + " reverting to signatures check.");
17036                return false;
17037            }
17038        }
17039        return true;
17040    }
17041
17042    private boolean checkUpgradeKeySetLP(PackageSetting oldPS, PackageParser.Package newPkg) {
17043        // Upgrade keysets are being used.  Determine if new package has a superset of the
17044        // required keys.
17045        long[] upgradeKeySets = oldPS.keySetData.getUpgradeKeySets();
17046        KeySetManagerService ksms = mSettings.mKeySetManagerService;
17047        for (int i = 0; i < upgradeKeySets.length; i++) {
17048            Set<PublicKey> upgradeSet = ksms.getPublicKeysFromKeySetLPr(upgradeKeySets[i]);
17049            if (upgradeSet != null && newPkg.mSigningKeys.containsAll(upgradeSet)) {
17050                return true;
17051            }
17052        }
17053        return false;
17054    }
17055
17056    private static void updateDigest(MessageDigest digest, File file) throws IOException {
17057        try (DigestInputStream digestStream =
17058                new DigestInputStream(new FileInputStream(file), digest)) {
17059            while (digestStream.read() != -1) {} // nothing to do; just plow through the file
17060        }
17061    }
17062
17063    private void replacePackageLIF(PackageParser.Package pkg, final int policyFlags, int scanFlags,
17064            UserHandle user, String installerPackageName, PackageInstalledInfo res,
17065            int installReason) {
17066        final boolean isInstantApp = (scanFlags & SCAN_AS_INSTANT_APP) != 0;
17067
17068        final PackageParser.Package oldPackage;
17069        final PackageSetting ps;
17070        final String pkgName = pkg.packageName;
17071        final int[] allUsers;
17072        final int[] installedUsers;
17073
17074        synchronized(mPackages) {
17075            oldPackage = mPackages.get(pkgName);
17076            if (DEBUG_INSTALL) Slog.d(TAG, "replacePackageLI: new=" + pkg + ", old=" + oldPackage);
17077
17078            // don't allow upgrade to target a release SDK from a pre-release SDK
17079            final boolean oldTargetsPreRelease = oldPackage.applicationInfo.targetSdkVersion
17080                    == android.os.Build.VERSION_CODES.CUR_DEVELOPMENT;
17081            final boolean newTargetsPreRelease = pkg.applicationInfo.targetSdkVersion
17082                    == android.os.Build.VERSION_CODES.CUR_DEVELOPMENT;
17083            if (oldTargetsPreRelease
17084                    && !newTargetsPreRelease
17085                    && ((policyFlags & PackageParser.PARSE_FORCE_SDK) == 0)) {
17086                Slog.w(TAG, "Can't install package targeting released sdk");
17087                res.setReturnCode(PackageManager.INSTALL_FAILED_UPDATE_INCOMPATIBLE);
17088                return;
17089            }
17090
17091            ps = mSettings.mPackages.get(pkgName);
17092
17093            // verify signatures are valid
17094            if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) {
17095                if (!checkUpgradeKeySetLP(ps, pkg)) {
17096                    res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
17097                            "New package not signed by keys specified by upgrade-keysets: "
17098                                    + pkgName);
17099                    return;
17100                }
17101            } else {
17102                // default to original signature matching
17103                if (compareSignatures(oldPackage.mSignatures, pkg.mSignatures)
17104                        != PackageManager.SIGNATURE_MATCH) {
17105                    res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
17106                            "New package has a different signature: " + pkgName);
17107                    return;
17108                }
17109            }
17110
17111            // don't allow a system upgrade unless the upgrade hash matches
17112            if (oldPackage.restrictUpdateHash != null && oldPackage.isSystemApp()) {
17113                byte[] digestBytes = null;
17114                try {
17115                    final MessageDigest digest = MessageDigest.getInstance("SHA-512");
17116                    updateDigest(digest, new File(pkg.baseCodePath));
17117                    if (!ArrayUtils.isEmpty(pkg.splitCodePaths)) {
17118                        for (String path : pkg.splitCodePaths) {
17119                            updateDigest(digest, new File(path));
17120                        }
17121                    }
17122                    digestBytes = digest.digest();
17123                } catch (NoSuchAlgorithmException | IOException e) {
17124                    res.setError(INSTALL_FAILED_INVALID_APK,
17125                            "Could not compute hash: " + pkgName);
17126                    return;
17127                }
17128                if (!Arrays.equals(oldPackage.restrictUpdateHash, digestBytes)) {
17129                    res.setError(INSTALL_FAILED_INVALID_APK,
17130                            "New package fails restrict-update check: " + pkgName);
17131                    return;
17132                }
17133                // retain upgrade restriction
17134                pkg.restrictUpdateHash = oldPackage.restrictUpdateHash;
17135            }
17136
17137            // Check for shared user id changes
17138            String invalidPackageName =
17139                    getParentOrChildPackageChangedSharedUser(oldPackage, pkg);
17140            if (invalidPackageName != null) {
17141                res.setError(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE,
17142                        "Package " + invalidPackageName + " tried to change user "
17143                                + oldPackage.mSharedUserId);
17144                return;
17145            }
17146
17147            // In case of rollback, remember per-user/profile install state
17148            allUsers = sUserManager.getUserIds();
17149            installedUsers = ps.queryInstalledUsers(allUsers, true);
17150
17151            // don't allow an upgrade from full to ephemeral
17152            if (isInstantApp) {
17153                if (user == null || user.getIdentifier() == UserHandle.USER_ALL) {
17154                    for (int currentUser : allUsers) {
17155                        if (!ps.getInstantApp(currentUser)) {
17156                            // can't downgrade from full to instant
17157                            Slog.w(TAG, "Can't replace full app with instant app: " + pkgName
17158                                    + " for user: " + currentUser);
17159                            res.setReturnCode(PackageManager.INSTALL_FAILED_INSTANT_APP_INVALID);
17160                            return;
17161                        }
17162                    }
17163                } else if (!ps.getInstantApp(user.getIdentifier())) {
17164                    // can't downgrade from full to instant
17165                    Slog.w(TAG, "Can't replace full app with instant app: " + pkgName
17166                            + " for user: " + user.getIdentifier());
17167                    res.setReturnCode(PackageManager.INSTALL_FAILED_INSTANT_APP_INVALID);
17168                    return;
17169                }
17170            }
17171        }
17172
17173        // Update what is removed
17174        res.removedInfo = new PackageRemovedInfo(this);
17175        res.removedInfo.uid = oldPackage.applicationInfo.uid;
17176        res.removedInfo.removedPackage = oldPackage.packageName;
17177        res.removedInfo.installerPackageName = ps.installerPackageName;
17178        res.removedInfo.isStaticSharedLib = pkg.staticSharedLibName != null;
17179        res.removedInfo.isUpdate = true;
17180        res.removedInfo.origUsers = installedUsers;
17181        res.removedInfo.installReasons = new SparseArray<>(installedUsers.length);
17182        for (int i = 0; i < installedUsers.length; i++) {
17183            final int userId = installedUsers[i];
17184            res.removedInfo.installReasons.put(userId, ps.getInstallReason(userId));
17185        }
17186
17187        final int childCount = (oldPackage.childPackages != null)
17188                ? oldPackage.childPackages.size() : 0;
17189        for (int i = 0; i < childCount; i++) {
17190            boolean childPackageUpdated = false;
17191            PackageParser.Package childPkg = oldPackage.childPackages.get(i);
17192            final PackageSetting childPs = mSettings.getPackageLPr(childPkg.packageName);
17193            if (res.addedChildPackages != null) {
17194                PackageInstalledInfo childRes = res.addedChildPackages.get(childPkg.packageName);
17195                if (childRes != null) {
17196                    childRes.removedInfo.uid = childPkg.applicationInfo.uid;
17197                    childRes.removedInfo.removedPackage = childPkg.packageName;
17198                    if (childPs != null) {
17199                        childRes.removedInfo.installerPackageName = childPs.installerPackageName;
17200                    }
17201                    childRes.removedInfo.isUpdate = true;
17202                    childRes.removedInfo.installReasons = res.removedInfo.installReasons;
17203                    childPackageUpdated = true;
17204                }
17205            }
17206            if (!childPackageUpdated) {
17207                PackageRemovedInfo childRemovedRes = new PackageRemovedInfo(this);
17208                childRemovedRes.removedPackage = childPkg.packageName;
17209                if (childPs != null) {
17210                    childRemovedRes.installerPackageName = childPs.installerPackageName;
17211                }
17212                childRemovedRes.isUpdate = false;
17213                childRemovedRes.dataRemoved = true;
17214                synchronized (mPackages) {
17215                    if (childPs != null) {
17216                        childRemovedRes.origUsers = childPs.queryInstalledUsers(allUsers, true);
17217                    }
17218                }
17219                if (res.removedInfo.removedChildPackages == null) {
17220                    res.removedInfo.removedChildPackages = new ArrayMap<>();
17221                }
17222                res.removedInfo.removedChildPackages.put(childPkg.packageName, childRemovedRes);
17223            }
17224        }
17225
17226        boolean sysPkg = (isSystemApp(oldPackage));
17227        if (sysPkg) {
17228            // Set the system/privileged flags as needed
17229            final boolean privileged =
17230                    (oldPackage.applicationInfo.privateFlags
17231                            & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0;
17232            final int systemPolicyFlags = policyFlags
17233                    | PackageParser.PARSE_IS_SYSTEM
17234                    | (privileged ? PackageParser.PARSE_IS_PRIVILEGED : 0);
17235
17236            replaceSystemPackageLIF(oldPackage, pkg, systemPolicyFlags, scanFlags,
17237                    user, allUsers, installerPackageName, res, installReason);
17238        } else {
17239            replaceNonSystemPackageLIF(oldPackage, pkg, policyFlags, scanFlags,
17240                    user, allUsers, installerPackageName, res, installReason);
17241        }
17242    }
17243
17244    @Override
17245    public List<String> getPreviousCodePaths(String packageName) {
17246        final int callingUid = Binder.getCallingUid();
17247        final List<String> result = new ArrayList<>();
17248        if (getInstantAppPackageName(callingUid) != null) {
17249            return result;
17250        }
17251        final PackageSetting ps = mSettings.mPackages.get(packageName);
17252        if (ps != null
17253                && ps.oldCodePaths != null
17254                && !filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
17255            result.addAll(ps.oldCodePaths);
17256        }
17257        return result;
17258    }
17259
17260    private void replaceNonSystemPackageLIF(PackageParser.Package deletedPackage,
17261            PackageParser.Package pkg, final int policyFlags, int scanFlags, UserHandle user,
17262            int[] allUsers, String installerPackageName, PackageInstalledInfo res,
17263            int installReason) {
17264        if (DEBUG_INSTALL) Slog.d(TAG, "replaceNonSystemPackageLI: new=" + pkg + ", old="
17265                + deletedPackage);
17266
17267        String pkgName = deletedPackage.packageName;
17268        boolean deletedPkg = true;
17269        boolean addedPkg = false;
17270        boolean updatedSettings = false;
17271        final boolean killApp = (scanFlags & SCAN_DONT_KILL_APP) == 0;
17272        final int deleteFlags = PackageManager.DELETE_KEEP_DATA
17273                | (killApp ? 0 : PackageManager.DELETE_DONT_KILL_APP);
17274
17275        final long origUpdateTime = (pkg.mExtras != null)
17276                ? ((PackageSetting)pkg.mExtras).lastUpdateTime : 0;
17277
17278        // First delete the existing package while retaining the data directory
17279        if (!deletePackageLIF(pkgName, null, true, allUsers, deleteFlags,
17280                res.removedInfo, true, pkg)) {
17281            // If the existing package wasn't successfully deleted
17282            res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, "replaceNonSystemPackageLI");
17283            deletedPkg = false;
17284        } else {
17285            // Successfully deleted the old package; proceed with replace.
17286
17287            // If deleted package lived in a container, give users a chance to
17288            // relinquish resources before killing.
17289            if (deletedPackage.isForwardLocked() || isExternal(deletedPackage)) {
17290                if (DEBUG_INSTALL) {
17291                    Slog.i(TAG, "upgrading pkg " + deletedPackage + " is ASEC-hosted -> UNAVAILABLE");
17292                }
17293                final int[] uidArray = new int[] { deletedPackage.applicationInfo.uid };
17294                final ArrayList<String> pkgList = new ArrayList<String>(1);
17295                pkgList.add(deletedPackage.applicationInfo.packageName);
17296                sendResourcesChangedBroadcast(false, true, pkgList, uidArray, null);
17297            }
17298
17299            clearAppDataLIF(pkg, UserHandle.USER_ALL, StorageManager.FLAG_STORAGE_DE
17300                    | StorageManager.FLAG_STORAGE_CE | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
17301            clearAppProfilesLIF(deletedPackage, UserHandle.USER_ALL);
17302
17303            try {
17304                final PackageParser.Package newPackage = scanPackageTracedLI(pkg, policyFlags,
17305                        scanFlags | SCAN_UPDATE_TIME, System.currentTimeMillis(), user);
17306                updateSettingsLI(newPackage, installerPackageName, allUsers, res, user,
17307                        installReason);
17308
17309                // Update the in-memory copy of the previous code paths.
17310                PackageSetting ps = mSettings.mPackages.get(pkgName);
17311                if (!killApp) {
17312                    if (ps.oldCodePaths == null) {
17313                        ps.oldCodePaths = new ArraySet<>();
17314                    }
17315                    Collections.addAll(ps.oldCodePaths, deletedPackage.baseCodePath);
17316                    if (deletedPackage.splitCodePaths != null) {
17317                        Collections.addAll(ps.oldCodePaths, deletedPackage.splitCodePaths);
17318                    }
17319                } else {
17320                    ps.oldCodePaths = null;
17321                }
17322                if (ps.childPackageNames != null) {
17323                    for (int i = ps.childPackageNames.size() - 1; i >= 0; --i) {
17324                        final String childPkgName = ps.childPackageNames.get(i);
17325                        final PackageSetting childPs = mSettings.mPackages.get(childPkgName);
17326                        childPs.oldCodePaths = ps.oldCodePaths;
17327                    }
17328                }
17329                // set instant app status, but, only if it's explicitly specified
17330                final boolean instantApp = (scanFlags & SCAN_AS_INSTANT_APP) != 0;
17331                final boolean fullApp = (scanFlags & SCAN_AS_FULL_APP) != 0;
17332                setInstantAppForUser(ps, user.getIdentifier(), instantApp, fullApp);
17333                prepareAppDataAfterInstallLIF(newPackage);
17334                addedPkg = true;
17335                mDexManager.notifyPackageUpdated(newPackage.packageName,
17336                        newPackage.baseCodePath, newPackage.splitCodePaths);
17337            } catch (PackageManagerException e) {
17338                res.setError("Package couldn't be installed in " + pkg.codePath, e);
17339            }
17340        }
17341
17342        if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
17343            if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, rolling pack: " + pkgName);
17344
17345            // Revert all internal state mutations and added folders for the failed install
17346            if (addedPkg) {
17347                deletePackageLIF(pkgName, null, true, allUsers, deleteFlags,
17348                        res.removedInfo, true, null);
17349            }
17350
17351            // Restore the old package
17352            if (deletedPkg) {
17353                if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, reinstalling: " + deletedPackage);
17354                File restoreFile = new File(deletedPackage.codePath);
17355                // Parse old package
17356                boolean oldExternal = isExternal(deletedPackage);
17357                int oldParseFlags  = mDefParseFlags | PackageParser.PARSE_CHATTY |
17358                        (deletedPackage.isForwardLocked() ? PackageParser.PARSE_FORWARD_LOCK : 0) |
17359                        (oldExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0);
17360                int oldScanFlags = SCAN_UPDATE_SIGNATURE | SCAN_UPDATE_TIME;
17361                try {
17362                    scanPackageTracedLI(restoreFile, oldParseFlags, oldScanFlags, origUpdateTime,
17363                            null);
17364                } catch (PackageManagerException e) {
17365                    Slog.e(TAG, "Failed to restore package : " + pkgName + " after failed upgrade: "
17366                            + e.getMessage());
17367                    return;
17368                }
17369
17370                synchronized (mPackages) {
17371                    // Ensure the installer package name up to date
17372                    setInstallerPackageNameLPw(deletedPackage, installerPackageName);
17373
17374                    // Update permissions for restored package
17375                    updatePermissionsLPw(deletedPackage, UPDATE_PERMISSIONS_ALL);
17376
17377                    mSettings.writeLPr();
17378                }
17379
17380                Slog.i(TAG, "Successfully restored package : " + pkgName + " after failed upgrade");
17381            }
17382        } else {
17383            synchronized (mPackages) {
17384                PackageSetting ps = mSettings.getPackageLPr(pkg.packageName);
17385                if (ps != null) {
17386                    res.removedInfo.removedForAllUsers = mPackages.get(ps.name) == null;
17387                    if (res.removedInfo.removedChildPackages != null) {
17388                        final int childCount = res.removedInfo.removedChildPackages.size();
17389                        // Iterate in reverse as we may modify the collection
17390                        for (int i = childCount - 1; i >= 0; i--) {
17391                            String childPackageName = res.removedInfo.removedChildPackages.keyAt(i);
17392                            if (res.addedChildPackages.containsKey(childPackageName)) {
17393                                res.removedInfo.removedChildPackages.removeAt(i);
17394                            } else {
17395                                PackageRemovedInfo childInfo = res.removedInfo
17396                                        .removedChildPackages.valueAt(i);
17397                                childInfo.removedForAllUsers = mPackages.get(
17398                                        childInfo.removedPackage) == null;
17399                            }
17400                        }
17401                    }
17402                }
17403            }
17404        }
17405    }
17406
17407    private void replaceSystemPackageLIF(PackageParser.Package deletedPackage,
17408            PackageParser.Package pkg, final int policyFlags, int scanFlags, UserHandle user,
17409            int[] allUsers, String installerPackageName, PackageInstalledInfo res,
17410            int installReason) {
17411        if (DEBUG_INSTALL) Slog.d(TAG, "replaceSystemPackageLI: new=" + pkg
17412                + ", old=" + deletedPackage);
17413
17414        final boolean disabledSystem;
17415
17416        // Remove existing system package
17417        removePackageLI(deletedPackage, true);
17418
17419        synchronized (mPackages) {
17420            disabledSystem = disableSystemPackageLPw(deletedPackage, pkg);
17421        }
17422        if (!disabledSystem) {
17423            // We didn't need to disable the .apk as a current system package,
17424            // which means we are replacing another update that is already
17425            // installed.  We need to make sure to delete the older one's .apk.
17426            res.removedInfo.args = createInstallArgsForExisting(0,
17427                    deletedPackage.applicationInfo.getCodePath(),
17428                    deletedPackage.applicationInfo.getResourcePath(),
17429                    getAppDexInstructionSets(deletedPackage.applicationInfo));
17430        } else {
17431            res.removedInfo.args = null;
17432        }
17433
17434        // Successfully disabled the old package. Now proceed with re-installation
17435        clearAppDataLIF(pkg, UserHandle.USER_ALL, StorageManager.FLAG_STORAGE_DE
17436                | StorageManager.FLAG_STORAGE_CE | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
17437        clearAppProfilesLIF(deletedPackage, UserHandle.USER_ALL);
17438
17439        res.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
17440        pkg.setApplicationInfoFlags(ApplicationInfo.FLAG_UPDATED_SYSTEM_APP,
17441                ApplicationInfo.FLAG_UPDATED_SYSTEM_APP);
17442
17443        PackageParser.Package newPackage = null;
17444        try {
17445            // Add the package to the internal data structures
17446            newPackage = scanPackageTracedLI(pkg, policyFlags, scanFlags, 0, user);
17447
17448            // Set the update and install times
17449            PackageSetting deletedPkgSetting = (PackageSetting) deletedPackage.mExtras;
17450            setInstallAndUpdateTime(newPackage, deletedPkgSetting.firstInstallTime,
17451                    System.currentTimeMillis());
17452
17453            // Update the package dynamic state if succeeded
17454            if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
17455                // Now that the install succeeded make sure we remove data
17456                // directories for any child package the update removed.
17457                final int deletedChildCount = (deletedPackage.childPackages != null)
17458                        ? deletedPackage.childPackages.size() : 0;
17459                final int newChildCount = (newPackage.childPackages != null)
17460                        ? newPackage.childPackages.size() : 0;
17461                for (int i = 0; i < deletedChildCount; i++) {
17462                    PackageParser.Package deletedChildPkg = deletedPackage.childPackages.get(i);
17463                    boolean childPackageDeleted = true;
17464                    for (int j = 0; j < newChildCount; j++) {
17465                        PackageParser.Package newChildPkg = newPackage.childPackages.get(j);
17466                        if (deletedChildPkg.packageName.equals(newChildPkg.packageName)) {
17467                            childPackageDeleted = false;
17468                            break;
17469                        }
17470                    }
17471                    if (childPackageDeleted) {
17472                        PackageSetting ps = mSettings.getDisabledSystemPkgLPr(
17473                                deletedChildPkg.packageName);
17474                        if (ps != null && res.removedInfo.removedChildPackages != null) {
17475                            PackageRemovedInfo removedChildRes = res.removedInfo
17476                                    .removedChildPackages.get(deletedChildPkg.packageName);
17477                            removePackageDataLIF(ps, allUsers, removedChildRes, 0, false);
17478                            removedChildRes.removedForAllUsers = mPackages.get(ps.name) == null;
17479                        }
17480                    }
17481                }
17482
17483                updateSettingsLI(newPackage, installerPackageName, allUsers, res, user,
17484                        installReason);
17485                prepareAppDataAfterInstallLIF(newPackage);
17486
17487                mDexManager.notifyPackageUpdated(newPackage.packageName,
17488                            newPackage.baseCodePath, newPackage.splitCodePaths);
17489            }
17490        } catch (PackageManagerException e) {
17491            res.setReturnCode(INSTALL_FAILED_INTERNAL_ERROR);
17492            res.setError("Package couldn't be installed in " + pkg.codePath, e);
17493        }
17494
17495        if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
17496            // Re installation failed. Restore old information
17497            // Remove new pkg information
17498            if (newPackage != null) {
17499                removeInstalledPackageLI(newPackage, true);
17500            }
17501            // Add back the old system package
17502            try {
17503                scanPackageTracedLI(deletedPackage, policyFlags, SCAN_UPDATE_SIGNATURE, 0, user);
17504            } catch (PackageManagerException e) {
17505                Slog.e(TAG, "Failed to restore original package: " + e.getMessage());
17506            }
17507
17508            synchronized (mPackages) {
17509                if (disabledSystem) {
17510                    enableSystemPackageLPw(deletedPackage);
17511                }
17512
17513                // Ensure the installer package name up to date
17514                setInstallerPackageNameLPw(deletedPackage, installerPackageName);
17515
17516                // Update permissions for restored package
17517                updatePermissionsLPw(deletedPackage, UPDATE_PERMISSIONS_ALL);
17518
17519                mSettings.writeLPr();
17520            }
17521
17522            Slog.i(TAG, "Successfully restored package : " + deletedPackage.packageName
17523                    + " after failed upgrade");
17524        }
17525    }
17526
17527    /**
17528     * Checks whether the parent or any of the child packages have a change shared
17529     * user. For a package to be a valid update the shred users of the parent and
17530     * the children should match. We may later support changing child shared users.
17531     * @param oldPkg The updated package.
17532     * @param newPkg The update package.
17533     * @return The shared user that change between the versions.
17534     */
17535    private String getParentOrChildPackageChangedSharedUser(PackageParser.Package oldPkg,
17536            PackageParser.Package newPkg) {
17537        // Check parent shared user
17538        if (!Objects.equals(oldPkg.mSharedUserId, newPkg.mSharedUserId)) {
17539            return newPkg.packageName;
17540        }
17541        // Check child shared users
17542        final int oldChildCount = (oldPkg.childPackages != null) ? oldPkg.childPackages.size() : 0;
17543        final int newChildCount = (newPkg.childPackages != null) ? newPkg.childPackages.size() : 0;
17544        for (int i = 0; i < newChildCount; i++) {
17545            PackageParser.Package newChildPkg = newPkg.childPackages.get(i);
17546            // If this child was present, did it have the same shared user?
17547            for (int j = 0; j < oldChildCount; j++) {
17548                PackageParser.Package oldChildPkg = oldPkg.childPackages.get(j);
17549                if (newChildPkg.packageName.equals(oldChildPkg.packageName)
17550                        && !Objects.equals(newChildPkg.mSharedUserId, oldChildPkg.mSharedUserId)) {
17551                    return newChildPkg.packageName;
17552                }
17553            }
17554        }
17555        return null;
17556    }
17557
17558    private void removeNativeBinariesLI(PackageSetting ps) {
17559        // Remove the lib path for the parent package
17560        if (ps != null) {
17561            NativeLibraryHelper.removeNativeBinariesLI(ps.legacyNativeLibraryPathString);
17562            // Remove the lib path for the child packages
17563            final int childCount = (ps.childPackageNames != null) ? ps.childPackageNames.size() : 0;
17564            for (int i = 0; i < childCount; i++) {
17565                PackageSetting childPs = null;
17566                synchronized (mPackages) {
17567                    childPs = mSettings.getPackageLPr(ps.childPackageNames.get(i));
17568                }
17569                if (childPs != null) {
17570                    NativeLibraryHelper.removeNativeBinariesLI(childPs
17571                            .legacyNativeLibraryPathString);
17572                }
17573            }
17574        }
17575    }
17576
17577    private void enableSystemPackageLPw(PackageParser.Package pkg) {
17578        // Enable the parent package
17579        mSettings.enableSystemPackageLPw(pkg.packageName);
17580        // Enable the child packages
17581        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
17582        for (int i = 0; i < childCount; i++) {
17583            PackageParser.Package childPkg = pkg.childPackages.get(i);
17584            mSettings.enableSystemPackageLPw(childPkg.packageName);
17585        }
17586    }
17587
17588    private boolean disableSystemPackageLPw(PackageParser.Package oldPkg,
17589            PackageParser.Package newPkg) {
17590        // Disable the parent package (parent always replaced)
17591        boolean disabled = mSettings.disableSystemPackageLPw(oldPkg.packageName, true);
17592        // Disable the child packages
17593        final int childCount = (oldPkg.childPackages != null) ? oldPkg.childPackages.size() : 0;
17594        for (int i = 0; i < childCount; i++) {
17595            PackageParser.Package childPkg = oldPkg.childPackages.get(i);
17596            final boolean replace = newPkg.hasChildPackage(childPkg.packageName);
17597            disabled |= mSettings.disableSystemPackageLPw(childPkg.packageName, replace);
17598        }
17599        return disabled;
17600    }
17601
17602    private void setInstallerPackageNameLPw(PackageParser.Package pkg,
17603            String installerPackageName) {
17604        // Enable the parent package
17605        mSettings.setInstallerPackageName(pkg.packageName, installerPackageName);
17606        // Enable the child packages
17607        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
17608        for (int i = 0; i < childCount; i++) {
17609            PackageParser.Package childPkg = pkg.childPackages.get(i);
17610            mSettings.setInstallerPackageName(childPkg.packageName, installerPackageName);
17611        }
17612    }
17613
17614    private int[] revokeUnusedSharedUserPermissionsLPw(SharedUserSetting su, int[] allUserIds) {
17615        // Collect all used permissions in the UID
17616        ArraySet<String> usedPermissions = new ArraySet<>();
17617        final int packageCount = su.packages.size();
17618        for (int i = 0; i < packageCount; i++) {
17619            PackageSetting ps = su.packages.valueAt(i);
17620            if (ps.pkg == null) {
17621                continue;
17622            }
17623            final int requestedPermCount = ps.pkg.requestedPermissions.size();
17624            for (int j = 0; j < requestedPermCount; j++) {
17625                String permission = ps.pkg.requestedPermissions.get(j);
17626                BasePermission bp = mSettings.mPermissions.get(permission);
17627                if (bp != null) {
17628                    usedPermissions.add(permission);
17629                }
17630            }
17631        }
17632
17633        PermissionsState permissionsState = su.getPermissionsState();
17634        // Prune install permissions
17635        List<PermissionState> installPermStates = permissionsState.getInstallPermissionStates();
17636        final int installPermCount = installPermStates.size();
17637        for (int i = installPermCount - 1; i >= 0;  i--) {
17638            PermissionState permissionState = installPermStates.get(i);
17639            if (!usedPermissions.contains(permissionState.getName())) {
17640                BasePermission bp = mSettings.mPermissions.get(permissionState.getName());
17641                if (bp != null) {
17642                    permissionsState.revokeInstallPermission(bp);
17643                    permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL,
17644                            PackageManager.MASK_PERMISSION_FLAGS, 0);
17645                }
17646            }
17647        }
17648
17649        int[] runtimePermissionChangedUserIds = EmptyArray.INT;
17650
17651        // Prune runtime permissions
17652        for (int userId : allUserIds) {
17653            List<PermissionState> runtimePermStates = permissionsState
17654                    .getRuntimePermissionStates(userId);
17655            final int runtimePermCount = runtimePermStates.size();
17656            for (int i = runtimePermCount - 1; i >= 0; i--) {
17657                PermissionState permissionState = runtimePermStates.get(i);
17658                if (!usedPermissions.contains(permissionState.getName())) {
17659                    BasePermission bp = mSettings.mPermissions.get(permissionState.getName());
17660                    if (bp != null) {
17661                        permissionsState.revokeRuntimePermission(bp, userId);
17662                        permissionsState.updatePermissionFlags(bp, userId,
17663                                PackageManager.MASK_PERMISSION_FLAGS, 0);
17664                        runtimePermissionChangedUserIds = ArrayUtils.appendInt(
17665                                runtimePermissionChangedUserIds, userId);
17666                    }
17667                }
17668            }
17669        }
17670
17671        return runtimePermissionChangedUserIds;
17672    }
17673
17674    private void updateSettingsLI(PackageParser.Package newPackage, String installerPackageName,
17675            int[] allUsers, PackageInstalledInfo res, UserHandle user, int installReason) {
17676        // Update the parent package setting
17677        updateSettingsInternalLI(newPackage, installerPackageName, allUsers, res.origUsers,
17678                res, user, installReason);
17679        // Update the child packages setting
17680        final int childCount = (newPackage.childPackages != null)
17681                ? newPackage.childPackages.size() : 0;
17682        for (int i = 0; i < childCount; i++) {
17683            PackageParser.Package childPackage = newPackage.childPackages.get(i);
17684            PackageInstalledInfo childRes = res.addedChildPackages.get(childPackage.packageName);
17685            updateSettingsInternalLI(childPackage, installerPackageName, allUsers,
17686                    childRes.origUsers, childRes, user, installReason);
17687        }
17688    }
17689
17690    private void updateSettingsInternalLI(PackageParser.Package newPackage,
17691            String installerPackageName, int[] allUsers, int[] installedForUsers,
17692            PackageInstalledInfo res, UserHandle user, int installReason) {
17693        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings");
17694
17695        String pkgName = newPackage.packageName;
17696        synchronized (mPackages) {
17697            //write settings. the installStatus will be incomplete at this stage.
17698            //note that the new package setting would have already been
17699            //added to mPackages. It hasn't been persisted yet.
17700            mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_INCOMPLETE);
17701            // TODO: Remove this write? It's also written at the end of this method
17702            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings");
17703            mSettings.writeLPr();
17704            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
17705        }
17706
17707        if (DEBUG_INSTALL) Slog.d(TAG, "New package installed in " + newPackage.codePath);
17708        synchronized (mPackages) {
17709            updatePermissionsLPw(newPackage.packageName, newPackage,
17710                    UPDATE_PERMISSIONS_REPLACE_PKG | (newPackage.permissions.size() > 0
17711                            ? UPDATE_PERMISSIONS_ALL : 0));
17712            // For system-bundled packages, we assume that installing an upgraded version
17713            // of the package implies that the user actually wants to run that new code,
17714            // so we enable the package.
17715            PackageSetting ps = mSettings.mPackages.get(pkgName);
17716            final int userId = user.getIdentifier();
17717            if (ps != null) {
17718                if (isSystemApp(newPackage)) {
17719                    if (DEBUG_INSTALL) {
17720                        Slog.d(TAG, "Implicitly enabling system package on upgrade: " + pkgName);
17721                    }
17722                    // Enable system package for requested users
17723                    if (res.origUsers != null) {
17724                        for (int origUserId : res.origUsers) {
17725                            if (userId == UserHandle.USER_ALL || userId == origUserId) {
17726                                ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT,
17727                                        origUserId, installerPackageName);
17728                            }
17729                        }
17730                    }
17731                    // Also convey the prior install/uninstall state
17732                    if (allUsers != null && installedForUsers != null) {
17733                        for (int currentUserId : allUsers) {
17734                            final boolean installed = ArrayUtils.contains(
17735                                    installedForUsers, currentUserId);
17736                            if (DEBUG_INSTALL) {
17737                                Slog.d(TAG, "    user " + currentUserId + " => " + installed);
17738                            }
17739                            ps.setInstalled(installed, currentUserId);
17740                        }
17741                        // these install state changes will be persisted in the
17742                        // upcoming call to mSettings.writeLPr().
17743                    }
17744                }
17745                // It's implied that when a user requests installation, they want the app to be
17746                // installed and enabled.
17747                if (userId != UserHandle.USER_ALL) {
17748                    ps.setInstalled(true, userId);
17749                    ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, userId, installerPackageName);
17750                }
17751
17752                // When replacing an existing package, preserve the original install reason for all
17753                // users that had the package installed before.
17754                final Set<Integer> previousUserIds = new ArraySet<>();
17755                if (res.removedInfo != null && res.removedInfo.installReasons != null) {
17756                    final int installReasonCount = res.removedInfo.installReasons.size();
17757                    for (int i = 0; i < installReasonCount; i++) {
17758                        final int previousUserId = res.removedInfo.installReasons.keyAt(i);
17759                        final int previousInstallReason = res.removedInfo.installReasons.valueAt(i);
17760                        ps.setInstallReason(previousInstallReason, previousUserId);
17761                        previousUserIds.add(previousUserId);
17762                    }
17763                }
17764
17765                // Set install reason for users that are having the package newly installed.
17766                if (userId == UserHandle.USER_ALL) {
17767                    for (int currentUserId : sUserManager.getUserIds()) {
17768                        if (!previousUserIds.contains(currentUserId)) {
17769                            ps.setInstallReason(installReason, currentUserId);
17770                        }
17771                    }
17772                } else if (!previousUserIds.contains(userId)) {
17773                    ps.setInstallReason(installReason, userId);
17774                }
17775                mSettings.writeKernelMappingLPr(ps);
17776            }
17777            res.name = pkgName;
17778            res.uid = newPackage.applicationInfo.uid;
17779            res.pkg = newPackage;
17780            mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_COMPLETE);
17781            mSettings.setInstallerPackageName(pkgName, installerPackageName);
17782            res.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
17783            //to update install status
17784            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings");
17785            mSettings.writeLPr();
17786            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
17787        }
17788
17789        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
17790    }
17791
17792    private void installPackageTracedLI(InstallArgs args, PackageInstalledInfo res) {
17793        try {
17794            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installPackage");
17795            installPackageLI(args, res);
17796        } finally {
17797            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
17798        }
17799    }
17800
17801    private void installPackageLI(InstallArgs args, PackageInstalledInfo res) {
17802        final int installFlags = args.installFlags;
17803        final String installerPackageName = args.installerPackageName;
17804        final String volumeUuid = args.volumeUuid;
17805        final File tmpPackageFile = new File(args.getCodePath());
17806        final boolean forwardLocked = ((installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0);
17807        final boolean onExternal = (((installFlags & PackageManager.INSTALL_EXTERNAL) != 0)
17808                || (args.volumeUuid != null));
17809        final boolean instantApp = ((installFlags & PackageManager.INSTALL_INSTANT_APP) != 0);
17810        final boolean fullApp = ((installFlags & PackageManager.INSTALL_FULL_APP) != 0);
17811        final boolean forceSdk = ((installFlags & PackageManager.INSTALL_FORCE_SDK) != 0);
17812        boolean replace = false;
17813        int scanFlags = SCAN_NEW_INSTALL | SCAN_UPDATE_SIGNATURE;
17814        if (args.move != null) {
17815            // moving a complete application; perform an initial scan on the new install location
17816            scanFlags |= SCAN_INITIAL;
17817        }
17818        if ((installFlags & PackageManager.INSTALL_DONT_KILL_APP) != 0) {
17819            scanFlags |= SCAN_DONT_KILL_APP;
17820        }
17821        if (instantApp) {
17822            scanFlags |= SCAN_AS_INSTANT_APP;
17823        }
17824        if (fullApp) {
17825            scanFlags |= SCAN_AS_FULL_APP;
17826        }
17827
17828        // Result object to be returned
17829        res.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
17830
17831        if (DEBUG_INSTALL) Slog.d(TAG, "installPackageLI: path=" + tmpPackageFile);
17832
17833        // Sanity check
17834        if (instantApp && (forwardLocked || onExternal)) {
17835            Slog.i(TAG, "Incompatible ephemeral install; fwdLocked=" + forwardLocked
17836                    + " external=" + onExternal);
17837            res.setReturnCode(PackageManager.INSTALL_FAILED_INSTANT_APP_INVALID);
17838            return;
17839        }
17840
17841        // Retrieve PackageSettings and parse package
17842        final int parseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY
17843                | PackageParser.PARSE_ENFORCE_CODE
17844                | (forwardLocked ? PackageParser.PARSE_FORWARD_LOCK : 0)
17845                | (onExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0)
17846                | (instantApp ? PackageParser.PARSE_IS_EPHEMERAL : 0)
17847                | (forceSdk ? PackageParser.PARSE_FORCE_SDK : 0);
17848        PackageParser pp = new PackageParser();
17849        pp.setSeparateProcesses(mSeparateProcesses);
17850        pp.setDisplayMetrics(mMetrics);
17851        pp.setCallback(mPackageParserCallback);
17852
17853        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "parsePackage");
17854        final PackageParser.Package pkg;
17855        try {
17856            pkg = pp.parsePackage(tmpPackageFile, parseFlags);
17857        } catch (PackageParserException e) {
17858            res.setError("Failed parse during installPackageLI", e);
17859            return;
17860        } finally {
17861            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
17862        }
17863
17864        // Instant apps must have target SDK >= O and have targetSanboxVersion >= 2
17865        if (instantApp && pkg.applicationInfo.targetSdkVersion <= Build.VERSION_CODES.N_MR1) {
17866            Slog.w(TAG, "Instant app package " + pkg.packageName + " does not target O");
17867            res.setError(INSTALL_FAILED_SANDBOX_VERSION_DOWNGRADE,
17868                    "Instant app package must target O");
17869            return;
17870        }
17871        if (instantApp && pkg.applicationInfo.targetSandboxVersion != 2) {
17872            Slog.w(TAG, "Instant app package " + pkg.packageName
17873                    + " does not target targetSandboxVersion 2");
17874            res.setError(INSTALL_FAILED_SANDBOX_VERSION_DOWNGRADE,
17875                    "Instant app package must use targetSanboxVersion 2");
17876            return;
17877        }
17878
17879        if (pkg.applicationInfo.isStaticSharedLibrary()) {
17880            // Static shared libraries have synthetic package names
17881            renameStaticSharedLibraryPackage(pkg);
17882
17883            // No static shared libs on external storage
17884            if (onExternal) {
17885                Slog.i(TAG, "Static shared libs can only be installed on internal storage.");
17886                res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION,
17887                        "Packages declaring static-shared libs cannot be updated");
17888                return;
17889            }
17890        }
17891
17892        // If we are installing a clustered package add results for the children
17893        if (pkg.childPackages != null) {
17894            synchronized (mPackages) {
17895                final int childCount = pkg.childPackages.size();
17896                for (int i = 0; i < childCount; i++) {
17897                    PackageParser.Package childPkg = pkg.childPackages.get(i);
17898                    PackageInstalledInfo childRes = new PackageInstalledInfo();
17899                    childRes.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
17900                    childRes.pkg = childPkg;
17901                    childRes.name = childPkg.packageName;
17902                    PackageSetting childPs = mSettings.getPackageLPr(childPkg.packageName);
17903                    if (childPs != null) {
17904                        childRes.origUsers = childPs.queryInstalledUsers(
17905                                sUserManager.getUserIds(), true);
17906                    }
17907                    if ((mPackages.containsKey(childPkg.packageName))) {
17908                        childRes.removedInfo = new PackageRemovedInfo(this);
17909                        childRes.removedInfo.removedPackage = childPkg.packageName;
17910                        childRes.removedInfo.installerPackageName = childPs.installerPackageName;
17911                    }
17912                    if (res.addedChildPackages == null) {
17913                        res.addedChildPackages = new ArrayMap<>();
17914                    }
17915                    res.addedChildPackages.put(childPkg.packageName, childRes);
17916                }
17917            }
17918        }
17919
17920        // If package doesn't declare API override, mark that we have an install
17921        // time CPU ABI override.
17922        if (TextUtils.isEmpty(pkg.cpuAbiOverride)) {
17923            pkg.cpuAbiOverride = args.abiOverride;
17924        }
17925
17926        String pkgName = res.name = pkg.packageName;
17927        if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_TEST_ONLY) != 0) {
17928            if ((installFlags & PackageManager.INSTALL_ALLOW_TEST) == 0) {
17929                res.setError(INSTALL_FAILED_TEST_ONLY, "installPackageLI");
17930                return;
17931            }
17932        }
17933
17934        try {
17935            // either use what we've been given or parse directly from the APK
17936            if (args.certificates != null) {
17937                try {
17938                    PackageParser.populateCertificates(pkg, args.certificates);
17939                } catch (PackageParserException e) {
17940                    // there was something wrong with the certificates we were given;
17941                    // try to pull them from the APK
17942                    PackageParser.collectCertificates(pkg, parseFlags);
17943                }
17944            } else {
17945                PackageParser.collectCertificates(pkg, parseFlags);
17946            }
17947        } catch (PackageParserException e) {
17948            res.setError("Failed collect during installPackageLI", e);
17949            return;
17950        }
17951
17952        // Get rid of all references to package scan path via parser.
17953        pp = null;
17954        String oldCodePath = null;
17955        boolean systemApp = false;
17956        synchronized (mPackages) {
17957            // Check if installing already existing package
17958            if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
17959                String oldName = mSettings.getRenamedPackageLPr(pkgName);
17960                if (pkg.mOriginalPackages != null
17961                        && pkg.mOriginalPackages.contains(oldName)
17962                        && mPackages.containsKey(oldName)) {
17963                    // This package is derived from an original package,
17964                    // and this device has been updating from that original
17965                    // name.  We must continue using the original name, so
17966                    // rename the new package here.
17967                    pkg.setPackageName(oldName);
17968                    pkgName = pkg.packageName;
17969                    replace = true;
17970                    if (DEBUG_INSTALL) Slog.d(TAG, "Replacing existing renamed package: oldName="
17971                            + oldName + " pkgName=" + pkgName);
17972                } else if (mPackages.containsKey(pkgName)) {
17973                    // This package, under its official name, already exists
17974                    // on the device; we should replace it.
17975                    replace = true;
17976                    if (DEBUG_INSTALL) Slog.d(TAG, "Replace existing pacakge: " + pkgName);
17977                }
17978
17979                // Child packages are installed through the parent package
17980                if (pkg.parentPackage != null) {
17981                    res.setError(PackageManager.INSTALL_PARSE_FAILED_BAD_PACKAGE_NAME,
17982                            "Package " + pkg.packageName + " is child of package "
17983                                    + pkg.parentPackage.parentPackage + ". Child packages "
17984                                    + "can be updated only through the parent package.");
17985                    return;
17986                }
17987
17988                if (replace) {
17989                    // Prevent apps opting out from runtime permissions
17990                    PackageParser.Package oldPackage = mPackages.get(pkgName);
17991                    final int oldTargetSdk = oldPackage.applicationInfo.targetSdkVersion;
17992                    final int newTargetSdk = pkg.applicationInfo.targetSdkVersion;
17993                    if (oldTargetSdk > Build.VERSION_CODES.LOLLIPOP_MR1
17994                            && newTargetSdk <= Build.VERSION_CODES.LOLLIPOP_MR1) {
17995                        res.setError(PackageManager.INSTALL_FAILED_PERMISSION_MODEL_DOWNGRADE,
17996                                "Package " + pkg.packageName + " new target SDK " + newTargetSdk
17997                                        + " doesn't support runtime permissions but the old"
17998                                        + " target SDK " + oldTargetSdk + " does.");
17999                        return;
18000                    }
18001                    // Prevent apps from downgrading their targetSandbox.
18002                    final int oldTargetSandbox = oldPackage.applicationInfo.targetSandboxVersion;
18003                    final int newTargetSandbox = pkg.applicationInfo.targetSandboxVersion;
18004                    if (oldTargetSandbox == 2 && newTargetSandbox != 2) {
18005                        res.setError(PackageManager.INSTALL_FAILED_SANDBOX_VERSION_DOWNGRADE,
18006                                "Package " + pkg.packageName + " new target sandbox "
18007                                + newTargetSandbox + " is incompatible with the previous value of"
18008                                + oldTargetSandbox + ".");
18009                        return;
18010                    }
18011
18012                    // Prevent installing of child packages
18013                    if (oldPackage.parentPackage != null) {
18014                        res.setError(PackageManager.INSTALL_PARSE_FAILED_BAD_PACKAGE_NAME,
18015                                "Package " + pkg.packageName + " is child of package "
18016                                        + oldPackage.parentPackage + ". Child packages "
18017                                        + "can be updated only through the parent package.");
18018                        return;
18019                    }
18020                }
18021            }
18022
18023            PackageSetting ps = mSettings.mPackages.get(pkgName);
18024            if (ps != null) {
18025                if (DEBUG_INSTALL) Slog.d(TAG, "Existing package: " + ps);
18026
18027                // Static shared libs have same package with different versions where
18028                // we internally use a synthetic package name to allow multiple versions
18029                // of the same package, therefore we need to compare signatures against
18030                // the package setting for the latest library version.
18031                PackageSetting signatureCheckPs = ps;
18032                if (pkg.applicationInfo.isStaticSharedLibrary()) {
18033                    SharedLibraryEntry libraryEntry = getLatestSharedLibraVersionLPr(pkg);
18034                    if (libraryEntry != null) {
18035                        signatureCheckPs = mSettings.getPackageLPr(libraryEntry.apk);
18036                    }
18037                }
18038
18039                // Quick sanity check that we're signed correctly if updating;
18040                // we'll check this again later when scanning, but we want to
18041                // bail early here before tripping over redefined permissions.
18042                if (shouldCheckUpgradeKeySetLP(signatureCheckPs, scanFlags)) {
18043                    if (!checkUpgradeKeySetLP(signatureCheckPs, pkg)) {
18044                        res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package "
18045                                + pkg.packageName + " upgrade keys do not match the "
18046                                + "previously installed version");
18047                        return;
18048                    }
18049                } else {
18050                    try {
18051                        verifySignaturesLP(signatureCheckPs, pkg);
18052                    } catch (PackageManagerException e) {
18053                        res.setError(e.error, e.getMessage());
18054                        return;
18055                    }
18056                }
18057
18058                oldCodePath = mSettings.mPackages.get(pkgName).codePathString;
18059                if (ps.pkg != null && ps.pkg.applicationInfo != null) {
18060                    systemApp = (ps.pkg.applicationInfo.flags &
18061                            ApplicationInfo.FLAG_SYSTEM) != 0;
18062                }
18063                res.origUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
18064            }
18065
18066            int N = pkg.permissions.size();
18067            for (int i = N-1; i >= 0; i--) {
18068                PackageParser.Permission perm = pkg.permissions.get(i);
18069                BasePermission bp = mSettings.mPermissions.get(perm.info.name);
18070
18071                // Don't allow anyone but the system to define ephemeral permissions.
18072                if ((perm.info.protectionLevel & PermissionInfo.PROTECTION_FLAG_EPHEMERAL) != 0
18073                        && !systemApp) {
18074                    Slog.w(TAG, "Non-System package " + pkg.packageName
18075                            + " attempting to delcare ephemeral permission "
18076                            + perm.info.name + "; Removing ephemeral.");
18077                    perm.info.protectionLevel &= ~PermissionInfo.PROTECTION_FLAG_EPHEMERAL;
18078                }
18079                // Check whether the newly-scanned package wants to define an already-defined perm
18080                if (bp != null) {
18081                    // If the defining package is signed with our cert, it's okay.  This
18082                    // also includes the "updating the same package" case, of course.
18083                    // "updating same package" could also involve key-rotation.
18084                    final boolean sigsOk;
18085                    if (bp.sourcePackage.equals(pkg.packageName)
18086                            && (bp.packageSetting instanceof PackageSetting)
18087                            && (shouldCheckUpgradeKeySetLP((PackageSetting) bp.packageSetting,
18088                                    scanFlags))) {
18089                        sigsOk = checkUpgradeKeySetLP((PackageSetting) bp.packageSetting, pkg);
18090                    } else {
18091                        sigsOk = compareSignatures(bp.packageSetting.signatures.mSignatures,
18092                                pkg.mSignatures) == PackageManager.SIGNATURE_MATCH;
18093                    }
18094                    if (!sigsOk) {
18095                        // If the owning package is the system itself, we log but allow
18096                        // install to proceed; we fail the install on all other permission
18097                        // redefinitions.
18098                        if (!bp.sourcePackage.equals("android")) {
18099                            res.setError(INSTALL_FAILED_DUPLICATE_PERMISSION, "Package "
18100                                    + pkg.packageName + " attempting to redeclare permission "
18101                                    + perm.info.name + " already owned by " + bp.sourcePackage);
18102                            res.origPermission = perm.info.name;
18103                            res.origPackage = bp.sourcePackage;
18104                            return;
18105                        } else {
18106                            Slog.w(TAG, "Package " + pkg.packageName
18107                                    + " attempting to redeclare system permission "
18108                                    + perm.info.name + "; ignoring new declaration");
18109                            pkg.permissions.remove(i);
18110                        }
18111                    } else if (!PLATFORM_PACKAGE_NAME.equals(pkg.packageName)) {
18112                        // Prevent apps to change protection level to dangerous from any other
18113                        // type as this would allow a privilege escalation where an app adds a
18114                        // normal/signature permission in other app's group and later redefines
18115                        // it as dangerous leading to the group auto-grant.
18116                        if ((perm.info.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE)
18117                                == PermissionInfo.PROTECTION_DANGEROUS) {
18118                            if (bp != null && !bp.isRuntime()) {
18119                                Slog.w(TAG, "Package " + pkg.packageName + " trying to change a "
18120                                        + "non-runtime permission " + perm.info.name
18121                                        + " to runtime; keeping old protection level");
18122                                perm.info.protectionLevel = bp.protectionLevel;
18123                            }
18124                        }
18125                    }
18126                }
18127            }
18128        }
18129
18130        if (systemApp) {
18131            if (onExternal) {
18132                // Abort update; system app can't be replaced with app on sdcard
18133                res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION,
18134                        "Cannot install updates to system apps on sdcard");
18135                return;
18136            } else if (instantApp) {
18137                // Abort update; system app can't be replaced with an instant app
18138                res.setError(INSTALL_FAILED_INSTANT_APP_INVALID,
18139                        "Cannot update a system app with an instant app");
18140                return;
18141            }
18142        }
18143
18144        if (args.move != null) {
18145            // We did an in-place move, so dex is ready to roll
18146            scanFlags |= SCAN_NO_DEX;
18147            scanFlags |= SCAN_MOVE;
18148
18149            synchronized (mPackages) {
18150                final PackageSetting ps = mSettings.mPackages.get(pkgName);
18151                if (ps == null) {
18152                    res.setError(INSTALL_FAILED_INTERNAL_ERROR,
18153                            "Missing settings for moved package " + pkgName);
18154                }
18155
18156                // We moved the entire application as-is, so bring over the
18157                // previously derived ABI information.
18158                pkg.applicationInfo.primaryCpuAbi = ps.primaryCpuAbiString;
18159                pkg.applicationInfo.secondaryCpuAbi = ps.secondaryCpuAbiString;
18160            }
18161
18162        } else if (!forwardLocked && !pkg.applicationInfo.isExternalAsec()) {
18163            // Enable SCAN_NO_DEX flag to skip dexopt at a later stage
18164            scanFlags |= SCAN_NO_DEX;
18165
18166            try {
18167                String abiOverride = (TextUtils.isEmpty(pkg.cpuAbiOverride) ?
18168                    args.abiOverride : pkg.cpuAbiOverride);
18169                final boolean extractNativeLibs = !pkg.isLibrary();
18170                derivePackageAbi(pkg, new File(pkg.codePath), abiOverride,
18171                        extractNativeLibs, mAppLib32InstallDir);
18172            } catch (PackageManagerException pme) {
18173                Slog.e(TAG, "Error deriving application ABI", pme);
18174                res.setError(INSTALL_FAILED_INTERNAL_ERROR, "Error deriving application ABI");
18175                return;
18176            }
18177
18178            // Shared libraries for the package need to be updated.
18179            synchronized (mPackages) {
18180                try {
18181                    updateSharedLibrariesLPr(pkg, null);
18182                } catch (PackageManagerException e) {
18183                    Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
18184                }
18185            }
18186
18187            // dexopt can take some time to complete, so, for instant apps, we skip this
18188            // step during installation. Instead, we'll take extra time the first time the
18189            // instant app starts. It's preferred to do it this way to provide continuous
18190            // progress to the user instead of mysteriously blocking somewhere in the
18191            // middle of running an instant app. The default behaviour can be overridden
18192            // via gservices.
18193            if (!instantApp || Global.getInt(
18194                        mContext.getContentResolver(), Global.INSTANT_APP_DEXOPT_ENABLED, 0) != 0) {
18195                Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt");
18196                // Do not run PackageDexOptimizer through the local performDexOpt
18197                // method because `pkg` may not be in `mPackages` yet.
18198                //
18199                // Also, don't fail application installs if the dexopt step fails.
18200                mPackageDexOptimizer.performDexOpt(pkg, pkg.usesLibraryFiles,
18201                        null /* instructionSets */, false /* checkProfiles */,
18202                        getCompilerFilterForReason(REASON_INSTALL),
18203                        getOrCreateCompilerPackageStats(pkg),
18204                        mDexManager.isUsedByOtherApps(pkg.packageName),
18205                        true /* bootComplete */);
18206                Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
18207            }
18208
18209            // Notify BackgroundDexOptService that the package has been changed.
18210            // If this is an update of a package which used to fail to compile,
18211            // BDOS will remove it from its blacklist.
18212            // TODO: Layering violation
18213            BackgroundDexOptService.notifyPackageChanged(pkg.packageName);
18214        }
18215
18216        if (!args.doRename(res.returnCode, pkg, oldCodePath)) {
18217            res.setError(INSTALL_FAILED_INSUFFICIENT_STORAGE, "Failed rename");
18218            return;
18219        }
18220
18221        startIntentFilterVerifications(args.user.getIdentifier(), replace, pkg);
18222
18223        try (PackageFreezer freezer = freezePackageForInstall(pkgName, installFlags,
18224                "installPackageLI")) {
18225            if (replace) {
18226                if (pkg.applicationInfo.isStaticSharedLibrary()) {
18227                    // Static libs have a synthetic package name containing the version
18228                    // and cannot be updated as an update would get a new package name,
18229                    // unless this is the exact same version code which is useful for
18230                    // development.
18231                    PackageParser.Package existingPkg = mPackages.get(pkg.packageName);
18232                    if (existingPkg != null && existingPkg.mVersionCode != pkg.mVersionCode) {
18233                        res.setError(INSTALL_FAILED_DUPLICATE_PACKAGE, "Packages declaring "
18234                                + "static-shared libs cannot be updated");
18235                        return;
18236                    }
18237                }
18238                replacePackageLIF(pkg, parseFlags, scanFlags | SCAN_REPLACING, args.user,
18239                        installerPackageName, res, args.installReason);
18240            } else {
18241                installNewPackageLIF(pkg, parseFlags, scanFlags | SCAN_DELETE_DATA_ON_FAILURES,
18242                        args.user, installerPackageName, volumeUuid, res, args.installReason);
18243            }
18244        }
18245
18246        synchronized (mPackages) {
18247            final PackageSetting ps = mSettings.mPackages.get(pkgName);
18248            if (ps != null) {
18249                res.newUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
18250                ps.setUpdateAvailable(false /*updateAvailable*/);
18251            }
18252
18253            final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
18254            for (int i = 0; i < childCount; i++) {
18255                PackageParser.Package childPkg = pkg.childPackages.get(i);
18256                PackageInstalledInfo childRes = res.addedChildPackages.get(childPkg.packageName);
18257                PackageSetting childPs = mSettings.getPackageLPr(childPkg.packageName);
18258                if (childPs != null) {
18259                    childRes.newUsers = childPs.queryInstalledUsers(
18260                            sUserManager.getUserIds(), true);
18261                }
18262            }
18263
18264            if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
18265                updateSequenceNumberLP(ps, res.newUsers);
18266                updateInstantAppInstallerLocked(pkgName);
18267            }
18268        }
18269    }
18270
18271    private void startIntentFilterVerifications(int userId, boolean replacing,
18272            PackageParser.Package pkg) {
18273        if (mIntentFilterVerifierComponent == null) {
18274            Slog.w(TAG, "No IntentFilter verification will not be done as "
18275                    + "there is no IntentFilterVerifier available!");
18276            return;
18277        }
18278
18279        final int verifierUid = getPackageUid(
18280                mIntentFilterVerifierComponent.getPackageName(),
18281                MATCH_DEBUG_TRIAGED_MISSING,
18282                (userId == UserHandle.USER_ALL) ? UserHandle.USER_SYSTEM : userId);
18283
18284        Message msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS);
18285        msg.obj = new IFVerificationParams(pkg, replacing, userId, verifierUid);
18286        mHandler.sendMessage(msg);
18287
18288        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
18289        for (int i = 0; i < childCount; i++) {
18290            PackageParser.Package childPkg = pkg.childPackages.get(i);
18291            msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS);
18292            msg.obj = new IFVerificationParams(childPkg, replacing, userId, verifierUid);
18293            mHandler.sendMessage(msg);
18294        }
18295    }
18296
18297    private void verifyIntentFiltersIfNeeded(int userId, int verifierUid, boolean replacing,
18298            PackageParser.Package pkg) {
18299        int size = pkg.activities.size();
18300        if (size == 0) {
18301            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
18302                    "No activity, so no need to verify any IntentFilter!");
18303            return;
18304        }
18305
18306        final boolean hasDomainURLs = hasDomainURLs(pkg);
18307        if (!hasDomainURLs) {
18308            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
18309                    "No domain URLs, so no need to verify any IntentFilter!");
18310            return;
18311        }
18312
18313        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Checking for userId:" + userId
18314                + " if any IntentFilter from the " + size
18315                + " Activities needs verification ...");
18316
18317        int count = 0;
18318        final String packageName = pkg.packageName;
18319
18320        synchronized (mPackages) {
18321            // If this is a new install and we see that we've already run verification for this
18322            // package, we have nothing to do: it means the state was restored from backup.
18323            if (!replacing) {
18324                IntentFilterVerificationInfo ivi =
18325                        mSettings.getIntentFilterVerificationLPr(packageName);
18326                if (ivi != null) {
18327                    if (DEBUG_DOMAIN_VERIFICATION) {
18328                        Slog.i(TAG, "Package " + packageName+ " already verified: status="
18329                                + ivi.getStatusString());
18330                    }
18331                    return;
18332                }
18333            }
18334
18335            // If any filters need to be verified, then all need to be.
18336            boolean needToVerify = false;
18337            for (PackageParser.Activity a : pkg.activities) {
18338                for (ActivityIntentInfo filter : a.intents) {
18339                    if (filter.needsVerification() && needsNetworkVerificationLPr(filter)) {
18340                        if (DEBUG_DOMAIN_VERIFICATION) {
18341                            Slog.d(TAG, "Intent filter needs verification, so processing all filters");
18342                        }
18343                        needToVerify = true;
18344                        break;
18345                    }
18346                }
18347            }
18348
18349            if (needToVerify) {
18350                final int verificationId = mIntentFilterVerificationToken++;
18351                for (PackageParser.Activity a : pkg.activities) {
18352                    for (ActivityIntentInfo filter : a.intents) {
18353                        if (filter.handlesWebUris(true) && needsNetworkVerificationLPr(filter)) {
18354                            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
18355                                    "Verification needed for IntentFilter:" + filter.toString());
18356                            mIntentFilterVerifier.addOneIntentFilterVerification(
18357                                    verifierUid, userId, verificationId, filter, packageName);
18358                            count++;
18359                        }
18360                    }
18361                }
18362            }
18363        }
18364
18365        if (count > 0) {
18366            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Starting " + count
18367                    + " IntentFilter verification" + (count > 1 ? "s" : "")
18368                    +  " for userId:" + userId);
18369            mIntentFilterVerifier.startVerifications(userId);
18370        } else {
18371            if (DEBUG_DOMAIN_VERIFICATION) {
18372                Slog.d(TAG, "No filters or not all autoVerify for " + packageName);
18373            }
18374        }
18375    }
18376
18377    private boolean needsNetworkVerificationLPr(ActivityIntentInfo filter) {
18378        final ComponentName cn  = filter.activity.getComponentName();
18379        final String packageName = cn.getPackageName();
18380
18381        IntentFilterVerificationInfo ivi = mSettings.getIntentFilterVerificationLPr(
18382                packageName);
18383        if (ivi == null) {
18384            return true;
18385        }
18386        int status = ivi.getStatus();
18387        switch (status) {
18388            case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED:
18389            case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK:
18390                return true;
18391
18392            default:
18393                // Nothing to do
18394                return false;
18395        }
18396    }
18397
18398    private static boolean isMultiArch(ApplicationInfo info) {
18399        return (info.flags & ApplicationInfo.FLAG_MULTIARCH) != 0;
18400    }
18401
18402    private static boolean isExternal(PackageParser.Package pkg) {
18403        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
18404    }
18405
18406    private static boolean isExternal(PackageSetting ps) {
18407        return (ps.pkgFlags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
18408    }
18409
18410    private static boolean isSystemApp(PackageParser.Package pkg) {
18411        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0;
18412    }
18413
18414    private static boolean isPrivilegedApp(PackageParser.Package pkg) {
18415        return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0;
18416    }
18417
18418    private static boolean hasDomainURLs(PackageParser.Package pkg) {
18419        return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_HAS_DOMAIN_URLS) != 0;
18420    }
18421
18422    private static boolean isSystemApp(PackageSetting ps) {
18423        return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0;
18424    }
18425
18426    private static boolean isUpdatedSystemApp(PackageSetting ps) {
18427        return (ps.pkgFlags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0;
18428    }
18429
18430    private int packageFlagsToInstallFlags(PackageSetting ps) {
18431        int installFlags = 0;
18432        if (isExternal(ps) && TextUtils.isEmpty(ps.volumeUuid)) {
18433            // This existing package was an external ASEC install when we have
18434            // the external flag without a UUID
18435            installFlags |= PackageManager.INSTALL_EXTERNAL;
18436        }
18437        if (ps.isForwardLocked()) {
18438            installFlags |= PackageManager.INSTALL_FORWARD_LOCK;
18439        }
18440        return installFlags;
18441    }
18442
18443    private String getVolumeUuidForPackage(PackageParser.Package pkg) {
18444        if (isExternal(pkg)) {
18445            if (TextUtils.isEmpty(pkg.volumeUuid)) {
18446                return StorageManager.UUID_PRIMARY_PHYSICAL;
18447            } else {
18448                return pkg.volumeUuid;
18449            }
18450        } else {
18451            return StorageManager.UUID_PRIVATE_INTERNAL;
18452        }
18453    }
18454
18455    private VersionInfo getSettingsVersionForPackage(PackageParser.Package pkg) {
18456        if (isExternal(pkg)) {
18457            if (TextUtils.isEmpty(pkg.volumeUuid)) {
18458                return mSettings.getExternalVersion();
18459            } else {
18460                return mSettings.findOrCreateVersion(pkg.volumeUuid);
18461            }
18462        } else {
18463            return mSettings.getInternalVersion();
18464        }
18465    }
18466
18467    private void deleteTempPackageFiles() {
18468        final FilenameFilter filter = new FilenameFilter() {
18469            public boolean accept(File dir, String name) {
18470                return name.startsWith("vmdl") && name.endsWith(".tmp");
18471            }
18472        };
18473        for (File file : mDrmAppPrivateInstallDir.listFiles(filter)) {
18474            file.delete();
18475        }
18476    }
18477
18478    @Override
18479    public void deletePackageAsUser(String packageName, int versionCode,
18480            IPackageDeleteObserver observer, int userId, int flags) {
18481        deletePackageVersioned(new VersionedPackage(packageName, versionCode),
18482                new LegacyPackageDeleteObserver(observer).getBinder(), userId, flags);
18483    }
18484
18485    @Override
18486    public void deletePackageVersioned(VersionedPackage versionedPackage,
18487            final IPackageDeleteObserver2 observer, final int userId, final int deleteFlags) {
18488        final int callingUid = Binder.getCallingUid();
18489        mContext.enforceCallingOrSelfPermission(
18490                android.Manifest.permission.DELETE_PACKAGES, null);
18491        final boolean canViewInstantApps = canViewInstantApps(callingUid, userId);
18492        Preconditions.checkNotNull(versionedPackage);
18493        Preconditions.checkNotNull(observer);
18494        Preconditions.checkArgumentInRange(versionedPackage.getVersionCode(),
18495                PackageManager.VERSION_CODE_HIGHEST,
18496                Integer.MAX_VALUE, "versionCode must be >= -1");
18497
18498        final String packageName = versionedPackage.getPackageName();
18499        final int versionCode = versionedPackage.getVersionCode();
18500        final String internalPackageName;
18501        synchronized (mPackages) {
18502            // Normalize package name to handle renamed packages and static libs
18503            internalPackageName = resolveInternalPackageNameLPr(versionedPackage.getPackageName(),
18504                    versionedPackage.getVersionCode());
18505        }
18506
18507        final int uid = Binder.getCallingUid();
18508        if (!isOrphaned(internalPackageName)
18509                && !isCallerAllowedToSilentlyUninstall(uid, internalPackageName)) {
18510            try {
18511                final Intent intent = new Intent(Intent.ACTION_UNINSTALL_PACKAGE);
18512                intent.setData(Uri.fromParts(PACKAGE_SCHEME, packageName, null));
18513                intent.putExtra(PackageInstaller.EXTRA_CALLBACK, observer.asBinder());
18514                observer.onUserActionRequired(intent);
18515            } catch (RemoteException re) {
18516            }
18517            return;
18518        }
18519        final boolean deleteAllUsers = (deleteFlags & PackageManager.DELETE_ALL_USERS) != 0;
18520        final int[] users = deleteAllUsers ? sUserManager.getUserIds() : new int[]{ userId };
18521        if (UserHandle.getUserId(uid) != userId || (deleteAllUsers && users.length > 1)) {
18522            mContext.enforceCallingOrSelfPermission(
18523                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
18524                    "deletePackage for user " + userId);
18525        }
18526
18527        if (isUserRestricted(userId, UserManager.DISALLOW_UNINSTALL_APPS)) {
18528            try {
18529                observer.onPackageDeleted(packageName,
18530                        PackageManager.DELETE_FAILED_USER_RESTRICTED, null);
18531            } catch (RemoteException re) {
18532            }
18533            return;
18534        }
18535
18536        if (!deleteAllUsers && getBlockUninstallForUser(internalPackageName, userId)) {
18537            try {
18538                observer.onPackageDeleted(packageName,
18539                        PackageManager.DELETE_FAILED_OWNER_BLOCKED, null);
18540            } catch (RemoteException re) {
18541            }
18542            return;
18543        }
18544
18545        if (DEBUG_REMOVE) {
18546            Slog.d(TAG, "deletePackageAsUser: pkg=" + internalPackageName + " user=" + userId
18547                    + " deleteAllUsers: " + deleteAllUsers + " version="
18548                    + (versionCode == PackageManager.VERSION_CODE_HIGHEST
18549                    ? "VERSION_CODE_HIGHEST" : versionCode));
18550        }
18551        // Queue up an async operation since the package deletion may take a little while.
18552        mHandler.post(new Runnable() {
18553            public void run() {
18554                mHandler.removeCallbacks(this);
18555                int returnCode;
18556                final PackageSetting ps = mSettings.mPackages.get(internalPackageName);
18557                boolean doDeletePackage = true;
18558                if (ps != null) {
18559                    final boolean targetIsInstantApp =
18560                            ps.getInstantApp(UserHandle.getUserId(callingUid));
18561                    doDeletePackage = !targetIsInstantApp
18562                            || canViewInstantApps;
18563                }
18564                if (doDeletePackage) {
18565                    if (!deleteAllUsers) {
18566                        returnCode = deletePackageX(internalPackageName, versionCode,
18567                                userId, deleteFlags);
18568                    } else {
18569                        int[] blockUninstallUserIds = getBlockUninstallForUsers(
18570                                internalPackageName, users);
18571                        // If nobody is blocking uninstall, proceed with delete for all users
18572                        if (ArrayUtils.isEmpty(blockUninstallUserIds)) {
18573                            returnCode = deletePackageX(internalPackageName, versionCode,
18574                                    userId, deleteFlags);
18575                        } else {
18576                            // Otherwise uninstall individually for users with blockUninstalls=false
18577                            final int userFlags = deleteFlags & ~PackageManager.DELETE_ALL_USERS;
18578                            for (int userId : users) {
18579                                if (!ArrayUtils.contains(blockUninstallUserIds, userId)) {
18580                                    returnCode = deletePackageX(internalPackageName, versionCode,
18581                                            userId, userFlags);
18582                                    if (returnCode != PackageManager.DELETE_SUCCEEDED) {
18583                                        Slog.w(TAG, "Package delete failed for user " + userId
18584                                                + ", returnCode " + returnCode);
18585                                    }
18586                                }
18587                            }
18588                            // The app has only been marked uninstalled for certain users.
18589                            // We still need to report that delete was blocked
18590                            returnCode = PackageManager.DELETE_FAILED_OWNER_BLOCKED;
18591                        }
18592                    }
18593                } else {
18594                    returnCode = PackageManager.DELETE_FAILED_INTERNAL_ERROR;
18595                }
18596                try {
18597                    observer.onPackageDeleted(packageName, returnCode, null);
18598                } catch (RemoteException e) {
18599                    Log.i(TAG, "Observer no longer exists.");
18600                } //end catch
18601            } //end run
18602        });
18603    }
18604
18605    private String resolveExternalPackageNameLPr(PackageParser.Package pkg) {
18606        if (pkg.staticSharedLibName != null) {
18607            return pkg.manifestPackageName;
18608        }
18609        return pkg.packageName;
18610    }
18611
18612    private String resolveInternalPackageNameLPr(String packageName, int versionCode) {
18613        // Handle renamed packages
18614        String normalizedPackageName = mSettings.getRenamedPackageLPr(packageName);
18615        packageName = normalizedPackageName != null ? normalizedPackageName : packageName;
18616
18617        // Is this a static library?
18618        SparseArray<SharedLibraryEntry> versionedLib =
18619                mStaticLibsByDeclaringPackage.get(packageName);
18620        if (versionedLib == null || versionedLib.size() <= 0) {
18621            return packageName;
18622        }
18623
18624        // Figure out which lib versions the caller can see
18625        SparseIntArray versionsCallerCanSee = null;
18626        final int callingAppId = UserHandle.getAppId(Binder.getCallingUid());
18627        if (callingAppId != Process.SYSTEM_UID && callingAppId != Process.SHELL_UID
18628                && callingAppId != Process.ROOT_UID) {
18629            versionsCallerCanSee = new SparseIntArray();
18630            String libName = versionedLib.valueAt(0).info.getName();
18631            String[] uidPackages = getPackagesForUid(Binder.getCallingUid());
18632            if (uidPackages != null) {
18633                for (String uidPackage : uidPackages) {
18634                    PackageSetting ps = mSettings.getPackageLPr(uidPackage);
18635                    final int libIdx = ArrayUtils.indexOf(ps.usesStaticLibraries, libName);
18636                    if (libIdx >= 0) {
18637                        final int libVersion = ps.usesStaticLibrariesVersions[libIdx];
18638                        versionsCallerCanSee.append(libVersion, libVersion);
18639                    }
18640                }
18641            }
18642        }
18643
18644        // Caller can see nothing - done
18645        if (versionsCallerCanSee != null && versionsCallerCanSee.size() <= 0) {
18646            return packageName;
18647        }
18648
18649        // Find the version the caller can see and the app version code
18650        SharedLibraryEntry highestVersion = null;
18651        final int versionCount = versionedLib.size();
18652        for (int i = 0; i < versionCount; i++) {
18653            SharedLibraryEntry libEntry = versionedLib.valueAt(i);
18654            if (versionsCallerCanSee != null && versionsCallerCanSee.indexOfKey(
18655                    libEntry.info.getVersion()) < 0) {
18656                continue;
18657            }
18658            final int libVersionCode = libEntry.info.getDeclaringPackage().getVersionCode();
18659            if (versionCode != PackageManager.VERSION_CODE_HIGHEST) {
18660                if (libVersionCode == versionCode) {
18661                    return libEntry.apk;
18662                }
18663            } else if (highestVersion == null) {
18664                highestVersion = libEntry;
18665            } else if (libVersionCode  > highestVersion.info
18666                    .getDeclaringPackage().getVersionCode()) {
18667                highestVersion = libEntry;
18668            }
18669        }
18670
18671        if (highestVersion != null) {
18672            return highestVersion.apk;
18673        }
18674
18675        return packageName;
18676    }
18677
18678    private boolean isCallerAllowedToSilentlyUninstall(int callingUid, String pkgName) {
18679        if (callingUid == Process.SHELL_UID || callingUid == Process.ROOT_UID
18680              || UserHandle.getAppId(callingUid) == Process.SYSTEM_UID) {
18681            return true;
18682        }
18683        final int callingUserId = UserHandle.getUserId(callingUid);
18684        // If the caller installed the pkgName, then allow it to silently uninstall.
18685        if (callingUid == getPackageUid(getInstallerPackageName(pkgName), 0, callingUserId)) {
18686            return true;
18687        }
18688
18689        // Allow package verifier to silently uninstall.
18690        if (mRequiredVerifierPackage != null &&
18691                callingUid == getPackageUid(mRequiredVerifierPackage, 0, callingUserId)) {
18692            return true;
18693        }
18694
18695        // Allow package uninstaller to silently uninstall.
18696        if (mRequiredUninstallerPackage != null &&
18697                callingUid == getPackageUid(mRequiredUninstallerPackage, 0, callingUserId)) {
18698            return true;
18699        }
18700
18701        // Allow storage manager to silently uninstall.
18702        if (mStorageManagerPackage != null &&
18703                callingUid == getPackageUid(mStorageManagerPackage, 0, callingUserId)) {
18704            return true;
18705        }
18706
18707        // Allow caller having MANAGE_PROFILE_AND_DEVICE_OWNERS permission to silently
18708        // uninstall for device owner provisioning.
18709        if (checkUidPermission(MANAGE_PROFILE_AND_DEVICE_OWNERS, callingUid)
18710                == PERMISSION_GRANTED) {
18711            return true;
18712        }
18713
18714        return false;
18715    }
18716
18717    private int[] getBlockUninstallForUsers(String packageName, int[] userIds) {
18718        int[] result = EMPTY_INT_ARRAY;
18719        for (int userId : userIds) {
18720            if (getBlockUninstallForUser(packageName, userId)) {
18721                result = ArrayUtils.appendInt(result, userId);
18722            }
18723        }
18724        return result;
18725    }
18726
18727    @Override
18728    public boolean isPackageDeviceAdminOnAnyUser(String packageName) {
18729        final int callingUid = Binder.getCallingUid();
18730        if (getInstantAppPackageName(callingUid) != null
18731                && !isCallerSameApp(packageName, callingUid)) {
18732            return false;
18733        }
18734        return isPackageDeviceAdmin(packageName, UserHandle.USER_ALL);
18735    }
18736
18737    private boolean isPackageDeviceAdmin(String packageName, int userId) {
18738        IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface(
18739                ServiceManager.getService(Context.DEVICE_POLICY_SERVICE));
18740        try {
18741            if (dpm != null) {
18742                final ComponentName deviceOwnerComponentName = dpm.getDeviceOwnerComponent(
18743                        /* callingUserOnly =*/ false);
18744                final String deviceOwnerPackageName = deviceOwnerComponentName == null ? null
18745                        : deviceOwnerComponentName.getPackageName();
18746                // Does the package contains the device owner?
18747                // TODO Do we have to do it even if userId != UserHandle.USER_ALL?  Otherwise,
18748                // this check is probably not needed, since DO should be registered as a device
18749                // admin on some user too. (Original bug for this: b/17657954)
18750                if (packageName.equals(deviceOwnerPackageName)) {
18751                    return true;
18752                }
18753                // Does it contain a device admin for any user?
18754                int[] users;
18755                if (userId == UserHandle.USER_ALL) {
18756                    users = sUserManager.getUserIds();
18757                } else {
18758                    users = new int[]{userId};
18759                }
18760                for (int i = 0; i < users.length; ++i) {
18761                    if (dpm.packageHasActiveAdmins(packageName, users[i])) {
18762                        return true;
18763                    }
18764                }
18765            }
18766        } catch (RemoteException e) {
18767        }
18768        return false;
18769    }
18770
18771    private boolean shouldKeepUninstalledPackageLPr(String packageName) {
18772        return mKeepUninstalledPackages != null && mKeepUninstalledPackages.contains(packageName);
18773    }
18774
18775    /**
18776     *  This method is an internal method that could be get invoked either
18777     *  to delete an installed package or to clean up a failed installation.
18778     *  After deleting an installed package, a broadcast is sent to notify any
18779     *  listeners that the package has been removed. For cleaning up a failed
18780     *  installation, the broadcast is not necessary since the package's
18781     *  installation wouldn't have sent the initial broadcast either
18782     *  The key steps in deleting a package are
18783     *  deleting the package information in internal structures like mPackages,
18784     *  deleting the packages base directories through installd
18785     *  updating mSettings to reflect current status
18786     *  persisting settings for later use
18787     *  sending a broadcast if necessary
18788     */
18789    int deletePackageX(String packageName, int versionCode, int userId, int deleteFlags) {
18790        final PackageRemovedInfo info = new PackageRemovedInfo(this);
18791        final boolean res;
18792
18793        final int removeUser = (deleteFlags & PackageManager.DELETE_ALL_USERS) != 0
18794                ? UserHandle.USER_ALL : userId;
18795
18796        if (isPackageDeviceAdmin(packageName, removeUser)) {
18797            Slog.w(TAG, "Not removing package " + packageName + ": has active device admin");
18798            return PackageManager.DELETE_FAILED_DEVICE_POLICY_MANAGER;
18799        }
18800
18801        PackageSetting uninstalledPs = null;
18802        PackageParser.Package pkg = null;
18803
18804        // for the uninstall-updates case and restricted profiles, remember the per-
18805        // user handle installed state
18806        int[] allUsers;
18807        synchronized (mPackages) {
18808            uninstalledPs = mSettings.mPackages.get(packageName);
18809            if (uninstalledPs == null) {
18810                Slog.w(TAG, "Not removing non-existent package " + packageName);
18811                return PackageManager.DELETE_FAILED_INTERNAL_ERROR;
18812            }
18813
18814            if (versionCode != PackageManager.VERSION_CODE_HIGHEST
18815                    && uninstalledPs.versionCode != versionCode) {
18816                Slog.w(TAG, "Not removing package " + packageName + " with versionCode "
18817                        + uninstalledPs.versionCode + " != " + versionCode);
18818                return PackageManager.DELETE_FAILED_INTERNAL_ERROR;
18819            }
18820
18821            // Static shared libs can be declared by any package, so let us not
18822            // allow removing a package if it provides a lib others depend on.
18823            pkg = mPackages.get(packageName);
18824
18825            allUsers = sUserManager.getUserIds();
18826
18827            if (pkg != null && pkg.staticSharedLibName != null) {
18828                SharedLibraryEntry libEntry = getSharedLibraryEntryLPr(pkg.staticSharedLibName,
18829                        pkg.staticSharedLibVersion);
18830                if (libEntry != null) {
18831                    for (int currUserId : allUsers) {
18832                        if (removeUser != UserHandle.USER_ALL && removeUser != currUserId) {
18833                            continue;
18834                        }
18835                        List<VersionedPackage> libClientPackages = getPackagesUsingSharedLibraryLPr(
18836                                libEntry.info, 0, currUserId);
18837                        if (!ArrayUtils.isEmpty(libClientPackages)) {
18838                            Slog.w(TAG, "Not removing package " + pkg.manifestPackageName
18839                                    + " hosting lib " + libEntry.info.getName() + " version "
18840                                    + libEntry.info.getVersion() + " used by " + libClientPackages
18841                                    + " for user " + currUserId);
18842                            return PackageManager.DELETE_FAILED_USED_SHARED_LIBRARY;
18843                        }
18844                    }
18845                }
18846            }
18847
18848            info.origUsers = uninstalledPs.queryInstalledUsers(allUsers, true);
18849        }
18850
18851        final int freezeUser;
18852        if (isUpdatedSystemApp(uninstalledPs)
18853                && ((deleteFlags & PackageManager.DELETE_SYSTEM_APP) == 0)) {
18854            // We're downgrading a system app, which will apply to all users, so
18855            // freeze them all during the downgrade
18856            freezeUser = UserHandle.USER_ALL;
18857        } else {
18858            freezeUser = removeUser;
18859        }
18860
18861        synchronized (mInstallLock) {
18862            if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageX: pkg=" + packageName + " user=" + userId);
18863            try (PackageFreezer freezer = freezePackageForDelete(packageName, freezeUser,
18864                    deleteFlags, "deletePackageX")) {
18865                res = deletePackageLIF(packageName, UserHandle.of(removeUser), true, allUsers,
18866                        deleteFlags | FLAGS_REMOVE_CHATTY, info, true, null);
18867            }
18868            synchronized (mPackages) {
18869                if (res) {
18870                    if (pkg != null) {
18871                        mInstantAppRegistry.onPackageUninstalledLPw(pkg, info.removedUsers);
18872                    }
18873                    updateSequenceNumberLP(uninstalledPs, info.removedUsers);
18874                    updateInstantAppInstallerLocked(packageName);
18875                }
18876            }
18877        }
18878
18879        if (res) {
18880            final boolean killApp = (deleteFlags & PackageManager.DELETE_DONT_KILL_APP) == 0;
18881            info.sendPackageRemovedBroadcasts(killApp);
18882            info.sendSystemPackageUpdatedBroadcasts();
18883            info.sendSystemPackageAppearedBroadcasts();
18884        }
18885        // Force a gc here.
18886        Runtime.getRuntime().gc();
18887        // Delete the resources here after sending the broadcast to let
18888        // other processes clean up before deleting resources.
18889        if (info.args != null) {
18890            synchronized (mInstallLock) {
18891                info.args.doPostDeleteLI(true);
18892            }
18893        }
18894
18895        return res ? PackageManager.DELETE_SUCCEEDED : PackageManager.DELETE_FAILED_INTERNAL_ERROR;
18896    }
18897
18898    static class PackageRemovedInfo {
18899        final PackageSender packageSender;
18900        String removedPackage;
18901        String installerPackageName;
18902        int uid = -1;
18903        int removedAppId = -1;
18904        int[] origUsers;
18905        int[] removedUsers = null;
18906        int[] broadcastUsers = null;
18907        SparseArray<Integer> installReasons;
18908        boolean isRemovedPackageSystemUpdate = false;
18909        boolean isUpdate;
18910        boolean dataRemoved;
18911        boolean removedForAllUsers;
18912        boolean isStaticSharedLib;
18913        // Clean up resources deleted packages.
18914        InstallArgs args = null;
18915        ArrayMap<String, PackageRemovedInfo> removedChildPackages;
18916        ArrayMap<String, PackageInstalledInfo> appearedChildPackages;
18917
18918        PackageRemovedInfo(PackageSender packageSender) {
18919            this.packageSender = packageSender;
18920        }
18921
18922        void sendPackageRemovedBroadcasts(boolean killApp) {
18923            sendPackageRemovedBroadcastInternal(killApp);
18924            final int childCount = removedChildPackages != null ? removedChildPackages.size() : 0;
18925            for (int i = 0; i < childCount; i++) {
18926                PackageRemovedInfo childInfo = removedChildPackages.valueAt(i);
18927                childInfo.sendPackageRemovedBroadcastInternal(killApp);
18928            }
18929        }
18930
18931        void sendSystemPackageUpdatedBroadcasts() {
18932            if (isRemovedPackageSystemUpdate) {
18933                sendSystemPackageUpdatedBroadcastsInternal();
18934                final int childCount = (removedChildPackages != null)
18935                        ? removedChildPackages.size() : 0;
18936                for (int i = 0; i < childCount; i++) {
18937                    PackageRemovedInfo childInfo = removedChildPackages.valueAt(i);
18938                    if (childInfo.isRemovedPackageSystemUpdate) {
18939                        childInfo.sendSystemPackageUpdatedBroadcastsInternal();
18940                    }
18941                }
18942            }
18943        }
18944
18945        void sendSystemPackageAppearedBroadcasts() {
18946            final int packageCount = (appearedChildPackages != null)
18947                    ? appearedChildPackages.size() : 0;
18948            for (int i = 0; i < packageCount; i++) {
18949                PackageInstalledInfo installedInfo = appearedChildPackages.valueAt(i);
18950                packageSender.sendPackageAddedForNewUsers(installedInfo.name,
18951                    true, UserHandle.getAppId(installedInfo.uid),
18952                    installedInfo.newUsers);
18953            }
18954        }
18955
18956        private void sendSystemPackageUpdatedBroadcastsInternal() {
18957            Bundle extras = new Bundle(2);
18958            extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid);
18959            extras.putBoolean(Intent.EXTRA_REPLACING, true);
18960            packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
18961                removedPackage, extras, 0, null /*targetPackage*/, null, null);
18962            packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED,
18963                removedPackage, extras, 0, null /*targetPackage*/, null, null);
18964            packageSender.sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED,
18965                null, null, 0, removedPackage, null, null);
18966            if (installerPackageName != null) {
18967                packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
18968                        removedPackage, extras, 0 /*flags*/,
18969                        installerPackageName, null, null);
18970                packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED,
18971                        removedPackage, extras, 0 /*flags*/,
18972                        installerPackageName, null, null);
18973            }
18974        }
18975
18976        private void sendPackageRemovedBroadcastInternal(boolean killApp) {
18977            // Don't send static shared library removal broadcasts as these
18978            // libs are visible only the the apps that depend on them an one
18979            // cannot remove the library if it has a dependency.
18980            if (isStaticSharedLib) {
18981                return;
18982            }
18983            Bundle extras = new Bundle(2);
18984            extras.putInt(Intent.EXTRA_UID, removedAppId >= 0  ? removedAppId : uid);
18985            extras.putBoolean(Intent.EXTRA_DATA_REMOVED, dataRemoved);
18986            extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, !killApp);
18987            if (isUpdate || isRemovedPackageSystemUpdate) {
18988                extras.putBoolean(Intent.EXTRA_REPLACING, true);
18989            }
18990            extras.putBoolean(Intent.EXTRA_REMOVED_FOR_ALL_USERS, removedForAllUsers);
18991            if (removedPackage != null) {
18992                packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED,
18993                    removedPackage, extras, 0, null /*targetPackage*/, null, broadcastUsers);
18994                if (installerPackageName != null) {
18995                    packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED,
18996                            removedPackage, extras, 0 /*flags*/,
18997                            installerPackageName, null, broadcastUsers);
18998                }
18999                if (dataRemoved && !isRemovedPackageSystemUpdate) {
19000                    packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_FULLY_REMOVED,
19001                        removedPackage, extras,
19002                        Intent.FLAG_RECEIVER_INCLUDE_BACKGROUND,
19003                        null, null, broadcastUsers);
19004                }
19005            }
19006            if (removedAppId >= 0) {
19007                packageSender.sendPackageBroadcast(Intent.ACTION_UID_REMOVED,
19008                    null, extras, Intent.FLAG_RECEIVER_INCLUDE_BACKGROUND,
19009                    null, null, broadcastUsers);
19010            }
19011        }
19012
19013        void populateUsers(int[] userIds, PackageSetting deletedPackageSetting) {
19014            removedUsers = userIds;
19015            if (removedUsers == null) {
19016                broadcastUsers = null;
19017                return;
19018            }
19019
19020            broadcastUsers = EMPTY_INT_ARRAY;
19021            for (int i = userIds.length - 1; i >= 0; --i) {
19022                final int userId = userIds[i];
19023                if (deletedPackageSetting.getInstantApp(userId)) {
19024                    continue;
19025                }
19026                broadcastUsers = ArrayUtils.appendInt(broadcastUsers, userId);
19027            }
19028        }
19029    }
19030
19031    /*
19032     * This method deletes the package from internal data structures. If the DONT_DELETE_DATA
19033     * flag is not set, the data directory is removed as well.
19034     * make sure this flag is set for partially installed apps. If not its meaningless to
19035     * delete a partially installed application.
19036     */
19037    private void removePackageDataLIF(PackageSetting ps, int[] allUserHandles,
19038            PackageRemovedInfo outInfo, int flags, boolean writeSettings) {
19039        String packageName = ps.name;
19040        if (DEBUG_REMOVE) Slog.d(TAG, "removePackageDataLI: " + ps);
19041        // Retrieve object to delete permissions for shared user later on
19042        final PackageParser.Package deletedPkg;
19043        final PackageSetting deletedPs;
19044        // reader
19045        synchronized (mPackages) {
19046            deletedPkg = mPackages.get(packageName);
19047            deletedPs = mSettings.mPackages.get(packageName);
19048            if (outInfo != null) {
19049                outInfo.removedPackage = packageName;
19050                outInfo.installerPackageName = ps.installerPackageName;
19051                outInfo.isStaticSharedLib = deletedPkg != null
19052                        && deletedPkg.staticSharedLibName != null;
19053                outInfo.populateUsers(deletedPs == null ? null
19054                        : deletedPs.queryInstalledUsers(sUserManager.getUserIds(), true), deletedPs);
19055            }
19056        }
19057
19058        removePackageLI(ps, (flags & FLAGS_REMOVE_CHATTY) != 0);
19059
19060        if ((flags & PackageManager.DELETE_KEEP_DATA) == 0) {
19061            final PackageParser.Package resolvedPkg;
19062            if (deletedPkg != null) {
19063                resolvedPkg = deletedPkg;
19064            } else {
19065                // We don't have a parsed package when it lives on an ejected
19066                // adopted storage device, so fake something together
19067                resolvedPkg = new PackageParser.Package(ps.name);
19068                resolvedPkg.setVolumeUuid(ps.volumeUuid);
19069            }
19070            destroyAppDataLIF(resolvedPkg, UserHandle.USER_ALL,
19071                    StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
19072            destroyAppProfilesLIF(resolvedPkg, UserHandle.USER_ALL);
19073            if (outInfo != null) {
19074                outInfo.dataRemoved = true;
19075            }
19076            schedulePackageCleaning(packageName, UserHandle.USER_ALL, true);
19077        }
19078
19079        int removedAppId = -1;
19080
19081        // writer
19082        synchronized (mPackages) {
19083            boolean installedStateChanged = false;
19084            if (deletedPs != null) {
19085                if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) {
19086                    clearIntentFilterVerificationsLPw(deletedPs.name, UserHandle.USER_ALL);
19087                    clearDefaultBrowserIfNeeded(packageName);
19088                    mSettings.mKeySetManagerService.removeAppKeySetDataLPw(packageName);
19089                    removedAppId = mSettings.removePackageLPw(packageName);
19090                    if (outInfo != null) {
19091                        outInfo.removedAppId = removedAppId;
19092                    }
19093                    updatePermissionsLPw(deletedPs.name, null, 0);
19094                    if (deletedPs.sharedUser != null) {
19095                        // Remove permissions associated with package. Since runtime
19096                        // permissions are per user we have to kill the removed package
19097                        // or packages running under the shared user of the removed
19098                        // package if revoking the permissions requested only by the removed
19099                        // package is successful and this causes a change in gids.
19100                        for (int userId : UserManagerService.getInstance().getUserIds()) {
19101                            final int userIdToKill = mSettings.updateSharedUserPermsLPw(deletedPs,
19102                                    userId);
19103                            if (userIdToKill == UserHandle.USER_ALL
19104                                    || userIdToKill >= UserHandle.USER_SYSTEM) {
19105                                // If gids changed for this user, kill all affected packages.
19106                                mHandler.post(new Runnable() {
19107                                    @Override
19108                                    public void run() {
19109                                        // This has to happen with no lock held.
19110                                        killApplication(deletedPs.name, deletedPs.appId,
19111                                                KILL_APP_REASON_GIDS_CHANGED);
19112                                    }
19113                                });
19114                                break;
19115                            }
19116                        }
19117                    }
19118                    clearPackagePreferredActivitiesLPw(deletedPs.name, UserHandle.USER_ALL);
19119                }
19120                // make sure to preserve per-user disabled state if this removal was just
19121                // a downgrade of a system app to the factory package
19122                if (allUserHandles != null && outInfo != null && outInfo.origUsers != null) {
19123                    if (DEBUG_REMOVE) {
19124                        Slog.d(TAG, "Propagating install state across downgrade");
19125                    }
19126                    for (int userId : allUserHandles) {
19127                        final boolean installed = ArrayUtils.contains(outInfo.origUsers, userId);
19128                        if (DEBUG_REMOVE) {
19129                            Slog.d(TAG, "    user " + userId + " => " + installed);
19130                        }
19131                        if (installed != ps.getInstalled(userId)) {
19132                            installedStateChanged = true;
19133                        }
19134                        ps.setInstalled(installed, userId);
19135                    }
19136                }
19137            }
19138            // can downgrade to reader
19139            if (writeSettings) {
19140                // Save settings now
19141                mSettings.writeLPr();
19142            }
19143            if (installedStateChanged) {
19144                mSettings.writeKernelMappingLPr(ps);
19145            }
19146        }
19147        if (removedAppId != -1) {
19148            // A user ID was deleted here. Go through all users and remove it
19149            // from KeyStore.
19150            removeKeystoreDataIfNeeded(UserHandle.USER_ALL, removedAppId);
19151        }
19152    }
19153
19154    static boolean locationIsPrivileged(File path) {
19155        try {
19156            final String privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app")
19157                    .getCanonicalPath();
19158            return path.getCanonicalPath().startsWith(privilegedAppDir);
19159        } catch (IOException e) {
19160            Slog.e(TAG, "Unable to access code path " + path);
19161        }
19162        return false;
19163    }
19164
19165    /*
19166     * Tries to delete system package.
19167     */
19168    private boolean deleteSystemPackageLIF(PackageParser.Package deletedPkg,
19169            PackageSetting deletedPs, int[] allUserHandles, int flags, PackageRemovedInfo outInfo,
19170            boolean writeSettings) {
19171        if (deletedPs.parentPackageName != null) {
19172            Slog.w(TAG, "Attempt to delete child system package " + deletedPkg.packageName);
19173            return false;
19174        }
19175
19176        final boolean applyUserRestrictions
19177                = (allUserHandles != null) && (outInfo.origUsers != null);
19178        final PackageSetting disabledPs;
19179        // Confirm if the system package has been updated
19180        // An updated system app can be deleted. This will also have to restore
19181        // the system pkg from system partition
19182        // reader
19183        synchronized (mPackages) {
19184            disabledPs = mSettings.getDisabledSystemPkgLPr(deletedPs.name);
19185        }
19186
19187        if (DEBUG_REMOVE) Slog.d(TAG, "deleteSystemPackageLI: newPs=" + deletedPkg.packageName
19188                + " disabledPs=" + disabledPs);
19189
19190        if (disabledPs == null) {
19191            Slog.w(TAG, "Attempt to delete unknown system package "+ deletedPkg.packageName);
19192            return false;
19193        } else if (DEBUG_REMOVE) {
19194            Slog.d(TAG, "Deleting system pkg from data partition");
19195        }
19196
19197        if (DEBUG_REMOVE) {
19198            if (applyUserRestrictions) {
19199                Slog.d(TAG, "Remembering install states:");
19200                for (int userId : allUserHandles) {
19201                    final boolean finstalled = ArrayUtils.contains(outInfo.origUsers, userId);
19202                    Slog.d(TAG, "   u=" + userId + " inst=" + finstalled);
19203                }
19204            }
19205        }
19206
19207        // Delete the updated package
19208        outInfo.isRemovedPackageSystemUpdate = true;
19209        if (outInfo.removedChildPackages != null) {
19210            final int childCount = (deletedPs.childPackageNames != null)
19211                    ? deletedPs.childPackageNames.size() : 0;
19212            for (int i = 0; i < childCount; i++) {
19213                String childPackageName = deletedPs.childPackageNames.get(i);
19214                if (disabledPs.childPackageNames != null && disabledPs.childPackageNames
19215                        .contains(childPackageName)) {
19216                    PackageRemovedInfo childInfo = outInfo.removedChildPackages.get(
19217                            childPackageName);
19218                    if (childInfo != null) {
19219                        childInfo.isRemovedPackageSystemUpdate = true;
19220                    }
19221                }
19222            }
19223        }
19224
19225        if (disabledPs.versionCode < deletedPs.versionCode) {
19226            // Delete data for downgrades
19227            flags &= ~PackageManager.DELETE_KEEP_DATA;
19228        } else {
19229            // Preserve data by setting flag
19230            flags |= PackageManager.DELETE_KEEP_DATA;
19231        }
19232
19233        boolean ret = deleteInstalledPackageLIF(deletedPs, true, flags, allUserHandles,
19234                outInfo, writeSettings, disabledPs.pkg);
19235        if (!ret) {
19236            return false;
19237        }
19238
19239        // writer
19240        synchronized (mPackages) {
19241            // Reinstate the old system package
19242            enableSystemPackageLPw(disabledPs.pkg);
19243            // Remove any native libraries from the upgraded package.
19244            removeNativeBinariesLI(deletedPs);
19245        }
19246
19247        // Install the system package
19248        if (DEBUG_REMOVE) Slog.d(TAG, "Re-installing system package: " + disabledPs);
19249        int parseFlags = mDefParseFlags
19250                | PackageParser.PARSE_MUST_BE_APK
19251                | PackageParser.PARSE_IS_SYSTEM
19252                | PackageParser.PARSE_IS_SYSTEM_DIR;
19253        if (locationIsPrivileged(disabledPs.codePath)) {
19254            parseFlags |= PackageParser.PARSE_IS_PRIVILEGED;
19255        }
19256
19257        final PackageParser.Package newPkg;
19258        try {
19259            newPkg = scanPackageTracedLI(disabledPs.codePath, parseFlags, 0 /* scanFlags */,
19260                0 /* currentTime */, null);
19261        } catch (PackageManagerException e) {
19262            Slog.w(TAG, "Failed to restore system package:" + deletedPkg.packageName + ": "
19263                    + e.getMessage());
19264            return false;
19265        }
19266
19267        try {
19268            // update shared libraries for the newly re-installed system package
19269            updateSharedLibrariesLPr(newPkg, null);
19270        } catch (PackageManagerException e) {
19271            Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
19272        }
19273
19274        prepareAppDataAfterInstallLIF(newPkg);
19275
19276        // writer
19277        synchronized (mPackages) {
19278            PackageSetting ps = mSettings.mPackages.get(newPkg.packageName);
19279
19280            // Propagate the permissions state as we do not want to drop on the floor
19281            // runtime permissions. The update permissions method below will take
19282            // care of removing obsolete permissions and grant install permissions.
19283            ps.getPermissionsState().copyFrom(deletedPs.getPermissionsState());
19284            updatePermissionsLPw(newPkg.packageName, newPkg,
19285                    UPDATE_PERMISSIONS_ALL | UPDATE_PERMISSIONS_REPLACE_PKG);
19286
19287            if (applyUserRestrictions) {
19288                boolean installedStateChanged = false;
19289                if (DEBUG_REMOVE) {
19290                    Slog.d(TAG, "Propagating install state across reinstall");
19291                }
19292                for (int userId : allUserHandles) {
19293                    final boolean installed = ArrayUtils.contains(outInfo.origUsers, userId);
19294                    if (DEBUG_REMOVE) {
19295                        Slog.d(TAG, "    user " + userId + " => " + installed);
19296                    }
19297                    if (installed != ps.getInstalled(userId)) {
19298                        installedStateChanged = true;
19299                    }
19300                    ps.setInstalled(installed, userId);
19301
19302                    mSettings.writeRuntimePermissionsForUserLPr(userId, false);
19303                }
19304                // Regardless of writeSettings we need to ensure that this restriction
19305                // state propagation is persisted
19306                mSettings.writeAllUsersPackageRestrictionsLPr();
19307                if (installedStateChanged) {
19308                    mSettings.writeKernelMappingLPr(ps);
19309                }
19310            }
19311            // can downgrade to reader here
19312            if (writeSettings) {
19313                mSettings.writeLPr();
19314            }
19315        }
19316        return true;
19317    }
19318
19319    private boolean deleteInstalledPackageLIF(PackageSetting ps,
19320            boolean deleteCodeAndResources, int flags, int[] allUserHandles,
19321            PackageRemovedInfo outInfo, boolean writeSettings,
19322            PackageParser.Package replacingPackage) {
19323        synchronized (mPackages) {
19324            if (outInfo != null) {
19325                outInfo.uid = ps.appId;
19326            }
19327
19328            if (outInfo != null && outInfo.removedChildPackages != null) {
19329                final int childCount = (ps.childPackageNames != null)
19330                        ? ps.childPackageNames.size() : 0;
19331                for (int i = 0; i < childCount; i++) {
19332                    String childPackageName = ps.childPackageNames.get(i);
19333                    PackageSetting childPs = mSettings.mPackages.get(childPackageName);
19334                    if (childPs == null) {
19335                        return false;
19336                    }
19337                    PackageRemovedInfo childInfo = outInfo.removedChildPackages.get(
19338                            childPackageName);
19339                    if (childInfo != null) {
19340                        childInfo.uid = childPs.appId;
19341                    }
19342                }
19343            }
19344        }
19345
19346        // Delete package data from internal structures and also remove data if flag is set
19347        removePackageDataLIF(ps, allUserHandles, outInfo, flags, writeSettings);
19348
19349        // Delete the child packages data
19350        final int childCount = (ps.childPackageNames != null) ? ps.childPackageNames.size() : 0;
19351        for (int i = 0; i < childCount; i++) {
19352            PackageSetting childPs;
19353            synchronized (mPackages) {
19354                childPs = mSettings.getPackageLPr(ps.childPackageNames.get(i));
19355            }
19356            if (childPs != null) {
19357                PackageRemovedInfo childOutInfo = (outInfo != null
19358                        && outInfo.removedChildPackages != null)
19359                        ? outInfo.removedChildPackages.get(childPs.name) : null;
19360                final int deleteFlags = (flags & DELETE_KEEP_DATA) != 0
19361                        && (replacingPackage != null
19362                        && !replacingPackage.hasChildPackage(childPs.name))
19363                        ? flags & ~DELETE_KEEP_DATA : flags;
19364                removePackageDataLIF(childPs, allUserHandles, childOutInfo,
19365                        deleteFlags, writeSettings);
19366            }
19367        }
19368
19369        // Delete application code and resources only for parent packages
19370        if (ps.parentPackageName == null) {
19371            if (deleteCodeAndResources && (outInfo != null)) {
19372                outInfo.args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
19373                        ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
19374                if (DEBUG_SD_INSTALL) Slog.i(TAG, "args=" + outInfo.args);
19375            }
19376        }
19377
19378        return true;
19379    }
19380
19381    @Override
19382    public boolean setBlockUninstallForUser(String packageName, boolean blockUninstall,
19383            int userId) {
19384        mContext.enforceCallingOrSelfPermission(
19385                android.Manifest.permission.DELETE_PACKAGES, null);
19386        synchronized (mPackages) {
19387            // Cannot block uninstall of static shared libs as they are
19388            // considered a part of the using app (emulating static linking).
19389            // Also static libs are installed always on internal storage.
19390            PackageParser.Package pkg = mPackages.get(packageName);
19391            if (pkg != null && pkg.staticSharedLibName != null) {
19392                Slog.w(TAG, "Cannot block uninstall of package: " + packageName
19393                        + " providing static shared library: " + pkg.staticSharedLibName);
19394                return false;
19395            }
19396            mSettings.setBlockUninstallLPw(userId, packageName, blockUninstall);
19397            mSettings.writePackageRestrictionsLPr(userId);
19398        }
19399        return true;
19400    }
19401
19402    @Override
19403    public boolean getBlockUninstallForUser(String packageName, int userId) {
19404        synchronized (mPackages) {
19405            final PackageSetting ps = mSettings.mPackages.get(packageName);
19406            if (ps == null || filterAppAccessLPr(ps, Binder.getCallingUid(), userId)) {
19407                return false;
19408            }
19409            return mSettings.getBlockUninstallLPr(userId, packageName);
19410        }
19411    }
19412
19413    @Override
19414    public boolean setRequiredForSystemUser(String packageName, boolean systemUserApp) {
19415        enforceSystemOrRoot("setRequiredForSystemUser can only be run by the system or root");
19416        synchronized (mPackages) {
19417            PackageSetting ps = mSettings.mPackages.get(packageName);
19418            if (ps == null) {
19419                Log.w(TAG, "Package doesn't exist: " + packageName);
19420                return false;
19421            }
19422            if (systemUserApp) {
19423                ps.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_REQUIRED_FOR_SYSTEM_USER;
19424            } else {
19425                ps.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_REQUIRED_FOR_SYSTEM_USER;
19426            }
19427            mSettings.writeLPr();
19428        }
19429        return true;
19430    }
19431
19432    /*
19433     * This method handles package deletion in general
19434     */
19435    private boolean deletePackageLIF(String packageName, UserHandle user,
19436            boolean deleteCodeAndResources, int[] allUserHandles, int flags,
19437            PackageRemovedInfo outInfo, boolean writeSettings,
19438            PackageParser.Package replacingPackage) {
19439        if (packageName == null) {
19440            Slog.w(TAG, "Attempt to delete null packageName.");
19441            return false;
19442        }
19443
19444        if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageLI: " + packageName + " user " + user);
19445
19446        PackageSetting ps;
19447        synchronized (mPackages) {
19448            ps = mSettings.mPackages.get(packageName);
19449            if (ps == null) {
19450                Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
19451                return false;
19452            }
19453
19454            if (ps.parentPackageName != null && (!isSystemApp(ps)
19455                    || (flags & PackageManager.DELETE_SYSTEM_APP) != 0)) {
19456                if (DEBUG_REMOVE) {
19457                    Slog.d(TAG, "Uninstalled child package:" + packageName + " for user:"
19458                            + ((user == null) ? UserHandle.USER_ALL : user));
19459                }
19460                final int removedUserId = (user != null) ? user.getIdentifier()
19461                        : UserHandle.USER_ALL;
19462                if (!clearPackageStateForUserLIF(ps, removedUserId, outInfo)) {
19463                    return false;
19464                }
19465                markPackageUninstalledForUserLPw(ps, user);
19466                scheduleWritePackageRestrictionsLocked(user);
19467                return true;
19468            }
19469        }
19470
19471        if (((!isSystemApp(ps) || (flags&PackageManager.DELETE_SYSTEM_APP) != 0) && user != null
19472                && user.getIdentifier() != UserHandle.USER_ALL)) {
19473            // The caller is asking that the package only be deleted for a single
19474            // user.  To do this, we just mark its uninstalled state and delete
19475            // its data. If this is a system app, we only allow this to happen if
19476            // they have set the special DELETE_SYSTEM_APP which requests different
19477            // semantics than normal for uninstalling system apps.
19478            markPackageUninstalledForUserLPw(ps, user);
19479
19480            if (!isSystemApp(ps)) {
19481                // Do not uninstall the APK if an app should be cached
19482                boolean keepUninstalledPackage = shouldKeepUninstalledPackageLPr(packageName);
19483                if (ps.isAnyInstalled(sUserManager.getUserIds()) || keepUninstalledPackage) {
19484                    // Other user still have this package installed, so all
19485                    // we need to do is clear this user's data and save that
19486                    // it is uninstalled.
19487                    if (DEBUG_REMOVE) Slog.d(TAG, "Still installed by other users");
19488                    if (!clearPackageStateForUserLIF(ps, user.getIdentifier(), outInfo)) {
19489                        return false;
19490                    }
19491                    scheduleWritePackageRestrictionsLocked(user);
19492                    return true;
19493                } else {
19494                    // We need to set it back to 'installed' so the uninstall
19495                    // broadcasts will be sent correctly.
19496                    if (DEBUG_REMOVE) Slog.d(TAG, "Not installed by other users, full delete");
19497                    ps.setInstalled(true, user.getIdentifier());
19498                    mSettings.writeKernelMappingLPr(ps);
19499                }
19500            } else {
19501                // This is a system app, so we assume that the
19502                // other users still have this package installed, so all
19503                // we need to do is clear this user's data and save that
19504                // it is uninstalled.
19505                if (DEBUG_REMOVE) Slog.d(TAG, "Deleting system app");
19506                if (!clearPackageStateForUserLIF(ps, user.getIdentifier(), outInfo)) {
19507                    return false;
19508                }
19509                scheduleWritePackageRestrictionsLocked(user);
19510                return true;
19511            }
19512        }
19513
19514        // If we are deleting a composite package for all users, keep track
19515        // of result for each child.
19516        if (ps.childPackageNames != null && outInfo != null) {
19517            synchronized (mPackages) {
19518                final int childCount = ps.childPackageNames.size();
19519                outInfo.removedChildPackages = new ArrayMap<>(childCount);
19520                for (int i = 0; i < childCount; i++) {
19521                    String childPackageName = ps.childPackageNames.get(i);
19522                    PackageRemovedInfo childInfo = new PackageRemovedInfo(this);
19523                    childInfo.removedPackage = childPackageName;
19524                    childInfo.installerPackageName = ps.installerPackageName;
19525                    outInfo.removedChildPackages.put(childPackageName, childInfo);
19526                    PackageSetting childPs = mSettings.getPackageLPr(childPackageName);
19527                    if (childPs != null) {
19528                        childInfo.origUsers = childPs.queryInstalledUsers(allUserHandles, true);
19529                    }
19530                }
19531            }
19532        }
19533
19534        boolean ret = false;
19535        if (isSystemApp(ps)) {
19536            if (DEBUG_REMOVE) Slog.d(TAG, "Removing system package: " + ps.name);
19537            // When an updated system application is deleted we delete the existing resources
19538            // as well and fall back to existing code in system partition
19539            ret = deleteSystemPackageLIF(ps.pkg, ps, allUserHandles, flags, outInfo, writeSettings);
19540        } else {
19541            if (DEBUG_REMOVE) Slog.d(TAG, "Removing non-system package: " + ps.name);
19542            ret = deleteInstalledPackageLIF(ps, deleteCodeAndResources, flags, allUserHandles,
19543                    outInfo, writeSettings, replacingPackage);
19544        }
19545
19546        // Take a note whether we deleted the package for all users
19547        if (outInfo != null) {
19548            outInfo.removedForAllUsers = mPackages.get(ps.name) == null;
19549            if (outInfo.removedChildPackages != null) {
19550                synchronized (mPackages) {
19551                    final int childCount = outInfo.removedChildPackages.size();
19552                    for (int i = 0; i < childCount; i++) {
19553                        PackageRemovedInfo childInfo = outInfo.removedChildPackages.valueAt(i);
19554                        if (childInfo != null) {
19555                            childInfo.removedForAllUsers = mPackages.get(
19556                                    childInfo.removedPackage) == null;
19557                        }
19558                    }
19559                }
19560            }
19561            // If we uninstalled an update to a system app there may be some
19562            // child packages that appeared as they are declared in the system
19563            // app but were not declared in the update.
19564            if (isSystemApp(ps)) {
19565                synchronized (mPackages) {
19566                    PackageSetting updatedPs = mSettings.getPackageLPr(ps.name);
19567                    final int childCount = (updatedPs.childPackageNames != null)
19568                            ? updatedPs.childPackageNames.size() : 0;
19569                    for (int i = 0; i < childCount; i++) {
19570                        String childPackageName = updatedPs.childPackageNames.get(i);
19571                        if (outInfo.removedChildPackages == null
19572                                || outInfo.removedChildPackages.indexOfKey(childPackageName) < 0) {
19573                            PackageSetting childPs = mSettings.getPackageLPr(childPackageName);
19574                            if (childPs == null) {
19575                                continue;
19576                            }
19577                            PackageInstalledInfo installRes = new PackageInstalledInfo();
19578                            installRes.name = childPackageName;
19579                            installRes.newUsers = childPs.queryInstalledUsers(allUserHandles, true);
19580                            installRes.pkg = mPackages.get(childPackageName);
19581                            installRes.uid = childPs.pkg.applicationInfo.uid;
19582                            if (outInfo.appearedChildPackages == null) {
19583                                outInfo.appearedChildPackages = new ArrayMap<>();
19584                            }
19585                            outInfo.appearedChildPackages.put(childPackageName, installRes);
19586                        }
19587                    }
19588                }
19589            }
19590        }
19591
19592        return ret;
19593    }
19594
19595    private void markPackageUninstalledForUserLPw(PackageSetting ps, UserHandle user) {
19596        final int[] userIds = (user == null || user.getIdentifier() == UserHandle.USER_ALL)
19597                ? sUserManager.getUserIds() : new int[] {user.getIdentifier()};
19598        for (int nextUserId : userIds) {
19599            if (DEBUG_REMOVE) {
19600                Slog.d(TAG, "Marking package:" + ps.name + " uninstalled for user:" + nextUserId);
19601            }
19602            ps.setUserState(nextUserId, 0, COMPONENT_ENABLED_STATE_DEFAULT,
19603                    false /*installed*/,
19604                    true /*stopped*/,
19605                    true /*notLaunched*/,
19606                    false /*hidden*/,
19607                    false /*suspended*/,
19608                    false /*instantApp*/,
19609                    null /*lastDisableAppCaller*/,
19610                    null /*enabledComponents*/,
19611                    null /*disabledComponents*/,
19612                    ps.readUserState(nextUserId).domainVerificationStatus,
19613                    0, PackageManager.INSTALL_REASON_UNKNOWN);
19614        }
19615        mSettings.writeKernelMappingLPr(ps);
19616    }
19617
19618    private boolean clearPackageStateForUserLIF(PackageSetting ps, int userId,
19619            PackageRemovedInfo outInfo) {
19620        final PackageParser.Package pkg;
19621        synchronized (mPackages) {
19622            pkg = mPackages.get(ps.name);
19623        }
19624
19625        final int[] userIds = (userId == UserHandle.USER_ALL) ? sUserManager.getUserIds()
19626                : new int[] {userId};
19627        for (int nextUserId : userIds) {
19628            if (DEBUG_REMOVE) {
19629                Slog.d(TAG, "Updating package:" + ps.name + " install state for user:"
19630                        + nextUserId);
19631            }
19632
19633            destroyAppDataLIF(pkg, userId,
19634                    StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
19635            destroyAppProfilesLIF(pkg, userId);
19636            clearDefaultBrowserIfNeededForUser(ps.name, userId);
19637            removeKeystoreDataIfNeeded(nextUserId, ps.appId);
19638            schedulePackageCleaning(ps.name, nextUserId, false);
19639            synchronized (mPackages) {
19640                if (clearPackagePreferredActivitiesLPw(ps.name, nextUserId)) {
19641                    scheduleWritePackageRestrictionsLocked(nextUserId);
19642                }
19643                resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, nextUserId);
19644            }
19645        }
19646
19647        if (outInfo != null) {
19648            outInfo.removedPackage = ps.name;
19649            outInfo.installerPackageName = ps.installerPackageName;
19650            outInfo.isStaticSharedLib = pkg != null && pkg.staticSharedLibName != null;
19651            outInfo.removedAppId = ps.appId;
19652            outInfo.removedUsers = userIds;
19653            outInfo.broadcastUsers = userIds;
19654        }
19655
19656        return true;
19657    }
19658
19659    private final class ClearStorageConnection implements ServiceConnection {
19660        IMediaContainerService mContainerService;
19661
19662        @Override
19663        public void onServiceConnected(ComponentName name, IBinder service) {
19664            synchronized (this) {
19665                mContainerService = IMediaContainerService.Stub
19666                        .asInterface(Binder.allowBlocking(service));
19667                notifyAll();
19668            }
19669        }
19670
19671        @Override
19672        public void onServiceDisconnected(ComponentName name) {
19673        }
19674    }
19675
19676    private void clearExternalStorageDataSync(String packageName, int userId, boolean allData) {
19677        if (DEFAULT_CONTAINER_PACKAGE.equals(packageName)) return;
19678
19679        final boolean mounted;
19680        if (Environment.isExternalStorageEmulated()) {
19681            mounted = true;
19682        } else {
19683            final String status = Environment.getExternalStorageState();
19684
19685            mounted = status.equals(Environment.MEDIA_MOUNTED)
19686                    || status.equals(Environment.MEDIA_MOUNTED_READ_ONLY);
19687        }
19688
19689        if (!mounted) {
19690            return;
19691        }
19692
19693        final Intent containerIntent = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
19694        int[] users;
19695        if (userId == UserHandle.USER_ALL) {
19696            users = sUserManager.getUserIds();
19697        } else {
19698            users = new int[] { userId };
19699        }
19700        final ClearStorageConnection conn = new ClearStorageConnection();
19701        if (mContext.bindServiceAsUser(
19702                containerIntent, conn, Context.BIND_AUTO_CREATE, UserHandle.SYSTEM)) {
19703            try {
19704                for (int curUser : users) {
19705                    long timeout = SystemClock.uptimeMillis() + 5000;
19706                    synchronized (conn) {
19707                        long now;
19708                        while (conn.mContainerService == null &&
19709                                (now = SystemClock.uptimeMillis()) < timeout) {
19710                            try {
19711                                conn.wait(timeout - now);
19712                            } catch (InterruptedException e) {
19713                            }
19714                        }
19715                    }
19716                    if (conn.mContainerService == null) {
19717                        return;
19718                    }
19719
19720                    final UserEnvironment userEnv = new UserEnvironment(curUser);
19721                    clearDirectory(conn.mContainerService,
19722                            userEnv.buildExternalStorageAppCacheDirs(packageName));
19723                    if (allData) {
19724                        clearDirectory(conn.mContainerService,
19725                                userEnv.buildExternalStorageAppDataDirs(packageName));
19726                        clearDirectory(conn.mContainerService,
19727                                userEnv.buildExternalStorageAppMediaDirs(packageName));
19728                    }
19729                }
19730            } finally {
19731                mContext.unbindService(conn);
19732            }
19733        }
19734    }
19735
19736    @Override
19737    public void clearApplicationProfileData(String packageName) {
19738        enforceSystemOrRoot("Only the system can clear all profile data");
19739
19740        final PackageParser.Package pkg;
19741        synchronized (mPackages) {
19742            pkg = mPackages.get(packageName);
19743        }
19744
19745        try (PackageFreezer freezer = freezePackage(packageName, "clearApplicationProfileData")) {
19746            synchronized (mInstallLock) {
19747                clearAppProfilesLIF(pkg, UserHandle.USER_ALL);
19748            }
19749        }
19750    }
19751
19752    @Override
19753    public void clearApplicationUserData(final String packageName,
19754            final IPackageDataObserver observer, final int userId) {
19755        mContext.enforceCallingOrSelfPermission(
19756                android.Manifest.permission.CLEAR_APP_USER_DATA, null);
19757
19758        final int callingUid = Binder.getCallingUid();
19759        enforceCrossUserPermission(callingUid, userId,
19760                true /* requireFullPermission */, false /* checkShell */, "clear application data");
19761
19762        final PackageSetting ps = mSettings.getPackageLPr(packageName);
19763        if (ps != null && filterAppAccessLPr(ps, callingUid, userId)) {
19764            return;
19765        }
19766        if (mProtectedPackages.isPackageDataProtected(userId, packageName)) {
19767            throw new SecurityException("Cannot clear data for a protected package: "
19768                    + packageName);
19769        }
19770        // Queue up an async operation since the package deletion may take a little while.
19771        mHandler.post(new Runnable() {
19772            public void run() {
19773                mHandler.removeCallbacks(this);
19774                final boolean succeeded;
19775                try (PackageFreezer freezer = freezePackage(packageName,
19776                        "clearApplicationUserData")) {
19777                    synchronized (mInstallLock) {
19778                        succeeded = clearApplicationUserDataLIF(packageName, userId);
19779                    }
19780                    clearExternalStorageDataSync(packageName, userId, true);
19781                    synchronized (mPackages) {
19782                        mInstantAppRegistry.deleteInstantApplicationMetadataLPw(
19783                                packageName, userId);
19784                    }
19785                }
19786                if (succeeded) {
19787                    // invoke DeviceStorageMonitor's update method to clear any notifications
19788                    DeviceStorageMonitorInternal dsm = LocalServices
19789                            .getService(DeviceStorageMonitorInternal.class);
19790                    if (dsm != null) {
19791                        dsm.checkMemory();
19792                    }
19793                }
19794                if(observer != null) {
19795                    try {
19796                        observer.onRemoveCompleted(packageName, succeeded);
19797                    } catch (RemoteException e) {
19798                        Log.i(TAG, "Observer no longer exists.");
19799                    }
19800                } //end if observer
19801            } //end run
19802        });
19803    }
19804
19805    private boolean clearApplicationUserDataLIF(String packageName, int userId) {
19806        if (packageName == null) {
19807            Slog.w(TAG, "Attempt to delete null packageName.");
19808            return false;
19809        }
19810
19811        // Try finding details about the requested package
19812        PackageParser.Package pkg;
19813        synchronized (mPackages) {
19814            pkg = mPackages.get(packageName);
19815            if (pkg == null) {
19816                final PackageSetting ps = mSettings.mPackages.get(packageName);
19817                if (ps != null) {
19818                    pkg = ps.pkg;
19819                }
19820            }
19821
19822            if (pkg == null) {
19823                Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
19824                return false;
19825            }
19826
19827            PackageSetting ps = (PackageSetting) pkg.mExtras;
19828            resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
19829        }
19830
19831        clearAppDataLIF(pkg, userId,
19832                StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
19833
19834        final int appId = UserHandle.getAppId(pkg.applicationInfo.uid);
19835        removeKeystoreDataIfNeeded(userId, appId);
19836
19837        UserManagerInternal umInternal = getUserManagerInternal();
19838        final int flags;
19839        if (umInternal.isUserUnlockingOrUnlocked(userId)) {
19840            flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
19841        } else if (umInternal.isUserRunning(userId)) {
19842            flags = StorageManager.FLAG_STORAGE_DE;
19843        } else {
19844            flags = 0;
19845        }
19846        prepareAppDataContentsLIF(pkg, userId, flags);
19847
19848        return true;
19849    }
19850
19851    /**
19852     * Reverts user permission state changes (permissions and flags) in
19853     * all packages for a given user.
19854     *
19855     * @param userId The device user for which to do a reset.
19856     */
19857    private void resetUserChangesToRuntimePermissionsAndFlagsLPw(int userId) {
19858        final int packageCount = mPackages.size();
19859        for (int i = 0; i < packageCount; i++) {
19860            PackageParser.Package pkg = mPackages.valueAt(i);
19861            PackageSetting ps = (PackageSetting) pkg.mExtras;
19862            resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
19863        }
19864    }
19865
19866    private void resetNetworkPolicies(int userId) {
19867        LocalServices.getService(NetworkPolicyManagerInternal.class).resetUserState(userId);
19868    }
19869
19870    /**
19871     * Reverts user permission state changes (permissions and flags).
19872     *
19873     * @param ps The package for which to reset.
19874     * @param userId The device user for which to do a reset.
19875     */
19876    private void resetUserChangesToRuntimePermissionsAndFlagsLPw(
19877            final PackageSetting ps, final int userId) {
19878        if (ps.pkg == null) {
19879            return;
19880        }
19881
19882        // These are flags that can change base on user actions.
19883        final int userSettableMask = FLAG_PERMISSION_USER_SET
19884                | FLAG_PERMISSION_USER_FIXED
19885                | FLAG_PERMISSION_REVOKE_ON_UPGRADE
19886                | FLAG_PERMISSION_REVIEW_REQUIRED;
19887
19888        final int policyOrSystemFlags = FLAG_PERMISSION_SYSTEM_FIXED
19889                | FLAG_PERMISSION_POLICY_FIXED;
19890
19891        boolean writeInstallPermissions = false;
19892        boolean writeRuntimePermissions = false;
19893
19894        final int permissionCount = ps.pkg.requestedPermissions.size();
19895        for (int i = 0; i < permissionCount; i++) {
19896            String permission = ps.pkg.requestedPermissions.get(i);
19897
19898            BasePermission bp = mSettings.mPermissions.get(permission);
19899            if (bp == null) {
19900                continue;
19901            }
19902
19903            // If shared user we just reset the state to which only this app contributed.
19904            if (ps.sharedUser != null) {
19905                boolean used = false;
19906                final int packageCount = ps.sharedUser.packages.size();
19907                for (int j = 0; j < packageCount; j++) {
19908                    PackageSetting pkg = ps.sharedUser.packages.valueAt(j);
19909                    if (pkg.pkg != null && !pkg.pkg.packageName.equals(ps.pkg.packageName)
19910                            && pkg.pkg.requestedPermissions.contains(permission)) {
19911                        used = true;
19912                        break;
19913                    }
19914                }
19915                if (used) {
19916                    continue;
19917                }
19918            }
19919
19920            PermissionsState permissionsState = ps.getPermissionsState();
19921
19922            final int oldFlags = permissionsState.getPermissionFlags(bp.name, userId);
19923
19924            // Always clear the user settable flags.
19925            final boolean hasInstallState = permissionsState.getInstallPermissionState(
19926                    bp.name) != null;
19927            // If permission review is enabled and this is a legacy app, mark the
19928            // permission as requiring a review as this is the initial state.
19929            int flags = 0;
19930            if (mPermissionReviewRequired
19931                    && ps.pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) {
19932                flags |= FLAG_PERMISSION_REVIEW_REQUIRED;
19933            }
19934            if (permissionsState.updatePermissionFlags(bp, userId, userSettableMask, flags)) {
19935                if (hasInstallState) {
19936                    writeInstallPermissions = true;
19937                } else {
19938                    writeRuntimePermissions = true;
19939                }
19940            }
19941
19942            // Below is only runtime permission handling.
19943            if (!bp.isRuntime()) {
19944                continue;
19945            }
19946
19947            // Never clobber system or policy.
19948            if ((oldFlags & policyOrSystemFlags) != 0) {
19949                continue;
19950            }
19951
19952            // If this permission was granted by default, make sure it is.
19953            if ((oldFlags & FLAG_PERMISSION_GRANTED_BY_DEFAULT) != 0) {
19954                if (permissionsState.grantRuntimePermission(bp, userId)
19955                        != PERMISSION_OPERATION_FAILURE) {
19956                    writeRuntimePermissions = true;
19957                }
19958            // If permission review is enabled the permissions for a legacy apps
19959            // are represented as constantly granted runtime ones, so don't revoke.
19960            } else if ((flags & FLAG_PERMISSION_REVIEW_REQUIRED) == 0) {
19961                // Otherwise, reset the permission.
19962                final int revokeResult = permissionsState.revokeRuntimePermission(bp, userId);
19963                switch (revokeResult) {
19964                    case PERMISSION_OPERATION_SUCCESS:
19965                    case PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: {
19966                        writeRuntimePermissions = true;
19967                        final int appId = ps.appId;
19968                        mHandler.post(new Runnable() {
19969                            @Override
19970                            public void run() {
19971                                killUid(appId, userId, KILL_APP_REASON_PERMISSIONS_REVOKED);
19972                            }
19973                        });
19974                    } break;
19975                }
19976            }
19977        }
19978
19979        // Synchronously write as we are taking permissions away.
19980        if (writeRuntimePermissions) {
19981            mSettings.writeRuntimePermissionsForUserLPr(userId, true);
19982        }
19983
19984        // Synchronously write as we are taking permissions away.
19985        if (writeInstallPermissions) {
19986            mSettings.writeLPr();
19987        }
19988    }
19989
19990    /**
19991     * Remove entries from the keystore daemon. Will only remove it if the
19992     * {@code appId} is valid.
19993     */
19994    private static void removeKeystoreDataIfNeeded(int userId, int appId) {
19995        if (appId < 0) {
19996            return;
19997        }
19998
19999        final KeyStore keyStore = KeyStore.getInstance();
20000        if (keyStore != null) {
20001            if (userId == UserHandle.USER_ALL) {
20002                for (final int individual : sUserManager.getUserIds()) {
20003                    keyStore.clearUid(UserHandle.getUid(individual, appId));
20004                }
20005            } else {
20006                keyStore.clearUid(UserHandle.getUid(userId, appId));
20007            }
20008        } else {
20009            Slog.w(TAG, "Could not contact keystore to clear entries for app id " + appId);
20010        }
20011    }
20012
20013    @Override
20014    public void deleteApplicationCacheFiles(final String packageName,
20015            final IPackageDataObserver observer) {
20016        final int userId = UserHandle.getCallingUserId();
20017        deleteApplicationCacheFilesAsUser(packageName, userId, observer);
20018    }
20019
20020    @Override
20021    public void deleteApplicationCacheFilesAsUser(final String packageName, final int userId,
20022            final IPackageDataObserver observer) {
20023        final int callingUid = Binder.getCallingUid();
20024        mContext.enforceCallingOrSelfPermission(
20025                android.Manifest.permission.DELETE_CACHE_FILES, null);
20026        enforceCrossUserPermission(callingUid, userId,
20027                /* requireFullPermission= */ true, /* checkShell= */ false,
20028                "delete application cache files");
20029        final int hasAccessInstantApps = mContext.checkCallingOrSelfPermission(
20030                android.Manifest.permission.ACCESS_INSTANT_APPS);
20031
20032        final PackageParser.Package pkg;
20033        synchronized (mPackages) {
20034            pkg = mPackages.get(packageName);
20035        }
20036
20037        // Queue up an async operation since the package deletion may take a little while.
20038        mHandler.post(new Runnable() {
20039            public void run() {
20040                final PackageSetting ps = (PackageSetting) pkg.mExtras;
20041                boolean doClearData = true;
20042                if (ps != null) {
20043                    final boolean targetIsInstantApp =
20044                            ps.getInstantApp(UserHandle.getUserId(callingUid));
20045                    doClearData = !targetIsInstantApp
20046                            || hasAccessInstantApps == PackageManager.PERMISSION_GRANTED;
20047                }
20048                if (doClearData) {
20049                    synchronized (mInstallLock) {
20050                        final int flags = StorageManager.FLAG_STORAGE_DE
20051                                | StorageManager.FLAG_STORAGE_CE;
20052                        // We're only clearing cache files, so we don't care if the
20053                        // app is unfrozen and still able to run
20054                        clearAppDataLIF(pkg, userId, flags | Installer.FLAG_CLEAR_CACHE_ONLY);
20055                        clearAppDataLIF(pkg, userId, flags | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
20056                    }
20057                    clearExternalStorageDataSync(packageName, userId, false);
20058                }
20059                if (observer != null) {
20060                    try {
20061                        observer.onRemoveCompleted(packageName, true);
20062                    } catch (RemoteException e) {
20063                        Log.i(TAG, "Observer no longer exists.");
20064                    }
20065                }
20066            }
20067        });
20068    }
20069
20070    @Override
20071    public void getPackageSizeInfo(final String packageName, int userHandle,
20072            final IPackageStatsObserver observer) {
20073        throw new UnsupportedOperationException(
20074                "Shame on you for calling the hidden API getPackageSizeInfo(). Shame!");
20075    }
20076
20077    private boolean getPackageSizeInfoLI(String packageName, int userId, PackageStats stats) {
20078        final PackageSetting ps;
20079        synchronized (mPackages) {
20080            ps = mSettings.mPackages.get(packageName);
20081            if (ps == null) {
20082                Slog.w(TAG, "Failed to find settings for " + packageName);
20083                return false;
20084            }
20085        }
20086
20087        final String[] packageNames = { packageName };
20088        final long[] ceDataInodes = { ps.getCeDataInode(userId) };
20089        final String[] codePaths = { ps.codePathString };
20090
20091        try {
20092            mInstaller.getAppSize(ps.volumeUuid, packageNames, userId, 0,
20093                    ps.appId, ceDataInodes, codePaths, stats);
20094
20095            // For now, ignore code size of packages on system partition
20096            if (isSystemApp(ps) && !isUpdatedSystemApp(ps)) {
20097                stats.codeSize = 0;
20098            }
20099
20100            // External clients expect these to be tracked separately
20101            stats.dataSize -= stats.cacheSize;
20102
20103        } catch (InstallerException e) {
20104            Slog.w(TAG, String.valueOf(e));
20105            return false;
20106        }
20107
20108        return true;
20109    }
20110
20111    private int getUidTargetSdkVersionLockedLPr(int uid) {
20112        Object obj = mSettings.getUserIdLPr(uid);
20113        if (obj instanceof SharedUserSetting) {
20114            final SharedUserSetting sus = (SharedUserSetting) obj;
20115            int vers = Build.VERSION_CODES.CUR_DEVELOPMENT;
20116            final Iterator<PackageSetting> it = sus.packages.iterator();
20117            while (it.hasNext()) {
20118                final PackageSetting ps = it.next();
20119                if (ps.pkg != null) {
20120                    int v = ps.pkg.applicationInfo.targetSdkVersion;
20121                    if (v < vers) vers = v;
20122                }
20123            }
20124            return vers;
20125        } else if (obj instanceof PackageSetting) {
20126            final PackageSetting ps = (PackageSetting) obj;
20127            if (ps.pkg != null) {
20128                return ps.pkg.applicationInfo.targetSdkVersion;
20129            }
20130        }
20131        return Build.VERSION_CODES.CUR_DEVELOPMENT;
20132    }
20133
20134    @Override
20135    public void addPreferredActivity(IntentFilter filter, int match,
20136            ComponentName[] set, ComponentName activity, int userId) {
20137        addPreferredActivityInternal(filter, match, set, activity, true, userId,
20138                "Adding preferred");
20139    }
20140
20141    private void addPreferredActivityInternal(IntentFilter filter, int match,
20142            ComponentName[] set, ComponentName activity, boolean always, int userId,
20143            String opname) {
20144        // writer
20145        int callingUid = Binder.getCallingUid();
20146        enforceCrossUserPermission(callingUid, userId,
20147                true /* requireFullPermission */, false /* checkShell */, "add preferred activity");
20148        if (filter.countActions() == 0) {
20149            Slog.w(TAG, "Cannot set a preferred activity with no filter actions");
20150            return;
20151        }
20152        synchronized (mPackages) {
20153            if (mContext.checkCallingOrSelfPermission(
20154                    android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
20155                    != PackageManager.PERMISSION_GRANTED) {
20156                if (getUidTargetSdkVersionLockedLPr(callingUid)
20157                        < Build.VERSION_CODES.FROYO) {
20158                    Slog.w(TAG, "Ignoring addPreferredActivity() from uid "
20159                            + callingUid);
20160                    return;
20161                }
20162                mContext.enforceCallingOrSelfPermission(
20163                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
20164            }
20165
20166            PreferredIntentResolver pir = mSettings.editPreferredActivitiesLPw(userId);
20167            Slog.i(TAG, opname + " activity " + activity.flattenToShortString() + " for user "
20168                    + userId + ":");
20169            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
20170            pir.addFilter(new PreferredActivity(filter, match, set, activity, always));
20171            scheduleWritePackageRestrictionsLocked(userId);
20172            postPreferredActivityChangedBroadcast(userId);
20173        }
20174    }
20175
20176    private void postPreferredActivityChangedBroadcast(int userId) {
20177        mHandler.post(() -> {
20178            final IActivityManager am = ActivityManager.getService();
20179            if (am == null) {
20180                return;
20181            }
20182
20183            final Intent intent = new Intent(Intent.ACTION_PREFERRED_ACTIVITY_CHANGED);
20184            intent.putExtra(Intent.EXTRA_USER_HANDLE, userId);
20185            try {
20186                am.broadcastIntent(null, intent, null, null,
20187                        0, null, null, null, android.app.AppOpsManager.OP_NONE,
20188                        null, false, false, userId);
20189            } catch (RemoteException e) {
20190            }
20191        });
20192    }
20193
20194    @Override
20195    public void replacePreferredActivity(IntentFilter filter, int match,
20196            ComponentName[] set, ComponentName activity, int userId) {
20197        if (filter.countActions() != 1) {
20198            throw new IllegalArgumentException(
20199                    "replacePreferredActivity expects filter to have only 1 action.");
20200        }
20201        if (filter.countDataAuthorities() != 0
20202                || filter.countDataPaths() != 0
20203                || filter.countDataSchemes() > 1
20204                || filter.countDataTypes() != 0) {
20205            throw new IllegalArgumentException(
20206                    "replacePreferredActivity expects filter to have no data authorities, " +
20207                    "paths, or types; and at most one scheme.");
20208        }
20209
20210        final int callingUid = Binder.getCallingUid();
20211        enforceCrossUserPermission(callingUid, userId,
20212                true /* requireFullPermission */, false /* checkShell */,
20213                "replace preferred activity");
20214        synchronized (mPackages) {
20215            if (mContext.checkCallingOrSelfPermission(
20216                    android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
20217                    != PackageManager.PERMISSION_GRANTED) {
20218                if (getUidTargetSdkVersionLockedLPr(callingUid)
20219                        < Build.VERSION_CODES.FROYO) {
20220                    Slog.w(TAG, "Ignoring replacePreferredActivity() from uid "
20221                            + Binder.getCallingUid());
20222                    return;
20223                }
20224                mContext.enforceCallingOrSelfPermission(
20225                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
20226            }
20227
20228            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
20229            if (pir != null) {
20230                // Get all of the existing entries that exactly match this filter.
20231                ArrayList<PreferredActivity> existing = pir.findFilters(filter);
20232                if (existing != null && existing.size() == 1) {
20233                    PreferredActivity cur = existing.get(0);
20234                    if (DEBUG_PREFERRED) {
20235                        Slog.i(TAG, "Checking replace of preferred:");
20236                        filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
20237                        if (!cur.mPref.mAlways) {
20238                            Slog.i(TAG, "  -- CUR; not mAlways!");
20239                        } else {
20240                            Slog.i(TAG, "  -- CUR: mMatch=" + cur.mPref.mMatch);
20241                            Slog.i(TAG, "  -- CUR: mSet="
20242                                    + Arrays.toString(cur.mPref.mSetComponents));
20243                            Slog.i(TAG, "  -- CUR: mComponent=" + cur.mPref.mShortComponent);
20244                            Slog.i(TAG, "  -- NEW: mMatch="
20245                                    + (match&IntentFilter.MATCH_CATEGORY_MASK));
20246                            Slog.i(TAG, "  -- CUR: mSet=" + Arrays.toString(set));
20247                            Slog.i(TAG, "  -- CUR: mComponent=" + activity.flattenToShortString());
20248                        }
20249                    }
20250                    if (cur.mPref.mAlways && cur.mPref.mComponent.equals(activity)
20251                            && cur.mPref.mMatch == (match&IntentFilter.MATCH_CATEGORY_MASK)
20252                            && cur.mPref.sameSet(set)) {
20253                        // Setting the preferred activity to what it happens to be already
20254                        if (DEBUG_PREFERRED) {
20255                            Slog.i(TAG, "Replacing with same preferred activity "
20256                                    + cur.mPref.mShortComponent + " for user "
20257                                    + userId + ":");
20258                            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
20259                        }
20260                        return;
20261                    }
20262                }
20263
20264                if (existing != null) {
20265                    if (DEBUG_PREFERRED) {
20266                        Slog.i(TAG, existing.size() + " existing preferred matches for:");
20267                        filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
20268                    }
20269                    for (int i = 0; i < existing.size(); i++) {
20270                        PreferredActivity pa = existing.get(i);
20271                        if (DEBUG_PREFERRED) {
20272                            Slog.i(TAG, "Removing existing preferred activity "
20273                                    + pa.mPref.mComponent + ":");
20274                            pa.dump(new LogPrinter(Log.INFO, TAG), "  ");
20275                        }
20276                        pir.removeFilter(pa);
20277                    }
20278                }
20279            }
20280            addPreferredActivityInternal(filter, match, set, activity, true, userId,
20281                    "Replacing preferred");
20282        }
20283    }
20284
20285    @Override
20286    public void clearPackagePreferredActivities(String packageName) {
20287        final int callingUid = Binder.getCallingUid();
20288        if (getInstantAppPackageName(callingUid) != null) {
20289            return;
20290        }
20291        // writer
20292        synchronized (mPackages) {
20293            PackageParser.Package pkg = mPackages.get(packageName);
20294            if (pkg == null || pkg.applicationInfo.uid != callingUid) {
20295                if (mContext.checkCallingOrSelfPermission(
20296                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
20297                        != PackageManager.PERMISSION_GRANTED) {
20298                    if (getUidTargetSdkVersionLockedLPr(callingUid)
20299                            < Build.VERSION_CODES.FROYO) {
20300                        Slog.w(TAG, "Ignoring clearPackagePreferredActivities() from uid "
20301                                + callingUid);
20302                        return;
20303                    }
20304                    mContext.enforceCallingOrSelfPermission(
20305                            android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
20306                }
20307            }
20308            final PackageSetting ps = mSettings.getPackageLPr(packageName);
20309            if (ps != null
20310                    && filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
20311                return;
20312            }
20313            int user = UserHandle.getCallingUserId();
20314            if (clearPackagePreferredActivitiesLPw(packageName, user)) {
20315                scheduleWritePackageRestrictionsLocked(user);
20316            }
20317        }
20318    }
20319
20320    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
20321    boolean clearPackagePreferredActivitiesLPw(String packageName, int userId) {
20322        ArrayList<PreferredActivity> removed = null;
20323        boolean changed = false;
20324        for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
20325            final int thisUserId = mSettings.mPreferredActivities.keyAt(i);
20326            PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
20327            if (userId != UserHandle.USER_ALL && userId != thisUserId) {
20328                continue;
20329            }
20330            Iterator<PreferredActivity> it = pir.filterIterator();
20331            while (it.hasNext()) {
20332                PreferredActivity pa = it.next();
20333                // Mark entry for removal only if it matches the package name
20334                // and the entry is of type "always".
20335                if (packageName == null ||
20336                        (pa.mPref.mComponent.getPackageName().equals(packageName)
20337                                && pa.mPref.mAlways)) {
20338                    if (removed == null) {
20339                        removed = new ArrayList<PreferredActivity>();
20340                    }
20341                    removed.add(pa);
20342                }
20343            }
20344            if (removed != null) {
20345                for (int j=0; j<removed.size(); j++) {
20346                    PreferredActivity pa = removed.get(j);
20347                    pir.removeFilter(pa);
20348                }
20349                changed = true;
20350            }
20351        }
20352        if (changed) {
20353            postPreferredActivityChangedBroadcast(userId);
20354        }
20355        return changed;
20356    }
20357
20358    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
20359    private void clearIntentFilterVerificationsLPw(int userId) {
20360        final int packageCount = mPackages.size();
20361        for (int i = 0; i < packageCount; i++) {
20362            PackageParser.Package pkg = mPackages.valueAt(i);
20363            clearIntentFilterVerificationsLPw(pkg.packageName, userId);
20364        }
20365    }
20366
20367    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
20368    void clearIntentFilterVerificationsLPw(String packageName, int userId) {
20369        if (userId == UserHandle.USER_ALL) {
20370            if (mSettings.removeIntentFilterVerificationLPw(packageName,
20371                    sUserManager.getUserIds())) {
20372                for (int oneUserId : sUserManager.getUserIds()) {
20373                    scheduleWritePackageRestrictionsLocked(oneUserId);
20374                }
20375            }
20376        } else {
20377            if (mSettings.removeIntentFilterVerificationLPw(packageName, userId)) {
20378                scheduleWritePackageRestrictionsLocked(userId);
20379            }
20380        }
20381    }
20382
20383    /** Clears state for all users, and touches intent filter verification policy */
20384    void clearDefaultBrowserIfNeeded(String packageName) {
20385        for (int oneUserId : sUserManager.getUserIds()) {
20386            clearDefaultBrowserIfNeededForUser(packageName, oneUserId);
20387        }
20388    }
20389
20390    private void clearDefaultBrowserIfNeededForUser(String packageName, int userId) {
20391        final String defaultBrowserPackageName = getDefaultBrowserPackageName(userId);
20392        if (!TextUtils.isEmpty(defaultBrowserPackageName)) {
20393            if (packageName.equals(defaultBrowserPackageName)) {
20394                setDefaultBrowserPackageName(null, userId);
20395            }
20396        }
20397    }
20398
20399    @Override
20400    public void resetApplicationPreferences(int userId) {
20401        mContext.enforceCallingOrSelfPermission(
20402                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
20403        final long identity = Binder.clearCallingIdentity();
20404        // writer
20405        try {
20406            synchronized (mPackages) {
20407                clearPackagePreferredActivitiesLPw(null, userId);
20408                mSettings.applyDefaultPreferredAppsLPw(this, userId);
20409                // TODO: We have to reset the default SMS and Phone. This requires
20410                // significant refactoring to keep all default apps in the package
20411                // manager (cleaner but more work) or have the services provide
20412                // callbacks to the package manager to request a default app reset.
20413                applyFactoryDefaultBrowserLPw(userId);
20414                clearIntentFilterVerificationsLPw(userId);
20415                primeDomainVerificationsLPw(userId);
20416                resetUserChangesToRuntimePermissionsAndFlagsLPw(userId);
20417                scheduleWritePackageRestrictionsLocked(userId);
20418            }
20419            resetNetworkPolicies(userId);
20420        } finally {
20421            Binder.restoreCallingIdentity(identity);
20422        }
20423    }
20424
20425    @Override
20426    public int getPreferredActivities(List<IntentFilter> outFilters,
20427            List<ComponentName> outActivities, String packageName) {
20428        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
20429            return 0;
20430        }
20431        int num = 0;
20432        final int userId = UserHandle.getCallingUserId();
20433        // reader
20434        synchronized (mPackages) {
20435            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
20436            if (pir != null) {
20437                final Iterator<PreferredActivity> it = pir.filterIterator();
20438                while (it.hasNext()) {
20439                    final PreferredActivity pa = it.next();
20440                    if (packageName == null
20441                            || (pa.mPref.mComponent.getPackageName().equals(packageName)
20442                                    && pa.mPref.mAlways)) {
20443                        if (outFilters != null) {
20444                            outFilters.add(new IntentFilter(pa));
20445                        }
20446                        if (outActivities != null) {
20447                            outActivities.add(pa.mPref.mComponent);
20448                        }
20449                    }
20450                }
20451            }
20452        }
20453
20454        return num;
20455    }
20456
20457    @Override
20458    public void addPersistentPreferredActivity(IntentFilter filter, ComponentName activity,
20459            int userId) {
20460        int callingUid = Binder.getCallingUid();
20461        if (callingUid != Process.SYSTEM_UID) {
20462            throw new SecurityException(
20463                    "addPersistentPreferredActivity can only be run by the system");
20464        }
20465        if (filter.countActions() == 0) {
20466            Slog.w(TAG, "Cannot set a preferred activity with no filter actions");
20467            return;
20468        }
20469        synchronized (mPackages) {
20470            Slog.i(TAG, "Adding persistent preferred activity " + activity + " for user " + userId +
20471                    ":");
20472            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
20473            mSettings.editPersistentPreferredActivitiesLPw(userId).addFilter(
20474                    new PersistentPreferredActivity(filter, activity));
20475            scheduleWritePackageRestrictionsLocked(userId);
20476            postPreferredActivityChangedBroadcast(userId);
20477        }
20478    }
20479
20480    @Override
20481    public void clearPackagePersistentPreferredActivities(String packageName, int userId) {
20482        int callingUid = Binder.getCallingUid();
20483        if (callingUid != Process.SYSTEM_UID) {
20484            throw new SecurityException(
20485                    "clearPackagePersistentPreferredActivities can only be run by the system");
20486        }
20487        ArrayList<PersistentPreferredActivity> removed = null;
20488        boolean changed = false;
20489        synchronized (mPackages) {
20490            for (int i=0; i<mSettings.mPersistentPreferredActivities.size(); i++) {
20491                final int thisUserId = mSettings.mPersistentPreferredActivities.keyAt(i);
20492                PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities
20493                        .valueAt(i);
20494                if (userId != thisUserId) {
20495                    continue;
20496                }
20497                Iterator<PersistentPreferredActivity> it = ppir.filterIterator();
20498                while (it.hasNext()) {
20499                    PersistentPreferredActivity ppa = it.next();
20500                    // Mark entry for removal only if it matches the package name.
20501                    if (ppa.mComponent.getPackageName().equals(packageName)) {
20502                        if (removed == null) {
20503                            removed = new ArrayList<PersistentPreferredActivity>();
20504                        }
20505                        removed.add(ppa);
20506                    }
20507                }
20508                if (removed != null) {
20509                    for (int j=0; j<removed.size(); j++) {
20510                        PersistentPreferredActivity ppa = removed.get(j);
20511                        ppir.removeFilter(ppa);
20512                    }
20513                    changed = true;
20514                }
20515            }
20516
20517            if (changed) {
20518                scheduleWritePackageRestrictionsLocked(userId);
20519                postPreferredActivityChangedBroadcast(userId);
20520            }
20521        }
20522    }
20523
20524    /**
20525     * Common machinery for picking apart a restored XML blob and passing
20526     * it to a caller-supplied functor to be applied to the running system.
20527     */
20528    private void restoreFromXml(XmlPullParser parser, int userId,
20529            String expectedStartTag, BlobXmlRestorer functor)
20530            throws IOException, XmlPullParserException {
20531        int type;
20532        while ((type = parser.next()) != XmlPullParser.START_TAG
20533                && type != XmlPullParser.END_DOCUMENT) {
20534        }
20535        if (type != XmlPullParser.START_TAG) {
20536            // oops didn't find a start tag?!
20537            if (DEBUG_BACKUP) {
20538                Slog.e(TAG, "Didn't find start tag during restore");
20539            }
20540            return;
20541        }
20542Slog.v(TAG, ":: restoreFromXml() : got to tag " + parser.getName());
20543        // this is supposed to be TAG_PREFERRED_BACKUP
20544        if (!expectedStartTag.equals(parser.getName())) {
20545            if (DEBUG_BACKUP) {
20546                Slog.e(TAG, "Found unexpected tag " + parser.getName());
20547            }
20548            return;
20549        }
20550
20551        // skip interfering stuff, then we're aligned with the backing implementation
20552        while ((type = parser.next()) == XmlPullParser.TEXT) { }
20553Slog.v(TAG, ":: stepped forward, applying functor at tag " + parser.getName());
20554        functor.apply(parser, userId);
20555    }
20556
20557    private interface BlobXmlRestorer {
20558        public void apply(XmlPullParser parser, int userId) throws IOException, XmlPullParserException;
20559    }
20560
20561    /**
20562     * Non-Binder method, support for the backup/restore mechanism: write the
20563     * full set of preferred activities in its canonical XML format.  Returns the
20564     * XML output as a byte array, or null if there is none.
20565     */
20566    @Override
20567    public byte[] getPreferredActivityBackup(int userId) {
20568        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
20569            throw new SecurityException("Only the system may call getPreferredActivityBackup()");
20570        }
20571
20572        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
20573        try {
20574            final XmlSerializer serializer = new FastXmlSerializer();
20575            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
20576            serializer.startDocument(null, true);
20577            serializer.startTag(null, TAG_PREFERRED_BACKUP);
20578
20579            synchronized (mPackages) {
20580                mSettings.writePreferredActivitiesLPr(serializer, userId, true);
20581            }
20582
20583            serializer.endTag(null, TAG_PREFERRED_BACKUP);
20584            serializer.endDocument();
20585            serializer.flush();
20586        } catch (Exception e) {
20587            if (DEBUG_BACKUP) {
20588                Slog.e(TAG, "Unable to write preferred activities for backup", e);
20589            }
20590            return null;
20591        }
20592
20593        return dataStream.toByteArray();
20594    }
20595
20596    @Override
20597    public void restorePreferredActivities(byte[] backup, int userId) {
20598        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
20599            throw new SecurityException("Only the system may call restorePreferredActivities()");
20600        }
20601
20602        try {
20603            final XmlPullParser parser = Xml.newPullParser();
20604            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
20605            restoreFromXml(parser, userId, TAG_PREFERRED_BACKUP,
20606                    new BlobXmlRestorer() {
20607                        @Override
20608                        public void apply(XmlPullParser parser, int userId)
20609                                throws XmlPullParserException, IOException {
20610                            synchronized (mPackages) {
20611                                mSettings.readPreferredActivitiesLPw(parser, userId);
20612                            }
20613                        }
20614                    } );
20615        } catch (Exception e) {
20616            if (DEBUG_BACKUP) {
20617                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
20618            }
20619        }
20620    }
20621
20622    /**
20623     * Non-Binder method, support for the backup/restore mechanism: write the
20624     * default browser (etc) settings in its canonical XML format.  Returns the default
20625     * browser XML representation as a byte array, or null if there is none.
20626     */
20627    @Override
20628    public byte[] getDefaultAppsBackup(int userId) {
20629        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
20630            throw new SecurityException("Only the system may call getDefaultAppsBackup()");
20631        }
20632
20633        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
20634        try {
20635            final XmlSerializer serializer = new FastXmlSerializer();
20636            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
20637            serializer.startDocument(null, true);
20638            serializer.startTag(null, TAG_DEFAULT_APPS);
20639
20640            synchronized (mPackages) {
20641                mSettings.writeDefaultAppsLPr(serializer, userId);
20642            }
20643
20644            serializer.endTag(null, TAG_DEFAULT_APPS);
20645            serializer.endDocument();
20646            serializer.flush();
20647        } catch (Exception e) {
20648            if (DEBUG_BACKUP) {
20649                Slog.e(TAG, "Unable to write default apps for backup", e);
20650            }
20651            return null;
20652        }
20653
20654        return dataStream.toByteArray();
20655    }
20656
20657    @Override
20658    public void restoreDefaultApps(byte[] backup, int userId) {
20659        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
20660            throw new SecurityException("Only the system may call restoreDefaultApps()");
20661        }
20662
20663        try {
20664            final XmlPullParser parser = Xml.newPullParser();
20665            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
20666            restoreFromXml(parser, userId, TAG_DEFAULT_APPS,
20667                    new BlobXmlRestorer() {
20668                        @Override
20669                        public void apply(XmlPullParser parser, int userId)
20670                                throws XmlPullParserException, IOException {
20671                            synchronized (mPackages) {
20672                                mSettings.readDefaultAppsLPw(parser, userId);
20673                            }
20674                        }
20675                    } );
20676        } catch (Exception e) {
20677            if (DEBUG_BACKUP) {
20678                Slog.e(TAG, "Exception restoring default apps: " + e.getMessage());
20679            }
20680        }
20681    }
20682
20683    @Override
20684    public byte[] getIntentFilterVerificationBackup(int userId) {
20685        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
20686            throw new SecurityException("Only the system may call getIntentFilterVerificationBackup()");
20687        }
20688
20689        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
20690        try {
20691            final XmlSerializer serializer = new FastXmlSerializer();
20692            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
20693            serializer.startDocument(null, true);
20694            serializer.startTag(null, TAG_INTENT_FILTER_VERIFICATION);
20695
20696            synchronized (mPackages) {
20697                mSettings.writeAllDomainVerificationsLPr(serializer, userId);
20698            }
20699
20700            serializer.endTag(null, TAG_INTENT_FILTER_VERIFICATION);
20701            serializer.endDocument();
20702            serializer.flush();
20703        } catch (Exception e) {
20704            if (DEBUG_BACKUP) {
20705                Slog.e(TAG, "Unable to write default apps for backup", e);
20706            }
20707            return null;
20708        }
20709
20710        return dataStream.toByteArray();
20711    }
20712
20713    @Override
20714    public void restoreIntentFilterVerification(byte[] backup, int userId) {
20715        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
20716            throw new SecurityException("Only the system may call restorePreferredActivities()");
20717        }
20718
20719        try {
20720            final XmlPullParser parser = Xml.newPullParser();
20721            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
20722            restoreFromXml(parser, userId, TAG_INTENT_FILTER_VERIFICATION,
20723                    new BlobXmlRestorer() {
20724                        @Override
20725                        public void apply(XmlPullParser parser, int userId)
20726                                throws XmlPullParserException, IOException {
20727                            synchronized (mPackages) {
20728                                mSettings.readAllDomainVerificationsLPr(parser, userId);
20729                                mSettings.writeLPr();
20730                            }
20731                        }
20732                    } );
20733        } catch (Exception e) {
20734            if (DEBUG_BACKUP) {
20735                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
20736            }
20737        }
20738    }
20739
20740    @Override
20741    public byte[] getPermissionGrantBackup(int userId) {
20742        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
20743            throw new SecurityException("Only the system may call getPermissionGrantBackup()");
20744        }
20745
20746        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
20747        try {
20748            final XmlSerializer serializer = new FastXmlSerializer();
20749            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
20750            serializer.startDocument(null, true);
20751            serializer.startTag(null, TAG_PERMISSION_BACKUP);
20752
20753            synchronized (mPackages) {
20754                serializeRuntimePermissionGrantsLPr(serializer, userId);
20755            }
20756
20757            serializer.endTag(null, TAG_PERMISSION_BACKUP);
20758            serializer.endDocument();
20759            serializer.flush();
20760        } catch (Exception e) {
20761            if (DEBUG_BACKUP) {
20762                Slog.e(TAG, "Unable to write default apps for backup", e);
20763            }
20764            return null;
20765        }
20766
20767        return dataStream.toByteArray();
20768    }
20769
20770    @Override
20771    public void restorePermissionGrants(byte[] backup, int userId) {
20772        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
20773            throw new SecurityException("Only the system may call restorePermissionGrants()");
20774        }
20775
20776        try {
20777            final XmlPullParser parser = Xml.newPullParser();
20778            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
20779            restoreFromXml(parser, userId, TAG_PERMISSION_BACKUP,
20780                    new BlobXmlRestorer() {
20781                        @Override
20782                        public void apply(XmlPullParser parser, int userId)
20783                                throws XmlPullParserException, IOException {
20784                            synchronized (mPackages) {
20785                                processRestoredPermissionGrantsLPr(parser, userId);
20786                            }
20787                        }
20788                    } );
20789        } catch (Exception e) {
20790            if (DEBUG_BACKUP) {
20791                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
20792            }
20793        }
20794    }
20795
20796    private void serializeRuntimePermissionGrantsLPr(XmlSerializer serializer, final int userId)
20797            throws IOException {
20798        serializer.startTag(null, TAG_ALL_GRANTS);
20799
20800        final int N = mSettings.mPackages.size();
20801        for (int i = 0; i < N; i++) {
20802            final PackageSetting ps = mSettings.mPackages.valueAt(i);
20803            boolean pkgGrantsKnown = false;
20804
20805            PermissionsState packagePerms = ps.getPermissionsState();
20806
20807            for (PermissionState state : packagePerms.getRuntimePermissionStates(userId)) {
20808                final int grantFlags = state.getFlags();
20809                // only look at grants that are not system/policy fixed
20810                if ((grantFlags & SYSTEM_RUNTIME_GRANT_MASK) == 0) {
20811                    final boolean isGranted = state.isGranted();
20812                    // And only back up the user-twiddled state bits
20813                    if (isGranted || (grantFlags & USER_RUNTIME_GRANT_MASK) != 0) {
20814                        final String packageName = mSettings.mPackages.keyAt(i);
20815                        if (!pkgGrantsKnown) {
20816                            serializer.startTag(null, TAG_GRANT);
20817                            serializer.attribute(null, ATTR_PACKAGE_NAME, packageName);
20818                            pkgGrantsKnown = true;
20819                        }
20820
20821                        final boolean userSet =
20822                                (grantFlags & FLAG_PERMISSION_USER_SET) != 0;
20823                        final boolean userFixed =
20824                                (grantFlags & FLAG_PERMISSION_USER_FIXED) != 0;
20825                        final boolean revoke =
20826                                (grantFlags & FLAG_PERMISSION_REVOKE_ON_UPGRADE) != 0;
20827
20828                        serializer.startTag(null, TAG_PERMISSION);
20829                        serializer.attribute(null, ATTR_PERMISSION_NAME, state.getName());
20830                        if (isGranted) {
20831                            serializer.attribute(null, ATTR_IS_GRANTED, "true");
20832                        }
20833                        if (userSet) {
20834                            serializer.attribute(null, ATTR_USER_SET, "true");
20835                        }
20836                        if (userFixed) {
20837                            serializer.attribute(null, ATTR_USER_FIXED, "true");
20838                        }
20839                        if (revoke) {
20840                            serializer.attribute(null, ATTR_REVOKE_ON_UPGRADE, "true");
20841                        }
20842                        serializer.endTag(null, TAG_PERMISSION);
20843                    }
20844                }
20845            }
20846
20847            if (pkgGrantsKnown) {
20848                serializer.endTag(null, TAG_GRANT);
20849            }
20850        }
20851
20852        serializer.endTag(null, TAG_ALL_GRANTS);
20853    }
20854
20855    private void processRestoredPermissionGrantsLPr(XmlPullParser parser, int userId)
20856            throws XmlPullParserException, IOException {
20857        String pkgName = null;
20858        int outerDepth = parser.getDepth();
20859        int type;
20860        while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
20861                && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) {
20862            if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) {
20863                continue;
20864            }
20865
20866            final String tagName = parser.getName();
20867            if (tagName.equals(TAG_GRANT)) {
20868                pkgName = parser.getAttributeValue(null, ATTR_PACKAGE_NAME);
20869                if (DEBUG_BACKUP) {
20870                    Slog.v(TAG, "+++ Restoring grants for package " + pkgName);
20871                }
20872            } else if (tagName.equals(TAG_PERMISSION)) {
20873
20874                final boolean isGranted = "true".equals(parser.getAttributeValue(null, ATTR_IS_GRANTED));
20875                final String permName = parser.getAttributeValue(null, ATTR_PERMISSION_NAME);
20876
20877                int newFlagSet = 0;
20878                if ("true".equals(parser.getAttributeValue(null, ATTR_USER_SET))) {
20879                    newFlagSet |= FLAG_PERMISSION_USER_SET;
20880                }
20881                if ("true".equals(parser.getAttributeValue(null, ATTR_USER_FIXED))) {
20882                    newFlagSet |= FLAG_PERMISSION_USER_FIXED;
20883                }
20884                if ("true".equals(parser.getAttributeValue(null, ATTR_REVOKE_ON_UPGRADE))) {
20885                    newFlagSet |= FLAG_PERMISSION_REVOKE_ON_UPGRADE;
20886                }
20887                if (DEBUG_BACKUP) {
20888                    Slog.v(TAG, "  + Restoring grant: pkg=" + pkgName + " perm=" + permName
20889                            + " granted=" + isGranted + " bits=0x" + Integer.toHexString(newFlagSet));
20890                }
20891                final PackageSetting ps = mSettings.mPackages.get(pkgName);
20892                if (ps != null) {
20893                    // Already installed so we apply the grant immediately
20894                    if (DEBUG_BACKUP) {
20895                        Slog.v(TAG, "        + already installed; applying");
20896                    }
20897                    PermissionsState perms = ps.getPermissionsState();
20898                    BasePermission bp = mSettings.mPermissions.get(permName);
20899                    if (bp != null) {
20900                        if (isGranted) {
20901                            perms.grantRuntimePermission(bp, userId);
20902                        }
20903                        if (newFlagSet != 0) {
20904                            perms.updatePermissionFlags(bp, userId, USER_RUNTIME_GRANT_MASK, newFlagSet);
20905                        }
20906                    }
20907                } else {
20908                    // Need to wait for post-restore install to apply the grant
20909                    if (DEBUG_BACKUP) {
20910                        Slog.v(TAG, "        - not yet installed; saving for later");
20911                    }
20912                    mSettings.processRestoredPermissionGrantLPr(pkgName, permName,
20913                            isGranted, newFlagSet, userId);
20914                }
20915            } else {
20916                PackageManagerService.reportSettingsProblem(Log.WARN,
20917                        "Unknown element under <" + TAG_PERMISSION_BACKUP + ">: " + tagName);
20918                XmlUtils.skipCurrentTag(parser);
20919            }
20920        }
20921
20922        scheduleWriteSettingsLocked();
20923        mSettings.writeRuntimePermissionsForUserLPr(userId, false);
20924    }
20925
20926    @Override
20927    public void addCrossProfileIntentFilter(IntentFilter intentFilter, String ownerPackage,
20928            int sourceUserId, int targetUserId, int flags) {
20929        mContext.enforceCallingOrSelfPermission(
20930                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
20931        int callingUid = Binder.getCallingUid();
20932        enforceOwnerRights(ownerPackage, callingUid);
20933        enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId);
20934        if (intentFilter.countActions() == 0) {
20935            Slog.w(TAG, "Cannot set a crossProfile intent filter with no filter actions");
20936            return;
20937        }
20938        synchronized (mPackages) {
20939            CrossProfileIntentFilter newFilter = new CrossProfileIntentFilter(intentFilter,
20940                    ownerPackage, targetUserId, flags);
20941            CrossProfileIntentResolver resolver =
20942                    mSettings.editCrossProfileIntentResolverLPw(sourceUserId);
20943            ArrayList<CrossProfileIntentFilter> existing = resolver.findFilters(intentFilter);
20944            // We have all those whose filter is equal. Now checking if the rest is equal as well.
20945            if (existing != null) {
20946                int size = existing.size();
20947                for (int i = 0; i < size; i++) {
20948                    if (newFilter.equalsIgnoreFilter(existing.get(i))) {
20949                        return;
20950                    }
20951                }
20952            }
20953            resolver.addFilter(newFilter);
20954            scheduleWritePackageRestrictionsLocked(sourceUserId);
20955        }
20956    }
20957
20958    @Override
20959    public void clearCrossProfileIntentFilters(int sourceUserId, String ownerPackage) {
20960        mContext.enforceCallingOrSelfPermission(
20961                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
20962        final int callingUid = Binder.getCallingUid();
20963        enforceOwnerRights(ownerPackage, callingUid);
20964        enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId);
20965        synchronized (mPackages) {
20966            CrossProfileIntentResolver resolver =
20967                    mSettings.editCrossProfileIntentResolverLPw(sourceUserId);
20968            ArraySet<CrossProfileIntentFilter> set =
20969                    new ArraySet<CrossProfileIntentFilter>(resolver.filterSet());
20970            for (CrossProfileIntentFilter filter : set) {
20971                if (filter.getOwnerPackage().equals(ownerPackage)) {
20972                    resolver.removeFilter(filter);
20973                }
20974            }
20975            scheduleWritePackageRestrictionsLocked(sourceUserId);
20976        }
20977    }
20978
20979    // Enforcing that callingUid is owning pkg on userId
20980    private void enforceOwnerRights(String pkg, int callingUid) {
20981        // The system owns everything.
20982        if (UserHandle.getAppId(callingUid) == Process.SYSTEM_UID) {
20983            return;
20984        }
20985        final int callingUserId = UserHandle.getUserId(callingUid);
20986        PackageInfo pi = getPackageInfo(pkg, 0, callingUserId);
20987        if (pi == null) {
20988            throw new IllegalArgumentException("Unknown package " + pkg + " on user "
20989                    + callingUserId);
20990        }
20991        if (!UserHandle.isSameApp(pi.applicationInfo.uid, callingUid)) {
20992            throw new SecurityException("Calling uid " + callingUid
20993                    + " does not own package " + pkg);
20994        }
20995    }
20996
20997    @Override
20998    public ComponentName getHomeActivities(List<ResolveInfo> allHomeCandidates) {
20999        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
21000            return null;
21001        }
21002        return getHomeActivitiesAsUser(allHomeCandidates, UserHandle.getCallingUserId());
21003    }
21004
21005    public void sendSessionCommitBroadcast(PackageInstaller.SessionInfo sessionInfo, int userId) {
21006        UserManagerService ums = UserManagerService.getInstance();
21007        if (ums != null) {
21008            final UserInfo parent = ums.getProfileParent(userId);
21009            final int launcherUid = (parent != null) ? parent.id : userId;
21010            final ComponentName launcherComponent = getDefaultHomeActivity(launcherUid);
21011            if (launcherComponent != null) {
21012                Intent launcherIntent = new Intent(PackageInstaller.ACTION_SESSION_COMMITTED)
21013                        .putExtra(PackageInstaller.EXTRA_SESSION, sessionInfo)
21014                        .putExtra(Intent.EXTRA_USER, UserHandle.of(userId))
21015                        .setPackage(launcherComponent.getPackageName());
21016                mContext.sendBroadcastAsUser(launcherIntent, UserHandle.of(launcherUid));
21017            }
21018        }
21019    }
21020
21021    /**
21022     * Report the 'Home' activity which is currently set as "always use this one". If non is set
21023     * then reports the most likely home activity or null if there are more than one.
21024     */
21025    private ComponentName getDefaultHomeActivity(int userId) {
21026        List<ResolveInfo> allHomeCandidates = new ArrayList<>();
21027        ComponentName cn = getHomeActivitiesAsUser(allHomeCandidates, userId);
21028        if (cn != null) {
21029            return cn;
21030        }
21031
21032        // Find the launcher with the highest priority and return that component if there are no
21033        // other home activity with the same priority.
21034        int lastPriority = Integer.MIN_VALUE;
21035        ComponentName lastComponent = null;
21036        final int size = allHomeCandidates.size();
21037        for (int i = 0; i < size; i++) {
21038            final ResolveInfo ri = allHomeCandidates.get(i);
21039            if (ri.priority > lastPriority) {
21040                lastComponent = ri.activityInfo.getComponentName();
21041                lastPriority = ri.priority;
21042            } else if (ri.priority == lastPriority) {
21043                // Two components found with same priority.
21044                lastComponent = null;
21045            }
21046        }
21047        return lastComponent;
21048    }
21049
21050    private Intent getHomeIntent() {
21051        Intent intent = new Intent(Intent.ACTION_MAIN);
21052        intent.addCategory(Intent.CATEGORY_HOME);
21053        intent.addCategory(Intent.CATEGORY_DEFAULT);
21054        return intent;
21055    }
21056
21057    private IntentFilter getHomeFilter() {
21058        IntentFilter filter = new IntentFilter(Intent.ACTION_MAIN);
21059        filter.addCategory(Intent.CATEGORY_HOME);
21060        filter.addCategory(Intent.CATEGORY_DEFAULT);
21061        return filter;
21062    }
21063
21064    ComponentName getHomeActivitiesAsUser(List<ResolveInfo> allHomeCandidates,
21065            int userId) {
21066        Intent intent  = getHomeIntent();
21067        List<ResolveInfo> list = queryIntentActivitiesInternal(intent, null,
21068                PackageManager.GET_META_DATA, userId);
21069        ResolveInfo preferred = findPreferredActivity(intent, null, 0, list, 0,
21070                true, false, false, userId);
21071
21072        allHomeCandidates.clear();
21073        if (list != null) {
21074            for (ResolveInfo ri : list) {
21075                allHomeCandidates.add(ri);
21076            }
21077        }
21078        return (preferred == null || preferred.activityInfo == null)
21079                ? null
21080                : new ComponentName(preferred.activityInfo.packageName,
21081                        preferred.activityInfo.name);
21082    }
21083
21084    @Override
21085    public void setHomeActivity(ComponentName comp, int userId) {
21086        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
21087            return;
21088        }
21089        ArrayList<ResolveInfo> homeActivities = new ArrayList<>();
21090        getHomeActivitiesAsUser(homeActivities, userId);
21091
21092        boolean found = false;
21093
21094        final int size = homeActivities.size();
21095        final ComponentName[] set = new ComponentName[size];
21096        for (int i = 0; i < size; i++) {
21097            final ResolveInfo candidate = homeActivities.get(i);
21098            final ActivityInfo info = candidate.activityInfo;
21099            final ComponentName activityName = new ComponentName(info.packageName, info.name);
21100            set[i] = activityName;
21101            if (!found && activityName.equals(comp)) {
21102                found = true;
21103            }
21104        }
21105        if (!found) {
21106            throw new IllegalArgumentException("Component " + comp + " cannot be home on user "
21107                    + userId);
21108        }
21109        replacePreferredActivity(getHomeFilter(), IntentFilter.MATCH_CATEGORY_EMPTY,
21110                set, comp, userId);
21111    }
21112
21113    private @Nullable String getSetupWizardPackageName() {
21114        final Intent intent = new Intent(Intent.ACTION_MAIN);
21115        intent.addCategory(Intent.CATEGORY_SETUP_WIZARD);
21116
21117        final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, null,
21118                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE
21119                        | MATCH_DISABLED_COMPONENTS,
21120                UserHandle.myUserId());
21121        if (matches.size() == 1) {
21122            return matches.get(0).getComponentInfo().packageName;
21123        } else {
21124            Slog.e(TAG, "There should probably be exactly one setup wizard; found " + matches.size()
21125                    + ": matches=" + matches);
21126            return null;
21127        }
21128    }
21129
21130    private @Nullable String getStorageManagerPackageName() {
21131        final Intent intent = new Intent(StorageManager.ACTION_MANAGE_STORAGE);
21132
21133        final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, null,
21134                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE
21135                        | MATCH_DISABLED_COMPONENTS,
21136                UserHandle.myUserId());
21137        if (matches.size() == 1) {
21138            return matches.get(0).getComponentInfo().packageName;
21139        } else {
21140            Slog.e(TAG, "There should probably be exactly one storage manager; found "
21141                    + matches.size() + ": matches=" + matches);
21142            return null;
21143        }
21144    }
21145
21146    @Override
21147    public void setApplicationEnabledSetting(String appPackageName,
21148            int newState, int flags, int userId, String callingPackage) {
21149        if (!sUserManager.exists(userId)) return;
21150        if (callingPackage == null) {
21151            callingPackage = Integer.toString(Binder.getCallingUid());
21152        }
21153        setEnabledSetting(appPackageName, null, newState, flags, userId, callingPackage);
21154    }
21155
21156    @Override
21157    public void setUpdateAvailable(String packageName, boolean updateAvailable) {
21158        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, null);
21159        synchronized (mPackages) {
21160            final PackageSetting pkgSetting = mSettings.mPackages.get(packageName);
21161            if (pkgSetting != null) {
21162                pkgSetting.setUpdateAvailable(updateAvailable);
21163            }
21164        }
21165    }
21166
21167    @Override
21168    public void setComponentEnabledSetting(ComponentName componentName,
21169            int newState, int flags, int userId) {
21170        if (!sUserManager.exists(userId)) return;
21171        setEnabledSetting(componentName.getPackageName(),
21172                componentName.getClassName(), newState, flags, userId, null);
21173    }
21174
21175    private void setEnabledSetting(final String packageName, String className, int newState,
21176            final int flags, int userId, String callingPackage) {
21177        if (!(newState == COMPONENT_ENABLED_STATE_DEFAULT
21178              || newState == COMPONENT_ENABLED_STATE_ENABLED
21179              || newState == COMPONENT_ENABLED_STATE_DISABLED
21180              || newState == COMPONENT_ENABLED_STATE_DISABLED_USER
21181              || newState == COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED)) {
21182            throw new IllegalArgumentException("Invalid new component state: "
21183                    + newState);
21184        }
21185        PackageSetting pkgSetting;
21186        final int callingUid = Binder.getCallingUid();
21187        final int permission;
21188        if (callingUid == Process.SYSTEM_UID) {
21189            permission = PackageManager.PERMISSION_GRANTED;
21190        } else {
21191            permission = mContext.checkCallingOrSelfPermission(
21192                    android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
21193        }
21194        enforceCrossUserPermission(callingUid, userId,
21195                false /* requireFullPermission */, true /* checkShell */, "set enabled");
21196        final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
21197        boolean sendNow = false;
21198        boolean isApp = (className == null);
21199        final boolean isCallerInstantApp = (getInstantAppPackageName(callingUid) != null);
21200        String componentName = isApp ? packageName : className;
21201        int packageUid = -1;
21202        ArrayList<String> components;
21203
21204        // reader
21205        synchronized (mPackages) {
21206            pkgSetting = mSettings.mPackages.get(packageName);
21207            if (pkgSetting == null) {
21208                if (!isCallerInstantApp) {
21209                    if (className == null) {
21210                        throw new IllegalArgumentException("Unknown package: " + packageName);
21211                    }
21212                    throw new IllegalArgumentException(
21213                            "Unknown component: " + packageName + "/" + className);
21214                } else {
21215                    // throw SecurityException to prevent leaking package information
21216                    throw new SecurityException(
21217                            "Attempt to change component state; "
21218                            + "pid=" + Binder.getCallingPid()
21219                            + ", uid=" + callingUid
21220                            + (className == null
21221                                    ? ", package=" + packageName
21222                                    : ", component=" + packageName + "/" + className));
21223                }
21224            }
21225        }
21226
21227        // Limit who can change which apps
21228        if (!UserHandle.isSameApp(callingUid, pkgSetting.appId)) {
21229            // Don't allow apps that don't have permission to modify other apps
21230            if (!allowedByPermission
21231                    || filterAppAccessLPr(pkgSetting, callingUid, userId)) {
21232                throw new SecurityException(
21233                        "Attempt to change component state; "
21234                        + "pid=" + Binder.getCallingPid()
21235                        + ", uid=" + callingUid
21236                        + (className == null
21237                                ? ", package=" + packageName
21238                                : ", component=" + packageName + "/" + className));
21239            }
21240            // Don't allow changing protected packages.
21241            if (mProtectedPackages.isPackageStateProtected(userId, packageName)) {
21242                throw new SecurityException("Cannot disable a protected package: " + packageName);
21243            }
21244        }
21245
21246        synchronized (mPackages) {
21247            if (callingUid == Process.SHELL_UID
21248                    && (pkgSetting.pkgFlags & ApplicationInfo.FLAG_TEST_ONLY) == 0) {
21249                // Shell can only change whole packages between ENABLED and DISABLED_USER states
21250                // unless it is a test package.
21251                int oldState = pkgSetting.getEnabled(userId);
21252                if (className == null
21253                    &&
21254                    (oldState == COMPONENT_ENABLED_STATE_DISABLED_USER
21255                     || oldState == COMPONENT_ENABLED_STATE_DEFAULT
21256                     || oldState == COMPONENT_ENABLED_STATE_ENABLED)
21257                    &&
21258                    (newState == COMPONENT_ENABLED_STATE_DISABLED_USER
21259                     || newState == COMPONENT_ENABLED_STATE_DEFAULT
21260                     || newState == COMPONENT_ENABLED_STATE_ENABLED)) {
21261                    // ok
21262                } else {
21263                    throw new SecurityException(
21264                            "Shell cannot change component state for " + packageName + "/"
21265                            + className + " to " + newState);
21266                }
21267            }
21268            if (className == null) {
21269                // We're dealing with an application/package level state change
21270                if (pkgSetting.getEnabled(userId) == newState) {
21271                    // Nothing to do
21272                    return;
21273                }
21274                if (newState == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT
21275                    || newState == PackageManager.COMPONENT_ENABLED_STATE_ENABLED) {
21276                    // Don't care about who enables an app.
21277                    callingPackage = null;
21278                }
21279                pkgSetting.setEnabled(newState, userId, callingPackage);
21280                // pkgSetting.pkg.mSetEnabled = newState;
21281            } else {
21282                // We're dealing with a component level state change
21283                // First, verify that this is a valid class name.
21284                PackageParser.Package pkg = pkgSetting.pkg;
21285                if (pkg == null || !pkg.hasComponentClassName(className)) {
21286                    if (pkg != null &&
21287                            pkg.applicationInfo.targetSdkVersion >=
21288                                    Build.VERSION_CODES.JELLY_BEAN) {
21289                        throw new IllegalArgumentException("Component class " + className
21290                                + " does not exist in " + packageName);
21291                    } else {
21292                        Slog.w(TAG, "Failed setComponentEnabledSetting: component class "
21293                                + className + " does not exist in " + packageName);
21294                    }
21295                }
21296                switch (newState) {
21297                case COMPONENT_ENABLED_STATE_ENABLED:
21298                    if (!pkgSetting.enableComponentLPw(className, userId)) {
21299                        return;
21300                    }
21301                    break;
21302                case COMPONENT_ENABLED_STATE_DISABLED:
21303                    if (!pkgSetting.disableComponentLPw(className, userId)) {
21304                        return;
21305                    }
21306                    break;
21307                case COMPONENT_ENABLED_STATE_DEFAULT:
21308                    if (!pkgSetting.restoreComponentLPw(className, userId)) {
21309                        return;
21310                    }
21311                    break;
21312                default:
21313                    Slog.e(TAG, "Invalid new component state: " + newState);
21314                    return;
21315                }
21316            }
21317            scheduleWritePackageRestrictionsLocked(userId);
21318            updateSequenceNumberLP(pkgSetting, new int[] { userId });
21319            final long callingId = Binder.clearCallingIdentity();
21320            try {
21321                updateInstantAppInstallerLocked(packageName);
21322            } finally {
21323                Binder.restoreCallingIdentity(callingId);
21324            }
21325            components = mPendingBroadcasts.get(userId, packageName);
21326            final boolean newPackage = components == null;
21327            if (newPackage) {
21328                components = new ArrayList<String>();
21329            }
21330            if (!components.contains(componentName)) {
21331                components.add(componentName);
21332            }
21333            if ((flags&PackageManager.DONT_KILL_APP) == 0) {
21334                sendNow = true;
21335                // Purge entry from pending broadcast list if another one exists already
21336                // since we are sending one right away.
21337                mPendingBroadcasts.remove(userId, packageName);
21338            } else {
21339                if (newPackage) {
21340                    mPendingBroadcasts.put(userId, packageName, components);
21341                }
21342                if (!mHandler.hasMessages(SEND_PENDING_BROADCAST)) {
21343                    // Schedule a message
21344                    mHandler.sendEmptyMessageDelayed(SEND_PENDING_BROADCAST, BROADCAST_DELAY);
21345                }
21346            }
21347        }
21348
21349        long callingId = Binder.clearCallingIdentity();
21350        try {
21351            if (sendNow) {
21352                packageUid = UserHandle.getUid(userId, pkgSetting.appId);
21353                sendPackageChangedBroadcast(packageName,
21354                        (flags&PackageManager.DONT_KILL_APP) != 0, components, packageUid);
21355            }
21356        } finally {
21357            Binder.restoreCallingIdentity(callingId);
21358        }
21359    }
21360
21361    @Override
21362    public void flushPackageRestrictionsAsUser(int userId) {
21363        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
21364            return;
21365        }
21366        if (!sUserManager.exists(userId)) {
21367            return;
21368        }
21369        enforceCrossUserPermission(Binder.getCallingUid(), userId, false /* requireFullPermission*/,
21370                false /* checkShell */, "flushPackageRestrictions");
21371        synchronized (mPackages) {
21372            mSettings.writePackageRestrictionsLPr(userId);
21373            mDirtyUsers.remove(userId);
21374            if (mDirtyUsers.isEmpty()) {
21375                mHandler.removeMessages(WRITE_PACKAGE_RESTRICTIONS);
21376            }
21377        }
21378    }
21379
21380    private void sendPackageChangedBroadcast(String packageName,
21381            boolean killFlag, ArrayList<String> componentNames, int packageUid) {
21382        if (DEBUG_INSTALL)
21383            Log.v(TAG, "Sending package changed: package=" + packageName + " components="
21384                    + componentNames);
21385        Bundle extras = new Bundle(4);
21386        extras.putString(Intent.EXTRA_CHANGED_COMPONENT_NAME, componentNames.get(0));
21387        String nameList[] = new String[componentNames.size()];
21388        componentNames.toArray(nameList);
21389        extras.putStringArray(Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST, nameList);
21390        extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, killFlag);
21391        extras.putInt(Intent.EXTRA_UID, packageUid);
21392        // If this is not reporting a change of the overall package, then only send it
21393        // to registered receivers.  We don't want to launch a swath of apps for every
21394        // little component state change.
21395        final int flags = !componentNames.contains(packageName)
21396                ? Intent.FLAG_RECEIVER_REGISTERED_ONLY : 0;
21397        sendPackageBroadcast(Intent.ACTION_PACKAGE_CHANGED,  packageName, extras, flags, null, null,
21398                new int[] {UserHandle.getUserId(packageUid)});
21399    }
21400
21401    @Override
21402    public void setPackageStoppedState(String packageName, boolean stopped, int userId) {
21403        if (!sUserManager.exists(userId)) return;
21404        final int callingUid = Binder.getCallingUid();
21405        if (getInstantAppPackageName(callingUid) != null) {
21406            return;
21407        }
21408        final int permission = mContext.checkCallingOrSelfPermission(
21409                android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
21410        final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
21411        enforceCrossUserPermission(callingUid, userId,
21412                true /* requireFullPermission */, true /* checkShell */, "stop package");
21413        // writer
21414        synchronized (mPackages) {
21415            final PackageSetting ps = mSettings.mPackages.get(packageName);
21416            if (!filterAppAccessLPr(ps, callingUid, userId)
21417                    && mSettings.setPackageStoppedStateLPw(this, packageName, stopped,
21418                            allowedByPermission, callingUid, userId)) {
21419                scheduleWritePackageRestrictionsLocked(userId);
21420            }
21421        }
21422    }
21423
21424    @Override
21425    public String getInstallerPackageName(String packageName) {
21426        final int callingUid = Binder.getCallingUid();
21427        if (getInstantAppPackageName(callingUid) != null) {
21428            return null;
21429        }
21430        // reader
21431        synchronized (mPackages) {
21432            final PackageSetting ps = mSettings.mPackages.get(packageName);
21433            if (filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
21434                return null;
21435            }
21436            return mSettings.getInstallerPackageNameLPr(packageName);
21437        }
21438    }
21439
21440    public boolean isOrphaned(String packageName) {
21441        // reader
21442        synchronized (mPackages) {
21443            return mSettings.isOrphaned(packageName);
21444        }
21445    }
21446
21447    @Override
21448    public int getApplicationEnabledSetting(String packageName, int userId) {
21449        if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
21450        int callingUid = Binder.getCallingUid();
21451        enforceCrossUserPermission(callingUid, userId,
21452                false /* requireFullPermission */, false /* checkShell */, "get enabled");
21453        // reader
21454        synchronized (mPackages) {
21455            if (filterAppAccessLPr(mSettings.getPackageLPr(packageName), callingUid, userId)) {
21456                return COMPONENT_ENABLED_STATE_DISABLED;
21457            }
21458            return mSettings.getApplicationEnabledSettingLPr(packageName, userId);
21459        }
21460    }
21461
21462    @Override
21463    public int getComponentEnabledSetting(ComponentName component, int userId) {
21464        if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
21465        int callingUid = Binder.getCallingUid();
21466        enforceCrossUserPermission(callingUid, userId,
21467                false /*requireFullPermission*/, false /*checkShell*/, "getComponentEnabled");
21468        synchronized (mPackages) {
21469            if (filterAppAccessLPr(mSettings.getPackageLPr(component.getPackageName()), callingUid,
21470                    component, TYPE_UNKNOWN, userId)) {
21471                return COMPONENT_ENABLED_STATE_DISABLED;
21472            }
21473            return mSettings.getComponentEnabledSettingLPr(component, userId);
21474        }
21475    }
21476
21477    @Override
21478    public void enterSafeMode() {
21479        enforceSystemOrRoot("Only the system can request entering safe mode");
21480
21481        if (!mSystemReady) {
21482            mSafeMode = true;
21483        }
21484    }
21485
21486    @Override
21487    public void systemReady() {
21488        enforceSystemOrRoot("Only the system can claim the system is ready");
21489
21490        mSystemReady = true;
21491        final ContentResolver resolver = mContext.getContentResolver();
21492        ContentObserver co = new ContentObserver(mHandler) {
21493            @Override
21494            public void onChange(boolean selfChange) {
21495                mEphemeralAppsDisabled =
21496                        (Global.getInt(resolver, Global.ENABLE_EPHEMERAL_FEATURE, 1) == 0) ||
21497                                (Secure.getInt(resolver, Secure.INSTANT_APPS_ENABLED, 1) == 0);
21498            }
21499        };
21500        mContext.getContentResolver().registerContentObserver(android.provider.Settings.Global
21501                        .getUriFor(Global.ENABLE_EPHEMERAL_FEATURE),
21502                false, co, UserHandle.USER_SYSTEM);
21503        mContext.getContentResolver().registerContentObserver(android.provider.Settings.Global
21504                        .getUriFor(Secure.INSTANT_APPS_ENABLED), false, co, UserHandle.USER_SYSTEM);
21505        co.onChange(true);
21506
21507        // Disable any carrier apps. We do this very early in boot to prevent the apps from being
21508        // disabled after already being started.
21509        CarrierAppUtils.disableCarrierAppsUntilPrivileged(mContext.getOpPackageName(), this,
21510                mContext.getContentResolver(), UserHandle.USER_SYSTEM);
21511
21512        // Read the compatibilty setting when the system is ready.
21513        boolean compatibilityModeEnabled = android.provider.Settings.Global.getInt(
21514                mContext.getContentResolver(),
21515                android.provider.Settings.Global.COMPATIBILITY_MODE, 1) == 1;
21516        PackageParser.setCompatibilityModeEnabled(compatibilityModeEnabled);
21517        if (DEBUG_SETTINGS) {
21518            Log.d(TAG, "compatibility mode:" + compatibilityModeEnabled);
21519        }
21520
21521        int[] grantPermissionsUserIds = EMPTY_INT_ARRAY;
21522
21523        synchronized (mPackages) {
21524            // Verify that all of the preferred activity components actually
21525            // exist.  It is possible for applications to be updated and at
21526            // that point remove a previously declared activity component that
21527            // had been set as a preferred activity.  We try to clean this up
21528            // the next time we encounter that preferred activity, but it is
21529            // possible for the user flow to never be able to return to that
21530            // situation so here we do a sanity check to make sure we haven't
21531            // left any junk around.
21532            ArrayList<PreferredActivity> removed = new ArrayList<PreferredActivity>();
21533            for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
21534                PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
21535                removed.clear();
21536                for (PreferredActivity pa : pir.filterSet()) {
21537                    if (mActivities.mActivities.get(pa.mPref.mComponent) == null) {
21538                        removed.add(pa);
21539                    }
21540                }
21541                if (removed.size() > 0) {
21542                    for (int r=0; r<removed.size(); r++) {
21543                        PreferredActivity pa = removed.get(r);
21544                        Slog.w(TAG, "Removing dangling preferred activity: "
21545                                + pa.mPref.mComponent);
21546                        pir.removeFilter(pa);
21547                    }
21548                    mSettings.writePackageRestrictionsLPr(
21549                            mSettings.mPreferredActivities.keyAt(i));
21550                }
21551            }
21552
21553            for (int userId : UserManagerService.getInstance().getUserIds()) {
21554                if (!mSettings.areDefaultRuntimePermissionsGrantedLPr(userId)) {
21555                    grantPermissionsUserIds = ArrayUtils.appendInt(
21556                            grantPermissionsUserIds, userId);
21557                }
21558            }
21559        }
21560        sUserManager.systemReady();
21561
21562        // If we upgraded grant all default permissions before kicking off.
21563        for (int userId : grantPermissionsUserIds) {
21564            mDefaultPermissionPolicy.grantDefaultPermissions(userId);
21565        }
21566
21567        // If we did not grant default permissions, we preload from this the
21568        // default permission exceptions lazily to ensure we don't hit the
21569        // disk on a new user creation.
21570        if (grantPermissionsUserIds == EMPTY_INT_ARRAY) {
21571            mDefaultPermissionPolicy.scheduleReadDefaultPermissionExceptions();
21572        }
21573
21574        // Kick off any messages waiting for system ready
21575        if (mPostSystemReadyMessages != null) {
21576            for (Message msg : mPostSystemReadyMessages) {
21577                msg.sendToTarget();
21578            }
21579            mPostSystemReadyMessages = null;
21580        }
21581
21582        // Watch for external volumes that come and go over time
21583        final StorageManager storage = mContext.getSystemService(StorageManager.class);
21584        storage.registerListener(mStorageListener);
21585
21586        mInstallerService.systemReady();
21587        mPackageDexOptimizer.systemReady();
21588
21589        StorageManagerInternal StorageManagerInternal = LocalServices.getService(
21590                StorageManagerInternal.class);
21591        StorageManagerInternal.addExternalStoragePolicy(
21592                new StorageManagerInternal.ExternalStorageMountPolicy() {
21593            @Override
21594            public int getMountMode(int uid, String packageName) {
21595                if (Process.isIsolated(uid)) {
21596                    return Zygote.MOUNT_EXTERNAL_NONE;
21597                }
21598                if (checkUidPermission(WRITE_MEDIA_STORAGE, uid) == PERMISSION_GRANTED) {
21599                    return Zygote.MOUNT_EXTERNAL_DEFAULT;
21600                }
21601                if (checkUidPermission(READ_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) {
21602                    return Zygote.MOUNT_EXTERNAL_DEFAULT;
21603                }
21604                if (checkUidPermission(WRITE_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) {
21605                    return Zygote.MOUNT_EXTERNAL_READ;
21606                }
21607                return Zygote.MOUNT_EXTERNAL_WRITE;
21608            }
21609
21610            @Override
21611            public boolean hasExternalStorage(int uid, String packageName) {
21612                return true;
21613            }
21614        });
21615
21616        // Now that we're mostly running, clean up stale users and apps
21617        sUserManager.reconcileUsers(StorageManager.UUID_PRIVATE_INTERNAL);
21618        reconcileApps(StorageManager.UUID_PRIVATE_INTERNAL);
21619
21620        if (mPrivappPermissionsViolations != null) {
21621            Slog.wtf(TAG,"Signature|privileged permissions not in "
21622                    + "privapp-permissions whitelist: " + mPrivappPermissionsViolations);
21623            mPrivappPermissionsViolations = null;
21624        }
21625    }
21626
21627    public void waitForAppDataPrepared() {
21628        if (mPrepareAppDataFuture == null) {
21629            return;
21630        }
21631        ConcurrentUtils.waitForFutureNoInterrupt(mPrepareAppDataFuture, "wait for prepareAppData");
21632        mPrepareAppDataFuture = null;
21633    }
21634
21635    @Override
21636    public boolean isSafeMode() {
21637        // allow instant applications
21638        return mSafeMode;
21639    }
21640
21641    @Override
21642    public boolean hasSystemUidErrors() {
21643        // allow instant applications
21644        return mHasSystemUidErrors;
21645    }
21646
21647    static String arrayToString(int[] array) {
21648        StringBuffer buf = new StringBuffer(128);
21649        buf.append('[');
21650        if (array != null) {
21651            for (int i=0; i<array.length; i++) {
21652                if (i > 0) buf.append(", ");
21653                buf.append(array[i]);
21654            }
21655        }
21656        buf.append(']');
21657        return buf.toString();
21658    }
21659
21660    static class DumpState {
21661        public static final int DUMP_LIBS = 1 << 0;
21662        public static final int DUMP_FEATURES = 1 << 1;
21663        public static final int DUMP_ACTIVITY_RESOLVERS = 1 << 2;
21664        public static final int DUMP_SERVICE_RESOLVERS = 1 << 3;
21665        public static final int DUMP_RECEIVER_RESOLVERS = 1 << 4;
21666        public static final int DUMP_CONTENT_RESOLVERS = 1 << 5;
21667        public static final int DUMP_PERMISSIONS = 1 << 6;
21668        public static final int DUMP_PACKAGES = 1 << 7;
21669        public static final int DUMP_SHARED_USERS = 1 << 8;
21670        public static final int DUMP_MESSAGES = 1 << 9;
21671        public static final int DUMP_PROVIDERS = 1 << 10;
21672        public static final int DUMP_VERIFIERS = 1 << 11;
21673        public static final int DUMP_PREFERRED = 1 << 12;
21674        public static final int DUMP_PREFERRED_XML = 1 << 13;
21675        public static final int DUMP_KEYSETS = 1 << 14;
21676        public static final int DUMP_VERSION = 1 << 15;
21677        public static final int DUMP_INSTALLS = 1 << 16;
21678        public static final int DUMP_INTENT_FILTER_VERIFIERS = 1 << 17;
21679        public static final int DUMP_DOMAIN_PREFERRED = 1 << 18;
21680        public static final int DUMP_FROZEN = 1 << 19;
21681        public static final int DUMP_DEXOPT = 1 << 20;
21682        public static final int DUMP_COMPILER_STATS = 1 << 21;
21683        public static final int DUMP_CHANGES = 1 << 22;
21684        public static final int DUMP_VOLUMES = 1 << 23;
21685
21686        public static final int OPTION_SHOW_FILTERS = 1 << 0;
21687
21688        private int mTypes;
21689
21690        private int mOptions;
21691
21692        private boolean mTitlePrinted;
21693
21694        private SharedUserSetting mSharedUser;
21695
21696        public boolean isDumping(int type) {
21697            if (mTypes == 0 && type != DUMP_PREFERRED_XML) {
21698                return true;
21699            }
21700
21701            return (mTypes & type) != 0;
21702        }
21703
21704        public void setDump(int type) {
21705            mTypes |= type;
21706        }
21707
21708        public boolean isOptionEnabled(int option) {
21709            return (mOptions & option) != 0;
21710        }
21711
21712        public void setOptionEnabled(int option) {
21713            mOptions |= option;
21714        }
21715
21716        public boolean onTitlePrinted() {
21717            final boolean printed = mTitlePrinted;
21718            mTitlePrinted = true;
21719            return printed;
21720        }
21721
21722        public boolean getTitlePrinted() {
21723            return mTitlePrinted;
21724        }
21725
21726        public void setTitlePrinted(boolean enabled) {
21727            mTitlePrinted = enabled;
21728        }
21729
21730        public SharedUserSetting getSharedUser() {
21731            return mSharedUser;
21732        }
21733
21734        public void setSharedUser(SharedUserSetting user) {
21735            mSharedUser = user;
21736        }
21737    }
21738
21739    @Override
21740    public void onShellCommand(FileDescriptor in, FileDescriptor out,
21741            FileDescriptor err, String[] args, ShellCallback callback,
21742            ResultReceiver resultReceiver) {
21743        (new PackageManagerShellCommand(this)).exec(
21744                this, in, out, err, args, callback, resultReceiver);
21745    }
21746
21747    @Override
21748    protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
21749        if (!DumpUtils.checkDumpAndUsageStatsPermission(mContext, TAG, pw)) return;
21750
21751        DumpState dumpState = new DumpState();
21752        boolean fullPreferred = false;
21753        boolean checkin = false;
21754
21755        String packageName = null;
21756        ArraySet<String> permissionNames = null;
21757
21758        int opti = 0;
21759        while (opti < args.length) {
21760            String opt = args[opti];
21761            if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') {
21762                break;
21763            }
21764            opti++;
21765
21766            if ("-a".equals(opt)) {
21767                // Right now we only know how to print all.
21768            } else if ("-h".equals(opt)) {
21769                pw.println("Package manager dump options:");
21770                pw.println("  [-h] [-f] [--checkin] [cmd] ...");
21771                pw.println("    --checkin: dump for a checkin");
21772                pw.println("    -f: print details of intent filters");
21773                pw.println("    -h: print this help");
21774                pw.println("  cmd may be one of:");
21775                pw.println("    l[ibraries]: list known shared libraries");
21776                pw.println("    f[eatures]: list device features");
21777                pw.println("    k[eysets]: print known keysets");
21778                pw.println("    r[esolvers] [activity|service|receiver|content]: dump intent resolvers");
21779                pw.println("    perm[issions]: dump permissions");
21780                pw.println("    permission [name ...]: dump declaration and use of given permission");
21781                pw.println("    pref[erred]: print preferred package settings");
21782                pw.println("    preferred-xml [--full]: print preferred package settings as xml");
21783                pw.println("    prov[iders]: dump content providers");
21784                pw.println("    p[ackages]: dump installed packages");
21785                pw.println("    s[hared-users]: dump shared user IDs");
21786                pw.println("    m[essages]: print collected runtime messages");
21787                pw.println("    v[erifiers]: print package verifier info");
21788                pw.println("    d[omain-preferred-apps]: print domains preferred apps");
21789                pw.println("    i[ntent-filter-verifiers]|ifv: print intent filter verifier info");
21790                pw.println("    version: print database version info");
21791                pw.println("    write: write current settings now");
21792                pw.println("    installs: details about install sessions");
21793                pw.println("    check-permission <permission> <package> [<user>]: does pkg hold perm?");
21794                pw.println("    dexopt: dump dexopt state");
21795                pw.println("    compiler-stats: dump compiler statistics");
21796                pw.println("    enabled-overlays: dump list of enabled overlay packages");
21797                pw.println("    <package.name>: info about given package");
21798                return;
21799            } else if ("--checkin".equals(opt)) {
21800                checkin = true;
21801            } else if ("-f".equals(opt)) {
21802                dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS);
21803            } else if ("--proto".equals(opt)) {
21804                dumpProto(fd);
21805                return;
21806            } else {
21807                pw.println("Unknown argument: " + opt + "; use -h for help");
21808            }
21809        }
21810
21811        // Is the caller requesting to dump a particular piece of data?
21812        if (opti < args.length) {
21813            String cmd = args[opti];
21814            opti++;
21815            // Is this a package name?
21816            if ("android".equals(cmd) || cmd.contains(".")) {
21817                packageName = cmd;
21818                // When dumping a single package, we always dump all of its
21819                // filter information since the amount of data will be reasonable.
21820                dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS);
21821            } else if ("check-permission".equals(cmd)) {
21822                if (opti >= args.length) {
21823                    pw.println("Error: check-permission missing permission argument");
21824                    return;
21825                }
21826                String perm = args[opti];
21827                opti++;
21828                if (opti >= args.length) {
21829                    pw.println("Error: check-permission missing package argument");
21830                    return;
21831                }
21832
21833                String pkg = args[opti];
21834                opti++;
21835                int user = UserHandle.getUserId(Binder.getCallingUid());
21836                if (opti < args.length) {
21837                    try {
21838                        user = Integer.parseInt(args[opti]);
21839                    } catch (NumberFormatException e) {
21840                        pw.println("Error: check-permission user argument is not a number: "
21841                                + args[opti]);
21842                        return;
21843                    }
21844                }
21845
21846                // Normalize package name to handle renamed packages and static libs
21847                pkg = resolveInternalPackageNameLPr(pkg, PackageManager.VERSION_CODE_HIGHEST);
21848
21849                pw.println(checkPermission(perm, pkg, user));
21850                return;
21851            } else if ("l".equals(cmd) || "libraries".equals(cmd)) {
21852                dumpState.setDump(DumpState.DUMP_LIBS);
21853            } else if ("f".equals(cmd) || "features".equals(cmd)) {
21854                dumpState.setDump(DumpState.DUMP_FEATURES);
21855            } else if ("r".equals(cmd) || "resolvers".equals(cmd)) {
21856                if (opti >= args.length) {
21857                    dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS
21858                            | DumpState.DUMP_SERVICE_RESOLVERS
21859                            | DumpState.DUMP_RECEIVER_RESOLVERS
21860                            | DumpState.DUMP_CONTENT_RESOLVERS);
21861                } else {
21862                    while (opti < args.length) {
21863                        String name = args[opti];
21864                        if ("a".equals(name) || "activity".equals(name)) {
21865                            dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS);
21866                        } else if ("s".equals(name) || "service".equals(name)) {
21867                            dumpState.setDump(DumpState.DUMP_SERVICE_RESOLVERS);
21868                        } else if ("r".equals(name) || "receiver".equals(name)) {
21869                            dumpState.setDump(DumpState.DUMP_RECEIVER_RESOLVERS);
21870                        } else if ("c".equals(name) || "content".equals(name)) {
21871                            dumpState.setDump(DumpState.DUMP_CONTENT_RESOLVERS);
21872                        } else {
21873                            pw.println("Error: unknown resolver table type: " + name);
21874                            return;
21875                        }
21876                        opti++;
21877                    }
21878                }
21879            } else if ("perm".equals(cmd) || "permissions".equals(cmd)) {
21880                dumpState.setDump(DumpState.DUMP_PERMISSIONS);
21881            } else if ("permission".equals(cmd)) {
21882                if (opti >= args.length) {
21883                    pw.println("Error: permission requires permission name");
21884                    return;
21885                }
21886                permissionNames = new ArraySet<>();
21887                while (opti < args.length) {
21888                    permissionNames.add(args[opti]);
21889                    opti++;
21890                }
21891                dumpState.setDump(DumpState.DUMP_PERMISSIONS
21892                        | DumpState.DUMP_PACKAGES | DumpState.DUMP_SHARED_USERS);
21893            } else if ("pref".equals(cmd) || "preferred".equals(cmd)) {
21894                dumpState.setDump(DumpState.DUMP_PREFERRED);
21895            } else if ("preferred-xml".equals(cmd)) {
21896                dumpState.setDump(DumpState.DUMP_PREFERRED_XML);
21897                if (opti < args.length && "--full".equals(args[opti])) {
21898                    fullPreferred = true;
21899                    opti++;
21900                }
21901            } else if ("d".equals(cmd) || "domain-preferred-apps".equals(cmd)) {
21902                dumpState.setDump(DumpState.DUMP_DOMAIN_PREFERRED);
21903            } else if ("p".equals(cmd) || "packages".equals(cmd)) {
21904                dumpState.setDump(DumpState.DUMP_PACKAGES);
21905            } else if ("s".equals(cmd) || "shared-users".equals(cmd)) {
21906                dumpState.setDump(DumpState.DUMP_SHARED_USERS);
21907            } else if ("prov".equals(cmd) || "providers".equals(cmd)) {
21908                dumpState.setDump(DumpState.DUMP_PROVIDERS);
21909            } else if ("m".equals(cmd) || "messages".equals(cmd)) {
21910                dumpState.setDump(DumpState.DUMP_MESSAGES);
21911            } else if ("v".equals(cmd) || "verifiers".equals(cmd)) {
21912                dumpState.setDump(DumpState.DUMP_VERIFIERS);
21913            } else if ("i".equals(cmd) || "ifv".equals(cmd)
21914                    || "intent-filter-verifiers".equals(cmd)) {
21915                dumpState.setDump(DumpState.DUMP_INTENT_FILTER_VERIFIERS);
21916            } else if ("version".equals(cmd)) {
21917                dumpState.setDump(DumpState.DUMP_VERSION);
21918            } else if ("k".equals(cmd) || "keysets".equals(cmd)) {
21919                dumpState.setDump(DumpState.DUMP_KEYSETS);
21920            } else if ("installs".equals(cmd)) {
21921                dumpState.setDump(DumpState.DUMP_INSTALLS);
21922            } else if ("frozen".equals(cmd)) {
21923                dumpState.setDump(DumpState.DUMP_FROZEN);
21924            } else if ("volumes".equals(cmd)) {
21925                dumpState.setDump(DumpState.DUMP_VOLUMES);
21926            } else if ("dexopt".equals(cmd)) {
21927                dumpState.setDump(DumpState.DUMP_DEXOPT);
21928            } else if ("compiler-stats".equals(cmd)) {
21929                dumpState.setDump(DumpState.DUMP_COMPILER_STATS);
21930            } else if ("changes".equals(cmd)) {
21931                dumpState.setDump(DumpState.DUMP_CHANGES);
21932            } else if ("write".equals(cmd)) {
21933                synchronized (mPackages) {
21934                    mSettings.writeLPr();
21935                    pw.println("Settings written.");
21936                    return;
21937                }
21938            }
21939        }
21940
21941        if (checkin) {
21942            pw.println("vers,1");
21943        }
21944
21945        // reader
21946        synchronized (mPackages) {
21947            if (dumpState.isDumping(DumpState.DUMP_VERSION) && packageName == null) {
21948                if (!checkin) {
21949                    if (dumpState.onTitlePrinted())
21950                        pw.println();
21951                    pw.println("Database versions:");
21952                    mSettings.dumpVersionLPr(new IndentingPrintWriter(pw, "  "));
21953                }
21954            }
21955
21956            if (dumpState.isDumping(DumpState.DUMP_VERIFIERS) && packageName == null) {
21957                if (!checkin) {
21958                    if (dumpState.onTitlePrinted())
21959                        pw.println();
21960                    pw.println("Verifiers:");
21961                    pw.print("  Required: ");
21962                    pw.print(mRequiredVerifierPackage);
21963                    pw.print(" (uid=");
21964                    pw.print(getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING,
21965                            UserHandle.USER_SYSTEM));
21966                    pw.println(")");
21967                } else if (mRequiredVerifierPackage != null) {
21968                    pw.print("vrfy,"); pw.print(mRequiredVerifierPackage);
21969                    pw.print(",");
21970                    pw.println(getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING,
21971                            UserHandle.USER_SYSTEM));
21972                }
21973            }
21974
21975            if (dumpState.isDumping(DumpState.DUMP_INTENT_FILTER_VERIFIERS) &&
21976                    packageName == null) {
21977                if (mIntentFilterVerifierComponent != null) {
21978                    String verifierPackageName = mIntentFilterVerifierComponent.getPackageName();
21979                    if (!checkin) {
21980                        if (dumpState.onTitlePrinted())
21981                            pw.println();
21982                        pw.println("Intent Filter Verifier:");
21983                        pw.print("  Using: ");
21984                        pw.print(verifierPackageName);
21985                        pw.print(" (uid=");
21986                        pw.print(getPackageUid(verifierPackageName, MATCH_DEBUG_TRIAGED_MISSING,
21987                                UserHandle.USER_SYSTEM));
21988                        pw.println(")");
21989                    } else if (verifierPackageName != null) {
21990                        pw.print("ifv,"); pw.print(verifierPackageName);
21991                        pw.print(",");
21992                        pw.println(getPackageUid(verifierPackageName, MATCH_DEBUG_TRIAGED_MISSING,
21993                                UserHandle.USER_SYSTEM));
21994                    }
21995                } else {
21996                    pw.println();
21997                    pw.println("No Intent Filter Verifier available!");
21998                }
21999            }
22000
22001            if (dumpState.isDumping(DumpState.DUMP_LIBS) && packageName == null) {
22002                boolean printedHeader = false;
22003                final Iterator<String> it = mSharedLibraries.keySet().iterator();
22004                while (it.hasNext()) {
22005                    String libName = it.next();
22006                    SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(libName);
22007                    if (versionedLib == null) {
22008                        continue;
22009                    }
22010                    final int versionCount = versionedLib.size();
22011                    for (int i = 0; i < versionCount; i++) {
22012                        SharedLibraryEntry libEntry = versionedLib.valueAt(i);
22013                        if (!checkin) {
22014                            if (!printedHeader) {
22015                                if (dumpState.onTitlePrinted())
22016                                    pw.println();
22017                                pw.println("Libraries:");
22018                                printedHeader = true;
22019                            }
22020                            pw.print("  ");
22021                        } else {
22022                            pw.print("lib,");
22023                        }
22024                        pw.print(libEntry.info.getName());
22025                        if (libEntry.info.isStatic()) {
22026                            pw.print(" version=" + libEntry.info.getVersion());
22027                        }
22028                        if (!checkin) {
22029                            pw.print(" -> ");
22030                        }
22031                        if (libEntry.path != null) {
22032                            pw.print(" (jar) ");
22033                            pw.print(libEntry.path);
22034                        } else {
22035                            pw.print(" (apk) ");
22036                            pw.print(libEntry.apk);
22037                        }
22038                        pw.println();
22039                    }
22040                }
22041            }
22042
22043            if (dumpState.isDumping(DumpState.DUMP_FEATURES) && packageName == null) {
22044                if (dumpState.onTitlePrinted())
22045                    pw.println();
22046                if (!checkin) {
22047                    pw.println("Features:");
22048                }
22049
22050                synchronized (mAvailableFeatures) {
22051                    for (FeatureInfo feat : mAvailableFeatures.values()) {
22052                        if (checkin) {
22053                            pw.print("feat,");
22054                            pw.print(feat.name);
22055                            pw.print(",");
22056                            pw.println(feat.version);
22057                        } else {
22058                            pw.print("  ");
22059                            pw.print(feat.name);
22060                            if (feat.version > 0) {
22061                                pw.print(" version=");
22062                                pw.print(feat.version);
22063                            }
22064                            pw.println();
22065                        }
22066                    }
22067                }
22068            }
22069
22070            if (!checkin && dumpState.isDumping(DumpState.DUMP_ACTIVITY_RESOLVERS)) {
22071                if (mActivities.dump(pw, dumpState.getTitlePrinted() ? "\nActivity Resolver Table:"
22072                        : "Activity Resolver Table:", "  ", packageName,
22073                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
22074                    dumpState.setTitlePrinted(true);
22075                }
22076            }
22077            if (!checkin && dumpState.isDumping(DumpState.DUMP_RECEIVER_RESOLVERS)) {
22078                if (mReceivers.dump(pw, dumpState.getTitlePrinted() ? "\nReceiver Resolver Table:"
22079                        : "Receiver Resolver Table:", "  ", packageName,
22080                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
22081                    dumpState.setTitlePrinted(true);
22082                }
22083            }
22084            if (!checkin && dumpState.isDumping(DumpState.DUMP_SERVICE_RESOLVERS)) {
22085                if (mServices.dump(pw, dumpState.getTitlePrinted() ? "\nService Resolver Table:"
22086                        : "Service Resolver Table:", "  ", packageName,
22087                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
22088                    dumpState.setTitlePrinted(true);
22089                }
22090            }
22091            if (!checkin && dumpState.isDumping(DumpState.DUMP_CONTENT_RESOLVERS)) {
22092                if (mProviders.dump(pw, dumpState.getTitlePrinted() ? "\nProvider Resolver Table:"
22093                        : "Provider Resolver Table:", "  ", packageName,
22094                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
22095                    dumpState.setTitlePrinted(true);
22096                }
22097            }
22098
22099            if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED)) {
22100                for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
22101                    PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
22102                    int user = mSettings.mPreferredActivities.keyAt(i);
22103                    if (pir.dump(pw,
22104                            dumpState.getTitlePrinted()
22105                                ? "\nPreferred Activities User " + user + ":"
22106                                : "Preferred Activities User " + user + ":", "  ",
22107                            packageName, true, false)) {
22108                        dumpState.setTitlePrinted(true);
22109                    }
22110                }
22111            }
22112
22113            if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED_XML)) {
22114                pw.flush();
22115                FileOutputStream fout = new FileOutputStream(fd);
22116                BufferedOutputStream str = new BufferedOutputStream(fout);
22117                XmlSerializer serializer = new FastXmlSerializer();
22118                try {
22119                    serializer.setOutput(str, StandardCharsets.UTF_8.name());
22120                    serializer.startDocument(null, true);
22121                    serializer.setFeature(
22122                            "http://xmlpull.org/v1/doc/features.html#indent-output", true);
22123                    mSettings.writePreferredActivitiesLPr(serializer, 0, fullPreferred);
22124                    serializer.endDocument();
22125                    serializer.flush();
22126                } catch (IllegalArgumentException e) {
22127                    pw.println("Failed writing: " + e);
22128                } catch (IllegalStateException e) {
22129                    pw.println("Failed writing: " + e);
22130                } catch (IOException e) {
22131                    pw.println("Failed writing: " + e);
22132                }
22133            }
22134
22135            if (!checkin
22136                    && dumpState.isDumping(DumpState.DUMP_DOMAIN_PREFERRED)
22137                    && packageName == null) {
22138                pw.println();
22139                int count = mSettings.mPackages.size();
22140                if (count == 0) {
22141                    pw.println("No applications!");
22142                    pw.println();
22143                } else {
22144                    final String prefix = "  ";
22145                    Collection<PackageSetting> allPackageSettings = mSettings.mPackages.values();
22146                    if (allPackageSettings.size() == 0) {
22147                        pw.println("No domain preferred apps!");
22148                        pw.println();
22149                    } else {
22150                        pw.println("App verification status:");
22151                        pw.println();
22152                        count = 0;
22153                        for (PackageSetting ps : allPackageSettings) {
22154                            IntentFilterVerificationInfo ivi = ps.getIntentFilterVerificationInfo();
22155                            if (ivi == null || ivi.getPackageName() == null) continue;
22156                            pw.println(prefix + "Package: " + ivi.getPackageName());
22157                            pw.println(prefix + "Domains: " + ivi.getDomainsString());
22158                            pw.println(prefix + "Status:  " + ivi.getStatusString());
22159                            pw.println();
22160                            count++;
22161                        }
22162                        if (count == 0) {
22163                            pw.println(prefix + "No app verification established.");
22164                            pw.println();
22165                        }
22166                        for (int userId : sUserManager.getUserIds()) {
22167                            pw.println("App linkages for user " + userId + ":");
22168                            pw.println();
22169                            count = 0;
22170                            for (PackageSetting ps : allPackageSettings) {
22171                                final long status = ps.getDomainVerificationStatusForUser(userId);
22172                                if (status >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED
22173                                        && !DEBUG_DOMAIN_VERIFICATION) {
22174                                    continue;
22175                                }
22176                                pw.println(prefix + "Package: " + ps.name);
22177                                pw.println(prefix + "Domains: " + dumpDomainString(ps.name));
22178                                String statusStr = IntentFilterVerificationInfo.
22179                                        getStatusStringFromValue(status);
22180                                pw.println(prefix + "Status:  " + statusStr);
22181                                pw.println();
22182                                count++;
22183                            }
22184                            if (count == 0) {
22185                                pw.println(prefix + "No configured app linkages.");
22186                                pw.println();
22187                            }
22188                        }
22189                    }
22190                }
22191            }
22192
22193            if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS)) {
22194                mSettings.dumpPermissionsLPr(pw, packageName, permissionNames, dumpState);
22195                if (packageName == null && permissionNames == null) {
22196                    for (int iperm=0; iperm<mAppOpPermissionPackages.size(); iperm++) {
22197                        if (iperm == 0) {
22198                            if (dumpState.onTitlePrinted())
22199                                pw.println();
22200                            pw.println("AppOp Permissions:");
22201                        }
22202                        pw.print("  AppOp Permission ");
22203                        pw.print(mAppOpPermissionPackages.keyAt(iperm));
22204                        pw.println(":");
22205                        ArraySet<String> pkgs = mAppOpPermissionPackages.valueAt(iperm);
22206                        for (int ipkg=0; ipkg<pkgs.size(); ipkg++) {
22207                            pw.print("    "); pw.println(pkgs.valueAt(ipkg));
22208                        }
22209                    }
22210                }
22211            }
22212
22213            if (!checkin && dumpState.isDumping(DumpState.DUMP_PROVIDERS)) {
22214                boolean printedSomething = false;
22215                for (PackageParser.Provider p : mProviders.mProviders.values()) {
22216                    if (packageName != null && !packageName.equals(p.info.packageName)) {
22217                        continue;
22218                    }
22219                    if (!printedSomething) {
22220                        if (dumpState.onTitlePrinted())
22221                            pw.println();
22222                        pw.println("Registered ContentProviders:");
22223                        printedSomething = true;
22224                    }
22225                    pw.print("  "); p.printComponentShortName(pw); pw.println(":");
22226                    pw.print("    "); pw.println(p.toString());
22227                }
22228                printedSomething = false;
22229                for (Map.Entry<String, PackageParser.Provider> entry :
22230                        mProvidersByAuthority.entrySet()) {
22231                    PackageParser.Provider p = entry.getValue();
22232                    if (packageName != null && !packageName.equals(p.info.packageName)) {
22233                        continue;
22234                    }
22235                    if (!printedSomething) {
22236                        if (dumpState.onTitlePrinted())
22237                            pw.println();
22238                        pw.println("ContentProvider Authorities:");
22239                        printedSomething = true;
22240                    }
22241                    pw.print("  ["); pw.print(entry.getKey()); pw.println("]:");
22242                    pw.print("    "); pw.println(p.toString());
22243                    if (p.info != null && p.info.applicationInfo != null) {
22244                        final String appInfo = p.info.applicationInfo.toString();
22245                        pw.print("      applicationInfo="); pw.println(appInfo);
22246                    }
22247                }
22248            }
22249
22250            if (!checkin && dumpState.isDumping(DumpState.DUMP_KEYSETS)) {
22251                mSettings.mKeySetManagerService.dumpLPr(pw, packageName, dumpState);
22252            }
22253
22254            if (dumpState.isDumping(DumpState.DUMP_PACKAGES)) {
22255                mSettings.dumpPackagesLPr(pw, packageName, permissionNames, dumpState, checkin);
22256            }
22257
22258            if (dumpState.isDumping(DumpState.DUMP_SHARED_USERS)) {
22259                mSettings.dumpSharedUsersLPr(pw, packageName, permissionNames, dumpState, checkin);
22260            }
22261
22262            if (dumpState.isDumping(DumpState.DUMP_CHANGES)) {
22263                if (dumpState.onTitlePrinted()) pw.println();
22264                pw.println("Package Changes:");
22265                pw.print("  Sequence number="); pw.println(mChangedPackagesSequenceNumber);
22266                final int K = mChangedPackages.size();
22267                for (int i = 0; i < K; i++) {
22268                    final SparseArray<String> changes = mChangedPackages.valueAt(i);
22269                    pw.print("  User "); pw.print(mChangedPackages.keyAt(i)); pw.println(":");
22270                    final int N = changes.size();
22271                    if (N == 0) {
22272                        pw.print("    "); pw.println("No packages changed");
22273                    } else {
22274                        for (int j = 0; j < N; j++) {
22275                            final String pkgName = changes.valueAt(j);
22276                            final int sequenceNumber = changes.keyAt(j);
22277                            pw.print("    ");
22278                            pw.print("seq=");
22279                            pw.print(sequenceNumber);
22280                            pw.print(", package=");
22281                            pw.println(pkgName);
22282                        }
22283                    }
22284                }
22285            }
22286
22287            if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS) && packageName == null) {
22288                mSettings.dumpRestoredPermissionGrantsLPr(pw, dumpState);
22289            }
22290
22291            if (!checkin && dumpState.isDumping(DumpState.DUMP_FROZEN) && packageName == null) {
22292                // XXX should handle packageName != null by dumping only install data that
22293                // the given package is involved with.
22294                if (dumpState.onTitlePrinted()) pw.println();
22295
22296                final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, "  ", 120);
22297                ipw.println();
22298                ipw.println("Frozen packages:");
22299                ipw.increaseIndent();
22300                if (mFrozenPackages.size() == 0) {
22301                    ipw.println("(none)");
22302                } else {
22303                    for (int i = 0; i < mFrozenPackages.size(); i++) {
22304                        ipw.println(mFrozenPackages.valueAt(i));
22305                    }
22306                }
22307                ipw.decreaseIndent();
22308            }
22309
22310            if (!checkin && dumpState.isDumping(DumpState.DUMP_VOLUMES) && packageName == null) {
22311                if (dumpState.onTitlePrinted()) pw.println();
22312
22313                final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, "  ", 120);
22314                ipw.println();
22315                ipw.println("Loaded volumes:");
22316                ipw.increaseIndent();
22317                if (mLoadedVolumes.size() == 0) {
22318                    ipw.println("(none)");
22319                } else {
22320                    for (int i = 0; i < mLoadedVolumes.size(); i++) {
22321                        ipw.println(mLoadedVolumes.valueAt(i));
22322                    }
22323                }
22324                ipw.decreaseIndent();
22325            }
22326
22327            if (!checkin && dumpState.isDumping(DumpState.DUMP_DEXOPT)) {
22328                if (dumpState.onTitlePrinted()) pw.println();
22329                dumpDexoptStateLPr(pw, packageName);
22330            }
22331
22332            if (!checkin && dumpState.isDumping(DumpState.DUMP_COMPILER_STATS)) {
22333                if (dumpState.onTitlePrinted()) pw.println();
22334                dumpCompilerStatsLPr(pw, packageName);
22335            }
22336
22337            if (!checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES) && packageName == null) {
22338                if (dumpState.onTitlePrinted()) pw.println();
22339                mSettings.dumpReadMessagesLPr(pw, dumpState);
22340
22341                pw.println();
22342                pw.println("Package warning messages:");
22343                BufferedReader in = null;
22344                String line = null;
22345                try {
22346                    in = new BufferedReader(new FileReader(getSettingsProblemFile()));
22347                    while ((line = in.readLine()) != null) {
22348                        if (line.contains("ignored: updated version")) continue;
22349                        pw.println(line);
22350                    }
22351                } catch (IOException ignored) {
22352                } finally {
22353                    IoUtils.closeQuietly(in);
22354                }
22355            }
22356
22357            if (checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES)) {
22358                BufferedReader in = null;
22359                String line = null;
22360                try {
22361                    in = new BufferedReader(new FileReader(getSettingsProblemFile()));
22362                    while ((line = in.readLine()) != null) {
22363                        if (line.contains("ignored: updated version")) continue;
22364                        pw.print("msg,");
22365                        pw.println(line);
22366                    }
22367                } catch (IOException ignored) {
22368                } finally {
22369                    IoUtils.closeQuietly(in);
22370                }
22371            }
22372        }
22373
22374        // PackageInstaller should be called outside of mPackages lock
22375        if (!checkin && dumpState.isDumping(DumpState.DUMP_INSTALLS) && packageName == null) {
22376            // XXX should handle packageName != null by dumping only install data that
22377            // the given package is involved with.
22378            if (dumpState.onTitlePrinted()) pw.println();
22379            mInstallerService.dump(new IndentingPrintWriter(pw, "  ", 120));
22380        }
22381    }
22382
22383    private void dumpProto(FileDescriptor fd) {
22384        final ProtoOutputStream proto = new ProtoOutputStream(fd);
22385
22386        synchronized (mPackages) {
22387            final long requiredVerifierPackageToken =
22388                    proto.start(PackageServiceDumpProto.REQUIRED_VERIFIER_PACKAGE);
22389            proto.write(PackageServiceDumpProto.PackageShortProto.NAME, mRequiredVerifierPackage);
22390            proto.write(
22391                    PackageServiceDumpProto.PackageShortProto.UID,
22392                    getPackageUid(
22393                            mRequiredVerifierPackage,
22394                            MATCH_DEBUG_TRIAGED_MISSING,
22395                            UserHandle.USER_SYSTEM));
22396            proto.end(requiredVerifierPackageToken);
22397
22398            if (mIntentFilterVerifierComponent != null) {
22399                String verifierPackageName = mIntentFilterVerifierComponent.getPackageName();
22400                final long verifierPackageToken =
22401                        proto.start(PackageServiceDumpProto.VERIFIER_PACKAGE);
22402                proto.write(PackageServiceDumpProto.PackageShortProto.NAME, verifierPackageName);
22403                proto.write(
22404                        PackageServiceDumpProto.PackageShortProto.UID,
22405                        getPackageUid(
22406                                verifierPackageName,
22407                                MATCH_DEBUG_TRIAGED_MISSING,
22408                                UserHandle.USER_SYSTEM));
22409                proto.end(verifierPackageToken);
22410            }
22411
22412            dumpSharedLibrariesProto(proto);
22413            dumpFeaturesProto(proto);
22414            mSettings.dumpPackagesProto(proto);
22415            mSettings.dumpSharedUsersProto(proto);
22416            dumpMessagesProto(proto);
22417        }
22418        proto.flush();
22419    }
22420
22421    private void dumpMessagesProto(ProtoOutputStream proto) {
22422        BufferedReader in = null;
22423        String line = null;
22424        try {
22425            in = new BufferedReader(new FileReader(getSettingsProblemFile()));
22426            while ((line = in.readLine()) != null) {
22427                if (line.contains("ignored: updated version")) continue;
22428                proto.write(PackageServiceDumpProto.MESSAGES, line);
22429            }
22430        } catch (IOException ignored) {
22431        } finally {
22432            IoUtils.closeQuietly(in);
22433        }
22434    }
22435
22436    private void dumpFeaturesProto(ProtoOutputStream proto) {
22437        synchronized (mAvailableFeatures) {
22438            final int count = mAvailableFeatures.size();
22439            for (int i = 0; i < count; i++) {
22440                final FeatureInfo feat = mAvailableFeatures.valueAt(i);
22441                final long featureToken = proto.start(PackageServiceDumpProto.FEATURES);
22442                proto.write(PackageServiceDumpProto.FeatureProto.NAME, feat.name);
22443                proto.write(PackageServiceDumpProto.FeatureProto.VERSION, feat.version);
22444                proto.end(featureToken);
22445            }
22446        }
22447    }
22448
22449    private void dumpSharedLibrariesProto(ProtoOutputStream proto) {
22450        final int count = mSharedLibraries.size();
22451        for (int i = 0; i < count; i++) {
22452            final String libName = mSharedLibraries.keyAt(i);
22453            SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(libName);
22454            if (versionedLib == null) {
22455                continue;
22456            }
22457            final int versionCount = versionedLib.size();
22458            for (int j = 0; j < versionCount; j++) {
22459                final SharedLibraryEntry libEntry = versionedLib.valueAt(j);
22460                final long sharedLibraryToken =
22461                        proto.start(PackageServiceDumpProto.SHARED_LIBRARIES);
22462                proto.write(PackageServiceDumpProto.SharedLibraryProto.NAME, libEntry.info.getName());
22463                final boolean isJar = (libEntry.path != null);
22464                proto.write(PackageServiceDumpProto.SharedLibraryProto.IS_JAR, isJar);
22465                if (isJar) {
22466                    proto.write(PackageServiceDumpProto.SharedLibraryProto.PATH, libEntry.path);
22467                } else {
22468                    proto.write(PackageServiceDumpProto.SharedLibraryProto.APK, libEntry.apk);
22469                }
22470                proto.end(sharedLibraryToken);
22471            }
22472        }
22473    }
22474
22475    private void dumpDexoptStateLPr(PrintWriter pw, String packageName) {
22476        final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, "  ", 120);
22477        ipw.println();
22478        ipw.println("Dexopt state:");
22479        ipw.increaseIndent();
22480        Collection<PackageParser.Package> packages = null;
22481        if (packageName != null) {
22482            PackageParser.Package targetPackage = mPackages.get(packageName);
22483            if (targetPackage != null) {
22484                packages = Collections.singletonList(targetPackage);
22485            } else {
22486                ipw.println("Unable to find package: " + packageName);
22487                return;
22488            }
22489        } else {
22490            packages = mPackages.values();
22491        }
22492
22493        for (PackageParser.Package pkg : packages) {
22494            ipw.println("[" + pkg.packageName + "]");
22495            ipw.increaseIndent();
22496            mPackageDexOptimizer.dumpDexoptState(ipw, pkg);
22497            ipw.decreaseIndent();
22498        }
22499    }
22500
22501    private void dumpCompilerStatsLPr(PrintWriter pw, String packageName) {
22502        final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, "  ", 120);
22503        ipw.println();
22504        ipw.println("Compiler stats:");
22505        ipw.increaseIndent();
22506        Collection<PackageParser.Package> packages = null;
22507        if (packageName != null) {
22508            PackageParser.Package targetPackage = mPackages.get(packageName);
22509            if (targetPackage != null) {
22510                packages = Collections.singletonList(targetPackage);
22511            } else {
22512                ipw.println("Unable to find package: " + packageName);
22513                return;
22514            }
22515        } else {
22516            packages = mPackages.values();
22517        }
22518
22519        for (PackageParser.Package pkg : packages) {
22520            ipw.println("[" + pkg.packageName + "]");
22521            ipw.increaseIndent();
22522
22523            CompilerStats.PackageStats stats = getCompilerPackageStats(pkg.packageName);
22524            if (stats == null) {
22525                ipw.println("(No recorded stats)");
22526            } else {
22527                stats.dump(ipw);
22528            }
22529            ipw.decreaseIndent();
22530        }
22531    }
22532
22533    private String dumpDomainString(String packageName) {
22534        List<IntentFilterVerificationInfo> iviList = getIntentFilterVerifications(packageName)
22535                .getList();
22536        List<IntentFilter> filters = getAllIntentFilters(packageName).getList();
22537
22538        ArraySet<String> result = new ArraySet<>();
22539        if (iviList.size() > 0) {
22540            for (IntentFilterVerificationInfo ivi : iviList) {
22541                for (String host : ivi.getDomains()) {
22542                    result.add(host);
22543                }
22544            }
22545        }
22546        if (filters != null && filters.size() > 0) {
22547            for (IntentFilter filter : filters) {
22548                if (filter.hasCategory(Intent.CATEGORY_BROWSABLE)
22549                        && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) ||
22550                                filter.hasDataScheme(IntentFilter.SCHEME_HTTPS))) {
22551                    result.addAll(filter.getHostsList());
22552                }
22553            }
22554        }
22555
22556        StringBuilder sb = new StringBuilder(result.size() * 16);
22557        for (String domain : result) {
22558            if (sb.length() > 0) sb.append(" ");
22559            sb.append(domain);
22560        }
22561        return sb.toString();
22562    }
22563
22564    // ------- apps on sdcard specific code -------
22565    static final boolean DEBUG_SD_INSTALL = false;
22566
22567    private static final String SD_ENCRYPTION_KEYSTORE_NAME = "AppsOnSD";
22568
22569    private static final String SD_ENCRYPTION_ALGORITHM = "AES";
22570
22571    private boolean mMediaMounted = false;
22572
22573    static String getEncryptKey() {
22574        try {
22575            String sdEncKey = SystemKeyStore.getInstance().retrieveKeyHexString(
22576                    SD_ENCRYPTION_KEYSTORE_NAME);
22577            if (sdEncKey == null) {
22578                sdEncKey = SystemKeyStore.getInstance().generateNewKeyHexString(128,
22579                        SD_ENCRYPTION_ALGORITHM, SD_ENCRYPTION_KEYSTORE_NAME);
22580                if (sdEncKey == null) {
22581                    Slog.e(TAG, "Failed to create encryption keys");
22582                    return null;
22583                }
22584            }
22585            return sdEncKey;
22586        } catch (NoSuchAlgorithmException nsae) {
22587            Slog.e(TAG, "Failed to create encryption keys with exception: " + nsae);
22588            return null;
22589        } catch (IOException ioe) {
22590            Slog.e(TAG, "Failed to retrieve encryption keys with exception: " + ioe);
22591            return null;
22592        }
22593    }
22594
22595    /*
22596     * Update media status on PackageManager.
22597     */
22598    @Override
22599    public void updateExternalMediaStatus(final boolean mediaStatus, final boolean reportStatus) {
22600        enforceSystemOrRoot("Media status can only be updated by the system");
22601        // reader; this apparently protects mMediaMounted, but should probably
22602        // be a different lock in that case.
22603        synchronized (mPackages) {
22604            Log.i(TAG, "Updating external media status from "
22605                    + (mMediaMounted ? "mounted" : "unmounted") + " to "
22606                    + (mediaStatus ? "mounted" : "unmounted"));
22607            if (DEBUG_SD_INSTALL)
22608                Log.i(TAG, "updateExternalMediaStatus:: mediaStatus=" + mediaStatus
22609                        + ", mMediaMounted=" + mMediaMounted);
22610            if (mediaStatus == mMediaMounted) {
22611                final Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1
22612                        : 0, -1);
22613                mHandler.sendMessage(msg);
22614                return;
22615            }
22616            mMediaMounted = mediaStatus;
22617        }
22618        // Queue up an async operation since the package installation may take a
22619        // little while.
22620        mHandler.post(new Runnable() {
22621            public void run() {
22622                updateExternalMediaStatusInner(mediaStatus, reportStatus, true);
22623            }
22624        });
22625    }
22626
22627    /**
22628     * Called by StorageManagerService when the initial ASECs to scan are available.
22629     * Should block until all the ASEC containers are finished being scanned.
22630     */
22631    public void scanAvailableAsecs() {
22632        updateExternalMediaStatusInner(true, false, false);
22633    }
22634
22635    /*
22636     * Collect information of applications on external media, map them against
22637     * existing containers and update information based on current mount status.
22638     * Please note that we always have to report status if reportStatus has been
22639     * set to true especially when unloading packages.
22640     */
22641    private void updateExternalMediaStatusInner(boolean isMounted, boolean reportStatus,
22642            boolean externalStorage) {
22643        ArrayMap<AsecInstallArgs, String> processCids = new ArrayMap<>();
22644        int[] uidArr = EmptyArray.INT;
22645
22646        final String[] list = PackageHelper.getSecureContainerList();
22647        if (ArrayUtils.isEmpty(list)) {
22648            Log.i(TAG, "No secure containers found");
22649        } else {
22650            // Process list of secure containers and categorize them
22651            // as active or stale based on their package internal state.
22652
22653            // reader
22654            synchronized (mPackages) {
22655                for (String cid : list) {
22656                    // Leave stages untouched for now; installer service owns them
22657                    if (PackageInstallerService.isStageName(cid)) continue;
22658
22659                    if (DEBUG_SD_INSTALL)
22660                        Log.i(TAG, "Processing container " + cid);
22661                    String pkgName = getAsecPackageName(cid);
22662                    if (pkgName == null) {
22663                        Slog.i(TAG, "Found stale container " + cid + " with no package name");
22664                        continue;
22665                    }
22666                    if (DEBUG_SD_INSTALL)
22667                        Log.i(TAG, "Looking for pkg : " + pkgName);
22668
22669                    final PackageSetting ps = mSettings.mPackages.get(pkgName);
22670                    if (ps == null) {
22671                        Slog.i(TAG, "Found stale container " + cid + " with no matching settings");
22672                        continue;
22673                    }
22674
22675                    /*
22676                     * Skip packages that are not external if we're unmounting
22677                     * external storage.
22678                     */
22679                    if (externalStorage && !isMounted && !isExternal(ps)) {
22680                        continue;
22681                    }
22682
22683                    final AsecInstallArgs args = new AsecInstallArgs(cid,
22684                            getAppDexInstructionSets(ps), ps.isForwardLocked());
22685                    // The package status is changed only if the code path
22686                    // matches between settings and the container id.
22687                    if (ps.codePathString != null
22688                            && ps.codePathString.startsWith(args.getCodePath())) {
22689                        if (DEBUG_SD_INSTALL) {
22690                            Log.i(TAG, "Container : " + cid + " corresponds to pkg : " + pkgName
22691                                    + " at code path: " + ps.codePathString);
22692                        }
22693
22694                        // We do have a valid package installed on sdcard
22695                        processCids.put(args, ps.codePathString);
22696                        final int uid = ps.appId;
22697                        if (uid != -1) {
22698                            uidArr = ArrayUtils.appendInt(uidArr, uid);
22699                        }
22700                    } else {
22701                        Slog.i(TAG, "Found stale container " + cid + ": expected codePath="
22702                                + ps.codePathString);
22703                    }
22704                }
22705            }
22706
22707            Arrays.sort(uidArr);
22708        }
22709
22710        // Process packages with valid entries.
22711        if (isMounted) {
22712            if (DEBUG_SD_INSTALL)
22713                Log.i(TAG, "Loading packages");
22714            loadMediaPackages(processCids, uidArr, externalStorage);
22715            startCleaningPackages();
22716            mInstallerService.onSecureContainersAvailable();
22717        } else {
22718            if (DEBUG_SD_INSTALL)
22719                Log.i(TAG, "Unloading packages");
22720            unloadMediaPackages(processCids, uidArr, reportStatus);
22721        }
22722    }
22723
22724    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
22725            ArrayList<ApplicationInfo> infos, IIntentReceiver finishedReceiver) {
22726        final int size = infos.size();
22727        final String[] packageNames = new String[size];
22728        final int[] packageUids = new int[size];
22729        for (int i = 0; i < size; i++) {
22730            final ApplicationInfo info = infos.get(i);
22731            packageNames[i] = info.packageName;
22732            packageUids[i] = info.uid;
22733        }
22734        sendResourcesChangedBroadcast(mediaStatus, replacing, packageNames, packageUids,
22735                finishedReceiver);
22736    }
22737
22738    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
22739            ArrayList<String> pkgList, int uidArr[], IIntentReceiver finishedReceiver) {
22740        sendResourcesChangedBroadcast(mediaStatus, replacing,
22741                pkgList.toArray(new String[pkgList.size()]), uidArr, finishedReceiver);
22742    }
22743
22744    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
22745            String[] pkgList, int uidArr[], IIntentReceiver finishedReceiver) {
22746        int size = pkgList.length;
22747        if (size > 0) {
22748            // Send broadcasts here
22749            Bundle extras = new Bundle();
22750            extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList);
22751            if (uidArr != null) {
22752                extras.putIntArray(Intent.EXTRA_CHANGED_UID_LIST, uidArr);
22753            }
22754            if (replacing) {
22755                extras.putBoolean(Intent.EXTRA_REPLACING, replacing);
22756            }
22757            String action = mediaStatus ? Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE
22758                    : Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE;
22759            sendPackageBroadcast(action, null, extras, 0, null, finishedReceiver, null);
22760        }
22761    }
22762
22763   /*
22764     * Look at potentially valid container ids from processCids If package
22765     * information doesn't match the one on record or package scanning fails,
22766     * the cid is added to list of removeCids. We currently don't delete stale
22767     * containers.
22768     */
22769    private void loadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int[] uidArr,
22770            boolean externalStorage) {
22771        ArrayList<String> pkgList = new ArrayList<String>();
22772        Set<AsecInstallArgs> keys = processCids.keySet();
22773
22774        for (AsecInstallArgs args : keys) {
22775            String codePath = processCids.get(args);
22776            if (DEBUG_SD_INSTALL)
22777                Log.i(TAG, "Loading container : " + args.cid);
22778            int retCode = PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
22779            try {
22780                // Make sure there are no container errors first.
22781                if (args.doPreInstall(PackageManager.INSTALL_SUCCEEDED) != PackageManager.INSTALL_SUCCEEDED) {
22782                    Slog.e(TAG, "Failed to mount cid : " + args.cid
22783                            + " when installing from sdcard");
22784                    continue;
22785                }
22786                // Check code path here.
22787                if (codePath == null || !codePath.startsWith(args.getCodePath())) {
22788                    Slog.e(TAG, "Container " + args.cid + " cachepath " + args.getCodePath()
22789                            + " does not match one in settings " + codePath);
22790                    continue;
22791                }
22792                // Parse package
22793                int parseFlags = mDefParseFlags;
22794                if (args.isExternalAsec()) {
22795                    parseFlags |= PackageParser.PARSE_EXTERNAL_STORAGE;
22796                }
22797                if (args.isFwdLocked()) {
22798                    parseFlags |= PackageParser.PARSE_FORWARD_LOCK;
22799                }
22800
22801                synchronized (mInstallLock) {
22802                    PackageParser.Package pkg = null;
22803                    try {
22804                        // Sadly we don't know the package name yet to freeze it
22805                        pkg = scanPackageTracedLI(new File(codePath), parseFlags,
22806                                SCAN_IGNORE_FROZEN, 0, null);
22807                    } catch (PackageManagerException e) {
22808                        Slog.w(TAG, "Failed to scan " + codePath + ": " + e.getMessage());
22809                    }
22810                    // Scan the package
22811                    if (pkg != null) {
22812                        /*
22813                         * TODO why is the lock being held? doPostInstall is
22814                         * called in other places without the lock. This needs
22815                         * to be straightened out.
22816                         */
22817                        // writer
22818                        synchronized (mPackages) {
22819                            retCode = PackageManager.INSTALL_SUCCEEDED;
22820                            pkgList.add(pkg.packageName);
22821                            // Post process args
22822                            args.doPostInstall(PackageManager.INSTALL_SUCCEEDED,
22823                                    pkg.applicationInfo.uid);
22824                        }
22825                    } else {
22826                        Slog.i(TAG, "Failed to install pkg from  " + codePath + " from sdcard");
22827                    }
22828                }
22829
22830            } finally {
22831                if (retCode != PackageManager.INSTALL_SUCCEEDED) {
22832                    Log.w(TAG, "Container " + args.cid + " is stale, retCode=" + retCode);
22833                }
22834            }
22835        }
22836        // writer
22837        synchronized (mPackages) {
22838            // If the platform SDK has changed since the last time we booted,
22839            // we need to re-grant app permission to catch any new ones that
22840            // appear. This is really a hack, and means that apps can in some
22841            // cases get permissions that the user didn't initially explicitly
22842            // allow... it would be nice to have some better way to handle
22843            // this situation.
22844            final VersionInfo ver = externalStorage ? mSettings.getExternalVersion()
22845                    : mSettings.getInternalVersion();
22846            final String volumeUuid = externalStorage ? StorageManager.UUID_PRIMARY_PHYSICAL
22847                    : StorageManager.UUID_PRIVATE_INTERNAL;
22848
22849            int updateFlags = UPDATE_PERMISSIONS_ALL;
22850            if (ver.sdkVersion != mSdkVersion) {
22851                logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to "
22852                        + mSdkVersion + "; regranting permissions for external");
22853                updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL;
22854            }
22855            updatePermissionsLPw(null, null, volumeUuid, updateFlags);
22856
22857            // Yay, everything is now upgraded
22858            ver.forceCurrent();
22859
22860            // can downgrade to reader
22861            // Persist settings
22862            mSettings.writeLPr();
22863        }
22864        // Send a broadcast to let everyone know we are done processing
22865        if (pkgList.size() > 0) {
22866            sendResourcesChangedBroadcast(true, false, pkgList, uidArr, null);
22867        }
22868    }
22869
22870   /*
22871     * Utility method to unload a list of specified containers
22872     */
22873    private void unloadAllContainers(Set<AsecInstallArgs> cidArgs) {
22874        // Just unmount all valid containers.
22875        for (AsecInstallArgs arg : cidArgs) {
22876            synchronized (mInstallLock) {
22877                arg.doPostDeleteLI(false);
22878           }
22879       }
22880   }
22881
22882    /*
22883     * Unload packages mounted on external media. This involves deleting package
22884     * data from internal structures, sending broadcasts about disabled packages,
22885     * gc'ing to free up references, unmounting all secure containers
22886     * corresponding to packages on external media, and posting a
22887     * UPDATED_MEDIA_STATUS message if status has been requested. Please note
22888     * that we always have to post this message if status has been requested no
22889     * matter what.
22890     */
22891    private void unloadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int uidArr[],
22892            final boolean reportStatus) {
22893        if (DEBUG_SD_INSTALL)
22894            Log.i(TAG, "unloading media packages");
22895        ArrayList<String> pkgList = new ArrayList<String>();
22896        ArrayList<AsecInstallArgs> failedList = new ArrayList<AsecInstallArgs>();
22897        final Set<AsecInstallArgs> keys = processCids.keySet();
22898        for (AsecInstallArgs args : keys) {
22899            String pkgName = args.getPackageName();
22900            if (DEBUG_SD_INSTALL)
22901                Log.i(TAG, "Trying to unload pkg : " + pkgName);
22902            // Delete package internally
22903            PackageRemovedInfo outInfo = new PackageRemovedInfo(this);
22904            synchronized (mInstallLock) {
22905                final int deleteFlags = PackageManager.DELETE_KEEP_DATA;
22906                final boolean res;
22907                try (PackageFreezer freezer = freezePackageForDelete(pkgName, deleteFlags,
22908                        "unloadMediaPackages")) {
22909                    res = deletePackageLIF(pkgName, null, false, null, deleteFlags, outInfo, false,
22910                            null);
22911                }
22912                if (res) {
22913                    pkgList.add(pkgName);
22914                } else {
22915                    Slog.e(TAG, "Failed to delete pkg from sdcard : " + pkgName);
22916                    failedList.add(args);
22917                }
22918            }
22919        }
22920
22921        // reader
22922        synchronized (mPackages) {
22923            // We didn't update the settings after removing each package;
22924            // write them now for all packages.
22925            mSettings.writeLPr();
22926        }
22927
22928        // We have to absolutely send UPDATED_MEDIA_STATUS only
22929        // after confirming that all the receivers processed the ordered
22930        // broadcast when packages get disabled, force a gc to clean things up.
22931        // and unload all the containers.
22932        if (pkgList.size() > 0) {
22933            sendResourcesChangedBroadcast(false, false, pkgList, uidArr,
22934                    new IIntentReceiver.Stub() {
22935                public void performReceive(Intent intent, int resultCode, String data,
22936                        Bundle extras, boolean ordered, boolean sticky,
22937                        int sendingUser) throws RemoteException {
22938                    Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS,
22939                            reportStatus ? 1 : 0, 1, keys);
22940                    mHandler.sendMessage(msg);
22941                }
22942            });
22943        } else {
22944            Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 : 0, -1,
22945                    keys);
22946            mHandler.sendMessage(msg);
22947        }
22948    }
22949
22950    private void loadPrivatePackages(final VolumeInfo vol) {
22951        mHandler.post(new Runnable() {
22952            @Override
22953            public void run() {
22954                loadPrivatePackagesInner(vol);
22955            }
22956        });
22957    }
22958
22959    private void loadPrivatePackagesInner(VolumeInfo vol) {
22960        final String volumeUuid = vol.fsUuid;
22961        if (TextUtils.isEmpty(volumeUuid)) {
22962            Slog.e(TAG, "Loading internal storage is probably a mistake; ignoring");
22963            return;
22964        }
22965
22966        final ArrayList<PackageFreezer> freezers = new ArrayList<>();
22967        final ArrayList<ApplicationInfo> loaded = new ArrayList<>();
22968        final int parseFlags = mDefParseFlags | PackageParser.PARSE_EXTERNAL_STORAGE;
22969
22970        final VersionInfo ver;
22971        final List<PackageSetting> packages;
22972        synchronized (mPackages) {
22973            ver = mSettings.findOrCreateVersion(volumeUuid);
22974            packages = mSettings.getVolumePackagesLPr(volumeUuid);
22975        }
22976
22977        for (PackageSetting ps : packages) {
22978            freezers.add(freezePackage(ps.name, "loadPrivatePackagesInner"));
22979            synchronized (mInstallLock) {
22980                final PackageParser.Package pkg;
22981                try {
22982                    pkg = scanPackageTracedLI(ps.codePath, parseFlags, SCAN_INITIAL, 0, null);
22983                    loaded.add(pkg.applicationInfo);
22984
22985                } catch (PackageManagerException e) {
22986                    Slog.w(TAG, "Failed to scan " + ps.codePath + ": " + e.getMessage());
22987                }
22988
22989                if (!Build.FINGERPRINT.equals(ver.fingerprint)) {
22990                    clearAppDataLIF(ps.pkg, UserHandle.USER_ALL,
22991                            StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE
22992                                    | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
22993                }
22994            }
22995        }
22996
22997        // Reconcile app data for all started/unlocked users
22998        final StorageManager sm = mContext.getSystemService(StorageManager.class);
22999        final UserManager um = mContext.getSystemService(UserManager.class);
23000        UserManagerInternal umInternal = getUserManagerInternal();
23001        for (UserInfo user : um.getUsers()) {
23002            final int flags;
23003            if (umInternal.isUserUnlockingOrUnlocked(user.id)) {
23004                flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
23005            } else if (umInternal.isUserRunning(user.id)) {
23006                flags = StorageManager.FLAG_STORAGE_DE;
23007            } else {
23008                continue;
23009            }
23010
23011            try {
23012                sm.prepareUserStorage(volumeUuid, user.id, user.serialNumber, flags);
23013                synchronized (mInstallLock) {
23014                    reconcileAppsDataLI(volumeUuid, user.id, flags, true /* migrateAppData */);
23015                }
23016            } catch (IllegalStateException e) {
23017                // Device was probably ejected, and we'll process that event momentarily
23018                Slog.w(TAG, "Failed to prepare storage: " + e);
23019            }
23020        }
23021
23022        synchronized (mPackages) {
23023            int updateFlags = UPDATE_PERMISSIONS_ALL;
23024            if (ver.sdkVersion != mSdkVersion) {
23025                logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to "
23026                        + mSdkVersion + "; regranting permissions for " + volumeUuid);
23027                updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL;
23028            }
23029            updatePermissionsLPw(null, null, volumeUuid, updateFlags);
23030
23031            // Yay, everything is now upgraded
23032            ver.forceCurrent();
23033
23034            mSettings.writeLPr();
23035        }
23036
23037        for (PackageFreezer freezer : freezers) {
23038            freezer.close();
23039        }
23040
23041        if (DEBUG_INSTALL) Slog.d(TAG, "Loaded packages " + loaded);
23042        sendResourcesChangedBroadcast(true, false, loaded, null);
23043        mLoadedVolumes.add(vol.getId());
23044    }
23045
23046    private void unloadPrivatePackages(final VolumeInfo vol) {
23047        mHandler.post(new Runnable() {
23048            @Override
23049            public void run() {
23050                unloadPrivatePackagesInner(vol);
23051            }
23052        });
23053    }
23054
23055    private void unloadPrivatePackagesInner(VolumeInfo vol) {
23056        final String volumeUuid = vol.fsUuid;
23057        if (TextUtils.isEmpty(volumeUuid)) {
23058            Slog.e(TAG, "Unloading internal storage is probably a mistake; ignoring");
23059            return;
23060        }
23061
23062        final ArrayList<ApplicationInfo> unloaded = new ArrayList<>();
23063        synchronized (mInstallLock) {
23064        synchronized (mPackages) {
23065            final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(volumeUuid);
23066            for (PackageSetting ps : packages) {
23067                if (ps.pkg == null) continue;
23068
23069                final ApplicationInfo info = ps.pkg.applicationInfo;
23070                final int deleteFlags = PackageManager.DELETE_KEEP_DATA;
23071                final PackageRemovedInfo outInfo = new PackageRemovedInfo(this);
23072
23073                try (PackageFreezer freezer = freezePackageForDelete(ps.name, deleteFlags,
23074                        "unloadPrivatePackagesInner")) {
23075                    if (deletePackageLIF(ps.name, null, false, null, deleteFlags, outInfo,
23076                            false, null)) {
23077                        unloaded.add(info);
23078                    } else {
23079                        Slog.w(TAG, "Failed to unload " + ps.codePath);
23080                    }
23081                }
23082
23083                // Try very hard to release any references to this package
23084                // so we don't risk the system server being killed due to
23085                // open FDs
23086                AttributeCache.instance().removePackage(ps.name);
23087            }
23088
23089            mSettings.writeLPr();
23090        }
23091        }
23092
23093        if (DEBUG_INSTALL) Slog.d(TAG, "Unloaded packages " + unloaded);
23094        sendResourcesChangedBroadcast(false, false, unloaded, null);
23095        mLoadedVolumes.remove(vol.getId());
23096
23097        // Try very hard to release any references to this path so we don't risk
23098        // the system server being killed due to open FDs
23099        ResourcesManager.getInstance().invalidatePath(vol.getPath().getAbsolutePath());
23100
23101        for (int i = 0; i < 3; i++) {
23102            System.gc();
23103            System.runFinalization();
23104        }
23105    }
23106
23107    private void assertPackageKnown(String volumeUuid, String packageName)
23108            throws PackageManagerException {
23109        synchronized (mPackages) {
23110            // Normalize package name to handle renamed packages
23111            packageName = normalizePackageNameLPr(packageName);
23112
23113            final PackageSetting ps = mSettings.mPackages.get(packageName);
23114            if (ps == null) {
23115                throw new PackageManagerException("Package " + packageName + " is unknown");
23116            } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) {
23117                throw new PackageManagerException(
23118                        "Package " + packageName + " found on unknown volume " + volumeUuid
23119                                + "; expected volume " + ps.volumeUuid);
23120            }
23121        }
23122    }
23123
23124    private void assertPackageKnownAndInstalled(String volumeUuid, String packageName, int userId)
23125            throws PackageManagerException {
23126        synchronized (mPackages) {
23127            // Normalize package name to handle renamed packages
23128            packageName = normalizePackageNameLPr(packageName);
23129
23130            final PackageSetting ps = mSettings.mPackages.get(packageName);
23131            if (ps == null) {
23132                throw new PackageManagerException("Package " + packageName + " is unknown");
23133            } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) {
23134                throw new PackageManagerException(
23135                        "Package " + packageName + " found on unknown volume " + volumeUuid
23136                                + "; expected volume " + ps.volumeUuid);
23137            } else if (!ps.getInstalled(userId)) {
23138                throw new PackageManagerException(
23139                        "Package " + packageName + " not installed for user " + userId);
23140            }
23141        }
23142    }
23143
23144    private List<String> collectAbsoluteCodePaths() {
23145        synchronized (mPackages) {
23146            List<String> codePaths = new ArrayList<>();
23147            final int packageCount = mSettings.mPackages.size();
23148            for (int i = 0; i < packageCount; i++) {
23149                final PackageSetting ps = mSettings.mPackages.valueAt(i);
23150                codePaths.add(ps.codePath.getAbsolutePath());
23151            }
23152            return codePaths;
23153        }
23154    }
23155
23156    /**
23157     * Examine all apps present on given mounted volume, and destroy apps that
23158     * aren't expected, either due to uninstallation or reinstallation on
23159     * another volume.
23160     */
23161    private void reconcileApps(String volumeUuid) {
23162        List<String> absoluteCodePaths = collectAbsoluteCodePaths();
23163        List<File> filesToDelete = null;
23164
23165        final File[] files = FileUtils.listFilesOrEmpty(
23166                Environment.getDataAppDirectory(volumeUuid));
23167        for (File file : files) {
23168            final boolean isPackage = (isApkFile(file) || file.isDirectory())
23169                    && !PackageInstallerService.isStageName(file.getName());
23170            if (!isPackage) {
23171                // Ignore entries which are not packages
23172                continue;
23173            }
23174
23175            String absolutePath = file.getAbsolutePath();
23176
23177            boolean pathValid = false;
23178            final int absoluteCodePathCount = absoluteCodePaths.size();
23179            for (int i = 0; i < absoluteCodePathCount; i++) {
23180                String absoluteCodePath = absoluteCodePaths.get(i);
23181                if (absolutePath.startsWith(absoluteCodePath)) {
23182                    pathValid = true;
23183                    break;
23184                }
23185            }
23186
23187            if (!pathValid) {
23188                if (filesToDelete == null) {
23189                    filesToDelete = new ArrayList<>();
23190                }
23191                filesToDelete.add(file);
23192            }
23193        }
23194
23195        if (filesToDelete != null) {
23196            final int fileToDeleteCount = filesToDelete.size();
23197            for (int i = 0; i < fileToDeleteCount; i++) {
23198                File fileToDelete = filesToDelete.get(i);
23199                logCriticalInfo(Log.WARN, "Destroying orphaned" + fileToDelete);
23200                synchronized (mInstallLock) {
23201                    removeCodePathLI(fileToDelete);
23202                }
23203            }
23204        }
23205    }
23206
23207    /**
23208     * Reconcile all app data for the given user.
23209     * <p>
23210     * Verifies that directories exist and that ownership and labeling is
23211     * correct for all installed apps on all mounted volumes.
23212     */
23213    void reconcileAppsData(int userId, int flags, boolean migrateAppsData) {
23214        final StorageManager storage = mContext.getSystemService(StorageManager.class);
23215        for (VolumeInfo vol : storage.getWritablePrivateVolumes()) {
23216            final String volumeUuid = vol.getFsUuid();
23217            synchronized (mInstallLock) {
23218                reconcileAppsDataLI(volumeUuid, userId, flags, migrateAppsData);
23219            }
23220        }
23221    }
23222
23223    private void reconcileAppsDataLI(String volumeUuid, int userId, int flags,
23224            boolean migrateAppData) {
23225        reconcileAppsDataLI(volumeUuid, userId, flags, migrateAppData, false /* onlyCoreApps */);
23226    }
23227
23228    /**
23229     * Reconcile all app data on given mounted volume.
23230     * <p>
23231     * Destroys app data that isn't expected, either due to uninstallation or
23232     * reinstallation on another volume.
23233     * <p>
23234     * Verifies that directories exist and that ownership and labeling is
23235     * correct for all installed apps.
23236     * @returns list of skipped non-core packages (if {@code onlyCoreApps} is true)
23237     */
23238    private List<String> reconcileAppsDataLI(String volumeUuid, int userId, int flags,
23239            boolean migrateAppData, boolean onlyCoreApps) {
23240        Slog.v(TAG, "reconcileAppsData for " + volumeUuid + " u" + userId + " 0x"
23241                + Integer.toHexString(flags) + " migrateAppData=" + migrateAppData);
23242        List<String> result = onlyCoreApps ? new ArrayList<>() : null;
23243
23244        final File ceDir = Environment.getDataUserCeDirectory(volumeUuid, userId);
23245        final File deDir = Environment.getDataUserDeDirectory(volumeUuid, userId);
23246
23247        // First look for stale data that doesn't belong, and check if things
23248        // have changed since we did our last restorecon
23249        if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) {
23250            if (StorageManager.isFileEncryptedNativeOrEmulated()
23251                    && !StorageManager.isUserKeyUnlocked(userId)) {
23252                throw new RuntimeException(
23253                        "Yikes, someone asked us to reconcile CE storage while " + userId
23254                                + " was still locked; this would have caused massive data loss!");
23255            }
23256
23257            final File[] files = FileUtils.listFilesOrEmpty(ceDir);
23258            for (File file : files) {
23259                final String packageName = file.getName();
23260                try {
23261                    assertPackageKnownAndInstalled(volumeUuid, packageName, userId);
23262                } catch (PackageManagerException e) {
23263                    logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e);
23264                    try {
23265                        mInstaller.destroyAppData(volumeUuid, packageName, userId,
23266                                StorageManager.FLAG_STORAGE_CE, 0);
23267                    } catch (InstallerException e2) {
23268                        logCriticalInfo(Log.WARN, "Failed to destroy: " + e2);
23269                    }
23270                }
23271            }
23272        }
23273        if ((flags & StorageManager.FLAG_STORAGE_DE) != 0) {
23274            final File[] files = FileUtils.listFilesOrEmpty(deDir);
23275            for (File file : files) {
23276                final String packageName = file.getName();
23277                try {
23278                    assertPackageKnownAndInstalled(volumeUuid, packageName, userId);
23279                } catch (PackageManagerException e) {
23280                    logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e);
23281                    try {
23282                        mInstaller.destroyAppData(volumeUuid, packageName, userId,
23283                                StorageManager.FLAG_STORAGE_DE, 0);
23284                    } catch (InstallerException e2) {
23285                        logCriticalInfo(Log.WARN, "Failed to destroy: " + e2);
23286                    }
23287                }
23288            }
23289        }
23290
23291        // Ensure that data directories are ready to roll for all packages
23292        // installed for this volume and user
23293        final List<PackageSetting> packages;
23294        synchronized (mPackages) {
23295            packages = mSettings.getVolumePackagesLPr(volumeUuid);
23296        }
23297        int preparedCount = 0;
23298        for (PackageSetting ps : packages) {
23299            final String packageName = ps.name;
23300            if (ps.pkg == null) {
23301                Slog.w(TAG, "Odd, missing scanned package " + packageName);
23302                // TODO: might be due to legacy ASEC apps; we should circle back
23303                // and reconcile again once they're scanned
23304                continue;
23305            }
23306            // Skip non-core apps if requested
23307            if (onlyCoreApps && !ps.pkg.coreApp) {
23308                result.add(packageName);
23309                continue;
23310            }
23311
23312            if (ps.getInstalled(userId)) {
23313                prepareAppDataAndMigrateLIF(ps.pkg, userId, flags, migrateAppData);
23314                preparedCount++;
23315            }
23316        }
23317
23318        Slog.v(TAG, "reconcileAppsData finished " + preparedCount + " packages");
23319        return result;
23320    }
23321
23322    /**
23323     * Prepare app data for the given app just after it was installed or
23324     * upgraded. This method carefully only touches users that it's installed
23325     * for, and it forces a restorecon to handle any seinfo changes.
23326     * <p>
23327     * Verifies that directories exist and that ownership and labeling is
23328     * correct for all installed apps. If there is an ownership mismatch, it
23329     * will try recovering system apps by wiping data; third-party app data is
23330     * left intact.
23331     * <p>
23332     * <em>Note: To avoid a deadlock, do not call this method with {@code mPackages} lock held</em>
23333     */
23334    private void prepareAppDataAfterInstallLIF(PackageParser.Package pkg) {
23335        final PackageSetting ps;
23336        synchronized (mPackages) {
23337            ps = mSettings.mPackages.get(pkg.packageName);
23338            mSettings.writeKernelMappingLPr(ps);
23339        }
23340
23341        final UserManager um = mContext.getSystemService(UserManager.class);
23342        UserManagerInternal umInternal = getUserManagerInternal();
23343        for (UserInfo user : um.getUsers()) {
23344            final int flags;
23345            if (umInternal.isUserUnlockingOrUnlocked(user.id)) {
23346                flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
23347            } else if (umInternal.isUserRunning(user.id)) {
23348                flags = StorageManager.FLAG_STORAGE_DE;
23349            } else {
23350                continue;
23351            }
23352
23353            if (ps.getInstalled(user.id)) {
23354                // TODO: when user data is locked, mark that we're still dirty
23355                prepareAppDataLIF(pkg, user.id, flags);
23356            }
23357        }
23358    }
23359
23360    /**
23361     * Prepare app data for the given app.
23362     * <p>
23363     * Verifies that directories exist and that ownership and labeling is
23364     * correct for all installed apps. If there is an ownership mismatch, this
23365     * will try recovering system apps by wiping data; third-party app data is
23366     * left intact.
23367     */
23368    private void prepareAppDataLIF(PackageParser.Package pkg, int userId, int flags) {
23369        if (pkg == null) {
23370            Slog.wtf(TAG, "Package was null!", new Throwable());
23371            return;
23372        }
23373        prepareAppDataLeafLIF(pkg, userId, flags);
23374        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
23375        for (int i = 0; i < childCount; i++) {
23376            prepareAppDataLeafLIF(pkg.childPackages.get(i), userId, flags);
23377        }
23378    }
23379
23380    private void prepareAppDataAndMigrateLIF(PackageParser.Package pkg, int userId, int flags,
23381            boolean maybeMigrateAppData) {
23382        prepareAppDataLIF(pkg, userId, flags);
23383
23384        if (maybeMigrateAppData && maybeMigrateAppDataLIF(pkg, userId)) {
23385            // We may have just shuffled around app data directories, so
23386            // prepare them one more time
23387            prepareAppDataLIF(pkg, userId, flags);
23388        }
23389    }
23390
23391    private void prepareAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) {
23392        if (DEBUG_APP_DATA) {
23393            Slog.v(TAG, "prepareAppData for " + pkg.packageName + " u" + userId + " 0x"
23394                    + Integer.toHexString(flags));
23395        }
23396
23397        final String volumeUuid = pkg.volumeUuid;
23398        final String packageName = pkg.packageName;
23399        final ApplicationInfo app = pkg.applicationInfo;
23400        final int appId = UserHandle.getAppId(app.uid);
23401
23402        Preconditions.checkNotNull(app.seInfo);
23403
23404        long ceDataInode = -1;
23405        try {
23406            ceDataInode = mInstaller.createAppData(volumeUuid, packageName, userId, flags,
23407                    appId, app.seInfo, app.targetSdkVersion);
23408        } catch (InstallerException e) {
23409            if (app.isSystemApp()) {
23410                logCriticalInfo(Log.ERROR, "Failed to create app data for " + packageName
23411                        + ", but trying to recover: " + e);
23412                destroyAppDataLeafLIF(pkg, userId, flags);
23413                try {
23414                    ceDataInode = mInstaller.createAppData(volumeUuid, packageName, userId, flags,
23415                            appId, app.seInfo, app.targetSdkVersion);
23416                    logCriticalInfo(Log.DEBUG, "Recovery succeeded!");
23417                } catch (InstallerException e2) {
23418                    logCriticalInfo(Log.DEBUG, "Recovery failed!");
23419                }
23420            } else {
23421                Slog.e(TAG, "Failed to create app data for " + packageName + ": " + e);
23422            }
23423        }
23424
23425        if ((flags & StorageManager.FLAG_STORAGE_CE) != 0 && ceDataInode != -1) {
23426            // TODO: mark this structure as dirty so we persist it!
23427            synchronized (mPackages) {
23428                final PackageSetting ps = mSettings.mPackages.get(packageName);
23429                if (ps != null) {
23430                    ps.setCeDataInode(ceDataInode, userId);
23431                }
23432            }
23433        }
23434
23435        prepareAppDataContentsLeafLIF(pkg, userId, flags);
23436    }
23437
23438    private void prepareAppDataContentsLIF(PackageParser.Package pkg, int userId, int flags) {
23439        if (pkg == null) {
23440            Slog.wtf(TAG, "Package was null!", new Throwable());
23441            return;
23442        }
23443        prepareAppDataContentsLeafLIF(pkg, userId, flags);
23444        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
23445        for (int i = 0; i < childCount; i++) {
23446            prepareAppDataContentsLeafLIF(pkg.childPackages.get(i), userId, flags);
23447        }
23448    }
23449
23450    private void prepareAppDataContentsLeafLIF(PackageParser.Package pkg, int userId, int flags) {
23451        final String volumeUuid = pkg.volumeUuid;
23452        final String packageName = pkg.packageName;
23453        final ApplicationInfo app = pkg.applicationInfo;
23454
23455        if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) {
23456            // Create a native library symlink only if we have native libraries
23457            // and if the native libraries are 32 bit libraries. We do not provide
23458            // this symlink for 64 bit libraries.
23459            if (app.primaryCpuAbi != null && !VMRuntime.is64BitAbi(app.primaryCpuAbi)) {
23460                final String nativeLibPath = app.nativeLibraryDir;
23461                try {
23462                    mInstaller.linkNativeLibraryDirectory(volumeUuid, packageName,
23463                            nativeLibPath, userId);
23464                } catch (InstallerException e) {
23465                    Slog.e(TAG, "Failed to link native for " + packageName + ": " + e);
23466                }
23467            }
23468        }
23469    }
23470
23471    /**
23472     * For system apps on non-FBE devices, this method migrates any existing
23473     * CE/DE data to match the {@code defaultToDeviceProtectedStorage} flag
23474     * requested by the app.
23475     */
23476    private boolean maybeMigrateAppDataLIF(PackageParser.Package pkg, int userId) {
23477        if (pkg.isSystemApp() && !StorageManager.isFileEncryptedNativeOrEmulated()
23478                && PackageManager.APPLY_DEFAULT_TO_DEVICE_PROTECTED_STORAGE) {
23479            final int storageTarget = pkg.applicationInfo.isDefaultToDeviceProtectedStorage()
23480                    ? StorageManager.FLAG_STORAGE_DE : StorageManager.FLAG_STORAGE_CE;
23481            try {
23482                mInstaller.migrateAppData(pkg.volumeUuid, pkg.packageName, userId,
23483                        storageTarget);
23484            } catch (InstallerException e) {
23485                logCriticalInfo(Log.WARN,
23486                        "Failed to migrate " + pkg.packageName + ": " + e.getMessage());
23487            }
23488            return true;
23489        } else {
23490            return false;
23491        }
23492    }
23493
23494    public PackageFreezer freezePackage(String packageName, String killReason) {
23495        return freezePackage(packageName, UserHandle.USER_ALL, killReason);
23496    }
23497
23498    public PackageFreezer freezePackage(String packageName, int userId, String killReason) {
23499        return new PackageFreezer(packageName, userId, killReason);
23500    }
23501
23502    public PackageFreezer freezePackageForInstall(String packageName, int installFlags,
23503            String killReason) {
23504        return freezePackageForInstall(packageName, UserHandle.USER_ALL, installFlags, killReason);
23505    }
23506
23507    public PackageFreezer freezePackageForInstall(String packageName, int userId, int installFlags,
23508            String killReason) {
23509        if ((installFlags & PackageManager.INSTALL_DONT_KILL_APP) != 0) {
23510            return new PackageFreezer();
23511        } else {
23512            return freezePackage(packageName, userId, killReason);
23513        }
23514    }
23515
23516    public PackageFreezer freezePackageForDelete(String packageName, int deleteFlags,
23517            String killReason) {
23518        return freezePackageForDelete(packageName, UserHandle.USER_ALL, deleteFlags, killReason);
23519    }
23520
23521    public PackageFreezer freezePackageForDelete(String packageName, int userId, int deleteFlags,
23522            String killReason) {
23523        if ((deleteFlags & PackageManager.DELETE_DONT_KILL_APP) != 0) {
23524            return new PackageFreezer();
23525        } else {
23526            return freezePackage(packageName, userId, killReason);
23527        }
23528    }
23529
23530    /**
23531     * Class that freezes and kills the given package upon creation, and
23532     * unfreezes it upon closing. This is typically used when doing surgery on
23533     * app code/data to prevent the app from running while you're working.
23534     */
23535    private class PackageFreezer implements AutoCloseable {
23536        private final String mPackageName;
23537        private final PackageFreezer[] mChildren;
23538
23539        private final boolean mWeFroze;
23540
23541        private final AtomicBoolean mClosed = new AtomicBoolean();
23542        private final CloseGuard mCloseGuard = CloseGuard.get();
23543
23544        /**
23545         * Create and return a stub freezer that doesn't actually do anything,
23546         * typically used when someone requested
23547         * {@link PackageManager#INSTALL_DONT_KILL_APP} or
23548         * {@link PackageManager#DELETE_DONT_KILL_APP}.
23549         */
23550        public PackageFreezer() {
23551            mPackageName = null;
23552            mChildren = null;
23553            mWeFroze = false;
23554            mCloseGuard.open("close");
23555        }
23556
23557        public PackageFreezer(String packageName, int userId, String killReason) {
23558            synchronized (mPackages) {
23559                mPackageName = packageName;
23560                mWeFroze = mFrozenPackages.add(mPackageName);
23561
23562                final PackageSetting ps = mSettings.mPackages.get(mPackageName);
23563                if (ps != null) {
23564                    killApplication(ps.name, ps.appId, userId, killReason);
23565                }
23566
23567                final PackageParser.Package p = mPackages.get(packageName);
23568                if (p != null && p.childPackages != null) {
23569                    final int N = p.childPackages.size();
23570                    mChildren = new PackageFreezer[N];
23571                    for (int i = 0; i < N; i++) {
23572                        mChildren[i] = new PackageFreezer(p.childPackages.get(i).packageName,
23573                                userId, killReason);
23574                    }
23575                } else {
23576                    mChildren = null;
23577                }
23578            }
23579            mCloseGuard.open("close");
23580        }
23581
23582        @Override
23583        protected void finalize() throws Throwable {
23584            try {
23585                if (mCloseGuard != null) {
23586                    mCloseGuard.warnIfOpen();
23587                }
23588
23589                close();
23590            } finally {
23591                super.finalize();
23592            }
23593        }
23594
23595        @Override
23596        public void close() {
23597            mCloseGuard.close();
23598            if (mClosed.compareAndSet(false, true)) {
23599                synchronized (mPackages) {
23600                    if (mWeFroze) {
23601                        mFrozenPackages.remove(mPackageName);
23602                    }
23603
23604                    if (mChildren != null) {
23605                        for (PackageFreezer freezer : mChildren) {
23606                            freezer.close();
23607                        }
23608                    }
23609                }
23610            }
23611        }
23612    }
23613
23614    /**
23615     * Verify that given package is currently frozen.
23616     */
23617    private void checkPackageFrozen(String packageName) {
23618        synchronized (mPackages) {
23619            if (!mFrozenPackages.contains(packageName)) {
23620                Slog.wtf(TAG, "Expected " + packageName + " to be frozen!", new Throwable());
23621            }
23622        }
23623    }
23624
23625    @Override
23626    public int movePackage(final String packageName, final String volumeUuid) {
23627        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null);
23628
23629        final int callingUid = Binder.getCallingUid();
23630        final UserHandle user = new UserHandle(UserHandle.getUserId(callingUid));
23631        final int moveId = mNextMoveId.getAndIncrement();
23632        mHandler.post(new Runnable() {
23633            @Override
23634            public void run() {
23635                try {
23636                    movePackageInternal(packageName, volumeUuid, moveId, callingUid, user);
23637                } catch (PackageManagerException e) {
23638                    Slog.w(TAG, "Failed to move " + packageName, e);
23639                    mMoveCallbacks.notifyStatusChanged(moveId, e.error);
23640                }
23641            }
23642        });
23643        return moveId;
23644    }
23645
23646    private void movePackageInternal(final String packageName, final String volumeUuid,
23647            final int moveId, final int callingUid, UserHandle user)
23648                    throws PackageManagerException {
23649        final StorageManager storage = mContext.getSystemService(StorageManager.class);
23650        final PackageManager pm = mContext.getPackageManager();
23651
23652        final boolean currentAsec;
23653        final String currentVolumeUuid;
23654        final File codeFile;
23655        final String installerPackageName;
23656        final String packageAbiOverride;
23657        final int appId;
23658        final String seinfo;
23659        final String label;
23660        final int targetSdkVersion;
23661        final PackageFreezer freezer;
23662        final int[] installedUserIds;
23663
23664        // reader
23665        synchronized (mPackages) {
23666            final PackageParser.Package pkg = mPackages.get(packageName);
23667            final PackageSetting ps = mSettings.mPackages.get(packageName);
23668            if (pkg == null
23669                    || ps == null
23670                    || filterAppAccessLPr(ps, callingUid, user.getIdentifier())) {
23671                throw new PackageManagerException(MOVE_FAILED_DOESNT_EXIST, "Missing package");
23672            }
23673            if (pkg.applicationInfo.isSystemApp()) {
23674                throw new PackageManagerException(MOVE_FAILED_SYSTEM_PACKAGE,
23675                        "Cannot move system application");
23676            }
23677
23678            final boolean isInternalStorage = VolumeInfo.ID_PRIVATE_INTERNAL.equals(volumeUuid);
23679            final boolean allow3rdPartyOnInternal = mContext.getResources().getBoolean(
23680                    com.android.internal.R.bool.config_allow3rdPartyAppOnInternal);
23681            if (isInternalStorage && !allow3rdPartyOnInternal) {
23682                throw new PackageManagerException(MOVE_FAILED_3RD_PARTY_NOT_ALLOWED_ON_INTERNAL,
23683                        "3rd party apps are not allowed on internal storage");
23684            }
23685
23686            if (pkg.applicationInfo.isExternalAsec()) {
23687                currentAsec = true;
23688                currentVolumeUuid = StorageManager.UUID_PRIMARY_PHYSICAL;
23689            } else if (pkg.applicationInfo.isForwardLocked()) {
23690                currentAsec = true;
23691                currentVolumeUuid = "forward_locked";
23692            } else {
23693                currentAsec = false;
23694                currentVolumeUuid = ps.volumeUuid;
23695
23696                final File probe = new File(pkg.codePath);
23697                final File probeOat = new File(probe, "oat");
23698                if (!probe.isDirectory() || !probeOat.isDirectory()) {
23699                    throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
23700                            "Move only supported for modern cluster style installs");
23701                }
23702            }
23703
23704            if (Objects.equals(currentVolumeUuid, volumeUuid)) {
23705                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
23706                        "Package already moved to " + volumeUuid);
23707            }
23708            if (pkg.applicationInfo.isInternal() && isPackageDeviceAdminOnAnyUser(packageName)) {
23709                throw new PackageManagerException(MOVE_FAILED_DEVICE_ADMIN,
23710                        "Device admin cannot be moved");
23711            }
23712
23713            if (mFrozenPackages.contains(packageName)) {
23714                throw new PackageManagerException(MOVE_FAILED_OPERATION_PENDING,
23715                        "Failed to move already frozen package");
23716            }
23717
23718            codeFile = new File(pkg.codePath);
23719            installerPackageName = ps.installerPackageName;
23720            packageAbiOverride = ps.cpuAbiOverrideString;
23721            appId = UserHandle.getAppId(pkg.applicationInfo.uid);
23722            seinfo = pkg.applicationInfo.seInfo;
23723            label = String.valueOf(pm.getApplicationLabel(pkg.applicationInfo));
23724            targetSdkVersion = pkg.applicationInfo.targetSdkVersion;
23725            freezer = freezePackage(packageName, "movePackageInternal");
23726            installedUserIds = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
23727        }
23728
23729        final Bundle extras = new Bundle();
23730        extras.putString(Intent.EXTRA_PACKAGE_NAME, packageName);
23731        extras.putString(Intent.EXTRA_TITLE, label);
23732        mMoveCallbacks.notifyCreated(moveId, extras);
23733
23734        int installFlags;
23735        final boolean moveCompleteApp;
23736        final File measurePath;
23737
23738        if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, volumeUuid)) {
23739            installFlags = INSTALL_INTERNAL;
23740            moveCompleteApp = !currentAsec;
23741            measurePath = Environment.getDataAppDirectory(volumeUuid);
23742        } else if (Objects.equals(StorageManager.UUID_PRIMARY_PHYSICAL, volumeUuid)) {
23743            installFlags = INSTALL_EXTERNAL;
23744            moveCompleteApp = false;
23745            measurePath = storage.getPrimaryPhysicalVolume().getPath();
23746        } else {
23747            final VolumeInfo volume = storage.findVolumeByUuid(volumeUuid);
23748            if (volume == null || volume.getType() != VolumeInfo.TYPE_PRIVATE
23749                    || !volume.isMountedWritable()) {
23750                freezer.close();
23751                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
23752                        "Move location not mounted private volume");
23753            }
23754
23755            Preconditions.checkState(!currentAsec);
23756
23757            installFlags = INSTALL_INTERNAL;
23758            moveCompleteApp = true;
23759            measurePath = Environment.getDataAppDirectory(volumeUuid);
23760        }
23761
23762        // If we're moving app data around, we need all the users unlocked
23763        if (moveCompleteApp) {
23764            for (int userId : installedUserIds) {
23765                if (StorageManager.isFileEncryptedNativeOrEmulated()
23766                        && !StorageManager.isUserKeyUnlocked(userId)) {
23767                    throw new PackageManagerException(MOVE_FAILED_LOCKED_USER,
23768                            "User " + userId + " must be unlocked");
23769                }
23770            }
23771        }
23772
23773        final PackageStats stats = new PackageStats(null, -1);
23774        synchronized (mInstaller) {
23775            for (int userId : installedUserIds) {
23776                if (!getPackageSizeInfoLI(packageName, userId, stats)) {
23777                    freezer.close();
23778                    throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
23779                            "Failed to measure package size");
23780                }
23781            }
23782        }
23783
23784        if (DEBUG_INSTALL) Slog.d(TAG, "Measured code size " + stats.codeSize + ", data size "
23785                + stats.dataSize);
23786
23787        final long startFreeBytes = measurePath.getUsableSpace();
23788        final long sizeBytes;
23789        if (moveCompleteApp) {
23790            sizeBytes = stats.codeSize + stats.dataSize;
23791        } else {
23792            sizeBytes = stats.codeSize;
23793        }
23794
23795        if (sizeBytes > storage.getStorageBytesUntilLow(measurePath)) {
23796            freezer.close();
23797            throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
23798                    "Not enough free space to move");
23799        }
23800
23801        mMoveCallbacks.notifyStatusChanged(moveId, 10);
23802
23803        final CountDownLatch installedLatch = new CountDownLatch(1);
23804        final IPackageInstallObserver2 installObserver = new IPackageInstallObserver2.Stub() {
23805            @Override
23806            public void onUserActionRequired(Intent intent) throws RemoteException {
23807                throw new IllegalStateException();
23808            }
23809
23810            @Override
23811            public void onPackageInstalled(String basePackageName, int returnCode, String msg,
23812                    Bundle extras) throws RemoteException {
23813                if (DEBUG_INSTALL) Slog.d(TAG, "Install result for move: "
23814                        + PackageManager.installStatusToString(returnCode, msg));
23815
23816                installedLatch.countDown();
23817                freezer.close();
23818
23819                final int status = PackageManager.installStatusToPublicStatus(returnCode);
23820                switch (status) {
23821                    case PackageInstaller.STATUS_SUCCESS:
23822                        mMoveCallbacks.notifyStatusChanged(moveId,
23823                                PackageManager.MOVE_SUCCEEDED);
23824                        break;
23825                    case PackageInstaller.STATUS_FAILURE_STORAGE:
23826                        mMoveCallbacks.notifyStatusChanged(moveId,
23827                                PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE);
23828                        break;
23829                    default:
23830                        mMoveCallbacks.notifyStatusChanged(moveId,
23831                                PackageManager.MOVE_FAILED_INTERNAL_ERROR);
23832                        break;
23833                }
23834            }
23835        };
23836
23837        final MoveInfo move;
23838        if (moveCompleteApp) {
23839            // Kick off a thread to report progress estimates
23840            new Thread() {
23841                @Override
23842                public void run() {
23843                    while (true) {
23844                        try {
23845                            if (installedLatch.await(1, TimeUnit.SECONDS)) {
23846                                break;
23847                            }
23848                        } catch (InterruptedException ignored) {
23849                        }
23850
23851                        final long deltaFreeBytes = startFreeBytes - measurePath.getUsableSpace();
23852                        final int progress = 10 + (int) MathUtils.constrain(
23853                                ((deltaFreeBytes * 80) / sizeBytes), 0, 80);
23854                        mMoveCallbacks.notifyStatusChanged(moveId, progress);
23855                    }
23856                }
23857            }.start();
23858
23859            final String dataAppName = codeFile.getName();
23860            move = new MoveInfo(moveId, currentVolumeUuid, volumeUuid, packageName,
23861                    dataAppName, appId, seinfo, targetSdkVersion);
23862        } else {
23863            move = null;
23864        }
23865
23866        installFlags |= PackageManager.INSTALL_REPLACE_EXISTING;
23867
23868        final Message msg = mHandler.obtainMessage(INIT_COPY);
23869        final OriginInfo origin = OriginInfo.fromExistingFile(codeFile);
23870        final InstallParams params = new InstallParams(origin, move, installObserver, installFlags,
23871                installerPackageName, volumeUuid, null /*verificationInfo*/, user,
23872                packageAbiOverride, null /*grantedPermissions*/, null /*certificates*/,
23873                PackageManager.INSTALL_REASON_UNKNOWN);
23874        params.setTraceMethod("movePackage").setTraceCookie(System.identityHashCode(params));
23875        msg.obj = params;
23876
23877        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "movePackage",
23878                System.identityHashCode(msg.obj));
23879        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
23880                System.identityHashCode(msg.obj));
23881
23882        mHandler.sendMessage(msg);
23883    }
23884
23885    @Override
23886    public int movePrimaryStorage(String volumeUuid) throws RemoteException {
23887        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null);
23888
23889        final int realMoveId = mNextMoveId.getAndIncrement();
23890        final Bundle extras = new Bundle();
23891        extras.putString(VolumeRecord.EXTRA_FS_UUID, volumeUuid);
23892        mMoveCallbacks.notifyCreated(realMoveId, extras);
23893
23894        final IPackageMoveObserver callback = new IPackageMoveObserver.Stub() {
23895            @Override
23896            public void onCreated(int moveId, Bundle extras) {
23897                // Ignored
23898            }
23899
23900            @Override
23901            public void onStatusChanged(int moveId, int status, long estMillis) {
23902                mMoveCallbacks.notifyStatusChanged(realMoveId, status, estMillis);
23903            }
23904        };
23905
23906        final StorageManager storage = mContext.getSystemService(StorageManager.class);
23907        storage.setPrimaryStorageUuid(volumeUuid, callback);
23908        return realMoveId;
23909    }
23910
23911    @Override
23912    public int getMoveStatus(int moveId) {
23913        mContext.enforceCallingOrSelfPermission(
23914                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
23915        return mMoveCallbacks.mLastStatus.get(moveId);
23916    }
23917
23918    @Override
23919    public void registerMoveCallback(IPackageMoveObserver callback) {
23920        mContext.enforceCallingOrSelfPermission(
23921                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
23922        mMoveCallbacks.register(callback);
23923    }
23924
23925    @Override
23926    public void unregisterMoveCallback(IPackageMoveObserver callback) {
23927        mContext.enforceCallingOrSelfPermission(
23928                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
23929        mMoveCallbacks.unregister(callback);
23930    }
23931
23932    @Override
23933    public boolean setInstallLocation(int loc) {
23934        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WRITE_SECURE_SETTINGS,
23935                null);
23936        if (getInstallLocation() == loc) {
23937            return true;
23938        }
23939        if (loc == PackageHelper.APP_INSTALL_AUTO || loc == PackageHelper.APP_INSTALL_INTERNAL
23940                || loc == PackageHelper.APP_INSTALL_EXTERNAL) {
23941            android.provider.Settings.Global.putInt(mContext.getContentResolver(),
23942                    android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, loc);
23943            return true;
23944        }
23945        return false;
23946   }
23947
23948    @Override
23949    public int getInstallLocation() {
23950        // allow instant app access
23951        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
23952                android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION,
23953                PackageHelper.APP_INSTALL_AUTO);
23954    }
23955
23956    /** Called by UserManagerService */
23957    void cleanUpUser(UserManagerService userManager, int userHandle) {
23958        synchronized (mPackages) {
23959            mDirtyUsers.remove(userHandle);
23960            mUserNeedsBadging.delete(userHandle);
23961            mSettings.removeUserLPw(userHandle);
23962            mPendingBroadcasts.remove(userHandle);
23963            mInstantAppRegistry.onUserRemovedLPw(userHandle);
23964            removeUnusedPackagesLPw(userManager, userHandle);
23965        }
23966    }
23967
23968    /**
23969     * We're removing userHandle and would like to remove any downloaded packages
23970     * that are no longer in use by any other user.
23971     * @param userHandle the user being removed
23972     */
23973    private void removeUnusedPackagesLPw(UserManagerService userManager, final int userHandle) {
23974        final boolean DEBUG_CLEAN_APKS = false;
23975        int [] users = userManager.getUserIds();
23976        Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator();
23977        while (psit.hasNext()) {
23978            PackageSetting ps = psit.next();
23979            if (ps.pkg == null) {
23980                continue;
23981            }
23982            final String packageName = ps.pkg.packageName;
23983            // Skip over if system app
23984            if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0) {
23985                continue;
23986            }
23987            if (DEBUG_CLEAN_APKS) {
23988                Slog.i(TAG, "Checking package " + packageName);
23989            }
23990            boolean keep = shouldKeepUninstalledPackageLPr(packageName);
23991            if (keep) {
23992                if (DEBUG_CLEAN_APKS) {
23993                    Slog.i(TAG, "  Keeping package " + packageName + " - requested by DO");
23994                }
23995            } else {
23996                for (int i = 0; i < users.length; i++) {
23997                    if (users[i] != userHandle && ps.getInstalled(users[i])) {
23998                        keep = true;
23999                        if (DEBUG_CLEAN_APKS) {
24000                            Slog.i(TAG, "  Keeping package " + packageName + " for user "
24001                                    + users[i]);
24002                        }
24003                        break;
24004                    }
24005                }
24006            }
24007            if (!keep) {
24008                if (DEBUG_CLEAN_APKS) {
24009                    Slog.i(TAG, "  Removing package " + packageName);
24010                }
24011                mHandler.post(new Runnable() {
24012                    public void run() {
24013                        deletePackageX(packageName, PackageManager.VERSION_CODE_HIGHEST,
24014                                userHandle, 0);
24015                    } //end run
24016                });
24017            }
24018        }
24019    }
24020
24021    /** Called by UserManagerService */
24022    void createNewUser(int userId, String[] disallowedPackages) {
24023        synchronized (mInstallLock) {
24024            mSettings.createNewUserLI(this, mInstaller, userId, disallowedPackages);
24025        }
24026        synchronized (mPackages) {
24027            scheduleWritePackageRestrictionsLocked(userId);
24028            scheduleWritePackageListLocked(userId);
24029            applyFactoryDefaultBrowserLPw(userId);
24030            primeDomainVerificationsLPw(userId);
24031        }
24032    }
24033
24034    void onNewUserCreated(final int userId) {
24035        mDefaultPermissionPolicy.grantDefaultPermissions(userId);
24036        // If permission review for legacy apps is required, we represent
24037        // dagerous permissions for such apps as always granted runtime
24038        // permissions to keep per user flag state whether review is needed.
24039        // Hence, if a new user is added we have to propagate dangerous
24040        // permission grants for these legacy apps.
24041        if (mPermissionReviewRequired) {
24042            updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL
24043                    | UPDATE_PERMISSIONS_REPLACE_ALL);
24044        }
24045    }
24046
24047    @Override
24048    public VerifierDeviceIdentity getVerifierDeviceIdentity() throws RemoteException {
24049        mContext.enforceCallingOrSelfPermission(
24050                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
24051                "Only package verification agents can read the verifier device identity");
24052
24053        synchronized (mPackages) {
24054            return mSettings.getVerifierDeviceIdentityLPw();
24055        }
24056    }
24057
24058    @Override
24059    public void setPermissionEnforced(String permission, boolean enforced) {
24060        // TODO: Now that we no longer change GID for storage, this should to away.
24061        mContext.enforceCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS,
24062                "setPermissionEnforced");
24063        if (READ_EXTERNAL_STORAGE.equals(permission)) {
24064            synchronized (mPackages) {
24065                if (mSettings.mReadExternalStorageEnforced == null
24066                        || mSettings.mReadExternalStorageEnforced != enforced) {
24067                    mSettings.mReadExternalStorageEnforced = enforced;
24068                    mSettings.writeLPr();
24069                }
24070            }
24071            // kill any non-foreground processes so we restart them and
24072            // grant/revoke the GID.
24073            final IActivityManager am = ActivityManager.getService();
24074            if (am != null) {
24075                final long token = Binder.clearCallingIdentity();
24076                try {
24077                    am.killProcessesBelowForeground("setPermissionEnforcement");
24078                } catch (RemoteException e) {
24079                } finally {
24080                    Binder.restoreCallingIdentity(token);
24081                }
24082            }
24083        } else {
24084            throw new IllegalArgumentException("No selective enforcement for " + permission);
24085        }
24086    }
24087
24088    @Override
24089    @Deprecated
24090    public boolean isPermissionEnforced(String permission) {
24091        // allow instant applications
24092        return true;
24093    }
24094
24095    @Override
24096    public boolean isStorageLow() {
24097        // allow instant applications
24098        final long token = Binder.clearCallingIdentity();
24099        try {
24100            final DeviceStorageMonitorInternal
24101                    dsm = LocalServices.getService(DeviceStorageMonitorInternal.class);
24102            if (dsm != null) {
24103                return dsm.isMemoryLow();
24104            } else {
24105                return false;
24106            }
24107        } finally {
24108            Binder.restoreCallingIdentity(token);
24109        }
24110    }
24111
24112    @Override
24113    public IPackageInstaller getPackageInstaller() {
24114        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
24115            return null;
24116        }
24117        return mInstallerService;
24118    }
24119
24120    private boolean userNeedsBadging(int userId) {
24121        int index = mUserNeedsBadging.indexOfKey(userId);
24122        if (index < 0) {
24123            final UserInfo userInfo;
24124            final long token = Binder.clearCallingIdentity();
24125            try {
24126                userInfo = sUserManager.getUserInfo(userId);
24127            } finally {
24128                Binder.restoreCallingIdentity(token);
24129            }
24130            final boolean b;
24131            if (userInfo != null && userInfo.isManagedProfile()) {
24132                b = true;
24133            } else {
24134                b = false;
24135            }
24136            mUserNeedsBadging.put(userId, b);
24137            return b;
24138        }
24139        return mUserNeedsBadging.valueAt(index);
24140    }
24141
24142    @Override
24143    public KeySet getKeySetByAlias(String packageName, String alias) {
24144        if (packageName == null || alias == null) {
24145            return null;
24146        }
24147        synchronized(mPackages) {
24148            final PackageParser.Package pkg = mPackages.get(packageName);
24149            if (pkg == null) {
24150                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
24151                throw new IllegalArgumentException("Unknown package: " + packageName);
24152            }
24153            final PackageSetting ps = (PackageSetting) pkg.mExtras;
24154            if (filterAppAccessLPr(ps, Binder.getCallingUid(), UserHandle.getCallingUserId())) {
24155                Slog.w(TAG, "KeySet requested for filtered package: " + packageName);
24156                throw new IllegalArgumentException("Unknown package: " + packageName);
24157            }
24158            KeySetManagerService ksms = mSettings.mKeySetManagerService;
24159            return new KeySet(ksms.getKeySetByAliasAndPackageNameLPr(packageName, alias));
24160        }
24161    }
24162
24163    @Override
24164    public KeySet getSigningKeySet(String packageName) {
24165        if (packageName == null) {
24166            return null;
24167        }
24168        synchronized(mPackages) {
24169            final int callingUid = Binder.getCallingUid();
24170            final int callingUserId = UserHandle.getUserId(callingUid);
24171            final PackageParser.Package pkg = mPackages.get(packageName);
24172            if (pkg == null) {
24173                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
24174                throw new IllegalArgumentException("Unknown package: " + packageName);
24175            }
24176            final PackageSetting ps = (PackageSetting) pkg.mExtras;
24177            if (filterAppAccessLPr(ps, callingUid, callingUserId)) {
24178                // filter and pretend the package doesn't exist
24179                Slog.w(TAG, "KeySet requested for filtered package: " + packageName
24180                        + ", uid:" + callingUid);
24181                throw new IllegalArgumentException("Unknown package: " + packageName);
24182            }
24183            if (pkg.applicationInfo.uid != callingUid
24184                    && Process.SYSTEM_UID != callingUid) {
24185                throw new SecurityException("May not access signing KeySet of other apps.");
24186            }
24187            KeySetManagerService ksms = mSettings.mKeySetManagerService;
24188            return new KeySet(ksms.getSigningKeySetByPackageNameLPr(packageName));
24189        }
24190    }
24191
24192    @Override
24193    public boolean isPackageSignedByKeySet(String packageName, KeySet ks) {
24194        final int callingUid = Binder.getCallingUid();
24195        if (getInstantAppPackageName(callingUid) != null) {
24196            return false;
24197        }
24198        if (packageName == null || ks == null) {
24199            return false;
24200        }
24201        synchronized(mPackages) {
24202            final PackageParser.Package pkg = mPackages.get(packageName);
24203            if (pkg == null
24204                    || filterAppAccessLPr((PackageSetting) pkg.mExtras, callingUid,
24205                            UserHandle.getUserId(callingUid))) {
24206                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
24207                throw new IllegalArgumentException("Unknown package: " + packageName);
24208            }
24209            IBinder ksh = ks.getToken();
24210            if (ksh instanceof KeySetHandle) {
24211                KeySetManagerService ksms = mSettings.mKeySetManagerService;
24212                return ksms.packageIsSignedByLPr(packageName, (KeySetHandle) ksh);
24213            }
24214            return false;
24215        }
24216    }
24217
24218    @Override
24219    public boolean isPackageSignedByKeySetExactly(String packageName, KeySet ks) {
24220        final int callingUid = Binder.getCallingUid();
24221        if (getInstantAppPackageName(callingUid) != null) {
24222            return false;
24223        }
24224        if (packageName == null || ks == null) {
24225            return false;
24226        }
24227        synchronized(mPackages) {
24228            final PackageParser.Package pkg = mPackages.get(packageName);
24229            if (pkg == null
24230                    || filterAppAccessLPr((PackageSetting) pkg.mExtras, callingUid,
24231                            UserHandle.getUserId(callingUid))) {
24232                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
24233                throw new IllegalArgumentException("Unknown package: " + packageName);
24234            }
24235            IBinder ksh = ks.getToken();
24236            if (ksh instanceof KeySetHandle) {
24237                KeySetManagerService ksms = mSettings.mKeySetManagerService;
24238                return ksms.packageIsSignedByExactlyLPr(packageName, (KeySetHandle) ksh);
24239            }
24240            return false;
24241        }
24242    }
24243
24244    private void deletePackageIfUnusedLPr(final String packageName) {
24245        PackageSetting ps = mSettings.mPackages.get(packageName);
24246        if (ps == null) {
24247            return;
24248        }
24249        if (!ps.isAnyInstalled(sUserManager.getUserIds())) {
24250            // TODO Implement atomic delete if package is unused
24251            // It is currently possible that the package will be deleted even if it is installed
24252            // after this method returns.
24253            mHandler.post(new Runnable() {
24254                public void run() {
24255                    deletePackageX(packageName, PackageManager.VERSION_CODE_HIGHEST,
24256                            0, PackageManager.DELETE_ALL_USERS);
24257                }
24258            });
24259        }
24260    }
24261
24262    /**
24263     * Check and throw if the given before/after packages would be considered a
24264     * downgrade.
24265     */
24266    private static void checkDowngrade(PackageParser.Package before, PackageInfoLite after)
24267            throws PackageManagerException {
24268        if (after.versionCode < before.mVersionCode) {
24269            throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
24270                    "Update version code " + after.versionCode + " is older than current "
24271                    + before.mVersionCode);
24272        } else if (after.versionCode == before.mVersionCode) {
24273            if (after.baseRevisionCode < before.baseRevisionCode) {
24274                throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
24275                        "Update base revision code " + after.baseRevisionCode
24276                        + " is older than current " + before.baseRevisionCode);
24277            }
24278
24279            if (!ArrayUtils.isEmpty(after.splitNames)) {
24280                for (int i = 0; i < after.splitNames.length; i++) {
24281                    final String splitName = after.splitNames[i];
24282                    final int j = ArrayUtils.indexOf(before.splitNames, splitName);
24283                    if (j != -1) {
24284                        if (after.splitRevisionCodes[i] < before.splitRevisionCodes[j]) {
24285                            throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
24286                                    "Update split " + splitName + " revision code "
24287                                    + after.splitRevisionCodes[i] + " is older than current "
24288                                    + before.splitRevisionCodes[j]);
24289                        }
24290                    }
24291                }
24292            }
24293        }
24294    }
24295
24296    private static class MoveCallbacks extends Handler {
24297        private static final int MSG_CREATED = 1;
24298        private static final int MSG_STATUS_CHANGED = 2;
24299
24300        private final RemoteCallbackList<IPackageMoveObserver>
24301                mCallbacks = new RemoteCallbackList<>();
24302
24303        private final SparseIntArray mLastStatus = new SparseIntArray();
24304
24305        public MoveCallbacks(Looper looper) {
24306            super(looper);
24307        }
24308
24309        public void register(IPackageMoveObserver callback) {
24310            mCallbacks.register(callback);
24311        }
24312
24313        public void unregister(IPackageMoveObserver callback) {
24314            mCallbacks.unregister(callback);
24315        }
24316
24317        @Override
24318        public void handleMessage(Message msg) {
24319            final SomeArgs args = (SomeArgs) msg.obj;
24320            final int n = mCallbacks.beginBroadcast();
24321            for (int i = 0; i < n; i++) {
24322                final IPackageMoveObserver callback = mCallbacks.getBroadcastItem(i);
24323                try {
24324                    invokeCallback(callback, msg.what, args);
24325                } catch (RemoteException ignored) {
24326                }
24327            }
24328            mCallbacks.finishBroadcast();
24329            args.recycle();
24330        }
24331
24332        private void invokeCallback(IPackageMoveObserver callback, int what, SomeArgs args)
24333                throws RemoteException {
24334            switch (what) {
24335                case MSG_CREATED: {
24336                    callback.onCreated(args.argi1, (Bundle) args.arg2);
24337                    break;
24338                }
24339                case MSG_STATUS_CHANGED: {
24340                    callback.onStatusChanged(args.argi1, args.argi2, (long) args.arg3);
24341                    break;
24342                }
24343            }
24344        }
24345
24346        private void notifyCreated(int moveId, Bundle extras) {
24347            Slog.v(TAG, "Move " + moveId + " created " + extras.toString());
24348
24349            final SomeArgs args = SomeArgs.obtain();
24350            args.argi1 = moveId;
24351            args.arg2 = extras;
24352            obtainMessage(MSG_CREATED, args).sendToTarget();
24353        }
24354
24355        private void notifyStatusChanged(int moveId, int status) {
24356            notifyStatusChanged(moveId, status, -1);
24357        }
24358
24359        private void notifyStatusChanged(int moveId, int status, long estMillis) {
24360            Slog.v(TAG, "Move " + moveId + " status " + status);
24361
24362            final SomeArgs args = SomeArgs.obtain();
24363            args.argi1 = moveId;
24364            args.argi2 = status;
24365            args.arg3 = estMillis;
24366            obtainMessage(MSG_STATUS_CHANGED, args).sendToTarget();
24367
24368            synchronized (mLastStatus) {
24369                mLastStatus.put(moveId, status);
24370            }
24371        }
24372    }
24373
24374    private final static class OnPermissionChangeListeners extends Handler {
24375        private static final int MSG_ON_PERMISSIONS_CHANGED = 1;
24376
24377        private final RemoteCallbackList<IOnPermissionsChangeListener> mPermissionListeners =
24378                new RemoteCallbackList<>();
24379
24380        public OnPermissionChangeListeners(Looper looper) {
24381            super(looper);
24382        }
24383
24384        @Override
24385        public void handleMessage(Message msg) {
24386            switch (msg.what) {
24387                case MSG_ON_PERMISSIONS_CHANGED: {
24388                    final int uid = msg.arg1;
24389                    handleOnPermissionsChanged(uid);
24390                } break;
24391            }
24392        }
24393
24394        public void addListenerLocked(IOnPermissionsChangeListener listener) {
24395            mPermissionListeners.register(listener);
24396
24397        }
24398
24399        public void removeListenerLocked(IOnPermissionsChangeListener listener) {
24400            mPermissionListeners.unregister(listener);
24401        }
24402
24403        public void onPermissionsChanged(int uid) {
24404            if (mPermissionListeners.getRegisteredCallbackCount() > 0) {
24405                obtainMessage(MSG_ON_PERMISSIONS_CHANGED, uid, 0).sendToTarget();
24406            }
24407        }
24408
24409        private void handleOnPermissionsChanged(int uid) {
24410            final int count = mPermissionListeners.beginBroadcast();
24411            try {
24412                for (int i = 0; i < count; i++) {
24413                    IOnPermissionsChangeListener callback = mPermissionListeners
24414                            .getBroadcastItem(i);
24415                    try {
24416                        callback.onPermissionsChanged(uid);
24417                    } catch (RemoteException e) {
24418                        Log.e(TAG, "Permission listener is dead", e);
24419                    }
24420                }
24421            } finally {
24422                mPermissionListeners.finishBroadcast();
24423            }
24424        }
24425    }
24426
24427    private class PackageManagerInternalImpl extends PackageManagerInternal {
24428        @Override
24429        public void setLocationPackagesProvider(PackagesProvider provider) {
24430            synchronized (mPackages) {
24431                mDefaultPermissionPolicy.setLocationPackagesProviderLPw(provider);
24432            }
24433        }
24434
24435        @Override
24436        public void setVoiceInteractionPackagesProvider(PackagesProvider provider) {
24437            synchronized (mPackages) {
24438                mDefaultPermissionPolicy.setVoiceInteractionPackagesProviderLPw(provider);
24439            }
24440        }
24441
24442        @Override
24443        public void setSmsAppPackagesProvider(PackagesProvider provider) {
24444            synchronized (mPackages) {
24445                mDefaultPermissionPolicy.setSmsAppPackagesProviderLPw(provider);
24446            }
24447        }
24448
24449        @Override
24450        public void setDialerAppPackagesProvider(PackagesProvider provider) {
24451            synchronized (mPackages) {
24452                mDefaultPermissionPolicy.setDialerAppPackagesProviderLPw(provider);
24453            }
24454        }
24455
24456        @Override
24457        public void setSimCallManagerPackagesProvider(PackagesProvider provider) {
24458            synchronized (mPackages) {
24459                mDefaultPermissionPolicy.setSimCallManagerPackagesProviderLPw(provider);
24460            }
24461        }
24462
24463        @Override
24464        public void setSyncAdapterPackagesprovider(SyncAdapterPackagesProvider provider) {
24465            synchronized (mPackages) {
24466                mDefaultPermissionPolicy.setSyncAdapterPackagesProviderLPw(provider);
24467            }
24468        }
24469
24470        @Override
24471        public void grantDefaultPermissionsToDefaultSmsApp(String packageName, int userId) {
24472            synchronized (mPackages) {
24473                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSmsAppLPr(
24474                        packageName, userId);
24475            }
24476        }
24477
24478        @Override
24479        public void grantDefaultPermissionsToDefaultDialerApp(String packageName, int userId) {
24480            synchronized (mPackages) {
24481                mSettings.setDefaultDialerPackageNameLPw(packageName, userId);
24482                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultDialerAppLPr(
24483                        packageName, userId);
24484            }
24485        }
24486
24487        @Override
24488        public void grantDefaultPermissionsToDefaultSimCallManager(String packageName, int userId) {
24489            synchronized (mPackages) {
24490                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSimCallManagerLPr(
24491                        packageName, userId);
24492            }
24493        }
24494
24495        @Override
24496        public void setKeepUninstalledPackages(final List<String> packageList) {
24497            Preconditions.checkNotNull(packageList);
24498            List<String> removedFromList = null;
24499            synchronized (mPackages) {
24500                if (mKeepUninstalledPackages != null) {
24501                    final int packagesCount = mKeepUninstalledPackages.size();
24502                    for (int i = 0; i < packagesCount; i++) {
24503                        String oldPackage = mKeepUninstalledPackages.get(i);
24504                        if (packageList != null && packageList.contains(oldPackage)) {
24505                            continue;
24506                        }
24507                        if (removedFromList == null) {
24508                            removedFromList = new ArrayList<>();
24509                        }
24510                        removedFromList.add(oldPackage);
24511                    }
24512                }
24513                mKeepUninstalledPackages = new ArrayList<>(packageList);
24514                if (removedFromList != null) {
24515                    final int removedCount = removedFromList.size();
24516                    for (int i = 0; i < removedCount; i++) {
24517                        deletePackageIfUnusedLPr(removedFromList.get(i));
24518                    }
24519                }
24520            }
24521        }
24522
24523        @Override
24524        public boolean isPermissionsReviewRequired(String packageName, int userId) {
24525            synchronized (mPackages) {
24526                // If we do not support permission review, done.
24527                if (!mPermissionReviewRequired) {
24528                    return false;
24529                }
24530
24531                PackageSetting packageSetting = mSettings.mPackages.get(packageName);
24532                if (packageSetting == null) {
24533                    return false;
24534                }
24535
24536                // Permission review applies only to apps not supporting the new permission model.
24537                if (packageSetting.pkg.applicationInfo.targetSdkVersion >= Build.VERSION_CODES.M) {
24538                    return false;
24539                }
24540
24541                // Legacy apps have the permission and get user consent on launch.
24542                PermissionsState permissionsState = packageSetting.getPermissionsState();
24543                return permissionsState.isPermissionReviewRequired(userId);
24544            }
24545        }
24546
24547        @Override
24548        public PackageInfo getPackageInfo(
24549                String packageName, int flags, int filterCallingUid, int userId) {
24550            return PackageManagerService.this
24551                    .getPackageInfoInternal(packageName, PackageManager.VERSION_CODE_HIGHEST,
24552                            flags, filterCallingUid, userId);
24553        }
24554
24555        @Override
24556        public ApplicationInfo getApplicationInfo(
24557                String packageName, int flags, int filterCallingUid, int userId) {
24558            return PackageManagerService.this
24559                    .getApplicationInfoInternal(packageName, flags, filterCallingUid, userId);
24560        }
24561
24562        @Override
24563        public ActivityInfo getActivityInfo(
24564                ComponentName component, int flags, int filterCallingUid, int userId) {
24565            return PackageManagerService.this
24566                    .getActivityInfoInternal(component, flags, filterCallingUid, userId);
24567        }
24568
24569        @Override
24570        public List<ResolveInfo> queryIntentActivities(
24571                Intent intent, int flags, int filterCallingUid, int userId) {
24572            final String resolvedType = intent.resolveTypeIfNeeded(mContext.getContentResolver());
24573            return PackageManagerService.this
24574                    .queryIntentActivitiesInternal(intent, resolvedType, flags, filterCallingUid,
24575                            userId, false /*resolveForStart*/);
24576        }
24577
24578        @Override
24579        public ComponentName getHomeActivitiesAsUser(List<ResolveInfo> allHomeCandidates,
24580                int userId) {
24581            return PackageManagerService.this.getHomeActivitiesAsUser(allHomeCandidates, userId);
24582        }
24583
24584        @Override
24585        public void setDeviceAndProfileOwnerPackages(
24586                int deviceOwnerUserId, String deviceOwnerPackage,
24587                SparseArray<String> profileOwnerPackages) {
24588            mProtectedPackages.setDeviceAndProfileOwnerPackages(
24589                    deviceOwnerUserId, deviceOwnerPackage, profileOwnerPackages);
24590        }
24591
24592        @Override
24593        public boolean isPackageDataProtected(int userId, String packageName) {
24594            return mProtectedPackages.isPackageDataProtected(userId, packageName);
24595        }
24596
24597        @Override
24598        public boolean isPackageEphemeral(int userId, String packageName) {
24599            synchronized (mPackages) {
24600                final PackageSetting ps = mSettings.mPackages.get(packageName);
24601                return ps != null ? ps.getInstantApp(userId) : false;
24602            }
24603        }
24604
24605        @Override
24606        public boolean wasPackageEverLaunched(String packageName, int userId) {
24607            synchronized (mPackages) {
24608                return mSettings.wasPackageEverLaunchedLPr(packageName, userId);
24609            }
24610        }
24611
24612        @Override
24613        public void grantRuntimePermission(String packageName, String name, int userId,
24614                boolean overridePolicy) {
24615            PackageManagerService.this.grantRuntimePermission(packageName, name, userId,
24616                    overridePolicy);
24617        }
24618
24619        @Override
24620        public void revokeRuntimePermission(String packageName, String name, int userId,
24621                boolean overridePolicy) {
24622            PackageManagerService.this.revokeRuntimePermission(packageName, name, userId,
24623                    overridePolicy);
24624        }
24625
24626        @Override
24627        public String getNameForUid(int uid) {
24628            return PackageManagerService.this.getNameForUid(uid);
24629        }
24630
24631        @Override
24632        public void requestInstantAppResolutionPhaseTwo(AuxiliaryResolveInfo responseObj,
24633                Intent origIntent, String resolvedType, String callingPackage,
24634                Bundle verificationBundle, int userId) {
24635            PackageManagerService.this.requestInstantAppResolutionPhaseTwo(
24636                    responseObj, origIntent, resolvedType, callingPackage, verificationBundle,
24637                    userId);
24638        }
24639
24640        @Override
24641        public void grantEphemeralAccess(int userId, Intent intent,
24642                int targetAppId, int ephemeralAppId) {
24643            synchronized (mPackages) {
24644                mInstantAppRegistry.grantInstantAccessLPw(userId, intent,
24645                        targetAppId, ephemeralAppId);
24646            }
24647        }
24648
24649        @Override
24650        public boolean isInstantAppInstallerComponent(ComponentName component) {
24651            synchronized (mPackages) {
24652                return mInstantAppInstallerActivity != null
24653                        && mInstantAppInstallerActivity.getComponentName().equals(component);
24654            }
24655        }
24656
24657        @Override
24658        public void pruneInstantApps() {
24659            mInstantAppRegistry.pruneInstantApps();
24660        }
24661
24662        @Override
24663        public String getSetupWizardPackageName() {
24664            return mSetupWizardPackage;
24665        }
24666
24667        public void setExternalSourcesPolicy(ExternalSourcesPolicy policy) {
24668            if (policy != null) {
24669                mExternalSourcesPolicy = policy;
24670            }
24671        }
24672
24673        @Override
24674        public boolean isPackagePersistent(String packageName) {
24675            synchronized (mPackages) {
24676                PackageParser.Package pkg = mPackages.get(packageName);
24677                return pkg != null
24678                        ? ((pkg.applicationInfo.flags&(ApplicationInfo.FLAG_SYSTEM
24679                                        | ApplicationInfo.FLAG_PERSISTENT)) ==
24680                                (ApplicationInfo.FLAG_SYSTEM | ApplicationInfo.FLAG_PERSISTENT))
24681                        : false;
24682            }
24683        }
24684
24685        @Override
24686        public List<PackageInfo> getOverlayPackages(int userId) {
24687            final ArrayList<PackageInfo> overlayPackages = new ArrayList<PackageInfo>();
24688            synchronized (mPackages) {
24689                for (PackageParser.Package p : mPackages.values()) {
24690                    if (p.mOverlayTarget != null) {
24691                        PackageInfo pkg = generatePackageInfo((PackageSetting)p.mExtras, 0, userId);
24692                        if (pkg != null) {
24693                            overlayPackages.add(pkg);
24694                        }
24695                    }
24696                }
24697            }
24698            return overlayPackages;
24699        }
24700
24701        @Override
24702        public List<String> getTargetPackageNames(int userId) {
24703            List<String> targetPackages = new ArrayList<>();
24704            synchronized (mPackages) {
24705                for (PackageParser.Package p : mPackages.values()) {
24706                    if (p.mOverlayTarget == null) {
24707                        targetPackages.add(p.packageName);
24708                    }
24709                }
24710            }
24711            return targetPackages;
24712        }
24713
24714        @Override
24715        public boolean setEnabledOverlayPackages(int userId, @NonNull String targetPackageName,
24716                @Nullable List<String> overlayPackageNames) {
24717            synchronized (mPackages) {
24718                if (targetPackageName == null || mPackages.get(targetPackageName) == null) {
24719                    Slog.e(TAG, "failed to find package " + targetPackageName);
24720                    return false;
24721                }
24722                ArrayList<String> overlayPaths = null;
24723                if (overlayPackageNames != null && overlayPackageNames.size() > 0) {
24724                    final int N = overlayPackageNames.size();
24725                    overlayPaths = new ArrayList<>(N);
24726                    for (int i = 0; i < N; i++) {
24727                        final String packageName = overlayPackageNames.get(i);
24728                        final PackageParser.Package pkg = mPackages.get(packageName);
24729                        if (pkg == null) {
24730                            Slog.e(TAG, "failed to find package " + packageName);
24731                            return false;
24732                        }
24733                        overlayPaths.add(pkg.baseCodePath);
24734                    }
24735                }
24736
24737                final PackageSetting ps = mSettings.mPackages.get(targetPackageName);
24738                ps.setOverlayPaths(overlayPaths, userId);
24739                return true;
24740            }
24741        }
24742
24743        @Override
24744        public ResolveInfo resolveIntent(Intent intent, String resolvedType,
24745                int flags, int userId) {
24746            return resolveIntentInternal(
24747                    intent, resolvedType, flags, userId, true /*resolveForStart*/);
24748        }
24749
24750        @Override
24751        public ResolveInfo resolveService(Intent intent, String resolvedType,
24752                int flags, int userId, int callingUid) {
24753            return resolveServiceInternal(intent, resolvedType, flags, userId, callingUid);
24754        }
24755
24756        @Override
24757        public void addIsolatedUid(int isolatedUid, int ownerUid) {
24758            synchronized (mPackages) {
24759                mIsolatedOwners.put(isolatedUid, ownerUid);
24760            }
24761        }
24762
24763        @Override
24764        public void removeIsolatedUid(int isolatedUid) {
24765            synchronized (mPackages) {
24766                mIsolatedOwners.delete(isolatedUid);
24767            }
24768        }
24769
24770        @Override
24771        public int getUidTargetSdkVersion(int uid) {
24772            synchronized (mPackages) {
24773                return getUidTargetSdkVersionLockedLPr(uid);
24774            }
24775        }
24776
24777        @Override
24778        public boolean canAccessInstantApps(int callingUid, int userId) {
24779            return PackageManagerService.this.canViewInstantApps(callingUid, userId);
24780        }
24781    }
24782
24783    @Override
24784    public void grantDefaultPermissionsToEnabledCarrierApps(String[] packageNames, int userId) {
24785        enforceSystemOrPhoneCaller("grantPermissionsToEnabledCarrierApps");
24786        synchronized (mPackages) {
24787            final long identity = Binder.clearCallingIdentity();
24788            try {
24789                mDefaultPermissionPolicy.grantDefaultPermissionsToEnabledCarrierAppsLPr(
24790                        packageNames, userId);
24791            } finally {
24792                Binder.restoreCallingIdentity(identity);
24793            }
24794        }
24795    }
24796
24797    @Override
24798    public void grantDefaultPermissionsToEnabledImsServices(String[] packageNames, int userId) {
24799        enforceSystemOrPhoneCaller("grantDefaultPermissionsToEnabledImsServices");
24800        synchronized (mPackages) {
24801            final long identity = Binder.clearCallingIdentity();
24802            try {
24803                mDefaultPermissionPolicy.grantDefaultPermissionsToEnabledImsServicesLPr(
24804                        packageNames, userId);
24805            } finally {
24806                Binder.restoreCallingIdentity(identity);
24807            }
24808        }
24809    }
24810
24811    private static void enforceSystemOrPhoneCaller(String tag) {
24812        int callingUid = Binder.getCallingUid();
24813        if (callingUid != Process.PHONE_UID && callingUid != Process.SYSTEM_UID) {
24814            throw new SecurityException(
24815                    "Cannot call " + tag + " from UID " + callingUid);
24816        }
24817    }
24818
24819    boolean isHistoricalPackageUsageAvailable() {
24820        return mPackageUsage.isHistoricalPackageUsageAvailable();
24821    }
24822
24823    /**
24824     * Return a <b>copy</b> of the collection of packages known to the package manager.
24825     * @return A copy of the values of mPackages.
24826     */
24827    Collection<PackageParser.Package> getPackages() {
24828        synchronized (mPackages) {
24829            return new ArrayList<>(mPackages.values());
24830        }
24831    }
24832
24833    /**
24834     * Logs process start information (including base APK hash) to the security log.
24835     * @hide
24836     */
24837    @Override
24838    public void logAppProcessStartIfNeeded(String processName, int uid, String seinfo,
24839            String apkFile, int pid) {
24840        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
24841            return;
24842        }
24843        if (!SecurityLog.isLoggingEnabled()) {
24844            return;
24845        }
24846        Bundle data = new Bundle();
24847        data.putLong("startTimestamp", System.currentTimeMillis());
24848        data.putString("processName", processName);
24849        data.putInt("uid", uid);
24850        data.putString("seinfo", seinfo);
24851        data.putString("apkFile", apkFile);
24852        data.putInt("pid", pid);
24853        Message msg = mProcessLoggingHandler.obtainMessage(
24854                ProcessLoggingHandler.LOG_APP_PROCESS_START_MSG);
24855        msg.setData(data);
24856        mProcessLoggingHandler.sendMessage(msg);
24857    }
24858
24859    public CompilerStats.PackageStats getCompilerPackageStats(String pkgName) {
24860        return mCompilerStats.getPackageStats(pkgName);
24861    }
24862
24863    public CompilerStats.PackageStats getOrCreateCompilerPackageStats(PackageParser.Package pkg) {
24864        return getOrCreateCompilerPackageStats(pkg.packageName);
24865    }
24866
24867    public CompilerStats.PackageStats getOrCreateCompilerPackageStats(String pkgName) {
24868        return mCompilerStats.getOrCreatePackageStats(pkgName);
24869    }
24870
24871    public void deleteCompilerPackageStats(String pkgName) {
24872        mCompilerStats.deletePackageStats(pkgName);
24873    }
24874
24875    @Override
24876    public int getInstallReason(String packageName, int userId) {
24877        final int callingUid = Binder.getCallingUid();
24878        enforceCrossUserPermission(callingUid, userId,
24879                true /* requireFullPermission */, false /* checkShell */,
24880                "get install reason");
24881        synchronized (mPackages) {
24882            final PackageSetting ps = mSettings.mPackages.get(packageName);
24883            if (filterAppAccessLPr(ps, callingUid, userId)) {
24884                return PackageManager.INSTALL_REASON_UNKNOWN;
24885            }
24886            if (ps != null) {
24887                return ps.getInstallReason(userId);
24888            }
24889        }
24890        return PackageManager.INSTALL_REASON_UNKNOWN;
24891    }
24892
24893    @Override
24894    public boolean canRequestPackageInstalls(String packageName, int userId) {
24895        return canRequestPackageInstallsInternal(packageName, 0, userId,
24896                true /* throwIfPermNotDeclared*/);
24897    }
24898
24899    private boolean canRequestPackageInstallsInternal(String packageName, int flags, int userId,
24900            boolean throwIfPermNotDeclared) {
24901        int callingUid = Binder.getCallingUid();
24902        int uid = getPackageUid(packageName, 0, userId);
24903        if (callingUid != uid && callingUid != Process.ROOT_UID
24904                && callingUid != Process.SYSTEM_UID) {
24905            throw new SecurityException(
24906                    "Caller uid " + callingUid + " does not own package " + packageName);
24907        }
24908        ApplicationInfo info = getApplicationInfo(packageName, flags, userId);
24909        if (info == null) {
24910            return false;
24911        }
24912        if (info.targetSdkVersion < Build.VERSION_CODES.O) {
24913            return false;
24914        }
24915        String appOpPermission = Manifest.permission.REQUEST_INSTALL_PACKAGES;
24916        String[] packagesDeclaringPermission = getAppOpPermissionPackages(appOpPermission);
24917        if (!ArrayUtils.contains(packagesDeclaringPermission, packageName)) {
24918            if (throwIfPermNotDeclared) {
24919                throw new SecurityException("Need to declare " + appOpPermission
24920                        + " to call this api");
24921            } else {
24922                Slog.e(TAG, "Need to declare " + appOpPermission + " to call this api");
24923                return false;
24924            }
24925        }
24926        if (sUserManager.hasUserRestriction(UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES, userId)) {
24927            return false;
24928        }
24929        if (mExternalSourcesPolicy != null) {
24930            int isTrusted = mExternalSourcesPolicy.getPackageTrustedToInstallApps(packageName, uid);
24931            if (isTrusted != PackageManagerInternal.ExternalSourcesPolicy.USER_DEFAULT) {
24932                return isTrusted == PackageManagerInternal.ExternalSourcesPolicy.USER_TRUSTED;
24933            }
24934        }
24935        return checkUidPermission(appOpPermission, uid) == PERMISSION_GRANTED;
24936    }
24937
24938    @Override
24939    public ComponentName getInstantAppResolverSettingsComponent() {
24940        return mInstantAppResolverSettingsComponent;
24941    }
24942
24943    @Override
24944    public ComponentName getInstantAppInstallerComponent() {
24945        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
24946            return null;
24947        }
24948        return mInstantAppInstallerActivity == null
24949                ? null : mInstantAppInstallerActivity.getComponentName();
24950    }
24951
24952    @Override
24953    public String getInstantAppAndroidId(String packageName, int userId) {
24954        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.ACCESS_INSTANT_APPS,
24955                "getInstantAppAndroidId");
24956        enforceCrossUserPermission(Binder.getCallingUid(), userId,
24957                true /* requireFullPermission */, false /* checkShell */,
24958                "getInstantAppAndroidId");
24959        // Make sure the target is an Instant App.
24960        if (!isInstantApp(packageName, userId)) {
24961            return null;
24962        }
24963        synchronized (mPackages) {
24964            return mInstantAppRegistry.getInstantAppAndroidIdLPw(packageName, userId);
24965        }
24966    }
24967}
24968
24969interface PackageSender {
24970    void sendPackageBroadcast(final String action, final String pkg,
24971        final Bundle extras, final int flags, final String targetPkg,
24972        final IIntentReceiver finishedReceiver, final int[] userIds);
24973    void sendPackageAddedForNewUsers(String packageName, boolean isSystem,
24974        int appId, int... userIds);
24975}
24976