PackageManagerService.java revision 03f85fef7f80e2faa8ee8f452195d42158d3376e
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.READ_EXTERNAL_STORAGE;
22import static android.Manifest.permission.REQUEST_DELETE_PACKAGES;
23import static android.Manifest.permission.WRITE_EXTERNAL_STORAGE;
24import static android.Manifest.permission.WRITE_MEDIA_STORAGE;
25import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DEFAULT;
26import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED;
27import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED;
28import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED_USER;
29import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_ENABLED;
30import static android.content.pm.PackageManager.DELETE_KEEP_DATA;
31import static android.content.pm.PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT;
32import static android.content.pm.PackageManager.FLAG_PERMISSION_POLICY_FIXED;
33import static android.content.pm.PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED;
34import static android.content.pm.PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE;
35import static android.content.pm.PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
36import static android.content.pm.PackageManager.FLAG_PERMISSION_USER_FIXED;
37import static android.content.pm.PackageManager.FLAG_PERMISSION_USER_SET;
38import static android.content.pm.PackageManager.INSTALL_EXTERNAL;
39import static android.content.pm.PackageManager.INSTALL_FAILED_ALREADY_EXISTS;
40import static android.content.pm.PackageManager.INSTALL_FAILED_CONFLICTING_PROVIDER;
41import static android.content.pm.PackageManager.INSTALL_FAILED_DUPLICATE_PACKAGE;
42import static android.content.pm.PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION;
43import static android.content.pm.PackageManager.INSTALL_FAILED_INSTANT_APP_INVALID;
44import static android.content.pm.PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
45import static android.content.pm.PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
46import static android.content.pm.PackageManager.INSTALL_FAILED_INVALID_APK;
47import static android.content.pm.PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
48import static android.content.pm.PackageManager.INSTALL_FAILED_MISSING_SHARED_LIBRARY;
49import static android.content.pm.PackageManager.INSTALL_FAILED_PACKAGE_CHANGED;
50import static android.content.pm.PackageManager.INSTALL_FAILED_REPLACE_COULDNT_DELETE;
51import static android.content.pm.PackageManager.INSTALL_FAILED_SHARED_USER_INCOMPATIBLE;
52import static android.content.pm.PackageManager.INSTALL_FAILED_TEST_ONLY;
53import static android.content.pm.PackageManager.INSTALL_FAILED_UPDATE_INCOMPATIBLE;
54import static android.content.pm.PackageManager.INSTALL_FAILED_USER_RESTRICTED;
55import static android.content.pm.PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE;
56import static android.content.pm.PackageManager.INSTALL_FORWARD_LOCK;
57import static android.content.pm.PackageManager.INSTALL_INTERNAL;
58import static android.content.pm.PackageManager.INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES;
59import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS;
60import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK;
61import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK;
62import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER;
63import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED;
64import static android.content.pm.PackageManager.MATCH_ALL;
65import static android.content.pm.PackageManager.MATCH_ANY_USER;
66import static android.content.pm.PackageManager.MATCH_DEBUG_TRIAGED_MISSING;
67import static android.content.pm.PackageManager.MATCH_DIRECT_BOOT_AWARE;
68import static android.content.pm.PackageManager.MATCH_DIRECT_BOOT_UNAWARE;
69import static android.content.pm.PackageManager.MATCH_DISABLED_COMPONENTS;
70import static android.content.pm.PackageManager.MATCH_FACTORY_ONLY;
71import static android.content.pm.PackageManager.MATCH_KNOWN_PACKAGES;
72import static android.content.pm.PackageManager.MATCH_SYSTEM_ONLY;
73import static android.content.pm.PackageManager.MATCH_UNINSTALLED_PACKAGES;
74import static android.content.pm.PackageManager.MOVE_FAILED_3RD_PARTY_NOT_ALLOWED_ON_INTERNAL;
75import static android.content.pm.PackageManager.MOVE_FAILED_DEVICE_ADMIN;
76import static android.content.pm.PackageManager.MOVE_FAILED_DOESNT_EXIST;
77import static android.content.pm.PackageManager.MOVE_FAILED_INTERNAL_ERROR;
78import static android.content.pm.PackageManager.MOVE_FAILED_OPERATION_PENDING;
79import static android.content.pm.PackageManager.MOVE_FAILED_SYSTEM_PACKAGE;
80import static android.content.pm.PackageManager.PERMISSION_DENIED;
81import static android.content.pm.PackageManager.PERMISSION_GRANTED;
82import static android.content.pm.PackageParser.PARSE_IS_PRIVILEGED;
83import static android.content.pm.PackageParser.isApkFile;
84import static android.os.Trace.TRACE_TAG_PACKAGE_MANAGER;
85import static android.system.OsConstants.O_CREAT;
86import static android.system.OsConstants.O_RDWR;
87import static com.android.internal.app.IntentForwarderActivity.FORWARD_INTENT_TO_MANAGED_PROFILE;
88import static com.android.internal.app.IntentForwarderActivity.FORWARD_INTENT_TO_PARENT;
89import static com.android.internal.content.NativeLibraryHelper.LIB64_DIR_NAME;
90import static com.android.internal.content.NativeLibraryHelper.LIB_DIR_NAME;
91import static com.android.internal.util.ArrayUtils.appendInt;
92import static com.android.server.pm.InstructionSets.getAppDexInstructionSets;
93import static com.android.server.pm.InstructionSets.getDexCodeInstructionSet;
94import static com.android.server.pm.InstructionSets.getDexCodeInstructionSets;
95import static com.android.server.pm.InstructionSets.getPreferredInstructionSet;
96import static com.android.server.pm.InstructionSets.getPrimaryInstructionSet;
97import static com.android.server.pm.PackageManagerServiceCompilerMapping.getCompilerFilterForReason;
98import static com.android.server.pm.PackageManagerServiceCompilerMapping.getDefaultCompilerFilter;
99import static com.android.server.pm.PermissionsState.PERMISSION_OPERATION_FAILURE;
100import static com.android.server.pm.PermissionsState.PERMISSION_OPERATION_SUCCESS;
101import static com.android.server.pm.PermissionsState.PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED;
102import static dalvik.system.DexFile.getNonProfileGuidedCompilerFilter;
103
104import android.Manifest;
105import android.annotation.IntDef;
106import android.annotation.NonNull;
107import android.annotation.Nullable;
108import android.app.ActivityManager;
109import android.app.AppOpsManager;
110import android.app.IActivityManager;
111import android.app.ResourcesManager;
112import android.app.admin.IDevicePolicyManager;
113import android.app.admin.SecurityLog;
114import android.app.backup.IBackupManager;
115import android.content.BroadcastReceiver;
116import android.content.ComponentName;
117import android.content.ContentResolver;
118import android.content.Context;
119import android.content.IIntentReceiver;
120import android.content.Intent;
121import android.content.IntentFilter;
122import android.content.IntentSender;
123import android.content.IntentSender.SendIntentException;
124import android.content.ServiceConnection;
125import android.content.pm.ActivityInfo;
126import android.content.pm.ApplicationInfo;
127import android.content.pm.AppsQueryHelper;
128import android.content.pm.AuxiliaryResolveInfo;
129import android.content.pm.ChangedPackages;
130import android.content.pm.FallbackCategoryProvider;
131import android.content.pm.FeatureInfo;
132import android.content.pm.IOnPermissionsChangeListener;
133import android.content.pm.IPackageDataObserver;
134import android.content.pm.IPackageDeleteObserver;
135import android.content.pm.IPackageDeleteObserver2;
136import android.content.pm.IPackageInstallObserver2;
137import android.content.pm.IPackageInstaller;
138import android.content.pm.IPackageManager;
139import android.content.pm.IPackageMoveObserver;
140import android.content.pm.IPackageStatsObserver;
141import android.content.pm.InstantAppInfo;
142import android.content.pm.InstantAppRequest;
143import android.content.pm.InstantAppResolveInfo;
144import android.content.pm.InstrumentationInfo;
145import android.content.pm.IntentFilterVerificationInfo;
146import android.content.pm.KeySet;
147import android.content.pm.PackageCleanItem;
148import android.content.pm.PackageInfo;
149import android.content.pm.PackageInfoLite;
150import android.content.pm.PackageInstaller;
151import android.content.pm.PackageManager;
152import android.content.pm.PackageManager.LegacyPackageDeleteObserver;
153import android.content.pm.PackageManagerInternal;
154import android.content.pm.PackageParser;
155import android.content.pm.PackageParser.ActivityIntentInfo;
156import android.content.pm.PackageParser.PackageLite;
157import android.content.pm.PackageParser.PackageParserException;
158import android.content.pm.PackageStats;
159import android.content.pm.PackageUserState;
160import android.content.pm.ParceledListSlice;
161import android.content.pm.PermissionGroupInfo;
162import android.content.pm.PermissionInfo;
163import android.content.pm.ProviderInfo;
164import android.content.pm.ResolveInfo;
165import android.content.pm.ServiceInfo;
166import android.content.pm.SharedLibraryInfo;
167import android.content.pm.Signature;
168import android.content.pm.UserInfo;
169import android.content.pm.VerifierDeviceIdentity;
170import android.content.pm.VerifierInfo;
171import android.content.pm.VersionedPackage;
172import android.content.res.Resources;
173import android.database.ContentObserver;
174import android.graphics.Bitmap;
175import android.hardware.display.DisplayManager;
176import android.net.Uri;
177import android.os.Binder;
178import android.os.Build;
179import android.os.Bundle;
180import android.os.Debug;
181import android.os.Environment;
182import android.os.Environment.UserEnvironment;
183import android.os.FileUtils;
184import android.os.Handler;
185import android.os.IBinder;
186import android.os.Looper;
187import android.os.Message;
188import android.os.Parcel;
189import android.os.ParcelFileDescriptor;
190import android.os.PatternMatcher;
191import android.os.Process;
192import android.os.RemoteCallbackList;
193import android.os.RemoteException;
194import android.os.ResultReceiver;
195import android.os.SELinux;
196import android.os.ServiceManager;
197import android.os.ShellCallback;
198import android.os.SystemClock;
199import android.os.SystemProperties;
200import android.os.Trace;
201import android.os.UserHandle;
202import android.os.UserManager;
203import android.os.UserManagerInternal;
204import android.os.storage.IStorageManager;
205import android.os.storage.StorageEventListener;
206import android.os.storage.StorageManager;
207import android.os.storage.StorageManagerInternal;
208import android.os.storage.VolumeInfo;
209import android.os.storage.VolumeRecord;
210import android.provider.Settings.Global;
211import android.provider.Settings.Secure;
212import android.security.KeyStore;
213import android.security.SystemKeyStore;
214import android.service.pm.PackageServiceDumpProto;
215import android.system.ErrnoException;
216import android.system.Os;
217import android.text.TextUtils;
218import android.text.format.DateUtils;
219import android.util.ArrayMap;
220import android.util.ArraySet;
221import android.util.Base64;
222import android.util.BootTimingsTraceLog;
223import android.util.DisplayMetrics;
224import android.util.EventLog;
225import android.util.ExceptionUtils;
226import android.util.Log;
227import android.util.LogPrinter;
228import android.util.MathUtils;
229import android.util.PackageUtils;
230import android.util.Pair;
231import android.util.PrintStreamPrinter;
232import android.util.Slog;
233import android.util.SparseArray;
234import android.util.SparseBooleanArray;
235import android.util.SparseIntArray;
236import android.util.Xml;
237import android.util.jar.StrictJarFile;
238import android.util.proto.ProtoOutputStream;
239import android.view.Display;
240
241import com.android.internal.R;
242import com.android.internal.annotations.GuardedBy;
243import com.android.internal.app.IMediaContainerService;
244import com.android.internal.app.ResolverActivity;
245import com.android.internal.content.NativeLibraryHelper;
246import com.android.internal.content.PackageHelper;
247import com.android.internal.logging.MetricsLogger;
248import com.android.internal.logging.nano.MetricsProto.MetricsEvent;
249import com.android.internal.os.IParcelFileDescriptorFactory;
250import com.android.internal.os.RoSystemProperties;
251import com.android.internal.os.SomeArgs;
252import com.android.internal.os.Zygote;
253import com.android.internal.telephony.CarrierAppUtils;
254import com.android.internal.util.ArrayUtils;
255import com.android.internal.util.ConcurrentUtils;
256import com.android.internal.util.DumpUtils;
257import com.android.internal.util.FastPrintWriter;
258import com.android.internal.util.FastXmlSerializer;
259import com.android.internal.util.IndentingPrintWriter;
260import com.android.internal.util.Preconditions;
261import com.android.internal.util.XmlUtils;
262import com.android.server.AttributeCache;
263import com.android.server.DeviceIdleController;
264import com.android.server.EventLogTags;
265import com.android.server.FgThread;
266import com.android.server.IntentResolver;
267import com.android.server.LocalServices;
268import com.android.server.LockGuard;
269import com.android.server.ServiceThread;
270import com.android.server.SystemConfig;
271import com.android.server.SystemServerInitThreadPool;
272import com.android.server.Watchdog;
273import com.android.server.net.NetworkPolicyManagerInternal;
274import com.android.server.pm.Installer.InstallerException;
275import com.android.server.pm.PermissionsState.PermissionState;
276import com.android.server.pm.Settings.DatabaseVersion;
277import com.android.server.pm.Settings.VersionInfo;
278import com.android.server.pm.dex.DexManager;
279import com.android.server.storage.DeviceStorageMonitorInternal;
280
281import dalvik.system.CloseGuard;
282import dalvik.system.DexFile;
283import dalvik.system.VMRuntime;
284
285import libcore.io.IoUtils;
286import libcore.util.EmptyArray;
287
288import org.xmlpull.v1.XmlPullParser;
289import org.xmlpull.v1.XmlPullParserException;
290import org.xmlpull.v1.XmlSerializer;
291
292import java.io.BufferedOutputStream;
293import java.io.BufferedReader;
294import java.io.ByteArrayInputStream;
295import java.io.ByteArrayOutputStream;
296import java.io.File;
297import java.io.FileDescriptor;
298import java.io.FileInputStream;
299import java.io.FileOutputStream;
300import java.io.FileReader;
301import java.io.FilenameFilter;
302import java.io.IOException;
303import java.io.PrintWriter;
304import java.lang.annotation.Retention;
305import java.lang.annotation.RetentionPolicy;
306import java.nio.charset.StandardCharsets;
307import java.security.DigestInputStream;
308import java.security.MessageDigest;
309import java.security.NoSuchAlgorithmException;
310import java.security.PublicKey;
311import java.security.SecureRandom;
312import java.security.cert.Certificate;
313import java.security.cert.CertificateEncodingException;
314import java.security.cert.CertificateException;
315import java.text.SimpleDateFormat;
316import java.util.ArrayList;
317import java.util.Arrays;
318import java.util.Collection;
319import java.util.Collections;
320import java.util.Comparator;
321import java.util.Date;
322import java.util.HashMap;
323import java.util.HashSet;
324import java.util.Iterator;
325import java.util.List;
326import java.util.Map;
327import java.util.Objects;
328import java.util.Set;
329import java.util.concurrent.CountDownLatch;
330import java.util.concurrent.Future;
331import java.util.concurrent.TimeUnit;
332import java.util.concurrent.atomic.AtomicBoolean;
333import java.util.concurrent.atomic.AtomicInteger;
334
335/**
336 * Keep track of all those APKs everywhere.
337 * <p>
338 * Internally there are two important locks:
339 * <ul>
340 * <li>{@link #mPackages} is used to guard all in-memory parsed package details
341 * and other related state. It is a fine-grained lock that should only be held
342 * momentarily, as it's one of the most contended locks in the system.
343 * <li>{@link #mInstallLock} is used to guard all {@code installd} access, whose
344 * operations typically involve heavy lifting of application data on disk. Since
345 * {@code installd} is single-threaded, and it's operations can often be slow,
346 * this lock should never be acquired while already holding {@link #mPackages}.
347 * Conversely, it's safe to acquire {@link #mPackages} momentarily while already
348 * holding {@link #mInstallLock}.
349 * </ul>
350 * Many internal methods rely on the caller to hold the appropriate locks, and
351 * this contract is expressed through method name suffixes:
352 * <ul>
353 * <li>fooLI(): the caller must hold {@link #mInstallLock}
354 * <li>fooLIF(): the caller must hold {@link #mInstallLock} and the package
355 * being modified must be frozen
356 * <li>fooLPr(): the caller must hold {@link #mPackages} for reading
357 * <li>fooLPw(): the caller must hold {@link #mPackages} for writing
358 * </ul>
359 * <p>
360 * Because this class is very central to the platform's security; please run all
361 * CTS and unit tests whenever making modifications:
362 *
363 * <pre>
364 * $ runtest -c android.content.pm.PackageManagerTests frameworks-core
365 * $ cts-tradefed run commandAndExit cts -m CtsAppSecurityHostTestCases
366 * </pre>
367 */
368public class PackageManagerService extends IPackageManager.Stub
369        implements PackageSender {
370    static final String TAG = "PackageManager";
371    static final boolean DEBUG_SETTINGS = false;
372    static final boolean DEBUG_PREFERRED = false;
373    static final boolean DEBUG_UPGRADE = false;
374    static final boolean DEBUG_DOMAIN_VERIFICATION = false;
375    private static final boolean DEBUG_BACKUP = false;
376    private static final boolean DEBUG_INSTALL = false;
377    private static final boolean DEBUG_REMOVE = false;
378    private static final boolean DEBUG_BROADCASTS = false;
379    private static final boolean DEBUG_SHOW_INFO = false;
380    private static final boolean DEBUG_PACKAGE_INFO = false;
381    private static final boolean DEBUG_INTENT_MATCHING = false;
382    private static final boolean DEBUG_PACKAGE_SCANNING = false;
383    private static final boolean DEBUG_VERIFY = false;
384    private static final boolean DEBUG_FILTERS = false;
385    private static final boolean DEBUG_PERMISSIONS = false;
386    private static final boolean DEBUG_SHARED_LIBRARIES = false;
387
388    // Debug output for dexopting. This is shared between PackageManagerService, OtaDexoptService
389    // and PackageDexOptimizer. All these classes have their own flag to allow switching a single
390    // user, but by default initialize to this.
391    public static final boolean DEBUG_DEXOPT = false;
392
393    private static final boolean DEBUG_ABI_SELECTION = false;
394    private static final boolean DEBUG_EPHEMERAL = Build.IS_DEBUGGABLE;
395    private static final boolean DEBUG_TRIAGED_MISSING = false;
396    private static final boolean DEBUG_APP_DATA = false;
397
398    /** REMOVE. According to Svet, this was only used to reset permissions during development. */
399    static final boolean CLEAR_RUNTIME_PERMISSIONS_ON_UPGRADE = false;
400
401    private static final boolean HIDE_EPHEMERAL_APIS = false;
402
403    private static final boolean ENABLE_FREE_CACHE_V2 =
404            SystemProperties.getBoolean("fw.free_cache_v2", true);
405
406    private static final int RADIO_UID = Process.PHONE_UID;
407    private static final int LOG_UID = Process.LOG_UID;
408    private static final int NFC_UID = Process.NFC_UID;
409    private static final int BLUETOOTH_UID = Process.BLUETOOTH_UID;
410    private static final int SHELL_UID = Process.SHELL_UID;
411
412    // Cap the size of permission trees that 3rd party apps can define
413    private static final int MAX_PERMISSION_TREE_FOOTPRINT = 32768;     // characters of text
414
415    // Suffix used during package installation when copying/moving
416    // package apks to install directory.
417    private static final String INSTALL_PACKAGE_SUFFIX = "-";
418
419    static final int SCAN_NO_DEX = 1<<1;
420    static final int SCAN_FORCE_DEX = 1<<2;
421    static final int SCAN_UPDATE_SIGNATURE = 1<<3;
422    static final int SCAN_NEW_INSTALL = 1<<4;
423    static final int SCAN_UPDATE_TIME = 1<<5;
424    static final int SCAN_BOOTING = 1<<6;
425    static final int SCAN_TRUSTED_OVERLAY = 1<<7;
426    static final int SCAN_DELETE_DATA_ON_FAILURES = 1<<8;
427    static final int SCAN_REPLACING = 1<<9;
428    static final int SCAN_REQUIRE_KNOWN = 1<<10;
429    static final int SCAN_MOVE = 1<<11;
430    static final int SCAN_INITIAL = 1<<12;
431    static final int SCAN_CHECK_ONLY = 1<<13;
432    static final int SCAN_DONT_KILL_APP = 1<<14;
433    static final int SCAN_IGNORE_FROZEN = 1<<15;
434    static final int SCAN_FIRST_BOOT_OR_UPGRADE = 1<<16;
435    static final int SCAN_AS_INSTANT_APP = 1<<17;
436    static final int SCAN_AS_FULL_APP = 1<<18;
437    /** Should not be with the scan flags */
438    static final int FLAGS_REMOVE_CHATTY = 1<<31;
439
440    private static final String STATIC_SHARED_LIB_DELIMITER = "_";
441
442    private static final int[] EMPTY_INT_ARRAY = new int[0];
443
444    private static final int TYPE_UNKNOWN = 0;
445    private static final int TYPE_ACTIVITY = 1;
446    private static final int TYPE_RECEIVER = 2;
447    private static final int TYPE_SERVICE = 3;
448    private static final int TYPE_PROVIDER = 4;
449    @IntDef(prefix = { "TYPE_" }, value = {
450            TYPE_UNKNOWN,
451            TYPE_ACTIVITY,
452            TYPE_RECEIVER,
453            TYPE_SERVICE,
454            TYPE_PROVIDER,
455    })
456    @Retention(RetentionPolicy.SOURCE)
457    public @interface ComponentType {}
458
459    /**
460     * Timeout (in milliseconds) after which the watchdog should declare that
461     * our handler thread is wedged.  The usual default for such things is one
462     * minute but we sometimes do very lengthy I/O operations on this thread,
463     * such as installing multi-gigabyte applications, so ours needs to be longer.
464     */
465    static final long WATCHDOG_TIMEOUT = 1000*60*10;     // ten minutes
466
467    /**
468     * Wall-clock timeout (in milliseconds) after which we *require* that an fstrim
469     * be run on this device.  We use the value in the Settings.Global.MANDATORY_FSTRIM_INTERVAL
470     * settings entry if available, otherwise we use the hardcoded default.  If it's been
471     * more than this long since the last fstrim, we force one during the boot sequence.
472     *
473     * This backstops other fstrim scheduling:  if the device is alive at midnight+idle,
474     * one gets run at the next available charging+idle time.  This final mandatory
475     * no-fstrim check kicks in only of the other scheduling criteria is never met.
476     */
477    private static final long DEFAULT_MANDATORY_FSTRIM_INTERVAL = 3 * DateUtils.DAY_IN_MILLIS;
478
479    /**
480     * Whether verification is enabled by default.
481     */
482    private static final boolean DEFAULT_VERIFY_ENABLE = true;
483
484    /**
485     * The default maximum time to wait for the verification agent to return in
486     * milliseconds.
487     */
488    private static final long DEFAULT_VERIFICATION_TIMEOUT = 10 * 1000;
489
490    /**
491     * The default response for package verification timeout.
492     *
493     * This can be either PackageManager.VERIFICATION_ALLOW or
494     * PackageManager.VERIFICATION_REJECT.
495     */
496    private static final int DEFAULT_VERIFICATION_RESPONSE = PackageManager.VERIFICATION_ALLOW;
497
498    static final String PLATFORM_PACKAGE_NAME = "android";
499
500    static final String DEFAULT_CONTAINER_PACKAGE = "com.android.defcontainer";
501
502    static final ComponentName DEFAULT_CONTAINER_COMPONENT = new ComponentName(
503            DEFAULT_CONTAINER_PACKAGE,
504            "com.android.defcontainer.DefaultContainerService");
505
506    private static final String KILL_APP_REASON_GIDS_CHANGED =
507            "permission grant or revoke changed gids";
508
509    private static final String KILL_APP_REASON_PERMISSIONS_REVOKED =
510            "permissions revoked";
511
512    private static final String PACKAGE_MIME_TYPE = "application/vnd.android.package-archive";
513
514    private static final String PACKAGE_SCHEME = "package";
515
516    private static final String VENDOR_OVERLAY_DIR = "/vendor/overlay";
517
518    /** Permission grant: not grant the permission. */
519    private static final int GRANT_DENIED = 1;
520
521    /** Permission grant: grant the permission as an install permission. */
522    private static final int GRANT_INSTALL = 2;
523
524    /** Permission grant: grant the permission as a runtime one. */
525    private static final int GRANT_RUNTIME = 3;
526
527    /** Permission grant: grant as runtime a permission that was granted as an install time one. */
528    private static final int GRANT_UPGRADE = 4;
529
530    /** Canonical intent used to identify what counts as a "web browser" app */
531    private static final Intent sBrowserIntent;
532    static {
533        sBrowserIntent = new Intent();
534        sBrowserIntent.setAction(Intent.ACTION_VIEW);
535        sBrowserIntent.addCategory(Intent.CATEGORY_BROWSABLE);
536        sBrowserIntent.setData(Uri.parse("http:"));
537    }
538
539    /**
540     * The set of all protected actions [i.e. those actions for which a high priority
541     * intent filter is disallowed].
542     */
543    private static final Set<String> PROTECTED_ACTIONS = new ArraySet<>();
544    static {
545        PROTECTED_ACTIONS.add(Intent.ACTION_SEND);
546        PROTECTED_ACTIONS.add(Intent.ACTION_SENDTO);
547        PROTECTED_ACTIONS.add(Intent.ACTION_SEND_MULTIPLE);
548        PROTECTED_ACTIONS.add(Intent.ACTION_VIEW);
549    }
550
551    // Compilation reasons.
552    public static final int REASON_FIRST_BOOT = 0;
553    public static final int REASON_BOOT = 1;
554    public static final int REASON_INSTALL = 2;
555    public static final int REASON_BACKGROUND_DEXOPT = 3;
556    public static final int REASON_AB_OTA = 4;
557
558    public static final int REASON_LAST = REASON_AB_OTA;
559
560    /** All dangerous permission names in the same order as the events in MetricsEvent */
561    private static final List<String> ALL_DANGEROUS_PERMISSIONS = Arrays.asList(
562            Manifest.permission.READ_CALENDAR,
563            Manifest.permission.WRITE_CALENDAR,
564            Manifest.permission.CAMERA,
565            Manifest.permission.READ_CONTACTS,
566            Manifest.permission.WRITE_CONTACTS,
567            Manifest.permission.GET_ACCOUNTS,
568            Manifest.permission.ACCESS_FINE_LOCATION,
569            Manifest.permission.ACCESS_COARSE_LOCATION,
570            Manifest.permission.RECORD_AUDIO,
571            Manifest.permission.READ_PHONE_STATE,
572            Manifest.permission.CALL_PHONE,
573            Manifest.permission.READ_CALL_LOG,
574            Manifest.permission.WRITE_CALL_LOG,
575            Manifest.permission.ADD_VOICEMAIL,
576            Manifest.permission.USE_SIP,
577            Manifest.permission.PROCESS_OUTGOING_CALLS,
578            Manifest.permission.READ_CELL_BROADCASTS,
579            Manifest.permission.BODY_SENSORS,
580            Manifest.permission.SEND_SMS,
581            Manifest.permission.RECEIVE_SMS,
582            Manifest.permission.READ_SMS,
583            Manifest.permission.RECEIVE_WAP_PUSH,
584            Manifest.permission.RECEIVE_MMS,
585            Manifest.permission.READ_EXTERNAL_STORAGE,
586            Manifest.permission.WRITE_EXTERNAL_STORAGE,
587            Manifest.permission.READ_PHONE_NUMBERS,
588            Manifest.permission.ANSWER_PHONE_CALLS);
589
590
591    /**
592     * Version number for the package parser cache. Increment this whenever the format or
593     * extent of cached data changes. See {@code PackageParser#setCacheDir}.
594     */
595    private static final String PACKAGE_PARSER_CACHE_VERSION = "1";
596
597    /**
598     * Whether the package parser cache is enabled.
599     */
600    private static final boolean DEFAULT_PACKAGE_PARSER_CACHE_ENABLED = true;
601
602    final ServiceThread mHandlerThread;
603
604    final PackageHandler mHandler;
605
606    private final ProcessLoggingHandler mProcessLoggingHandler;
607
608    /**
609     * Messages for {@link #mHandler} that need to wait for system ready before
610     * being dispatched.
611     */
612    private ArrayList<Message> mPostSystemReadyMessages;
613
614    final int mSdkVersion = Build.VERSION.SDK_INT;
615
616    final Context mContext;
617    final boolean mFactoryTest;
618    final boolean mOnlyCore;
619    final DisplayMetrics mMetrics;
620    final int mDefParseFlags;
621    final String[] mSeparateProcesses;
622    final boolean mIsUpgrade;
623    final boolean mIsPreNUpgrade;
624    final boolean mIsPreNMR1Upgrade;
625
626    // Have we told the Activity Manager to whitelist the default container service by uid yet?
627    @GuardedBy("mPackages")
628    boolean mDefaultContainerWhitelisted = false;
629
630    @GuardedBy("mPackages")
631    private boolean mDexOptDialogShown;
632
633    /** The location for ASEC container files on internal storage. */
634    final String mAsecInternalPath;
635
636    // Used for privilege escalation. MUST NOT BE CALLED WITH mPackages
637    // LOCK HELD.  Can be called with mInstallLock held.
638    @GuardedBy("mInstallLock")
639    final Installer mInstaller;
640
641    /** Directory where installed third-party apps stored */
642    final File mAppInstallDir;
643
644    /**
645     * Directory to which applications installed internally have their
646     * 32 bit native libraries copied.
647     */
648    private File mAppLib32InstallDir;
649
650    // Directory containing the private parts (e.g. code and non-resource assets) of forward-locked
651    // apps.
652    final File mDrmAppPrivateInstallDir;
653
654    // ----------------------------------------------------------------
655
656    // Lock for state used when installing and doing other long running
657    // operations.  Methods that must be called with this lock held have
658    // the suffix "LI".
659    final Object mInstallLock = new Object();
660
661    // ----------------------------------------------------------------
662
663    // Keys are String (package name), values are Package.  This also serves
664    // as the lock for the global state.  Methods that must be called with
665    // this lock held have the prefix "LP".
666    @GuardedBy("mPackages")
667    final ArrayMap<String, PackageParser.Package> mPackages =
668            new ArrayMap<String, PackageParser.Package>();
669
670    final ArrayMap<String, Set<String>> mKnownCodebase =
671            new ArrayMap<String, Set<String>>();
672
673    // Keys are isolated uids and values are the uid of the application
674    // that created the isolated proccess.
675    @GuardedBy("mPackages")
676    final SparseIntArray mIsolatedOwners = new SparseIntArray();
677
678    // List of APK paths to load for each user and package. This data is never
679    // persisted by the package manager. Instead, the overlay manager will
680    // ensure the data is up-to-date in runtime.
681    @GuardedBy("mPackages")
682    final SparseArray<ArrayMap<String, ArrayList<String>>> mEnabledOverlayPaths =
683        new SparseArray<ArrayMap<String, ArrayList<String>>>();
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    boolean mFirstBoot;
731
732    PackageManagerInternal.ExternalSourcesPolicy mExternalSourcesPolicy;
733
734    // System configuration read by SystemConfig.
735    final int[] mGlobalGids;
736    final SparseArray<ArraySet<String>> mSystemPermissions;
737    @GuardedBy("mAvailableFeatures")
738    final ArrayMap<String, FeatureInfo> mAvailableFeatures;
739
740    // If mac_permissions.xml was found for seinfo labeling.
741    boolean mFoundPolicyFile;
742
743    private final InstantAppRegistry mInstantAppRegistry;
744
745    @GuardedBy("mPackages")
746    int mChangedPackagesSequenceNumber;
747    /**
748     * List of changed [installed, removed or updated] packages.
749     * mapping from user id -> sequence number -> package name
750     */
751    @GuardedBy("mPackages")
752    final SparseArray<SparseArray<String>> mChangedPackages = new SparseArray<>();
753    /**
754     * The sequence number of the last change to a package.
755     * mapping from user id -> package name -> sequence number
756     */
757    @GuardedBy("mPackages")
758    final SparseArray<Map<String, Integer>> mChangedPackagesSequenceNumbers = new SparseArray<>();
759
760    class PackageParserCallback implements PackageParser.Callback {
761        @Override public final boolean hasFeature(String feature) {
762            return PackageManagerService.this.hasSystemFeature(feature, 0);
763        }
764
765        final List<PackageParser.Package> getStaticOverlayPackagesLocked(
766                Collection<PackageParser.Package> allPackages, String targetPackageName) {
767            List<PackageParser.Package> overlayPackages = null;
768            for (PackageParser.Package p : allPackages) {
769                if (targetPackageName.equals(p.mOverlayTarget) && p.mIsStaticOverlay) {
770                    if (overlayPackages == null) {
771                        overlayPackages = new ArrayList<PackageParser.Package>();
772                    }
773                    overlayPackages.add(p);
774                }
775            }
776            if (overlayPackages != null) {
777                Comparator<PackageParser.Package> cmp = new Comparator<PackageParser.Package>() {
778                    public int compare(PackageParser.Package p1, PackageParser.Package p2) {
779                        return p1.mOverlayPriority - p2.mOverlayPriority;
780                    }
781                };
782                Collections.sort(overlayPackages, cmp);
783            }
784            return overlayPackages;
785        }
786
787        final String[] getStaticOverlayPathsLocked(Collection<PackageParser.Package> allPackages,
788                String targetPackageName, String targetPath) {
789            if ("android".equals(targetPackageName)) {
790                // Static RROs targeting to "android", ie framework-res.apk, are already applied by
791                // native AssetManager.
792                return null;
793            }
794            List<PackageParser.Package> overlayPackages =
795                    getStaticOverlayPackagesLocked(allPackages, targetPackageName);
796            if (overlayPackages == null || overlayPackages.isEmpty()) {
797                return null;
798            }
799            List<String> overlayPathList = null;
800            for (PackageParser.Package overlayPackage : overlayPackages) {
801                if (targetPath == null) {
802                    if (overlayPathList == null) {
803                        overlayPathList = new ArrayList<String>();
804                    }
805                    overlayPathList.add(overlayPackage.baseCodePath);
806                    continue;
807                }
808
809                try {
810                    // Creates idmaps for system to parse correctly the Android manifest of the
811                    // target package.
812                    //
813                    // OverlayManagerService will update each of them with a correct gid from its
814                    // target package app id.
815                    mInstaller.idmap(targetPath, overlayPackage.baseCodePath,
816                            UserHandle.getSharedAppGid(
817                                    UserHandle.getUserGid(UserHandle.USER_SYSTEM)));
818                    if (overlayPathList == null) {
819                        overlayPathList = new ArrayList<String>();
820                    }
821                    overlayPathList.add(overlayPackage.baseCodePath);
822                } catch (InstallerException e) {
823                    Slog.e(TAG, "Failed to generate idmap for " + targetPath + " and " +
824                            overlayPackage.baseCodePath);
825                }
826            }
827            return overlayPathList == null ? null : overlayPathList.toArray(new String[0]);
828        }
829
830        String[] getStaticOverlayPaths(String targetPackageName, String targetPath) {
831            synchronized (mPackages) {
832                return getStaticOverlayPathsLocked(
833                        mPackages.values(), targetPackageName, targetPath);
834            }
835        }
836
837        @Override public final String[] getOverlayApks(String targetPackageName) {
838            return getStaticOverlayPaths(targetPackageName, null);
839        }
840
841        @Override public final String[] getOverlayPaths(String targetPackageName,
842                String targetPath) {
843            return getStaticOverlayPaths(targetPackageName, targetPath);
844        }
845    };
846
847    class ParallelPackageParserCallback extends PackageParserCallback {
848        List<PackageParser.Package> mOverlayPackages = null;
849
850        void findStaticOverlayPackages() {
851            synchronized (mPackages) {
852                for (PackageParser.Package p : mPackages.values()) {
853                    if (p.mIsStaticOverlay) {
854                        if (mOverlayPackages == null) {
855                            mOverlayPackages = new ArrayList<PackageParser.Package>();
856                        }
857                        mOverlayPackages.add(p);
858                    }
859                }
860            }
861        }
862
863        @Override
864        synchronized String[] getStaticOverlayPaths(String targetPackageName, String targetPath) {
865            // We can trust mOverlayPackages without holding mPackages because package uninstall
866            // can't happen while running parallel parsing.
867            // Moreover holding mPackages on each parsing thread causes dead-lock.
868            return mOverlayPackages == null ? null :
869                    getStaticOverlayPathsLocked(mOverlayPackages, targetPackageName, targetPath);
870        }
871    }
872
873    final PackageParser.Callback mPackageParserCallback = new PackageParserCallback();
874    final ParallelPackageParserCallback mParallelPackageParserCallback =
875            new ParallelPackageParserCallback();
876
877    public static final class SharedLibraryEntry {
878        public final String path;
879        public final String apk;
880        public final SharedLibraryInfo info;
881
882        SharedLibraryEntry(String _path, String _apk, String name, int version, int type,
883                String declaringPackageName, int declaringPackageVersionCode) {
884            path = _path;
885            apk = _apk;
886            info = new SharedLibraryInfo(name, version, type, new VersionedPackage(
887                    declaringPackageName, declaringPackageVersionCode), null);
888        }
889    }
890
891    // Currently known shared libraries.
892    final ArrayMap<String, SparseArray<SharedLibraryEntry>> mSharedLibraries = new ArrayMap<>();
893    final ArrayMap<String, SparseArray<SharedLibraryEntry>> mStaticLibsByDeclaringPackage =
894            new ArrayMap<>();
895
896    // All available activities, for your resolving pleasure.
897    final ActivityIntentResolver mActivities =
898            new ActivityIntentResolver();
899
900    // All available receivers, for your resolving pleasure.
901    final ActivityIntentResolver mReceivers =
902            new ActivityIntentResolver();
903
904    // All available services, for your resolving pleasure.
905    final ServiceIntentResolver mServices = new ServiceIntentResolver();
906
907    // All available providers, for your resolving pleasure.
908    final ProviderIntentResolver mProviders = new ProviderIntentResolver();
909
910    // Mapping from provider base names (first directory in content URI codePath)
911    // to the provider information.
912    final ArrayMap<String, PackageParser.Provider> mProvidersByAuthority =
913            new ArrayMap<String, PackageParser.Provider>();
914
915    // Mapping from instrumentation class names to info about them.
916    final ArrayMap<ComponentName, PackageParser.Instrumentation> mInstrumentation =
917            new ArrayMap<ComponentName, PackageParser.Instrumentation>();
918
919    // Mapping from permission names to info about them.
920    final ArrayMap<String, PackageParser.PermissionGroup> mPermissionGroups =
921            new ArrayMap<String, PackageParser.PermissionGroup>();
922
923    // Packages whose data we have transfered into another package, thus
924    // should no longer exist.
925    final ArraySet<String> mTransferedPackages = new ArraySet<String>();
926
927    // Broadcast actions that are only available to the system.
928    final ArraySet<String> mProtectedBroadcasts = new ArraySet<String>();
929
930    /** List of packages waiting for verification. */
931    final SparseArray<PackageVerificationState> mPendingVerification
932            = new SparseArray<PackageVerificationState>();
933
934    /** Set of packages associated with each app op permission. */
935    final ArrayMap<String, ArraySet<String>> mAppOpPermissionPackages = new ArrayMap<>();
936
937    final PackageInstallerService mInstallerService;
938
939    private final PackageDexOptimizer mPackageDexOptimizer;
940    // DexManager handles the usage of dex files (e.g. secondary files, whether or not a package
941    // is used by other apps).
942    private final DexManager mDexManager;
943
944    private AtomicInteger mNextMoveId = new AtomicInteger();
945    private final MoveCallbacks mMoveCallbacks;
946
947    private final OnPermissionChangeListeners mOnPermissionChangeListeners;
948
949    // Cache of users who need badging.
950    SparseBooleanArray mUserNeedsBadging = new SparseBooleanArray();
951
952    /** Token for keys in mPendingVerification. */
953    private int mPendingVerificationToken = 0;
954
955    volatile boolean mSystemReady;
956    volatile boolean mSafeMode;
957    volatile boolean mHasSystemUidErrors;
958    private volatile boolean mEphemeralAppsDisabled;
959
960    ApplicationInfo mAndroidApplication;
961    final ActivityInfo mResolveActivity = new ActivityInfo();
962    final ResolveInfo mResolveInfo = new ResolveInfo();
963    ComponentName mResolveComponentName;
964    PackageParser.Package mPlatformPackage;
965    ComponentName mCustomResolverComponentName;
966
967    boolean mResolverReplaced = false;
968
969    private final @Nullable ComponentName mIntentFilterVerifierComponent;
970    private final @Nullable IntentFilterVerifier<ActivityIntentInfo> mIntentFilterVerifier;
971
972    private int mIntentFilterVerificationToken = 0;
973
974    /** The service connection to the ephemeral resolver */
975    final EphemeralResolverConnection mInstantAppResolverConnection;
976    /** Component used to show resolver settings for Instant Apps */
977    final ComponentName mInstantAppResolverSettingsComponent;
978
979    /** Activity used to install instant applications */
980    ActivityInfo mInstantAppInstallerActivity;
981    final ResolveInfo mInstantAppInstallerInfo = new ResolveInfo();
982
983    final SparseArray<IntentFilterVerificationState> mIntentFilterVerificationStates
984            = new SparseArray<IntentFilterVerificationState>();
985
986    final DefaultPermissionGrantPolicy mDefaultPermissionPolicy;
987
988    // List of packages names to keep cached, even if they are uninstalled for all users
989    private List<String> mKeepUninstalledPackages;
990
991    private UserManagerInternal mUserManagerInternal;
992
993    private DeviceIdleController.LocalService mDeviceIdleController;
994
995    private File mCacheDir;
996
997    private ArraySet<String> mPrivappPermissionsViolations;
998
999    private Future<?> mPrepareAppDataFuture;
1000
1001    private static class IFVerificationParams {
1002        PackageParser.Package pkg;
1003        boolean replacing;
1004        int userId;
1005        int verifierUid;
1006
1007        public IFVerificationParams(PackageParser.Package _pkg, boolean _replacing,
1008                int _userId, int _verifierUid) {
1009            pkg = _pkg;
1010            replacing = _replacing;
1011            userId = _userId;
1012            replacing = _replacing;
1013            verifierUid = _verifierUid;
1014        }
1015    }
1016
1017    private interface IntentFilterVerifier<T extends IntentFilter> {
1018        boolean addOneIntentFilterVerification(int verifierId, int userId, int verificationId,
1019                                               T filter, String packageName);
1020        void startVerifications(int userId);
1021        void receiveVerificationResponse(int verificationId);
1022    }
1023
1024    private class IntentVerifierProxy implements IntentFilterVerifier<ActivityIntentInfo> {
1025        private Context mContext;
1026        private ComponentName mIntentFilterVerifierComponent;
1027        private ArrayList<Integer> mCurrentIntentFilterVerifications = new ArrayList<Integer>();
1028
1029        public IntentVerifierProxy(Context context, ComponentName verifierComponent) {
1030            mContext = context;
1031            mIntentFilterVerifierComponent = verifierComponent;
1032        }
1033
1034        private String getDefaultScheme() {
1035            return IntentFilter.SCHEME_HTTPS;
1036        }
1037
1038        @Override
1039        public void startVerifications(int userId) {
1040            // Launch verifications requests
1041            int count = mCurrentIntentFilterVerifications.size();
1042            for (int n=0; n<count; n++) {
1043                int verificationId = mCurrentIntentFilterVerifications.get(n);
1044                final IntentFilterVerificationState ivs =
1045                        mIntentFilterVerificationStates.get(verificationId);
1046
1047                String packageName = ivs.getPackageName();
1048
1049                ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters();
1050                final int filterCount = filters.size();
1051                ArraySet<String> domainsSet = new ArraySet<>();
1052                for (int m=0; m<filterCount; m++) {
1053                    PackageParser.ActivityIntentInfo filter = filters.get(m);
1054                    domainsSet.addAll(filter.getHostsList());
1055                }
1056                synchronized (mPackages) {
1057                    if (mSettings.createIntentFilterVerificationIfNeededLPw(
1058                            packageName, domainsSet) != null) {
1059                        scheduleWriteSettingsLocked();
1060                    }
1061                }
1062                sendVerificationRequest(userId, verificationId, ivs);
1063            }
1064            mCurrentIntentFilterVerifications.clear();
1065        }
1066
1067        private void sendVerificationRequest(int userId, int verificationId,
1068                IntentFilterVerificationState ivs) {
1069
1070            Intent verificationIntent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION);
1071            verificationIntent.putExtra(
1072                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_ID,
1073                    verificationId);
1074            verificationIntent.putExtra(
1075                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_URI_SCHEME,
1076                    getDefaultScheme());
1077            verificationIntent.putExtra(
1078                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_HOSTS,
1079                    ivs.getHostsString());
1080            verificationIntent.putExtra(
1081                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_PACKAGE_NAME,
1082                    ivs.getPackageName());
1083            verificationIntent.setComponent(mIntentFilterVerifierComponent);
1084            verificationIntent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
1085
1086            DeviceIdleController.LocalService idleController = getDeviceIdleController();
1087            idleController.addPowerSaveTempWhitelistApp(Process.myUid(),
1088                    mIntentFilterVerifierComponent.getPackageName(), getVerificationTimeout(),
1089                    userId, false, "intent filter verifier");
1090
1091            UserHandle user = new UserHandle(userId);
1092            mContext.sendBroadcastAsUser(verificationIntent, user);
1093            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1094                    "Sending IntentFilter verification broadcast");
1095        }
1096
1097        public void receiveVerificationResponse(int verificationId) {
1098            IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId);
1099
1100            final boolean verified = ivs.isVerified();
1101
1102            ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters();
1103            final int count = filters.size();
1104            if (DEBUG_DOMAIN_VERIFICATION) {
1105                Slog.i(TAG, "Received verification response " + verificationId
1106                        + " for " + count + " filters, verified=" + verified);
1107            }
1108            for (int n=0; n<count; n++) {
1109                PackageParser.ActivityIntentInfo filter = filters.get(n);
1110                filter.setVerified(verified);
1111
1112                if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "IntentFilter " + filter.toString()
1113                        + " verified with result:" + verified + " and hosts:"
1114                        + ivs.getHostsString());
1115            }
1116
1117            mIntentFilterVerificationStates.remove(verificationId);
1118
1119            final String packageName = ivs.getPackageName();
1120            IntentFilterVerificationInfo ivi = null;
1121
1122            synchronized (mPackages) {
1123                ivi = mSettings.getIntentFilterVerificationLPr(packageName);
1124            }
1125            if (ivi == null) {
1126                Slog.w(TAG, "IntentFilterVerificationInfo not found for verificationId:"
1127                        + verificationId + " packageName:" + packageName);
1128                return;
1129            }
1130            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1131                    "Updating IntentFilterVerificationInfo for package " + packageName
1132                            +" verificationId:" + verificationId);
1133
1134            synchronized (mPackages) {
1135                if (verified) {
1136                    ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS);
1137                } else {
1138                    ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK);
1139                }
1140                scheduleWriteSettingsLocked();
1141
1142                final int userId = ivs.getUserId();
1143                if (userId != UserHandle.USER_ALL) {
1144                    final int userStatus =
1145                            mSettings.getIntentFilterVerificationStatusLPr(packageName, userId);
1146
1147                    int updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED;
1148                    boolean needUpdate = false;
1149
1150                    // We cannot override the STATUS_ALWAYS / STATUS_NEVER states if they have
1151                    // already been set by the User thru the Disambiguation dialog
1152                    switch (userStatus) {
1153                        case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED:
1154                            if (verified) {
1155                                updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS;
1156                            } else {
1157                                updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK;
1158                            }
1159                            needUpdate = true;
1160                            break;
1161
1162                        case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK:
1163                            if (verified) {
1164                                updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS;
1165                                needUpdate = true;
1166                            }
1167                            break;
1168
1169                        default:
1170                            // Nothing to do
1171                    }
1172
1173                    if (needUpdate) {
1174                        mSettings.updateIntentFilterVerificationStatusLPw(
1175                                packageName, updatedStatus, userId);
1176                        scheduleWritePackageRestrictionsLocked(userId);
1177                    }
1178                }
1179            }
1180        }
1181
1182        @Override
1183        public boolean addOneIntentFilterVerification(int verifierUid, int userId, int verificationId,
1184                    ActivityIntentInfo filter, String packageName) {
1185            if (!hasValidDomains(filter)) {
1186                return false;
1187            }
1188            IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId);
1189            if (ivs == null) {
1190                ivs = createDomainVerificationState(verifierUid, userId, verificationId,
1191                        packageName);
1192            }
1193            if (DEBUG_DOMAIN_VERIFICATION) {
1194                Slog.d(TAG, "Adding verification filter for " + packageName + ": " + filter);
1195            }
1196            ivs.addFilter(filter);
1197            return true;
1198        }
1199
1200        private IntentFilterVerificationState createDomainVerificationState(int verifierUid,
1201                int userId, int verificationId, String packageName) {
1202            IntentFilterVerificationState ivs = new IntentFilterVerificationState(
1203                    verifierUid, userId, packageName);
1204            ivs.setPendingState();
1205            synchronized (mPackages) {
1206                mIntentFilterVerificationStates.append(verificationId, ivs);
1207                mCurrentIntentFilterVerifications.add(verificationId);
1208            }
1209            return ivs;
1210        }
1211    }
1212
1213    private static boolean hasValidDomains(ActivityIntentInfo filter) {
1214        return filter.hasCategory(Intent.CATEGORY_BROWSABLE)
1215                && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) ||
1216                        filter.hasDataScheme(IntentFilter.SCHEME_HTTPS));
1217    }
1218
1219    // Set of pending broadcasts for aggregating enable/disable of components.
1220    static class PendingPackageBroadcasts {
1221        // for each user id, a map of <package name -> components within that package>
1222        final SparseArray<ArrayMap<String, ArrayList<String>>> mUidMap;
1223
1224        public PendingPackageBroadcasts() {
1225            mUidMap = new SparseArray<ArrayMap<String, ArrayList<String>>>(2);
1226        }
1227
1228        public ArrayList<String> get(int userId, String packageName) {
1229            ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId);
1230            return packages.get(packageName);
1231        }
1232
1233        public void put(int userId, String packageName, ArrayList<String> components) {
1234            ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId);
1235            packages.put(packageName, components);
1236        }
1237
1238        public void remove(int userId, String packageName) {
1239            ArrayMap<String, ArrayList<String>> packages = mUidMap.get(userId);
1240            if (packages != null) {
1241                packages.remove(packageName);
1242            }
1243        }
1244
1245        public void remove(int userId) {
1246            mUidMap.remove(userId);
1247        }
1248
1249        public int userIdCount() {
1250            return mUidMap.size();
1251        }
1252
1253        public int userIdAt(int n) {
1254            return mUidMap.keyAt(n);
1255        }
1256
1257        public ArrayMap<String, ArrayList<String>> packagesForUserId(int userId) {
1258            return mUidMap.get(userId);
1259        }
1260
1261        public int size() {
1262            // total number of pending broadcast entries across all userIds
1263            int num = 0;
1264            for (int i = 0; i< mUidMap.size(); i++) {
1265                num += mUidMap.valueAt(i).size();
1266            }
1267            return num;
1268        }
1269
1270        public void clear() {
1271            mUidMap.clear();
1272        }
1273
1274        private ArrayMap<String, ArrayList<String>> getOrAllocate(int userId) {
1275            ArrayMap<String, ArrayList<String>> map = mUidMap.get(userId);
1276            if (map == null) {
1277                map = new ArrayMap<String, ArrayList<String>>();
1278                mUidMap.put(userId, map);
1279            }
1280            return map;
1281        }
1282    }
1283    final PendingPackageBroadcasts mPendingBroadcasts = new PendingPackageBroadcasts();
1284
1285    // Service Connection to remote media container service to copy
1286    // package uri's from external media onto secure containers
1287    // or internal storage.
1288    private IMediaContainerService mContainerService = null;
1289
1290    static final int SEND_PENDING_BROADCAST = 1;
1291    static final int MCS_BOUND = 3;
1292    static final int END_COPY = 4;
1293    static final int INIT_COPY = 5;
1294    static final int MCS_UNBIND = 6;
1295    static final int START_CLEANING_PACKAGE = 7;
1296    static final int FIND_INSTALL_LOC = 8;
1297    static final int POST_INSTALL = 9;
1298    static final int MCS_RECONNECT = 10;
1299    static final int MCS_GIVE_UP = 11;
1300    static final int UPDATED_MEDIA_STATUS = 12;
1301    static final int WRITE_SETTINGS = 13;
1302    static final int WRITE_PACKAGE_RESTRICTIONS = 14;
1303    static final int PACKAGE_VERIFIED = 15;
1304    static final int CHECK_PENDING_VERIFICATION = 16;
1305    static final int START_INTENT_FILTER_VERIFICATIONS = 17;
1306    static final int INTENT_FILTER_VERIFIED = 18;
1307    static final int WRITE_PACKAGE_LIST = 19;
1308    static final int INSTANT_APP_RESOLUTION_PHASE_TWO = 20;
1309
1310    static final int WRITE_SETTINGS_DELAY = 10*1000;  // 10 seconds
1311
1312    // Delay time in millisecs
1313    static final int BROADCAST_DELAY = 10 * 1000;
1314
1315    static UserManagerService sUserManager;
1316
1317    // Stores a list of users whose package restrictions file needs to be updated
1318    private ArraySet<Integer> mDirtyUsers = new ArraySet<Integer>();
1319
1320    final private DefaultContainerConnection mDefContainerConn =
1321            new DefaultContainerConnection();
1322    class DefaultContainerConnection implements ServiceConnection {
1323        public void onServiceConnected(ComponentName name, IBinder service) {
1324            if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceConnected");
1325            final IMediaContainerService imcs = IMediaContainerService.Stub
1326                    .asInterface(Binder.allowBlocking(service));
1327            mHandler.sendMessage(mHandler.obtainMessage(MCS_BOUND, imcs));
1328        }
1329
1330        public void onServiceDisconnected(ComponentName name) {
1331            if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceDisconnected");
1332        }
1333    }
1334
1335    // Recordkeeping of restore-after-install operations that are currently in flight
1336    // between the Package Manager and the Backup Manager
1337    static class PostInstallData {
1338        public InstallArgs args;
1339        public PackageInstalledInfo res;
1340
1341        PostInstallData(InstallArgs _a, PackageInstalledInfo _r) {
1342            args = _a;
1343            res = _r;
1344        }
1345    }
1346
1347    final SparseArray<PostInstallData> mRunningInstalls = new SparseArray<PostInstallData>();
1348    int mNextInstallToken = 1;  // nonzero; will be wrapped back to 1 when ++ overflows
1349
1350    // XML tags for backup/restore of various bits of state
1351    private static final String TAG_PREFERRED_BACKUP = "pa";
1352    private static final String TAG_DEFAULT_APPS = "da";
1353    private static final String TAG_INTENT_FILTER_VERIFICATION = "iv";
1354
1355    private static final String TAG_PERMISSION_BACKUP = "perm-grant-backup";
1356    private static final String TAG_ALL_GRANTS = "rt-grants";
1357    private static final String TAG_GRANT = "grant";
1358    private static final String ATTR_PACKAGE_NAME = "pkg";
1359
1360    private static final String TAG_PERMISSION = "perm";
1361    private static final String ATTR_PERMISSION_NAME = "name";
1362    private static final String ATTR_IS_GRANTED = "g";
1363    private static final String ATTR_USER_SET = "set";
1364    private static final String ATTR_USER_FIXED = "fixed";
1365    private static final String ATTR_REVOKE_ON_UPGRADE = "rou";
1366
1367    // System/policy permission grants are not backed up
1368    private static final int SYSTEM_RUNTIME_GRANT_MASK =
1369            FLAG_PERMISSION_POLICY_FIXED
1370            | FLAG_PERMISSION_SYSTEM_FIXED
1371            | FLAG_PERMISSION_GRANTED_BY_DEFAULT;
1372
1373    // And we back up these user-adjusted states
1374    private static final int USER_RUNTIME_GRANT_MASK =
1375            FLAG_PERMISSION_USER_SET
1376            | FLAG_PERMISSION_USER_FIXED
1377            | FLAG_PERMISSION_REVOKE_ON_UPGRADE;
1378
1379    final @Nullable String mRequiredVerifierPackage;
1380    final @NonNull String mRequiredInstallerPackage;
1381    final @NonNull String mRequiredUninstallerPackage;
1382    final @Nullable String mSetupWizardPackage;
1383    final @Nullable String mStorageManagerPackage;
1384    final @NonNull String mServicesSystemSharedLibraryPackageName;
1385    final @NonNull String mSharedSystemSharedLibraryPackageName;
1386
1387    final boolean mPermissionReviewRequired;
1388
1389    private final PackageUsage mPackageUsage = new PackageUsage();
1390    private final CompilerStats mCompilerStats = new CompilerStats();
1391
1392    class PackageHandler extends Handler {
1393        private boolean mBound = false;
1394        final ArrayList<HandlerParams> mPendingInstalls =
1395            new ArrayList<HandlerParams>();
1396
1397        private boolean connectToService() {
1398            if (DEBUG_SD_INSTALL) Log.i(TAG, "Trying to bind to" +
1399                    " DefaultContainerService");
1400            Intent service = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
1401            Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1402            if (mContext.bindServiceAsUser(service, mDefContainerConn,
1403                    Context.BIND_AUTO_CREATE, UserHandle.SYSTEM)) {
1404                Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1405                mBound = true;
1406                return true;
1407            }
1408            Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1409            return false;
1410        }
1411
1412        private void disconnectService() {
1413            mContainerService = null;
1414            mBound = false;
1415            Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1416            mContext.unbindService(mDefContainerConn);
1417            Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1418        }
1419
1420        PackageHandler(Looper looper) {
1421            super(looper);
1422        }
1423
1424        public void handleMessage(Message msg) {
1425            try {
1426                doHandleMessage(msg);
1427            } finally {
1428                Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1429            }
1430        }
1431
1432        void doHandleMessage(Message msg) {
1433            switch (msg.what) {
1434                case INIT_COPY: {
1435                    HandlerParams params = (HandlerParams) msg.obj;
1436                    int idx = mPendingInstalls.size();
1437                    if (DEBUG_INSTALL) Slog.i(TAG, "init_copy idx=" + idx + ": " + params);
1438                    // If a bind was already initiated we dont really
1439                    // need to do anything. The pending install
1440                    // will be processed later on.
1441                    if (!mBound) {
1442                        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS",
1443                                System.identityHashCode(mHandler));
1444                        // If this is the only one pending we might
1445                        // have to bind to the service again.
1446                        if (!connectToService()) {
1447                            Slog.e(TAG, "Failed to bind to media container service");
1448                            params.serviceError();
1449                            Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS",
1450                                    System.identityHashCode(mHandler));
1451                            if (params.traceMethod != null) {
1452                                Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, params.traceMethod,
1453                                        params.traceCookie);
1454                            }
1455                            return;
1456                        } else {
1457                            // Once we bind to the service, the first
1458                            // pending request will be processed.
1459                            mPendingInstalls.add(idx, params);
1460                        }
1461                    } else {
1462                        mPendingInstalls.add(idx, params);
1463                        // Already bound to the service. Just make
1464                        // sure we trigger off processing the first request.
1465                        if (idx == 0) {
1466                            mHandler.sendEmptyMessage(MCS_BOUND);
1467                        }
1468                    }
1469                    break;
1470                }
1471                case MCS_BOUND: {
1472                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_bound");
1473                    if (msg.obj != null) {
1474                        mContainerService = (IMediaContainerService) msg.obj;
1475                        Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS",
1476                                System.identityHashCode(mHandler));
1477                    }
1478                    if (mContainerService == null) {
1479                        if (!mBound) {
1480                            // Something seriously wrong since we are not bound and we are not
1481                            // waiting for connection. Bail out.
1482                            Slog.e(TAG, "Cannot bind to media container service");
1483                            for (HandlerParams params : mPendingInstalls) {
1484                                // Indicate service bind error
1485                                params.serviceError();
1486                                Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1487                                        System.identityHashCode(params));
1488                                if (params.traceMethod != null) {
1489                                    Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER,
1490                                            params.traceMethod, params.traceCookie);
1491                                }
1492                                return;
1493                            }
1494                            mPendingInstalls.clear();
1495                        } else {
1496                            Slog.w(TAG, "Waiting to connect to media container service");
1497                        }
1498                    } else if (mPendingInstalls.size() > 0) {
1499                        HandlerParams params = mPendingInstalls.get(0);
1500                        if (params != null) {
1501                            Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1502                                    System.identityHashCode(params));
1503                            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "startCopy");
1504                            if (params.startCopy()) {
1505                                // We are done...  look for more work or to
1506                                // go idle.
1507                                if (DEBUG_SD_INSTALL) Log.i(TAG,
1508                                        "Checking for more work or unbind...");
1509                                // Delete pending install
1510                                if (mPendingInstalls.size() > 0) {
1511                                    mPendingInstalls.remove(0);
1512                                }
1513                                if (mPendingInstalls.size() == 0) {
1514                                    if (mBound) {
1515                                        if (DEBUG_SD_INSTALL) Log.i(TAG,
1516                                                "Posting delayed MCS_UNBIND");
1517                                        removeMessages(MCS_UNBIND);
1518                                        Message ubmsg = obtainMessage(MCS_UNBIND);
1519                                        // Unbind after a little delay, to avoid
1520                                        // continual thrashing.
1521                                        sendMessageDelayed(ubmsg, 10000);
1522                                    }
1523                                } else {
1524                                    // There are more pending requests in queue.
1525                                    // Just post MCS_BOUND message to trigger processing
1526                                    // of next pending install.
1527                                    if (DEBUG_SD_INSTALL) Log.i(TAG,
1528                                            "Posting MCS_BOUND for next work");
1529                                    mHandler.sendEmptyMessage(MCS_BOUND);
1530                                }
1531                            }
1532                            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
1533                        }
1534                    } else {
1535                        // Should never happen ideally.
1536                        Slog.w(TAG, "Empty queue");
1537                    }
1538                    break;
1539                }
1540                case MCS_RECONNECT: {
1541                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_reconnect");
1542                    if (mPendingInstalls.size() > 0) {
1543                        if (mBound) {
1544                            disconnectService();
1545                        }
1546                        if (!connectToService()) {
1547                            Slog.e(TAG, "Failed to bind to media container service");
1548                            for (HandlerParams params : mPendingInstalls) {
1549                                // Indicate service bind error
1550                                params.serviceError();
1551                                Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1552                                        System.identityHashCode(params));
1553                            }
1554                            mPendingInstalls.clear();
1555                        }
1556                    }
1557                    break;
1558                }
1559                case MCS_UNBIND: {
1560                    // If there is no actual work left, then time to unbind.
1561                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_unbind");
1562
1563                    if (mPendingInstalls.size() == 0 && mPendingVerification.size() == 0) {
1564                        if (mBound) {
1565                            if (DEBUG_INSTALL) Slog.i(TAG, "calling disconnectService()");
1566
1567                            disconnectService();
1568                        }
1569                    } else if (mPendingInstalls.size() > 0) {
1570                        // There are more pending requests in queue.
1571                        // Just post MCS_BOUND message to trigger processing
1572                        // of next pending install.
1573                        mHandler.sendEmptyMessage(MCS_BOUND);
1574                    }
1575
1576                    break;
1577                }
1578                case MCS_GIVE_UP: {
1579                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_giveup too many retries");
1580                    HandlerParams params = mPendingInstalls.remove(0);
1581                    Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1582                            System.identityHashCode(params));
1583                    break;
1584                }
1585                case SEND_PENDING_BROADCAST: {
1586                    String packages[];
1587                    ArrayList<String> components[];
1588                    int size = 0;
1589                    int uids[];
1590                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1591                    synchronized (mPackages) {
1592                        if (mPendingBroadcasts == null) {
1593                            return;
1594                        }
1595                        size = mPendingBroadcasts.size();
1596                        if (size <= 0) {
1597                            // Nothing to be done. Just return
1598                            return;
1599                        }
1600                        packages = new String[size];
1601                        components = new ArrayList[size];
1602                        uids = new int[size];
1603                        int i = 0;  // filling out the above arrays
1604
1605                        for (int n = 0; n < mPendingBroadcasts.userIdCount(); n++) {
1606                            int packageUserId = mPendingBroadcasts.userIdAt(n);
1607                            Iterator<Map.Entry<String, ArrayList<String>>> it
1608                                    = mPendingBroadcasts.packagesForUserId(packageUserId)
1609                                            .entrySet().iterator();
1610                            while (it.hasNext() && i < size) {
1611                                Map.Entry<String, ArrayList<String>> ent = it.next();
1612                                packages[i] = ent.getKey();
1613                                components[i] = ent.getValue();
1614                                PackageSetting ps = mSettings.mPackages.get(ent.getKey());
1615                                uids[i] = (ps != null)
1616                                        ? UserHandle.getUid(packageUserId, ps.appId)
1617                                        : -1;
1618                                i++;
1619                            }
1620                        }
1621                        size = i;
1622                        mPendingBroadcasts.clear();
1623                    }
1624                    // Send broadcasts
1625                    for (int i = 0; i < size; i++) {
1626                        sendPackageChangedBroadcast(packages[i], true, components[i], uids[i]);
1627                    }
1628                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1629                    break;
1630                }
1631                case START_CLEANING_PACKAGE: {
1632                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1633                    final String packageName = (String)msg.obj;
1634                    final int userId = msg.arg1;
1635                    final boolean andCode = msg.arg2 != 0;
1636                    synchronized (mPackages) {
1637                        if (userId == UserHandle.USER_ALL) {
1638                            int[] users = sUserManager.getUserIds();
1639                            for (int user : users) {
1640                                mSettings.addPackageToCleanLPw(
1641                                        new PackageCleanItem(user, packageName, andCode));
1642                            }
1643                        } else {
1644                            mSettings.addPackageToCleanLPw(
1645                                    new PackageCleanItem(userId, packageName, andCode));
1646                        }
1647                    }
1648                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1649                    startCleaningPackages();
1650                } break;
1651                case POST_INSTALL: {
1652                    if (DEBUG_INSTALL) Log.v(TAG, "Handling post-install for " + msg.arg1);
1653
1654                    PostInstallData data = mRunningInstalls.get(msg.arg1);
1655                    final boolean didRestore = (msg.arg2 != 0);
1656                    mRunningInstalls.delete(msg.arg1);
1657
1658                    if (data != null) {
1659                        InstallArgs args = data.args;
1660                        PackageInstalledInfo parentRes = data.res;
1661
1662                        final boolean grantPermissions = (args.installFlags
1663                                & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0;
1664                        final boolean killApp = (args.installFlags
1665                                & PackageManager.INSTALL_DONT_KILL_APP) == 0;
1666                        final String[] grantedPermissions = args.installGrantPermissions;
1667
1668                        // Handle the parent package
1669                        handlePackagePostInstall(parentRes, grantPermissions, killApp,
1670                                grantedPermissions, didRestore, args.installerPackageName,
1671                                args.observer);
1672
1673                        // Handle the child packages
1674                        final int childCount = (parentRes.addedChildPackages != null)
1675                                ? parentRes.addedChildPackages.size() : 0;
1676                        for (int i = 0; i < childCount; i++) {
1677                            PackageInstalledInfo childRes = parentRes.addedChildPackages.valueAt(i);
1678                            handlePackagePostInstall(childRes, grantPermissions, killApp,
1679                                    grantedPermissions, false, args.installerPackageName,
1680                                    args.observer);
1681                        }
1682
1683                        // Log tracing if needed
1684                        if (args.traceMethod != null) {
1685                            Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, args.traceMethod,
1686                                    args.traceCookie);
1687                        }
1688                    } else {
1689                        Slog.e(TAG, "Bogus post-install token " + msg.arg1);
1690                    }
1691
1692                    Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "postInstall", msg.arg1);
1693                } break;
1694                case UPDATED_MEDIA_STATUS: {
1695                    if (DEBUG_SD_INSTALL) Log.i(TAG, "Got message UPDATED_MEDIA_STATUS");
1696                    boolean reportStatus = msg.arg1 == 1;
1697                    boolean doGc = msg.arg2 == 1;
1698                    if (DEBUG_SD_INSTALL) Log.i(TAG, "reportStatus=" + reportStatus + ", doGc = " + doGc);
1699                    if (doGc) {
1700                        // Force a gc to clear up stale containers.
1701                        Runtime.getRuntime().gc();
1702                    }
1703                    if (msg.obj != null) {
1704                        @SuppressWarnings("unchecked")
1705                        Set<AsecInstallArgs> args = (Set<AsecInstallArgs>) msg.obj;
1706                        if (DEBUG_SD_INSTALL) Log.i(TAG, "Unloading all containers");
1707                        // Unload containers
1708                        unloadAllContainers(args);
1709                    }
1710                    if (reportStatus) {
1711                        try {
1712                            if (DEBUG_SD_INSTALL) Log.i(TAG,
1713                                    "Invoking StorageManagerService call back");
1714                            PackageHelper.getStorageManager().finishMediaUpdate();
1715                        } catch (RemoteException e) {
1716                            Log.e(TAG, "StorageManagerService not running?");
1717                        }
1718                    }
1719                } break;
1720                case WRITE_SETTINGS: {
1721                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1722                    synchronized (mPackages) {
1723                        removeMessages(WRITE_SETTINGS);
1724                        removeMessages(WRITE_PACKAGE_RESTRICTIONS);
1725                        mSettings.writeLPr();
1726                        mDirtyUsers.clear();
1727                    }
1728                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1729                } break;
1730                case WRITE_PACKAGE_RESTRICTIONS: {
1731                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1732                    synchronized (mPackages) {
1733                        removeMessages(WRITE_PACKAGE_RESTRICTIONS);
1734                        for (int userId : mDirtyUsers) {
1735                            mSettings.writePackageRestrictionsLPr(userId);
1736                        }
1737                        mDirtyUsers.clear();
1738                    }
1739                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1740                } break;
1741                case WRITE_PACKAGE_LIST: {
1742                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1743                    synchronized (mPackages) {
1744                        removeMessages(WRITE_PACKAGE_LIST);
1745                        mSettings.writePackageListLPr(msg.arg1);
1746                    }
1747                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1748                } break;
1749                case CHECK_PENDING_VERIFICATION: {
1750                    final int verificationId = msg.arg1;
1751                    final PackageVerificationState state = mPendingVerification.get(verificationId);
1752
1753                    if ((state != null) && !state.timeoutExtended()) {
1754                        final InstallArgs args = state.getInstallArgs();
1755                        final Uri originUri = Uri.fromFile(args.origin.resolvedFile);
1756
1757                        Slog.i(TAG, "Verification timed out for " + originUri);
1758                        mPendingVerification.remove(verificationId);
1759
1760                        int ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
1761
1762                        final UserHandle user = args.getUser();
1763                        if (getDefaultVerificationResponse(user)
1764                                == PackageManager.VERIFICATION_ALLOW) {
1765                            Slog.i(TAG, "Continuing with installation of " + originUri);
1766                            state.setVerifierResponse(Binder.getCallingUid(),
1767                                    PackageManager.VERIFICATION_ALLOW_WITHOUT_SUFFICIENT);
1768                            broadcastPackageVerified(verificationId, originUri,
1769                                    PackageManager.VERIFICATION_ALLOW, user);
1770                            try {
1771                                ret = args.copyApk(mContainerService, true);
1772                            } catch (RemoteException e) {
1773                                Slog.e(TAG, "Could not contact the ContainerService");
1774                            }
1775                        } else {
1776                            broadcastPackageVerified(verificationId, originUri,
1777                                    PackageManager.VERIFICATION_REJECT, user);
1778                        }
1779
1780                        Trace.asyncTraceEnd(
1781                                TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId);
1782
1783                        processPendingInstall(args, ret);
1784                        mHandler.sendEmptyMessage(MCS_UNBIND);
1785                    }
1786                    break;
1787                }
1788                case PACKAGE_VERIFIED: {
1789                    final int verificationId = msg.arg1;
1790
1791                    final PackageVerificationState state = mPendingVerification.get(verificationId);
1792                    if (state == null) {
1793                        Slog.w(TAG, "Invalid verification token " + verificationId + " received");
1794                        break;
1795                    }
1796
1797                    final PackageVerificationResponse response = (PackageVerificationResponse) msg.obj;
1798
1799                    state.setVerifierResponse(response.callerUid, response.code);
1800
1801                    if (state.isVerificationComplete()) {
1802                        mPendingVerification.remove(verificationId);
1803
1804                        final InstallArgs args = state.getInstallArgs();
1805                        final Uri originUri = Uri.fromFile(args.origin.resolvedFile);
1806
1807                        int ret;
1808                        if (state.isInstallAllowed()) {
1809                            ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
1810                            broadcastPackageVerified(verificationId, originUri,
1811                                    response.code, state.getInstallArgs().getUser());
1812                            try {
1813                                ret = args.copyApk(mContainerService, true);
1814                            } catch (RemoteException e) {
1815                                Slog.e(TAG, "Could not contact the ContainerService");
1816                            }
1817                        } else {
1818                            ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
1819                        }
1820
1821                        Trace.asyncTraceEnd(
1822                                TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId);
1823
1824                        processPendingInstall(args, ret);
1825                        mHandler.sendEmptyMessage(MCS_UNBIND);
1826                    }
1827
1828                    break;
1829                }
1830                case START_INTENT_FILTER_VERIFICATIONS: {
1831                    IFVerificationParams params = (IFVerificationParams) msg.obj;
1832                    verifyIntentFiltersIfNeeded(params.userId, params.verifierUid,
1833                            params.replacing, params.pkg);
1834                    break;
1835                }
1836                case INTENT_FILTER_VERIFIED: {
1837                    final int verificationId = msg.arg1;
1838
1839                    final IntentFilterVerificationState state = mIntentFilterVerificationStates.get(
1840                            verificationId);
1841                    if (state == null) {
1842                        Slog.w(TAG, "Invalid IntentFilter verification token "
1843                                + verificationId + " received");
1844                        break;
1845                    }
1846
1847                    final int userId = state.getUserId();
1848
1849                    if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1850                            "Processing IntentFilter verification with token:"
1851                            + verificationId + " and userId:" + userId);
1852
1853                    final IntentFilterVerificationResponse response =
1854                            (IntentFilterVerificationResponse) msg.obj;
1855
1856                    state.setVerifierResponse(response.callerUid, response.code);
1857
1858                    if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1859                            "IntentFilter verification with token:" + verificationId
1860                            + " and userId:" + userId
1861                            + " is settings verifier response with response code:"
1862                            + response.code);
1863
1864                    if (response.code == PackageManager.INTENT_FILTER_VERIFICATION_FAILURE) {
1865                        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Domains failing verification: "
1866                                + response.getFailedDomainsString());
1867                    }
1868
1869                    if (state.isVerificationComplete()) {
1870                        mIntentFilterVerifier.receiveVerificationResponse(verificationId);
1871                    } else {
1872                        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1873                                "IntentFilter verification with token:" + verificationId
1874                                + " was not said to be complete");
1875                    }
1876
1877                    break;
1878                }
1879                case INSTANT_APP_RESOLUTION_PHASE_TWO: {
1880                    InstantAppResolver.doInstantAppResolutionPhaseTwo(mContext,
1881                            mInstantAppResolverConnection,
1882                            (InstantAppRequest) msg.obj,
1883                            mInstantAppInstallerActivity,
1884                            mHandler);
1885                }
1886            }
1887        }
1888    }
1889
1890    private void handlePackagePostInstall(PackageInstalledInfo res, boolean grantPermissions,
1891            boolean killApp, String[] grantedPermissions,
1892            boolean launchedForRestore, String installerPackage,
1893            IPackageInstallObserver2 installObserver) {
1894        if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
1895            // Send the removed broadcasts
1896            if (res.removedInfo != null) {
1897                res.removedInfo.sendPackageRemovedBroadcasts(killApp);
1898            }
1899
1900            // Now that we successfully installed the package, grant runtime
1901            // permissions if requested before broadcasting the install. Also
1902            // for legacy apps in permission review mode we clear the permission
1903            // review flag which is used to emulate runtime permissions for
1904            // legacy apps.
1905            if (grantPermissions) {
1906                grantRequestedRuntimePermissions(res.pkg, res.newUsers, grantedPermissions);
1907            }
1908
1909            final boolean update = res.removedInfo != null
1910                    && res.removedInfo.removedPackage != null;
1911            final String origInstallerPackageName = res.removedInfo != null
1912                    ? res.removedInfo.installerPackageName : null;
1913
1914            // If this is the first time we have child packages for a disabled privileged
1915            // app that had no children, we grant requested runtime permissions to the new
1916            // children if the parent on the system image had them already granted.
1917            if (res.pkg.parentPackage != null) {
1918                synchronized (mPackages) {
1919                    grantRuntimePermissionsGrantedToDisabledPrivSysPackageParentLPw(res.pkg);
1920                }
1921            }
1922
1923            synchronized (mPackages) {
1924                mInstantAppRegistry.onPackageInstalledLPw(res.pkg, res.newUsers);
1925            }
1926
1927            final String packageName = res.pkg.applicationInfo.packageName;
1928
1929            // Determine the set of users who are adding this package for
1930            // the first time vs. those who are seeing an update.
1931            int[] firstUsers = EMPTY_INT_ARRAY;
1932            int[] updateUsers = EMPTY_INT_ARRAY;
1933            final boolean allNewUsers = res.origUsers == null || res.origUsers.length == 0;
1934            final PackageSetting ps = (PackageSetting) res.pkg.mExtras;
1935            for (int newUser : res.newUsers) {
1936                if (ps.getInstantApp(newUser)) {
1937                    continue;
1938                }
1939                if (allNewUsers) {
1940                    firstUsers = ArrayUtils.appendInt(firstUsers, newUser);
1941                    continue;
1942                }
1943                boolean isNew = true;
1944                for (int origUser : res.origUsers) {
1945                    if (origUser == newUser) {
1946                        isNew = false;
1947                        break;
1948                    }
1949                }
1950                if (isNew) {
1951                    firstUsers = ArrayUtils.appendInt(firstUsers, newUser);
1952                } else {
1953                    updateUsers = ArrayUtils.appendInt(updateUsers, newUser);
1954                }
1955            }
1956
1957            // Send installed broadcasts if the package is not a static shared lib.
1958            if (res.pkg.staticSharedLibName == null) {
1959                mProcessLoggingHandler.invalidateProcessLoggingBaseApkHash(res.pkg.baseCodePath);
1960
1961                // Send added for users that see the package for the first time
1962                // sendPackageAddedForNewUsers also deals with system apps
1963                int appId = UserHandle.getAppId(res.uid);
1964                boolean isSystem = res.pkg.applicationInfo.isSystemApp();
1965                sendPackageAddedForNewUsers(packageName, isSystem, appId, firstUsers);
1966
1967                // Send added for users that don't see the package for the first time
1968                Bundle extras = new Bundle(1);
1969                extras.putInt(Intent.EXTRA_UID, res.uid);
1970                if (update) {
1971                    extras.putBoolean(Intent.EXTRA_REPLACING, true);
1972                }
1973                sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName,
1974                        extras, 0 /*flags*/,
1975                        null /*targetPackage*/, null /*finishedReceiver*/, updateUsers);
1976                if (origInstallerPackageName != null) {
1977                    sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName,
1978                            extras, 0 /*flags*/,
1979                            origInstallerPackageName, null /*finishedReceiver*/, updateUsers);
1980                }
1981
1982                // Send replaced for users that don't see the package for the first time
1983                if (update) {
1984                    sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED,
1985                            packageName, extras, 0 /*flags*/,
1986                            null /*targetPackage*/, null /*finishedReceiver*/,
1987                            updateUsers);
1988                    if (origInstallerPackageName != null) {
1989                        sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, packageName,
1990                                extras, 0 /*flags*/,
1991                                origInstallerPackageName, null /*finishedReceiver*/, updateUsers);
1992                    }
1993                    sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED,
1994                            null /*package*/, null /*extras*/, 0 /*flags*/,
1995                            packageName /*targetPackage*/,
1996                            null /*finishedReceiver*/, updateUsers);
1997                } else if (launchedForRestore && !isSystemApp(res.pkg)) {
1998                    // First-install and we did a restore, so we're responsible for the
1999                    // first-launch broadcast.
2000                    if (DEBUG_BACKUP) {
2001                        Slog.i(TAG, "Post-restore of " + packageName
2002                                + " sending FIRST_LAUNCH in " + Arrays.toString(firstUsers));
2003                    }
2004                    sendFirstLaunchBroadcast(packageName, installerPackage, firstUsers);
2005                }
2006
2007                // Send broadcast package appeared if forward locked/external for all users
2008                // treat asec-hosted packages like removable media on upgrade
2009                if (res.pkg.isForwardLocked() || isExternal(res.pkg)) {
2010                    if (DEBUG_INSTALL) {
2011                        Slog.i(TAG, "upgrading pkg " + res.pkg
2012                                + " is ASEC-hosted -> AVAILABLE");
2013                    }
2014                    final int[] uidArray = new int[]{res.pkg.applicationInfo.uid};
2015                    ArrayList<String> pkgList = new ArrayList<>(1);
2016                    pkgList.add(packageName);
2017                    sendResourcesChangedBroadcast(true, true, pkgList, uidArray, null);
2018                }
2019            }
2020
2021            // Work that needs to happen on first install within each user
2022            if (firstUsers != null && firstUsers.length > 0) {
2023                synchronized (mPackages) {
2024                    for (int userId : firstUsers) {
2025                        // If this app is a browser and it's newly-installed for some
2026                        // users, clear any default-browser state in those users. The
2027                        // app's nature doesn't depend on the user, so we can just check
2028                        // its browser nature in any user and generalize.
2029                        if (packageIsBrowser(packageName, userId)) {
2030                            mSettings.setDefaultBrowserPackageNameLPw(null, userId);
2031                        }
2032
2033                        // We may also need to apply pending (restored) runtime
2034                        // permission grants within these users.
2035                        mSettings.applyPendingPermissionGrantsLPw(packageName, userId);
2036                    }
2037                }
2038            }
2039
2040            // Log current value of "unknown sources" setting
2041            EventLog.writeEvent(EventLogTags.UNKNOWN_SOURCES_ENABLED,
2042                    getUnknownSourcesSettings());
2043
2044            // Remove the replaced package's older resources safely now
2045            // We delete after a gc for applications  on sdcard.
2046            if (res.removedInfo != null && res.removedInfo.args != null) {
2047                Runtime.getRuntime().gc();
2048                synchronized (mInstallLock) {
2049                    res.removedInfo.args.doPostDeleteLI(true);
2050                }
2051            } else {
2052                // Force a gc to clear up things. Ask for a background one, it's fine to go on
2053                // and not block here.
2054                VMRuntime.getRuntime().requestConcurrentGC();
2055            }
2056
2057            // Notify DexManager that the package was installed for new users.
2058            // The updated users should already be indexed and the package code paths
2059            // should not change.
2060            // Don't notify the manager for ephemeral apps as they are not expected to
2061            // survive long enough to benefit of background optimizations.
2062            for (int userId : firstUsers) {
2063                PackageInfo info = getPackageInfo(packageName, /*flags*/ 0, userId);
2064                // There's a race currently where some install events may interleave with an uninstall.
2065                // This can lead to package info being null (b/36642664).
2066                if (info != null) {
2067                    mDexManager.notifyPackageInstalled(info, userId);
2068                }
2069            }
2070        }
2071
2072        // If someone is watching installs - notify them
2073        if (installObserver != null) {
2074            try {
2075                Bundle extras = extrasForInstallResult(res);
2076                installObserver.onPackageInstalled(res.name, res.returnCode,
2077                        res.returnMsg, extras);
2078            } catch (RemoteException e) {
2079                Slog.i(TAG, "Observer no longer exists.");
2080            }
2081        }
2082    }
2083
2084    private void grantRuntimePermissionsGrantedToDisabledPrivSysPackageParentLPw(
2085            PackageParser.Package pkg) {
2086        if (pkg.parentPackage == null) {
2087            return;
2088        }
2089        if (pkg.requestedPermissions == null) {
2090            return;
2091        }
2092        final PackageSetting disabledSysParentPs = mSettings
2093                .getDisabledSystemPkgLPr(pkg.parentPackage.packageName);
2094        if (disabledSysParentPs == null || disabledSysParentPs.pkg == null
2095                || !disabledSysParentPs.isPrivileged()
2096                || (disabledSysParentPs.childPackageNames != null
2097                        && !disabledSysParentPs.childPackageNames.isEmpty())) {
2098            return;
2099        }
2100        final int[] allUserIds = sUserManager.getUserIds();
2101        final int permCount = pkg.requestedPermissions.size();
2102        for (int i = 0; i < permCount; i++) {
2103            String permission = pkg.requestedPermissions.get(i);
2104            BasePermission bp = mSettings.mPermissions.get(permission);
2105            if (bp == null || !(bp.isRuntime() || bp.isDevelopment())) {
2106                continue;
2107            }
2108            for (int userId : allUserIds) {
2109                if (disabledSysParentPs.getPermissionsState().hasRuntimePermission(
2110                        permission, userId)) {
2111                    grantRuntimePermission(pkg.packageName, permission, userId);
2112                }
2113            }
2114        }
2115    }
2116
2117    private StorageEventListener mStorageListener = new StorageEventListener() {
2118        @Override
2119        public void onVolumeStateChanged(VolumeInfo vol, int oldState, int newState) {
2120            if (vol.type == VolumeInfo.TYPE_PRIVATE) {
2121                if (vol.state == VolumeInfo.STATE_MOUNTED) {
2122                    final String volumeUuid = vol.getFsUuid();
2123
2124                    // Clean up any users or apps that were removed or recreated
2125                    // while this volume was missing
2126                    sUserManager.reconcileUsers(volumeUuid);
2127                    reconcileApps(volumeUuid);
2128
2129                    // Clean up any install sessions that expired or were
2130                    // cancelled while this volume was missing
2131                    mInstallerService.onPrivateVolumeMounted(volumeUuid);
2132
2133                    loadPrivatePackages(vol);
2134
2135                } else if (vol.state == VolumeInfo.STATE_EJECTING) {
2136                    unloadPrivatePackages(vol);
2137                }
2138            }
2139
2140            if (vol.type == VolumeInfo.TYPE_PUBLIC && vol.isPrimary()) {
2141                if (vol.state == VolumeInfo.STATE_MOUNTED) {
2142                    updateExternalMediaStatus(true, false);
2143                } else if (vol.state == VolumeInfo.STATE_EJECTING) {
2144                    updateExternalMediaStatus(false, false);
2145                }
2146            }
2147        }
2148
2149        @Override
2150        public void onVolumeForgotten(String fsUuid) {
2151            if (TextUtils.isEmpty(fsUuid)) {
2152                Slog.e(TAG, "Forgetting internal storage is probably a mistake; ignoring");
2153                return;
2154            }
2155
2156            // Remove any apps installed on the forgotten volume
2157            synchronized (mPackages) {
2158                final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(fsUuid);
2159                for (PackageSetting ps : packages) {
2160                    Slog.d(TAG, "Destroying " + ps.name + " because volume was forgotten");
2161                    deletePackageVersioned(new VersionedPackage(ps.name,
2162                            PackageManager.VERSION_CODE_HIGHEST),
2163                            new LegacyPackageDeleteObserver(null).getBinder(),
2164                            UserHandle.USER_SYSTEM, PackageManager.DELETE_ALL_USERS);
2165                    // Try very hard to release any references to this package
2166                    // so we don't risk the system server being killed due to
2167                    // open FDs
2168                    AttributeCache.instance().removePackage(ps.name);
2169                }
2170
2171                mSettings.onVolumeForgotten(fsUuid);
2172                mSettings.writeLPr();
2173            }
2174        }
2175    };
2176
2177    private void grantRequestedRuntimePermissions(PackageParser.Package pkg, int[] userIds,
2178            String[] grantedPermissions) {
2179        for (int userId : userIds) {
2180            grantRequestedRuntimePermissionsForUser(pkg, userId, grantedPermissions);
2181        }
2182    }
2183
2184    private void grantRequestedRuntimePermissionsForUser(PackageParser.Package pkg, int userId,
2185            String[] grantedPermissions) {
2186        SettingBase sb = (SettingBase) pkg.mExtras;
2187        if (sb == null) {
2188            return;
2189        }
2190
2191        PermissionsState permissionsState = sb.getPermissionsState();
2192
2193        final int immutableFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED
2194                | PackageManager.FLAG_PERMISSION_POLICY_FIXED;
2195
2196        final boolean supportsRuntimePermissions = pkg.applicationInfo.targetSdkVersion
2197                >= Build.VERSION_CODES.M;
2198
2199        final boolean instantApp = isInstantApp(pkg.packageName, userId);
2200
2201        for (String permission : pkg.requestedPermissions) {
2202            final BasePermission bp;
2203            synchronized (mPackages) {
2204                bp = mSettings.mPermissions.get(permission);
2205            }
2206            if (bp != null && (bp.isRuntime() || bp.isDevelopment())
2207                    && (!instantApp || bp.isInstant())
2208                    && (supportsRuntimePermissions || !bp.isRuntimeOnly())
2209                    && (grantedPermissions == null
2210                           || ArrayUtils.contains(grantedPermissions, permission))) {
2211                final int flags = permissionsState.getPermissionFlags(permission, userId);
2212                if (supportsRuntimePermissions) {
2213                    // Installer cannot change immutable permissions.
2214                    if ((flags & immutableFlags) == 0) {
2215                        grantRuntimePermission(pkg.packageName, permission, userId);
2216                    }
2217                } else if (mPermissionReviewRequired) {
2218                    // In permission review mode we clear the review flag when we
2219                    // are asked to install the app with all permissions granted.
2220                    if ((flags & PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED) != 0) {
2221                        updatePermissionFlags(permission, pkg.packageName,
2222                                PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED, 0, userId);
2223                    }
2224                }
2225            }
2226        }
2227    }
2228
2229    Bundle extrasForInstallResult(PackageInstalledInfo res) {
2230        Bundle extras = null;
2231        switch (res.returnCode) {
2232            case PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION: {
2233                extras = new Bundle();
2234                extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PERMISSION,
2235                        res.origPermission);
2236                extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PACKAGE,
2237                        res.origPackage);
2238                break;
2239            }
2240            case PackageManager.INSTALL_SUCCEEDED: {
2241                extras = new Bundle();
2242                extras.putBoolean(Intent.EXTRA_REPLACING,
2243                        res.removedInfo != null && res.removedInfo.removedPackage != null);
2244                break;
2245            }
2246        }
2247        return extras;
2248    }
2249
2250    void scheduleWriteSettingsLocked() {
2251        if (!mHandler.hasMessages(WRITE_SETTINGS)) {
2252            mHandler.sendEmptyMessageDelayed(WRITE_SETTINGS, WRITE_SETTINGS_DELAY);
2253        }
2254    }
2255
2256    void scheduleWritePackageListLocked(int userId) {
2257        if (!mHandler.hasMessages(WRITE_PACKAGE_LIST)) {
2258            Message msg = mHandler.obtainMessage(WRITE_PACKAGE_LIST);
2259            msg.arg1 = userId;
2260            mHandler.sendMessageDelayed(msg, WRITE_SETTINGS_DELAY);
2261        }
2262    }
2263
2264    void scheduleWritePackageRestrictionsLocked(UserHandle user) {
2265        final int userId = user == null ? UserHandle.USER_ALL : user.getIdentifier();
2266        scheduleWritePackageRestrictionsLocked(userId);
2267    }
2268
2269    void scheduleWritePackageRestrictionsLocked(int userId) {
2270        final int[] userIds = (userId == UserHandle.USER_ALL)
2271                ? sUserManager.getUserIds() : new int[]{userId};
2272        for (int nextUserId : userIds) {
2273            if (!sUserManager.exists(nextUserId)) return;
2274            mDirtyUsers.add(nextUserId);
2275            if (!mHandler.hasMessages(WRITE_PACKAGE_RESTRICTIONS)) {
2276                mHandler.sendEmptyMessageDelayed(WRITE_PACKAGE_RESTRICTIONS, WRITE_SETTINGS_DELAY);
2277            }
2278        }
2279    }
2280
2281    public static PackageManagerService main(Context context, Installer installer,
2282            boolean factoryTest, boolean onlyCore) {
2283        // Self-check for initial settings.
2284        PackageManagerServiceCompilerMapping.checkProperties();
2285
2286        PackageManagerService m = new PackageManagerService(context, installer,
2287                factoryTest, onlyCore);
2288        m.enableSystemUserPackages();
2289        ServiceManager.addService("package", m);
2290        return m;
2291    }
2292
2293    private void enableSystemUserPackages() {
2294        if (!UserManager.isSplitSystemUser()) {
2295            return;
2296        }
2297        // For system user, enable apps based on the following conditions:
2298        // - app is whitelisted or belong to one of these groups:
2299        //   -- system app which has no launcher icons
2300        //   -- system app which has INTERACT_ACROSS_USERS permission
2301        //   -- system IME app
2302        // - app is not in the blacklist
2303        AppsQueryHelper queryHelper = new AppsQueryHelper(this);
2304        Set<String> enableApps = new ArraySet<>();
2305        enableApps.addAll(queryHelper.queryApps(AppsQueryHelper.GET_NON_LAUNCHABLE_APPS
2306                | AppsQueryHelper.GET_APPS_WITH_INTERACT_ACROSS_USERS_PERM
2307                | AppsQueryHelper.GET_IMES, /* systemAppsOnly */ true, UserHandle.SYSTEM));
2308        ArraySet<String> wlApps = SystemConfig.getInstance().getSystemUserWhitelistedApps();
2309        enableApps.addAll(wlApps);
2310        enableApps.addAll(queryHelper.queryApps(AppsQueryHelper.GET_REQUIRED_FOR_SYSTEM_USER,
2311                /* systemAppsOnly */ false, UserHandle.SYSTEM));
2312        ArraySet<String> blApps = SystemConfig.getInstance().getSystemUserBlacklistedApps();
2313        enableApps.removeAll(blApps);
2314        Log.i(TAG, "Applications installed for system user: " + enableApps);
2315        List<String> allAps = queryHelper.queryApps(0, /* systemAppsOnly */ false,
2316                UserHandle.SYSTEM);
2317        final int allAppsSize = allAps.size();
2318        synchronized (mPackages) {
2319            for (int i = 0; i < allAppsSize; i++) {
2320                String pName = allAps.get(i);
2321                PackageSetting pkgSetting = mSettings.mPackages.get(pName);
2322                // Should not happen, but we shouldn't be failing if it does
2323                if (pkgSetting == null) {
2324                    continue;
2325                }
2326                boolean install = enableApps.contains(pName);
2327                if (pkgSetting.getInstalled(UserHandle.USER_SYSTEM) != install) {
2328                    Log.i(TAG, (install ? "Installing " : "Uninstalling ") + pName
2329                            + " for system user");
2330                    pkgSetting.setInstalled(install, UserHandle.USER_SYSTEM);
2331                }
2332            }
2333            scheduleWritePackageRestrictionsLocked(UserHandle.USER_SYSTEM);
2334        }
2335    }
2336
2337    private static void getDefaultDisplayMetrics(Context context, DisplayMetrics metrics) {
2338        DisplayManager displayManager = (DisplayManager) context.getSystemService(
2339                Context.DISPLAY_SERVICE);
2340        displayManager.getDisplay(Display.DEFAULT_DISPLAY).getMetrics(metrics);
2341    }
2342
2343    /**
2344     * Requests that files preopted on a secondary system partition be copied to the data partition
2345     * if possible.  Note that the actual copying of the files is accomplished by init for security
2346     * reasons. This simply requests that the copy takes place and awaits confirmation of its
2347     * completion. See platform/system/extras/cppreopt/ for the implementation of the actual copy.
2348     */
2349    private static void requestCopyPreoptedFiles() {
2350        final int WAIT_TIME_MS = 100;
2351        final String CP_PREOPT_PROPERTY = "sys.cppreopt";
2352        if (SystemProperties.getInt("ro.cp_system_other_odex", 0) == 1) {
2353            SystemProperties.set(CP_PREOPT_PROPERTY, "requested");
2354            // We will wait for up to 100 seconds.
2355            final long timeStart = SystemClock.uptimeMillis();
2356            final long timeEnd = timeStart + 100 * 1000;
2357            long timeNow = timeStart;
2358            while (!SystemProperties.get(CP_PREOPT_PROPERTY).equals("finished")) {
2359                try {
2360                    Thread.sleep(WAIT_TIME_MS);
2361                } catch (InterruptedException e) {
2362                    // Do nothing
2363                }
2364                timeNow = SystemClock.uptimeMillis();
2365                if (timeNow > timeEnd) {
2366                    SystemProperties.set(CP_PREOPT_PROPERTY, "timed-out");
2367                    Slog.wtf(TAG, "cppreopt did not finish!");
2368                    break;
2369                }
2370            }
2371
2372            Slog.i(TAG, "cppreopts took " + (timeNow - timeStart) + " ms");
2373        }
2374    }
2375
2376    public PackageManagerService(Context context, Installer installer,
2377            boolean factoryTest, boolean onlyCore) {
2378        LockGuard.installLock(mPackages, LockGuard.INDEX_PACKAGES);
2379        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "create package manager");
2380        EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_START,
2381                SystemClock.uptimeMillis());
2382
2383        if (mSdkVersion <= 0) {
2384            Slog.w(TAG, "**** ro.build.version.sdk not set!");
2385        }
2386
2387        mContext = context;
2388
2389        mPermissionReviewRequired = context.getResources().getBoolean(
2390                R.bool.config_permissionReviewRequired);
2391
2392        mFactoryTest = factoryTest;
2393        mOnlyCore = onlyCore;
2394        mMetrics = new DisplayMetrics();
2395        mSettings = new Settings(mPackages);
2396        mSettings.addSharedUserLPw("android.uid.system", Process.SYSTEM_UID,
2397                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2398        mSettings.addSharedUserLPw("android.uid.phone", RADIO_UID,
2399                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2400        mSettings.addSharedUserLPw("android.uid.log", LOG_UID,
2401                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2402        mSettings.addSharedUserLPw("android.uid.nfc", NFC_UID,
2403                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2404        mSettings.addSharedUserLPw("android.uid.bluetooth", BLUETOOTH_UID,
2405                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2406        mSettings.addSharedUserLPw("android.uid.shell", SHELL_UID,
2407                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2408
2409        String separateProcesses = SystemProperties.get("debug.separate_processes");
2410        if (separateProcesses != null && separateProcesses.length() > 0) {
2411            if ("*".equals(separateProcesses)) {
2412                mDefParseFlags = PackageParser.PARSE_IGNORE_PROCESSES;
2413                mSeparateProcesses = null;
2414                Slog.w(TAG, "Running with debug.separate_processes: * (ALL)");
2415            } else {
2416                mDefParseFlags = 0;
2417                mSeparateProcesses = separateProcesses.split(",");
2418                Slog.w(TAG, "Running with debug.separate_processes: "
2419                        + separateProcesses);
2420            }
2421        } else {
2422            mDefParseFlags = 0;
2423            mSeparateProcesses = null;
2424        }
2425
2426        mInstaller = installer;
2427        mPackageDexOptimizer = new PackageDexOptimizer(installer, mInstallLock, context,
2428                "*dexopt*");
2429        mDexManager = new DexManager(this, mPackageDexOptimizer, installer, mInstallLock);
2430        mMoveCallbacks = new MoveCallbacks(FgThread.get().getLooper());
2431
2432        mOnPermissionChangeListeners = new OnPermissionChangeListeners(
2433                FgThread.get().getLooper());
2434
2435        getDefaultDisplayMetrics(context, mMetrics);
2436
2437        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "get system config");
2438        SystemConfig systemConfig = SystemConfig.getInstance();
2439        mGlobalGids = systemConfig.getGlobalGids();
2440        mSystemPermissions = systemConfig.getSystemPermissions();
2441        mAvailableFeatures = systemConfig.getAvailableFeatures();
2442        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
2443
2444        mProtectedPackages = new ProtectedPackages(mContext);
2445
2446        synchronized (mInstallLock) {
2447        // writer
2448        synchronized (mPackages) {
2449            mHandlerThread = new ServiceThread(TAG,
2450                    Process.THREAD_PRIORITY_BACKGROUND, true /*allowIo*/);
2451            mHandlerThread.start();
2452            mHandler = new PackageHandler(mHandlerThread.getLooper());
2453            mProcessLoggingHandler = new ProcessLoggingHandler();
2454            Watchdog.getInstance().addThread(mHandler, WATCHDOG_TIMEOUT);
2455
2456            mDefaultPermissionPolicy = new DefaultPermissionGrantPolicy(this);
2457            mInstantAppRegistry = new InstantAppRegistry(this);
2458
2459            File dataDir = Environment.getDataDirectory();
2460            mAppInstallDir = new File(dataDir, "app");
2461            mAppLib32InstallDir = new File(dataDir, "app-lib");
2462            mAsecInternalPath = new File(dataDir, "app-asec").getPath();
2463            mDrmAppPrivateInstallDir = new File(dataDir, "app-private");
2464            sUserManager = new UserManagerService(context, this,
2465                    new UserDataPreparer(mInstaller, mInstallLock, mContext, mOnlyCore), mPackages);
2466
2467            // Propagate permission configuration in to package manager.
2468            ArrayMap<String, SystemConfig.PermissionEntry> permConfig
2469                    = systemConfig.getPermissions();
2470            for (int i=0; i<permConfig.size(); i++) {
2471                SystemConfig.PermissionEntry perm = permConfig.valueAt(i);
2472                BasePermission bp = mSettings.mPermissions.get(perm.name);
2473                if (bp == null) {
2474                    bp = new BasePermission(perm.name, "android", BasePermission.TYPE_BUILTIN);
2475                    mSettings.mPermissions.put(perm.name, bp);
2476                }
2477                if (perm.gids != null) {
2478                    bp.setGids(perm.gids, perm.perUser);
2479                }
2480            }
2481
2482            ArrayMap<String, String> libConfig = systemConfig.getSharedLibraries();
2483            final int builtInLibCount = libConfig.size();
2484            for (int i = 0; i < builtInLibCount; i++) {
2485                String name = libConfig.keyAt(i);
2486                String path = libConfig.valueAt(i);
2487                addSharedLibraryLPw(path, null, name, SharedLibraryInfo.VERSION_UNDEFINED,
2488                        SharedLibraryInfo.TYPE_BUILTIN, PLATFORM_PACKAGE_NAME, 0);
2489            }
2490
2491            mFoundPolicyFile = SELinuxMMAC.readInstallPolicy();
2492
2493            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "read user settings");
2494            mFirstBoot = !mSettings.readLPw(sUserManager.getUsers(false));
2495            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
2496
2497            // Clean up orphaned packages for which the code path doesn't exist
2498            // and they are an update to a system app - caused by bug/32321269
2499            final int packageSettingCount = mSettings.mPackages.size();
2500            for (int i = packageSettingCount - 1; i >= 0; i--) {
2501                PackageSetting ps = mSettings.mPackages.valueAt(i);
2502                if (!isExternal(ps) && (ps.codePath == null || !ps.codePath.exists())
2503                        && mSettings.getDisabledSystemPkgLPr(ps.name) != null) {
2504                    mSettings.mPackages.removeAt(i);
2505                    mSettings.enableSystemPackageLPw(ps.name);
2506                }
2507            }
2508
2509            if (mFirstBoot) {
2510                requestCopyPreoptedFiles();
2511            }
2512
2513            String customResolverActivity = Resources.getSystem().getString(
2514                    R.string.config_customResolverActivity);
2515            if (TextUtils.isEmpty(customResolverActivity)) {
2516                customResolverActivity = null;
2517            } else {
2518                mCustomResolverComponentName = ComponentName.unflattenFromString(
2519                        customResolverActivity);
2520            }
2521
2522            long startTime = SystemClock.uptimeMillis();
2523
2524            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SYSTEM_SCAN_START,
2525                    startTime);
2526
2527            final String bootClassPath = System.getenv("BOOTCLASSPATH");
2528            final String systemServerClassPath = System.getenv("SYSTEMSERVERCLASSPATH");
2529
2530            if (bootClassPath == null) {
2531                Slog.w(TAG, "No BOOTCLASSPATH found!");
2532            }
2533
2534            if (systemServerClassPath == null) {
2535                Slog.w(TAG, "No SYSTEMSERVERCLASSPATH found!");
2536            }
2537
2538            File frameworkDir = new File(Environment.getRootDirectory(), "framework");
2539
2540            final VersionInfo ver = mSettings.getInternalVersion();
2541            mIsUpgrade = !Build.FINGERPRINT.equals(ver.fingerprint);
2542            if (mIsUpgrade) {
2543                logCriticalInfo(Log.INFO,
2544                        "Upgrading from " + ver.fingerprint + " to " + Build.FINGERPRINT);
2545            }
2546
2547            // when upgrading from pre-M, promote system app permissions from install to runtime
2548            mPromoteSystemApps =
2549                    mIsUpgrade && ver.sdkVersion <= Build.VERSION_CODES.LOLLIPOP_MR1;
2550
2551            // When upgrading from pre-N, we need to handle package extraction like first boot,
2552            // as there is no profiling data available.
2553            mIsPreNUpgrade = mIsUpgrade && ver.sdkVersion < Build.VERSION_CODES.N;
2554
2555            mIsPreNMR1Upgrade = mIsUpgrade && ver.sdkVersion < Build.VERSION_CODES.N_MR1;
2556
2557            // save off the names of pre-existing system packages prior to scanning; we don't
2558            // want to automatically grant runtime permissions for new system apps
2559            if (mPromoteSystemApps) {
2560                Iterator<PackageSetting> pkgSettingIter = mSettings.mPackages.values().iterator();
2561                while (pkgSettingIter.hasNext()) {
2562                    PackageSetting ps = pkgSettingIter.next();
2563                    if (isSystemApp(ps)) {
2564                        mExistingSystemPackages.add(ps.name);
2565                    }
2566                }
2567            }
2568
2569            mCacheDir = preparePackageParserCache(mIsUpgrade);
2570
2571            // Set flag to monitor and not change apk file paths when
2572            // scanning install directories.
2573            int scanFlags = SCAN_BOOTING | SCAN_INITIAL;
2574
2575            if (mIsUpgrade || mFirstBoot) {
2576                scanFlags = scanFlags | SCAN_FIRST_BOOT_OR_UPGRADE;
2577            }
2578
2579            // Collect vendor overlay packages. (Do this before scanning any apps.)
2580            // For security and version matching reason, only consider
2581            // overlay packages if they reside in the right directory.
2582            scanDirTracedLI(new File(VENDOR_OVERLAY_DIR), mDefParseFlags
2583                    | PackageParser.PARSE_IS_SYSTEM
2584                    | PackageParser.PARSE_IS_SYSTEM_DIR
2585                    | PackageParser.PARSE_TRUSTED_OVERLAY, scanFlags | SCAN_TRUSTED_OVERLAY, 0);
2586
2587            mParallelPackageParserCallback.findStaticOverlayPackages();
2588
2589            // Find base frameworks (resource packages without code).
2590            scanDirTracedLI(frameworkDir, mDefParseFlags
2591                    | PackageParser.PARSE_IS_SYSTEM
2592                    | PackageParser.PARSE_IS_SYSTEM_DIR
2593                    | PackageParser.PARSE_IS_PRIVILEGED,
2594                    scanFlags | SCAN_NO_DEX, 0);
2595
2596            // Collected privileged system packages.
2597            final File privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app");
2598            scanDirTracedLI(privilegedAppDir, mDefParseFlags
2599                    | PackageParser.PARSE_IS_SYSTEM
2600                    | PackageParser.PARSE_IS_SYSTEM_DIR
2601                    | PackageParser.PARSE_IS_PRIVILEGED, scanFlags, 0);
2602
2603            // Collect ordinary system packages.
2604            final File systemAppDir = new File(Environment.getRootDirectory(), "app");
2605            scanDirTracedLI(systemAppDir, mDefParseFlags
2606                    | PackageParser.PARSE_IS_SYSTEM
2607                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
2608
2609            // Collect all vendor packages.
2610            File vendorAppDir = new File("/vendor/app");
2611            try {
2612                vendorAppDir = vendorAppDir.getCanonicalFile();
2613            } catch (IOException e) {
2614                // failed to look up canonical path, continue with original one
2615            }
2616            scanDirTracedLI(vendorAppDir, mDefParseFlags
2617                    | PackageParser.PARSE_IS_SYSTEM
2618                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
2619
2620            // Collect all OEM packages.
2621            final File oemAppDir = new File(Environment.getOemDirectory(), "app");
2622            scanDirTracedLI(oemAppDir, mDefParseFlags
2623                    | PackageParser.PARSE_IS_SYSTEM
2624                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
2625
2626            // Prune any system packages that no longer exist.
2627            final List<String> possiblyDeletedUpdatedSystemApps = new ArrayList<String>();
2628            if (!mOnlyCore) {
2629                Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator();
2630                while (psit.hasNext()) {
2631                    PackageSetting ps = psit.next();
2632
2633                    /*
2634                     * If this is not a system app, it can't be a
2635                     * disable system app.
2636                     */
2637                    if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0) {
2638                        continue;
2639                    }
2640
2641                    /*
2642                     * If the package is scanned, it's not erased.
2643                     */
2644                    final PackageParser.Package scannedPkg = mPackages.get(ps.name);
2645                    if (scannedPkg != null) {
2646                        /*
2647                         * If the system app is both scanned and in the
2648                         * disabled packages list, then it must have been
2649                         * added via OTA. Remove it from the currently
2650                         * scanned package so the previously user-installed
2651                         * application can be scanned.
2652                         */
2653                        if (mSettings.isDisabledSystemPackageLPr(ps.name)) {
2654                            logCriticalInfo(Log.WARN, "Expecting better updated system app for "
2655                                    + ps.name + "; removing system app.  Last known codePath="
2656                                    + ps.codePathString + ", installStatus=" + ps.installStatus
2657                                    + ", versionCode=" + ps.versionCode + "; scanned versionCode="
2658                                    + scannedPkg.mVersionCode);
2659                            removePackageLI(scannedPkg, true);
2660                            mExpectingBetter.put(ps.name, ps.codePath);
2661                        }
2662
2663                        continue;
2664                    }
2665
2666                    if (!mSettings.isDisabledSystemPackageLPr(ps.name)) {
2667                        psit.remove();
2668                        logCriticalInfo(Log.WARN, "System package " + ps.name
2669                                + " no longer exists; it's data will be wiped");
2670                        // Actual deletion of code and data will be handled by later
2671                        // reconciliation step
2672                    } else {
2673                        final PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(ps.name);
2674                        if (disabledPs.codePath == null || !disabledPs.codePath.exists()) {
2675                            possiblyDeletedUpdatedSystemApps.add(ps.name);
2676                        }
2677                    }
2678                }
2679            }
2680
2681            //look for any incomplete package installations
2682            ArrayList<PackageSetting> deletePkgsList = mSettings.getListOfIncompleteInstallPackagesLPr();
2683            for (int i = 0; i < deletePkgsList.size(); i++) {
2684                // Actual deletion of code and data will be handled by later
2685                // reconciliation step
2686                final String packageName = deletePkgsList.get(i).name;
2687                logCriticalInfo(Log.WARN, "Cleaning up incompletely installed app: " + packageName);
2688                synchronized (mPackages) {
2689                    mSettings.removePackageLPw(packageName);
2690                }
2691            }
2692
2693            //delete tmp files
2694            deleteTempPackageFiles();
2695
2696            // Remove any shared userIDs that have no associated packages
2697            mSettings.pruneSharedUsersLPw();
2698
2699            if (!mOnlyCore) {
2700                EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_DATA_SCAN_START,
2701                        SystemClock.uptimeMillis());
2702                scanDirTracedLI(mAppInstallDir, 0, scanFlags | SCAN_REQUIRE_KNOWN, 0);
2703
2704                scanDirTracedLI(mDrmAppPrivateInstallDir, mDefParseFlags
2705                        | PackageParser.PARSE_FORWARD_LOCK,
2706                        scanFlags | SCAN_REQUIRE_KNOWN, 0);
2707
2708                /**
2709                 * Remove disable package settings for any updated system
2710                 * apps that were removed via an OTA. If they're not a
2711                 * previously-updated app, remove them completely.
2712                 * Otherwise, just revoke their system-level permissions.
2713                 */
2714                for (String deletedAppName : possiblyDeletedUpdatedSystemApps) {
2715                    PackageParser.Package deletedPkg = mPackages.get(deletedAppName);
2716                    mSettings.removeDisabledSystemPackageLPw(deletedAppName);
2717
2718                    String msg;
2719                    if (deletedPkg == null) {
2720                        msg = "Updated system package " + deletedAppName
2721                                + " no longer exists; it's data will be wiped";
2722                        // Actual deletion of code and data will be handled by later
2723                        // reconciliation step
2724                    } else {
2725                        msg = "Updated system app + " + deletedAppName
2726                                + " no longer present; removing system privileges for "
2727                                + deletedAppName;
2728
2729                        deletedPkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_SYSTEM;
2730
2731                        PackageSetting deletedPs = mSettings.mPackages.get(deletedAppName);
2732                        deletedPs.pkgFlags &= ~ApplicationInfo.FLAG_SYSTEM;
2733                    }
2734                    logCriticalInfo(Log.WARN, msg);
2735                }
2736
2737                /**
2738                 * Make sure all system apps that we expected to appear on
2739                 * the userdata partition actually showed up. If they never
2740                 * appeared, crawl back and revive the system version.
2741                 */
2742                for (int i = 0; i < mExpectingBetter.size(); i++) {
2743                    final String packageName = mExpectingBetter.keyAt(i);
2744                    if (!mPackages.containsKey(packageName)) {
2745                        final File scanFile = mExpectingBetter.valueAt(i);
2746
2747                        logCriticalInfo(Log.WARN, "Expected better " + packageName
2748                                + " but never showed up; reverting to system");
2749
2750                        int reparseFlags = mDefParseFlags;
2751                        if (FileUtils.contains(privilegedAppDir, scanFile)) {
2752                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2753                                    | PackageParser.PARSE_IS_SYSTEM_DIR
2754                                    | PackageParser.PARSE_IS_PRIVILEGED;
2755                        } else if (FileUtils.contains(systemAppDir, scanFile)) {
2756                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2757                                    | PackageParser.PARSE_IS_SYSTEM_DIR;
2758                        } else if (FileUtils.contains(vendorAppDir, scanFile)) {
2759                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2760                                    | PackageParser.PARSE_IS_SYSTEM_DIR;
2761                        } else if (FileUtils.contains(oemAppDir, scanFile)) {
2762                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2763                                    | PackageParser.PARSE_IS_SYSTEM_DIR;
2764                        } else {
2765                            Slog.e(TAG, "Ignoring unexpected fallback path " + scanFile);
2766                            continue;
2767                        }
2768
2769                        mSettings.enableSystemPackageLPw(packageName);
2770
2771                        try {
2772                            scanPackageTracedLI(scanFile, reparseFlags, scanFlags, 0, null);
2773                        } catch (PackageManagerException e) {
2774                            Slog.e(TAG, "Failed to parse original system package: "
2775                                    + e.getMessage());
2776                        }
2777                    }
2778                }
2779            }
2780            mExpectingBetter.clear();
2781
2782            // Resolve the storage manager.
2783            mStorageManagerPackage = getStorageManagerPackageName();
2784
2785            // Resolve protected action filters. Only the setup wizard is allowed to
2786            // have a high priority filter for these actions.
2787            mSetupWizardPackage = getSetupWizardPackageName();
2788            if (mProtectedFilters.size() > 0) {
2789                if (DEBUG_FILTERS && mSetupWizardPackage == null) {
2790                    Slog.i(TAG, "No setup wizard;"
2791                        + " All protected intents capped to priority 0");
2792                }
2793                for (ActivityIntentInfo filter : mProtectedFilters) {
2794                    if (filter.activity.info.packageName.equals(mSetupWizardPackage)) {
2795                        if (DEBUG_FILTERS) {
2796                            Slog.i(TAG, "Found setup wizard;"
2797                                + " allow priority " + filter.getPriority() + ";"
2798                                + " package: " + filter.activity.info.packageName
2799                                + " activity: " + filter.activity.className
2800                                + " priority: " + filter.getPriority());
2801                        }
2802                        // skip setup wizard; allow it to keep the high priority filter
2803                        continue;
2804                    }
2805                    if (DEBUG_FILTERS) {
2806                        Slog.i(TAG, "Protected action; cap priority to 0;"
2807                                + " package: " + filter.activity.info.packageName
2808                                + " activity: " + filter.activity.className
2809                                + " origPrio: " + filter.getPriority());
2810                    }
2811                    filter.setPriority(0);
2812                }
2813            }
2814            mDeferProtectedFilters = false;
2815            mProtectedFilters.clear();
2816
2817            // Now that we know all of the shared libraries, update all clients to have
2818            // the correct library paths.
2819            updateAllSharedLibrariesLPw(null);
2820
2821            for (SharedUserSetting setting : mSettings.getAllSharedUsersLPw()) {
2822                // NOTE: We ignore potential failures here during a system scan (like
2823                // the rest of the commands above) because there's precious little we
2824                // can do about it. A settings error is reported, though.
2825                adjustCpuAbisForSharedUserLPw(setting.packages, null /*scannedPackage*/);
2826            }
2827
2828            // Now that we know all the packages we are keeping,
2829            // read and update their last usage times.
2830            mPackageUsage.read(mPackages);
2831            mCompilerStats.read();
2832
2833            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SCAN_END,
2834                    SystemClock.uptimeMillis());
2835            Slog.i(TAG, "Time to scan packages: "
2836                    + ((SystemClock.uptimeMillis()-startTime)/1000f)
2837                    + " seconds");
2838
2839            // If the platform SDK has changed since the last time we booted,
2840            // we need to re-grant app permission to catch any new ones that
2841            // appear.  This is really a hack, and means that apps can in some
2842            // cases get permissions that the user didn't initially explicitly
2843            // allow...  it would be nice to have some better way to handle
2844            // this situation.
2845            int updateFlags = UPDATE_PERMISSIONS_ALL;
2846            if (ver.sdkVersion != mSdkVersion) {
2847                Slog.i(TAG, "Platform changed from " + ver.sdkVersion + " to "
2848                        + mSdkVersion + "; regranting permissions for internal storage");
2849                updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL;
2850            }
2851            updatePermissionsLPw(null, null, StorageManager.UUID_PRIVATE_INTERNAL, updateFlags);
2852            ver.sdkVersion = mSdkVersion;
2853
2854            // If this is the first boot or an update from pre-M, and it is a normal
2855            // boot, then we need to initialize the default preferred apps across
2856            // all defined users.
2857            if (!onlyCore && (mPromoteSystemApps || mFirstBoot)) {
2858                for (UserInfo user : sUserManager.getUsers(true)) {
2859                    mSettings.applyDefaultPreferredAppsLPw(this, user.id);
2860                    applyFactoryDefaultBrowserLPw(user.id);
2861                    primeDomainVerificationsLPw(user.id);
2862                }
2863            }
2864
2865            // Prepare storage for system user really early during boot,
2866            // since core system apps like SettingsProvider and SystemUI
2867            // can't wait for user to start
2868            final int storageFlags;
2869            if (StorageManager.isFileEncryptedNativeOrEmulated()) {
2870                storageFlags = StorageManager.FLAG_STORAGE_DE;
2871            } else {
2872                storageFlags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
2873            }
2874            List<String> deferPackages = reconcileAppsDataLI(StorageManager.UUID_PRIVATE_INTERNAL,
2875                    UserHandle.USER_SYSTEM, storageFlags, true /* migrateAppData */,
2876                    true /* onlyCoreApps */);
2877            mPrepareAppDataFuture = SystemServerInitThreadPool.get().submit(() -> {
2878                BootTimingsTraceLog traceLog = new BootTimingsTraceLog("SystemServerTimingAsync",
2879                        Trace.TRACE_TAG_PACKAGE_MANAGER);
2880                traceLog.traceBegin("AppDataFixup");
2881                try {
2882                    mInstaller.fixupAppData(StorageManager.UUID_PRIVATE_INTERNAL,
2883                            StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
2884                } catch (InstallerException e) {
2885                    Slog.w(TAG, "Trouble fixing GIDs", e);
2886                }
2887                traceLog.traceEnd();
2888
2889                traceLog.traceBegin("AppDataPrepare");
2890                if (deferPackages == null || deferPackages.isEmpty()) {
2891                    return;
2892                }
2893                int count = 0;
2894                for (String pkgName : deferPackages) {
2895                    PackageParser.Package pkg = null;
2896                    synchronized (mPackages) {
2897                        PackageSetting ps = mSettings.getPackageLPr(pkgName);
2898                        if (ps != null && ps.getInstalled(UserHandle.USER_SYSTEM)) {
2899                            pkg = ps.pkg;
2900                        }
2901                    }
2902                    if (pkg != null) {
2903                        synchronized (mInstallLock) {
2904                            prepareAppDataAndMigrateLIF(pkg, UserHandle.USER_SYSTEM, storageFlags,
2905                                    true /* maybeMigrateAppData */);
2906                        }
2907                        count++;
2908                    }
2909                }
2910                traceLog.traceEnd();
2911                Slog.i(TAG, "Deferred reconcileAppsData finished " + count + " packages");
2912            }, "prepareAppData");
2913
2914            // If this is first boot after an OTA, and a normal boot, then
2915            // we need to clear code cache directories.
2916            // Note that we do *not* clear the application profiles. These remain valid
2917            // across OTAs and are used to drive profile verification (post OTA) and
2918            // profile compilation (without waiting to collect a fresh set of profiles).
2919            if (mIsUpgrade && !onlyCore) {
2920                Slog.i(TAG, "Build fingerprint changed; clearing code caches");
2921                for (int i = 0; i < mSettings.mPackages.size(); i++) {
2922                    final PackageSetting ps = mSettings.mPackages.valueAt(i);
2923                    if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, ps.volumeUuid)) {
2924                        // No apps are running this early, so no need to freeze
2925                        clearAppDataLIF(ps.pkg, UserHandle.USER_ALL,
2926                                StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE
2927                                        | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
2928                    }
2929                }
2930                ver.fingerprint = Build.FINGERPRINT;
2931            }
2932
2933            checkDefaultBrowser();
2934
2935            // clear only after permissions and other defaults have been updated
2936            mExistingSystemPackages.clear();
2937            mPromoteSystemApps = false;
2938
2939            // All the changes are done during package scanning.
2940            ver.databaseVersion = Settings.CURRENT_DATABASE_VERSION;
2941
2942            // can downgrade to reader
2943            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "write settings");
2944            mSettings.writeLPr();
2945            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
2946
2947            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_READY,
2948                    SystemClock.uptimeMillis());
2949
2950            if (!mOnlyCore) {
2951                mRequiredVerifierPackage = getRequiredButNotReallyRequiredVerifierLPr();
2952                mRequiredInstallerPackage = getRequiredInstallerLPr();
2953                mRequiredUninstallerPackage = getRequiredUninstallerLPr();
2954                mIntentFilterVerifierComponent = getIntentFilterVerifierComponentNameLPr();
2955                if (mIntentFilterVerifierComponent != null) {
2956                    mIntentFilterVerifier = new IntentVerifierProxy(mContext,
2957                            mIntentFilterVerifierComponent);
2958                } else {
2959                    mIntentFilterVerifier = null;
2960                }
2961                mServicesSystemSharedLibraryPackageName = getRequiredSharedLibraryLPr(
2962                        PackageManager.SYSTEM_SHARED_LIBRARY_SERVICES,
2963                        SharedLibraryInfo.VERSION_UNDEFINED);
2964                mSharedSystemSharedLibraryPackageName = getRequiredSharedLibraryLPr(
2965                        PackageManager.SYSTEM_SHARED_LIBRARY_SHARED,
2966                        SharedLibraryInfo.VERSION_UNDEFINED);
2967            } else {
2968                mRequiredVerifierPackage = null;
2969                mRequiredInstallerPackage = null;
2970                mRequiredUninstallerPackage = null;
2971                mIntentFilterVerifierComponent = null;
2972                mIntentFilterVerifier = null;
2973                mServicesSystemSharedLibraryPackageName = null;
2974                mSharedSystemSharedLibraryPackageName = null;
2975            }
2976
2977            mInstallerService = new PackageInstallerService(context, this);
2978            final Pair<ComponentName, String> instantAppResolverComponent =
2979                    getInstantAppResolverLPr();
2980            if (instantAppResolverComponent != null) {
2981                if (DEBUG_EPHEMERAL) {
2982                    Slog.d(TAG, "Set ephemeral resolver: " + instantAppResolverComponent);
2983                }
2984                mInstantAppResolverConnection = new EphemeralResolverConnection(
2985                        mContext, instantAppResolverComponent.first,
2986                        instantAppResolverComponent.second);
2987                mInstantAppResolverSettingsComponent =
2988                        getInstantAppResolverSettingsLPr(instantAppResolverComponent.first);
2989            } else {
2990                mInstantAppResolverConnection = null;
2991                mInstantAppResolverSettingsComponent = null;
2992            }
2993            updateInstantAppInstallerLocked(null);
2994
2995            // Read and update the usage of dex files.
2996            // Do this at the end of PM init so that all the packages have their
2997            // data directory reconciled.
2998            // At this point we know the code paths of the packages, so we can validate
2999            // the disk file and build the internal cache.
3000            // The usage file is expected to be small so loading and verifying it
3001            // should take a fairly small time compare to the other activities (e.g. package
3002            // scanning).
3003            final Map<Integer, List<PackageInfo>> userPackages = new HashMap<>();
3004            final int[] currentUserIds = UserManagerService.getInstance().getUserIds();
3005            for (int userId : currentUserIds) {
3006                userPackages.put(userId, getInstalledPackages(/*flags*/ 0, userId).getList());
3007            }
3008            mDexManager.load(userPackages);
3009        } // synchronized (mPackages)
3010        } // synchronized (mInstallLock)
3011
3012        // Now after opening every single application zip, make sure they
3013        // are all flushed.  Not really needed, but keeps things nice and
3014        // tidy.
3015        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "GC");
3016        Runtime.getRuntime().gc();
3017        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
3018
3019        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "loadFallbacks");
3020        FallbackCategoryProvider.loadFallbacks();
3021        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
3022
3023        // The initial scanning above does many calls into installd while
3024        // holding the mPackages lock, but we're mostly interested in yelling
3025        // once we have a booted system.
3026        mInstaller.setWarnIfHeld(mPackages);
3027
3028        // Expose private service for system components to use.
3029        LocalServices.addService(PackageManagerInternal.class, new PackageManagerInternalImpl());
3030        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
3031    }
3032
3033    private void updateInstantAppInstallerLocked(String modifiedPackage) {
3034        // we're only interested in updating the installer appliction when 1) it's not
3035        // already set or 2) the modified package is the installer
3036        if (mInstantAppInstallerActivity != null
3037                && !mInstantAppInstallerActivity.getComponentName().getPackageName()
3038                        .equals(modifiedPackage)) {
3039            return;
3040        }
3041        setUpInstantAppInstallerActivityLP(getInstantAppInstallerLPr());
3042    }
3043
3044    private static File preparePackageParserCache(boolean isUpgrade) {
3045        if (!DEFAULT_PACKAGE_PARSER_CACHE_ENABLED) {
3046            return null;
3047        }
3048
3049        // Disable package parsing on eng builds to allow for faster incremental development.
3050        if ("eng".equals(Build.TYPE)) {
3051            return null;
3052        }
3053
3054        if (SystemProperties.getBoolean("pm.boot.disable_package_cache", false)) {
3055            Slog.i(TAG, "Disabling package parser cache due to system property.");
3056            return null;
3057        }
3058
3059        // The base directory for the package parser cache lives under /data/system/.
3060        final File cacheBaseDir = FileUtils.createDir(Environment.getDataSystemDirectory(),
3061                "package_cache");
3062        if (cacheBaseDir == null) {
3063            return null;
3064        }
3065
3066        // If this is a system upgrade scenario, delete the contents of the package cache dir.
3067        // This also serves to "GC" unused entries when the package cache version changes (which
3068        // can only happen during upgrades).
3069        if (isUpgrade) {
3070            FileUtils.deleteContents(cacheBaseDir);
3071        }
3072
3073
3074        // Return the versioned package cache directory. This is something like
3075        // "/data/system/package_cache/1"
3076        File cacheDir = FileUtils.createDir(cacheBaseDir, PACKAGE_PARSER_CACHE_VERSION);
3077
3078        // The following is a workaround to aid development on non-numbered userdebug
3079        // builds or cases where "adb sync" is used on userdebug builds. If we detect that
3080        // the system partition is newer.
3081        //
3082        // NOTE: When no BUILD_NUMBER is set by the build system, it defaults to a build
3083        // that starts with "eng." to signify that this is an engineering build and not
3084        // destined for release.
3085        if ("userdebug".equals(Build.TYPE) && Build.VERSION.INCREMENTAL.startsWith("eng.")) {
3086            Slog.w(TAG, "Wiping cache directory because the system partition changed.");
3087
3088            // Heuristic: If the /system directory has been modified recently due to an "adb sync"
3089            // or a regular make, then blow away the cache. Note that mtimes are *NOT* reliable
3090            // in general and should not be used for production changes. In this specific case,
3091            // we know that they will work.
3092            File frameworkDir = new File(Environment.getRootDirectory(), "framework");
3093            if (cacheDir.lastModified() < frameworkDir.lastModified()) {
3094                FileUtils.deleteContents(cacheBaseDir);
3095                cacheDir = FileUtils.createDir(cacheBaseDir, PACKAGE_PARSER_CACHE_VERSION);
3096            }
3097        }
3098
3099        return cacheDir;
3100    }
3101
3102    @Override
3103    public boolean isFirstBoot() {
3104        // allow instant applications
3105        return mFirstBoot;
3106    }
3107
3108    @Override
3109    public boolean isOnlyCoreApps() {
3110        // allow instant applications
3111        return mOnlyCore;
3112    }
3113
3114    @Override
3115    public boolean isUpgrade() {
3116        // allow instant applications
3117        return mIsUpgrade;
3118    }
3119
3120    private @Nullable String getRequiredButNotReallyRequiredVerifierLPr() {
3121        final Intent intent = new Intent(Intent.ACTION_PACKAGE_NEEDS_VERIFICATION);
3122
3123        final List<ResolveInfo> matches = queryIntentReceiversInternal(intent, PACKAGE_MIME_TYPE,
3124                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
3125                UserHandle.USER_SYSTEM);
3126        if (matches.size() == 1) {
3127            return matches.get(0).getComponentInfo().packageName;
3128        } else if (matches.size() == 0) {
3129            Log.e(TAG, "There should probably be a verifier, but, none were found");
3130            return null;
3131        }
3132        throw new RuntimeException("There must be exactly one verifier; found " + matches);
3133    }
3134
3135    private @NonNull String getRequiredSharedLibraryLPr(String name, int version) {
3136        synchronized (mPackages) {
3137            SharedLibraryEntry libraryEntry = getSharedLibraryEntryLPr(name, version);
3138            if (libraryEntry == null) {
3139                throw new IllegalStateException("Missing required shared library:" + name);
3140            }
3141            return libraryEntry.apk;
3142        }
3143    }
3144
3145    private @NonNull String getRequiredInstallerLPr() {
3146        final Intent intent = new Intent(Intent.ACTION_INSTALL_PACKAGE);
3147        intent.addCategory(Intent.CATEGORY_DEFAULT);
3148        intent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE);
3149
3150        final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, PACKAGE_MIME_TYPE,
3151                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
3152                UserHandle.USER_SYSTEM);
3153        if (matches.size() == 1) {
3154            ResolveInfo resolveInfo = matches.get(0);
3155            if (!resolveInfo.activityInfo.applicationInfo.isPrivilegedApp()) {
3156                throw new RuntimeException("The installer must be a privileged app");
3157            }
3158            return matches.get(0).getComponentInfo().packageName;
3159        } else {
3160            throw new RuntimeException("There must be exactly one installer; found " + matches);
3161        }
3162    }
3163
3164    private @NonNull String getRequiredUninstallerLPr() {
3165        final Intent intent = new Intent(Intent.ACTION_UNINSTALL_PACKAGE);
3166        intent.addCategory(Intent.CATEGORY_DEFAULT);
3167        intent.setData(Uri.fromParts(PACKAGE_SCHEME, "foo.bar", null));
3168
3169        final ResolveInfo resolveInfo = resolveIntent(intent, null,
3170                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
3171                UserHandle.USER_SYSTEM);
3172        if (resolveInfo == null ||
3173                mResolveActivity.name.equals(resolveInfo.getComponentInfo().name)) {
3174            throw new RuntimeException("There must be exactly one uninstaller; found "
3175                    + resolveInfo);
3176        }
3177        return resolveInfo.getComponentInfo().packageName;
3178    }
3179
3180    private @NonNull ComponentName getIntentFilterVerifierComponentNameLPr() {
3181        final Intent intent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION);
3182
3183        final List<ResolveInfo> matches = queryIntentReceiversInternal(intent, PACKAGE_MIME_TYPE,
3184                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
3185                UserHandle.USER_SYSTEM);
3186        ResolveInfo best = null;
3187        final int N = matches.size();
3188        for (int i = 0; i < N; i++) {
3189            final ResolveInfo cur = matches.get(i);
3190            final String packageName = cur.getComponentInfo().packageName;
3191            if (checkPermission(android.Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT,
3192                    packageName, UserHandle.USER_SYSTEM) != PackageManager.PERMISSION_GRANTED) {
3193                continue;
3194            }
3195
3196            if (best == null || cur.priority > best.priority) {
3197                best = cur;
3198            }
3199        }
3200
3201        if (best != null) {
3202            return best.getComponentInfo().getComponentName();
3203        }
3204        Slog.w(TAG, "Intent filter verifier not found");
3205        return null;
3206    }
3207
3208    @Override
3209    public @Nullable ComponentName getInstantAppResolverComponent() {
3210        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
3211            return null;
3212        }
3213        synchronized (mPackages) {
3214            final Pair<ComponentName, String> instantAppResolver = getInstantAppResolverLPr();
3215            if (instantAppResolver == null) {
3216                return null;
3217            }
3218            return instantAppResolver.first;
3219        }
3220    }
3221
3222    private @Nullable Pair<ComponentName, String> getInstantAppResolverLPr() {
3223        final String[] packageArray =
3224                mContext.getResources().getStringArray(R.array.config_ephemeralResolverPackage);
3225        if (packageArray.length == 0 && !Build.IS_DEBUGGABLE) {
3226            if (DEBUG_EPHEMERAL) {
3227                Slog.d(TAG, "Ephemeral resolver NOT found; empty package list");
3228            }
3229            return null;
3230        }
3231
3232        final int callingUid = Binder.getCallingUid();
3233        final int resolveFlags =
3234                MATCH_DIRECT_BOOT_AWARE
3235                | MATCH_DIRECT_BOOT_UNAWARE
3236                | (!Build.IS_DEBUGGABLE ? MATCH_SYSTEM_ONLY : 0);
3237        String actionName = Intent.ACTION_RESOLVE_INSTANT_APP_PACKAGE;
3238        final Intent resolverIntent = new Intent(actionName);
3239        List<ResolveInfo> resolvers = queryIntentServicesInternal(resolverIntent, null,
3240                resolveFlags, UserHandle.USER_SYSTEM, callingUid, false /*includeInstantApps*/);
3241        // temporarily look for the old action
3242        if (resolvers.size() == 0) {
3243            if (DEBUG_EPHEMERAL) {
3244                Slog.d(TAG, "Ephemeral resolver not found with new action; try old one");
3245            }
3246            actionName = Intent.ACTION_RESOLVE_EPHEMERAL_PACKAGE;
3247            resolverIntent.setAction(actionName);
3248            resolvers = queryIntentServicesInternal(resolverIntent, null,
3249                    resolveFlags, UserHandle.USER_SYSTEM, callingUid, false /*includeInstantApps*/);
3250        }
3251        final int N = resolvers.size();
3252        if (N == 0) {
3253            if (DEBUG_EPHEMERAL) {
3254                Slog.d(TAG, "Ephemeral resolver NOT found; no matching intent filters");
3255            }
3256            return null;
3257        }
3258
3259        final Set<String> possiblePackages = new ArraySet<>(Arrays.asList(packageArray));
3260        for (int i = 0; i < N; i++) {
3261            final ResolveInfo info = resolvers.get(i);
3262
3263            if (info.serviceInfo == null) {
3264                continue;
3265            }
3266
3267            final String packageName = info.serviceInfo.packageName;
3268            if (!possiblePackages.contains(packageName) && !Build.IS_DEBUGGABLE) {
3269                if (DEBUG_EPHEMERAL) {
3270                    Slog.d(TAG, "Ephemeral resolver not in allowed package list;"
3271                            + " pkg: " + packageName + ", info:" + info);
3272                }
3273                continue;
3274            }
3275
3276            if (DEBUG_EPHEMERAL) {
3277                Slog.v(TAG, "Ephemeral resolver found;"
3278                        + " pkg: " + packageName + ", info:" + info);
3279            }
3280            return new Pair<>(new ComponentName(packageName, info.serviceInfo.name), actionName);
3281        }
3282        if (DEBUG_EPHEMERAL) {
3283            Slog.v(TAG, "Ephemeral resolver NOT found");
3284        }
3285        return null;
3286    }
3287
3288    private @Nullable ActivityInfo getInstantAppInstallerLPr() {
3289        final Intent intent = new Intent(Intent.ACTION_INSTALL_INSTANT_APP_PACKAGE);
3290        intent.addCategory(Intent.CATEGORY_DEFAULT);
3291        intent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE);
3292
3293        final int resolveFlags =
3294                MATCH_DIRECT_BOOT_AWARE
3295                | MATCH_DIRECT_BOOT_UNAWARE
3296                | (!Build.IS_DEBUGGABLE ? MATCH_SYSTEM_ONLY : 0);
3297        List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, PACKAGE_MIME_TYPE,
3298                resolveFlags, UserHandle.USER_SYSTEM);
3299        // temporarily look for the old action
3300        if (matches.isEmpty()) {
3301            if (DEBUG_EPHEMERAL) {
3302                Slog.d(TAG, "Ephemeral installer not found with new action; try old one");
3303            }
3304            intent.setAction(Intent.ACTION_INSTALL_EPHEMERAL_PACKAGE);
3305            matches = queryIntentActivitiesInternal(intent, PACKAGE_MIME_TYPE,
3306                    resolveFlags, UserHandle.USER_SYSTEM);
3307        }
3308        Iterator<ResolveInfo> iter = matches.iterator();
3309        while (iter.hasNext()) {
3310            final ResolveInfo rInfo = iter.next();
3311            final PackageSetting ps = mSettings.mPackages.get(rInfo.activityInfo.packageName);
3312            if (ps != null) {
3313                final PermissionsState permissionsState = ps.getPermissionsState();
3314                if (permissionsState.hasPermission(Manifest.permission.INSTALL_PACKAGES, 0)) {
3315                    continue;
3316                }
3317            }
3318            iter.remove();
3319        }
3320        if (matches.size() == 0) {
3321            return null;
3322        } else if (matches.size() == 1) {
3323            return (ActivityInfo) matches.get(0).getComponentInfo();
3324        } else {
3325            throw new RuntimeException(
3326                    "There must be at most one ephemeral installer; found " + matches);
3327        }
3328    }
3329
3330    private @Nullable ComponentName getInstantAppResolverSettingsLPr(
3331            @NonNull ComponentName resolver) {
3332        final Intent intent =  new Intent(Intent.ACTION_INSTANT_APP_RESOLVER_SETTINGS)
3333                .addCategory(Intent.CATEGORY_DEFAULT)
3334                .setPackage(resolver.getPackageName());
3335        final int resolveFlags = MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE;
3336        List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, null, resolveFlags,
3337                UserHandle.USER_SYSTEM);
3338        // temporarily look for the old action
3339        if (matches.isEmpty()) {
3340            if (DEBUG_EPHEMERAL) {
3341                Slog.d(TAG, "Ephemeral resolver settings not found with new action; try old one");
3342            }
3343            intent.setAction(Intent.ACTION_EPHEMERAL_RESOLVER_SETTINGS);
3344            matches = queryIntentActivitiesInternal(intent, null, resolveFlags,
3345                    UserHandle.USER_SYSTEM);
3346        }
3347        if (matches.isEmpty()) {
3348            return null;
3349        }
3350        return matches.get(0).getComponentInfo().getComponentName();
3351    }
3352
3353    private void primeDomainVerificationsLPw(int userId) {
3354        if (DEBUG_DOMAIN_VERIFICATION) {
3355            Slog.d(TAG, "Priming domain verifications in user " + userId);
3356        }
3357
3358        SystemConfig systemConfig = SystemConfig.getInstance();
3359        ArraySet<String> packages = systemConfig.getLinkedApps();
3360
3361        for (String packageName : packages) {
3362            PackageParser.Package pkg = mPackages.get(packageName);
3363            if (pkg != null) {
3364                if (!pkg.isSystemApp()) {
3365                    Slog.w(TAG, "Non-system app '" + packageName + "' in sysconfig <app-link>");
3366                    continue;
3367                }
3368
3369                ArraySet<String> domains = null;
3370                for (PackageParser.Activity a : pkg.activities) {
3371                    for (ActivityIntentInfo filter : a.intents) {
3372                        if (hasValidDomains(filter)) {
3373                            if (domains == null) {
3374                                domains = new ArraySet<String>();
3375                            }
3376                            domains.addAll(filter.getHostsList());
3377                        }
3378                    }
3379                }
3380
3381                if (domains != null && domains.size() > 0) {
3382                    if (DEBUG_DOMAIN_VERIFICATION) {
3383                        Slog.v(TAG, "      + " + packageName);
3384                    }
3385                    // 'Undefined' in the global IntentFilterVerificationInfo, i.e. the usual
3386                    // state w.r.t. the formal app-linkage "no verification attempted" state;
3387                    // and then 'always' in the per-user state actually used for intent resolution.
3388                    final IntentFilterVerificationInfo ivi;
3389                    ivi = mSettings.createIntentFilterVerificationIfNeededLPw(packageName, domains);
3390                    ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED);
3391                    mSettings.updateIntentFilterVerificationStatusLPw(packageName,
3392                            INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS, userId);
3393                } else {
3394                    Slog.w(TAG, "Sysconfig <app-link> package '" + packageName
3395                            + "' does not handle web links");
3396                }
3397            } else {
3398                Slog.w(TAG, "Unknown package " + packageName + " in sysconfig <app-link>");
3399            }
3400        }
3401
3402        scheduleWritePackageRestrictionsLocked(userId);
3403        scheduleWriteSettingsLocked();
3404    }
3405
3406    private void applyFactoryDefaultBrowserLPw(int userId) {
3407        // The default browser app's package name is stored in a string resource,
3408        // with a product-specific overlay used for vendor customization.
3409        String browserPkg = mContext.getResources().getString(
3410                com.android.internal.R.string.default_browser);
3411        if (!TextUtils.isEmpty(browserPkg)) {
3412            // non-empty string => required to be a known package
3413            PackageSetting ps = mSettings.mPackages.get(browserPkg);
3414            if (ps == null) {
3415                Slog.e(TAG, "Product default browser app does not exist: " + browserPkg);
3416                browserPkg = null;
3417            } else {
3418                mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId);
3419            }
3420        }
3421
3422        // Nothing valid explicitly set? Make the factory-installed browser the explicit
3423        // default.  If there's more than one, just leave everything alone.
3424        if (browserPkg == null) {
3425            calculateDefaultBrowserLPw(userId);
3426        }
3427    }
3428
3429    private void calculateDefaultBrowserLPw(int userId) {
3430        List<String> allBrowsers = resolveAllBrowserApps(userId);
3431        final String browserPkg = (allBrowsers.size() == 1) ? allBrowsers.get(0) : null;
3432        mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId);
3433    }
3434
3435    private List<String> resolveAllBrowserApps(int userId) {
3436        // Resolve the canonical browser intent and check that the handleAllWebDataURI boolean is set
3437        List<ResolveInfo> list = queryIntentActivitiesInternal(sBrowserIntent, null,
3438                PackageManager.MATCH_ALL, userId);
3439
3440        final int count = list.size();
3441        List<String> result = new ArrayList<String>(count);
3442        for (int i=0; i<count; i++) {
3443            ResolveInfo info = list.get(i);
3444            if (info.activityInfo == null
3445                    || !info.handleAllWebDataURI
3446                    || (info.activityInfo.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) == 0
3447                    || result.contains(info.activityInfo.packageName)) {
3448                continue;
3449            }
3450            result.add(info.activityInfo.packageName);
3451        }
3452
3453        return result;
3454    }
3455
3456    private boolean packageIsBrowser(String packageName, int userId) {
3457        List<ResolveInfo> list = queryIntentActivitiesInternal(sBrowserIntent, null,
3458                PackageManager.MATCH_ALL, userId);
3459        final int N = list.size();
3460        for (int i = 0; i < N; i++) {
3461            ResolveInfo info = list.get(i);
3462            if (packageName.equals(info.activityInfo.packageName)) {
3463                return true;
3464            }
3465        }
3466        return false;
3467    }
3468
3469    private void checkDefaultBrowser() {
3470        final int myUserId = UserHandle.myUserId();
3471        final String packageName = getDefaultBrowserPackageName(myUserId);
3472        if (packageName != null) {
3473            PackageInfo info = getPackageInfo(packageName, 0, myUserId);
3474            if (info == null) {
3475                Slog.w(TAG, "Default browser no longer installed: " + packageName);
3476                synchronized (mPackages) {
3477                    applyFactoryDefaultBrowserLPw(myUserId);    // leaves ambiguous when > 1
3478                }
3479            }
3480        }
3481    }
3482
3483    @Override
3484    public boolean onTransact(int code, Parcel data, Parcel reply, int flags)
3485            throws RemoteException {
3486        try {
3487            return super.onTransact(code, data, reply, flags);
3488        } catch (RuntimeException e) {
3489            if (!(e instanceof SecurityException) && !(e instanceof IllegalArgumentException)) {
3490                Slog.wtf(TAG, "Package Manager Crash", e);
3491            }
3492            throw e;
3493        }
3494    }
3495
3496    static int[] appendInts(int[] cur, int[] add) {
3497        if (add == null) return cur;
3498        if (cur == null) return add;
3499        final int N = add.length;
3500        for (int i=0; i<N; i++) {
3501            cur = appendInt(cur, add[i]);
3502        }
3503        return cur;
3504    }
3505
3506    /**
3507     * Returns whether or not a full application can see an instant application.
3508     * <p>
3509     * Currently, there are three cases in which this can occur:
3510     * <ol>
3511     * <li>The calling application is a "special" process. The special
3512     *     processes are {@link Process#SYSTEM_UID}, {@link Process#SHELL_UID}
3513     *     and {@code 0}</li>
3514     * <li>The calling application has the permission
3515     *     {@link android.Manifest.permission#ACCESS_INSTANT_APPS}</li>
3516     * <li>[TODO] The calling application is the default launcher on the
3517     *     system partition.</li>
3518     * </ol>
3519     */
3520    private boolean canViewInstantApps(int callingUid, int userId) {
3521        if (callingUid == Process.SYSTEM_UID
3522                || callingUid == Process.SHELL_UID
3523                || callingUid == Process.ROOT_UID) {
3524            return true;
3525        }
3526        if (mContext.checkCallingOrSelfPermission(
3527                android.Manifest.permission.ACCESS_INSTANT_APPS) == PERMISSION_GRANTED) {
3528            return true;
3529        }
3530        if (mContext.checkCallingOrSelfPermission(
3531                android.Manifest.permission.VIEW_INSTANT_APPS) == PERMISSION_GRANTED) {
3532            final ComponentName homeComponent = getDefaultHomeActivity(userId);
3533            if (homeComponent != null
3534                    && isCallerSameApp(homeComponent.getPackageName(), callingUid)) {
3535                return true;
3536            }
3537        }
3538        return false;
3539    }
3540
3541    private PackageInfo generatePackageInfo(PackageSetting ps, int flags, int userId) {
3542        if (!sUserManager.exists(userId)) return null;
3543        if (ps == null) {
3544            return null;
3545        }
3546        PackageParser.Package p = ps.pkg;
3547        if (p == null) {
3548            return null;
3549        }
3550        final int callingUid = Binder.getCallingUid();
3551        // Filter out ephemeral app metadata:
3552        //   * The system/shell/root can see metadata for any app
3553        //   * An installed app can see metadata for 1) other installed apps
3554        //     and 2) ephemeral apps that have explicitly interacted with it
3555        //   * Ephemeral apps can only see their own data and exposed installed apps
3556        //   * Holding a signature permission allows seeing instant apps
3557        if (filterAppAccessLPr(ps, callingUid, userId)) {
3558            return null;
3559        }
3560
3561        final PermissionsState permissionsState = ps.getPermissionsState();
3562
3563        // Compute GIDs only if requested
3564        final int[] gids = (flags & PackageManager.GET_GIDS) == 0
3565                ? EMPTY_INT_ARRAY : permissionsState.computeGids(userId);
3566        // Compute granted permissions only if package has requested permissions
3567        final Set<String> permissions = ArrayUtils.isEmpty(p.requestedPermissions)
3568                ? Collections.<String>emptySet() : permissionsState.getPermissions(userId);
3569        final PackageUserState state = ps.readUserState(userId);
3570
3571        if ((flags & MATCH_UNINSTALLED_PACKAGES) != 0
3572                && ps.isSystem()) {
3573            flags |= MATCH_ANY_USER;
3574        }
3575
3576        PackageInfo packageInfo = PackageParser.generatePackageInfo(p, gids, flags,
3577                ps.firstInstallTime, ps.lastUpdateTime, permissions, state, userId);
3578
3579        if (packageInfo == null) {
3580            return null;
3581        }
3582
3583        rebaseEnabledOverlays(packageInfo.applicationInfo, userId);
3584
3585        packageInfo.packageName = packageInfo.applicationInfo.packageName =
3586                resolveExternalPackageNameLPr(p);
3587
3588        return packageInfo;
3589    }
3590
3591    @Override
3592    public void checkPackageStartable(String packageName, int userId) {
3593        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
3594            throw new SecurityException("Instant applications don't have access to this method");
3595        }
3596        final boolean userKeyUnlocked = StorageManager.isUserKeyUnlocked(userId);
3597        synchronized (mPackages) {
3598            final PackageSetting ps = mSettings.mPackages.get(packageName);
3599            if (ps == null) {
3600                throw new SecurityException("Package " + packageName + " was not found!");
3601            }
3602
3603            if (!ps.getInstalled(userId)) {
3604                throw new SecurityException(
3605                        "Package " + packageName + " was not installed for user " + userId + "!");
3606            }
3607
3608            if (mSafeMode && !ps.isSystem()) {
3609                throw new SecurityException("Package " + packageName + " not a system app!");
3610            }
3611
3612            if (mFrozenPackages.contains(packageName)) {
3613                throw new SecurityException("Package " + packageName + " is currently frozen!");
3614            }
3615
3616            if (!userKeyUnlocked && !(ps.pkg.applicationInfo.isDirectBootAware()
3617                    || ps.pkg.applicationInfo.isPartiallyDirectBootAware())) {
3618                throw new SecurityException("Package " + packageName + " is not encryption aware!");
3619            }
3620        }
3621    }
3622
3623    @Override
3624    public boolean isPackageAvailable(String packageName, int userId) {
3625        if (!sUserManager.exists(userId)) return false;
3626        final int callingUid = Binder.getCallingUid();
3627        enforceCrossUserPermission(callingUid, userId,
3628                false /*requireFullPermission*/, false /*checkShell*/, "is package available");
3629        synchronized (mPackages) {
3630            PackageParser.Package p = mPackages.get(packageName);
3631            if (p != null) {
3632                final PackageSetting ps = (PackageSetting) p.mExtras;
3633                if (filterAppAccessLPr(ps, callingUid, userId)) {
3634                    return false;
3635                }
3636                if (ps != null) {
3637                    final PackageUserState state = ps.readUserState(userId);
3638                    if (state != null) {
3639                        return PackageParser.isAvailable(state);
3640                    }
3641                }
3642            }
3643        }
3644        return false;
3645    }
3646
3647    @Override
3648    public PackageInfo getPackageInfo(String packageName, int flags, int userId) {
3649        return getPackageInfoInternal(packageName, PackageManager.VERSION_CODE_HIGHEST,
3650                flags, userId);
3651    }
3652
3653    @Override
3654    public PackageInfo getPackageInfoVersioned(VersionedPackage versionedPackage,
3655            int flags, int userId) {
3656        return getPackageInfoInternal(versionedPackage.getPackageName(),
3657                versionedPackage.getVersionCode(), flags, userId);
3658    }
3659
3660    private PackageInfo getPackageInfoInternal(String packageName, int versionCode,
3661            int flags, int userId) {
3662        if (!sUserManager.exists(userId)) return null;
3663        final int callingUid = Binder.getCallingUid();
3664        flags = updateFlagsForPackage(flags, userId, packageName);
3665        enforceCrossUserPermission(callingUid, userId,
3666                false /* requireFullPermission */, false /* checkShell */, "get package info");
3667
3668        // reader
3669        synchronized (mPackages) {
3670            // Normalize package name to handle renamed packages and static libs
3671            packageName = resolveInternalPackageNameLPr(packageName, versionCode);
3672
3673            final boolean matchFactoryOnly = (flags & MATCH_FACTORY_ONLY) != 0;
3674            if (matchFactoryOnly) {
3675                final PackageSetting ps = mSettings.getDisabledSystemPkgLPr(packageName);
3676                if (ps != null) {
3677                    if (filterSharedLibPackageLPr(ps, callingUid, userId, flags)) {
3678                        return null;
3679                    }
3680                    if (filterAppAccessLPr(ps, callingUid, userId)) {
3681                        return null;
3682                    }
3683                    return generatePackageInfo(ps, flags, userId);
3684                }
3685            }
3686
3687            PackageParser.Package p = mPackages.get(packageName);
3688            if (matchFactoryOnly && p != null && !isSystemApp(p)) {
3689                return null;
3690            }
3691            if (DEBUG_PACKAGE_INFO)
3692                Log.v(TAG, "getPackageInfo " + packageName + ": " + p);
3693            if (p != null) {
3694                final PackageSetting ps = (PackageSetting) p.mExtras;
3695                if (filterSharedLibPackageLPr(ps, callingUid, userId, flags)) {
3696                    return null;
3697                }
3698                if (ps != null && filterAppAccessLPr(ps, callingUid, userId)) {
3699                    return null;
3700                }
3701                return generatePackageInfo((PackageSetting)p.mExtras, flags, userId);
3702            }
3703            if (!matchFactoryOnly && (flags & MATCH_KNOWN_PACKAGES) != 0) {
3704                final PackageSetting ps = mSettings.mPackages.get(packageName);
3705                if (ps == null) return null;
3706                if (filterSharedLibPackageLPr(ps, callingUid, userId, flags)) {
3707                    return null;
3708                }
3709                if (filterAppAccessLPr(ps, callingUid, userId)) {
3710                    return null;
3711                }
3712                return generatePackageInfo(ps, flags, userId);
3713            }
3714        }
3715        return null;
3716    }
3717
3718    private boolean isComponentVisibleToInstantApp(@Nullable ComponentName component) {
3719        if (isComponentVisibleToInstantApp(component, TYPE_ACTIVITY)) {
3720            return true;
3721        }
3722        if (isComponentVisibleToInstantApp(component, TYPE_SERVICE)) {
3723            return true;
3724        }
3725        if (isComponentVisibleToInstantApp(component, TYPE_PROVIDER)) {
3726            return true;
3727        }
3728        return false;
3729    }
3730
3731    private boolean isComponentVisibleToInstantApp(
3732            @Nullable ComponentName component, @ComponentType int type) {
3733        if (type == TYPE_ACTIVITY) {
3734            final PackageParser.Activity activity = mActivities.mActivities.get(component);
3735            return activity != null
3736                    ? (activity.info.flags & ActivityInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0
3737                    : false;
3738        } else if (type == TYPE_RECEIVER) {
3739            final PackageParser.Activity activity = mReceivers.mActivities.get(component);
3740            return activity != null
3741                    ? (activity.info.flags & ActivityInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0
3742                    : false;
3743        } else if (type == TYPE_SERVICE) {
3744            final PackageParser.Service service = mServices.mServices.get(component);
3745            return service != null
3746                    ? (service.info.flags & ServiceInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0
3747                    : false;
3748        } else if (type == TYPE_PROVIDER) {
3749            final PackageParser.Provider provider = mProviders.mProviders.get(component);
3750            return provider != null
3751                    ? (provider.info.flags & ProviderInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0
3752                    : false;
3753        } else if (type == TYPE_UNKNOWN) {
3754            return isComponentVisibleToInstantApp(component);
3755        }
3756        return false;
3757    }
3758
3759    /**
3760     * Returns whether or not access to the application should be filtered.
3761     * <p>
3762     * Access may be limited based upon whether the calling or target applications
3763     * are instant applications.
3764     *
3765     * @see #canAccessInstantApps(int)
3766     */
3767    private boolean filterAppAccessLPr(@Nullable PackageSetting ps, int callingUid,
3768            @Nullable ComponentName component, @ComponentType int componentType, int userId) {
3769        // if we're in an isolated process, get the real calling UID
3770        if (Process.isIsolated(callingUid)) {
3771            callingUid = mIsolatedOwners.get(callingUid);
3772        }
3773        final String instantAppPkgName = getInstantAppPackageName(callingUid);
3774        final boolean callerIsInstantApp = instantAppPkgName != null;
3775        if (ps == null) {
3776            if (callerIsInstantApp) {
3777                // pretend the application exists, but, needs to be filtered
3778                return true;
3779            }
3780            return false;
3781        }
3782        // if the target and caller are the same application, don't filter
3783        if (isCallerSameApp(ps.name, callingUid)) {
3784            return false;
3785        }
3786        if (callerIsInstantApp) {
3787            // request for a specific component; if it hasn't been explicitly exposed, filter
3788            if (component != null) {
3789                return !isComponentVisibleToInstantApp(component, componentType);
3790            }
3791            // request for application; if no components have been explicitly exposed, filter
3792            return ps.getInstantApp(userId) || !ps.pkg.visibleToInstantApps;
3793        }
3794        if (ps.getInstantApp(userId)) {
3795            // caller can see all components of all instant applications, don't filter
3796            if (canViewInstantApps(callingUid, userId)) {
3797                return false;
3798            }
3799            // request for a specific instant application component, filter
3800            if (component != null) {
3801                return true;
3802            }
3803            // request for an instant application; if the caller hasn't been granted access, filter
3804            return !mInstantAppRegistry.isInstantAccessGranted(
3805                    userId, UserHandle.getAppId(callingUid), ps.appId);
3806        }
3807        return false;
3808    }
3809
3810    /**
3811     * @see #filterAppAccessLPr(PackageSetting, int, ComponentName, boolean, int)
3812     */
3813    private boolean filterAppAccessLPr(@Nullable PackageSetting ps, int callingUid, int userId) {
3814        return filterAppAccessLPr(ps, callingUid, null, TYPE_UNKNOWN, userId);
3815    }
3816
3817    private boolean filterSharedLibPackageLPr(@Nullable PackageSetting ps, int uid, int userId,
3818            int flags) {
3819        // Callers can access only the libs they depend on, otherwise they need to explicitly
3820        // ask for the shared libraries given the caller is allowed to access all static libs.
3821        if ((flags & PackageManager.MATCH_STATIC_SHARED_LIBRARIES) != 0) {
3822            // System/shell/root get to see all static libs
3823            final int appId = UserHandle.getAppId(uid);
3824            if (appId == Process.SYSTEM_UID || appId == Process.SHELL_UID
3825                    || appId == Process.ROOT_UID) {
3826                return false;
3827            }
3828        }
3829
3830        // No package means no static lib as it is always on internal storage
3831        if (ps == null || ps.pkg == null || !ps.pkg.applicationInfo.isStaticSharedLibrary()) {
3832            return false;
3833        }
3834
3835        final SharedLibraryEntry libEntry = getSharedLibraryEntryLPr(ps.pkg.staticSharedLibName,
3836                ps.pkg.staticSharedLibVersion);
3837        if (libEntry == null) {
3838            return false;
3839        }
3840
3841        final int resolvedUid = UserHandle.getUid(userId, UserHandle.getAppId(uid));
3842        final String[] uidPackageNames = getPackagesForUid(resolvedUid);
3843        if (uidPackageNames == null) {
3844            return true;
3845        }
3846
3847        for (String uidPackageName : uidPackageNames) {
3848            if (ps.name.equals(uidPackageName)) {
3849                return false;
3850            }
3851            PackageSetting uidPs = mSettings.getPackageLPr(uidPackageName);
3852            if (uidPs != null) {
3853                final int index = ArrayUtils.indexOf(uidPs.usesStaticLibraries,
3854                        libEntry.info.getName());
3855                if (index < 0) {
3856                    continue;
3857                }
3858                if (uidPs.pkg.usesStaticLibrariesVersions[index] == libEntry.info.getVersion()) {
3859                    return false;
3860                }
3861            }
3862        }
3863        return true;
3864    }
3865
3866    @Override
3867    public String[] currentToCanonicalPackageNames(String[] names) {
3868        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
3869            return names;
3870        }
3871        String[] out = new String[names.length];
3872        // reader
3873        synchronized (mPackages) {
3874            for (int i=names.length-1; i>=0; i--) {
3875                PackageSetting ps = mSettings.mPackages.get(names[i]);
3876                out[i] = ps != null && ps.realName != null ? ps.realName : names[i];
3877            }
3878        }
3879        return out;
3880    }
3881
3882    @Override
3883    public String[] canonicalToCurrentPackageNames(String[] names) {
3884        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
3885            return names;
3886        }
3887        String[] out = new String[names.length];
3888        // reader
3889        synchronized (mPackages) {
3890            for (int i=names.length-1; i>=0; i--) {
3891                String cur = mSettings.getRenamedPackageLPr(names[i]);
3892                out[i] = cur != null ? cur : names[i];
3893            }
3894        }
3895        return out;
3896    }
3897
3898    @Override
3899    public int getPackageUid(String packageName, int flags, int userId) {
3900        if (!sUserManager.exists(userId)) return -1;
3901        final int callingUid = Binder.getCallingUid();
3902        flags = updateFlagsForPackage(flags, userId, packageName);
3903        enforceCrossUserPermission(callingUid, userId,
3904                false /*requireFullPermission*/, false /*checkShell*/, "getPackageUid");
3905
3906        // reader
3907        synchronized (mPackages) {
3908            final PackageParser.Package p = mPackages.get(packageName);
3909            if (p != null && p.isMatch(flags)) {
3910                PackageSetting ps = (PackageSetting) p.mExtras;
3911                if (filterAppAccessLPr(ps, callingUid, userId)) {
3912                    return -1;
3913                }
3914                return UserHandle.getUid(userId, p.applicationInfo.uid);
3915            }
3916            if ((flags & MATCH_KNOWN_PACKAGES) != 0) {
3917                final PackageSetting ps = mSettings.mPackages.get(packageName);
3918                if (ps != null && ps.isMatch(flags)
3919                        && !filterAppAccessLPr(ps, callingUid, userId)) {
3920                    return UserHandle.getUid(userId, ps.appId);
3921                }
3922            }
3923        }
3924
3925        return -1;
3926    }
3927
3928    @Override
3929    public int[] getPackageGids(String packageName, int flags, int userId) {
3930        if (!sUserManager.exists(userId)) return null;
3931        final int callingUid = Binder.getCallingUid();
3932        flags = updateFlagsForPackage(flags, userId, packageName);
3933        enforceCrossUserPermission(callingUid, userId,
3934                false /*requireFullPermission*/, false /*checkShell*/, "getPackageGids");
3935
3936        // reader
3937        synchronized (mPackages) {
3938            final PackageParser.Package p = mPackages.get(packageName);
3939            if (p != null && p.isMatch(flags)) {
3940                PackageSetting ps = (PackageSetting) p.mExtras;
3941                if (filterAppAccessLPr(ps, callingUid, userId)) {
3942                    return null;
3943                }
3944                // TODO: Shouldn't this be checking for package installed state for userId and
3945                // return null?
3946                return ps.getPermissionsState().computeGids(userId);
3947            }
3948            if ((flags & MATCH_KNOWN_PACKAGES) != 0) {
3949                final PackageSetting ps = mSettings.mPackages.get(packageName);
3950                if (ps != null && ps.isMatch(flags)
3951                        && !filterAppAccessLPr(ps, callingUid, userId)) {
3952                    return ps.getPermissionsState().computeGids(userId);
3953                }
3954            }
3955        }
3956
3957        return null;
3958    }
3959
3960    static PermissionInfo generatePermissionInfo(BasePermission bp, int flags) {
3961        if (bp.perm != null) {
3962            return PackageParser.generatePermissionInfo(bp.perm, flags);
3963        }
3964        PermissionInfo pi = new PermissionInfo();
3965        pi.name = bp.name;
3966        pi.packageName = bp.sourcePackage;
3967        pi.nonLocalizedLabel = bp.name;
3968        pi.protectionLevel = bp.protectionLevel;
3969        return pi;
3970    }
3971
3972    @Override
3973    public PermissionInfo getPermissionInfo(String name, int flags) {
3974        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
3975            return null;
3976        }
3977        // reader
3978        synchronized (mPackages) {
3979            final BasePermission p = mSettings.mPermissions.get(name);
3980            if (p != null) {
3981                return generatePermissionInfo(p, flags);
3982            }
3983            return null;
3984        }
3985    }
3986
3987    @Override
3988    public @Nullable ParceledListSlice<PermissionInfo> queryPermissionsByGroup(String group,
3989            int flags) {
3990        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
3991            return null;
3992        }
3993        // reader
3994        synchronized (mPackages) {
3995            if (group != null && !mPermissionGroups.containsKey(group)) {
3996                // This is thrown as NameNotFoundException
3997                return null;
3998            }
3999
4000            ArrayList<PermissionInfo> out = new ArrayList<PermissionInfo>(10);
4001            for (BasePermission p : mSettings.mPermissions.values()) {
4002                if (group == null) {
4003                    if (p.perm == null || p.perm.info.group == null) {
4004                        out.add(generatePermissionInfo(p, flags));
4005                    }
4006                } else {
4007                    if (p.perm != null && group.equals(p.perm.info.group)) {
4008                        out.add(PackageParser.generatePermissionInfo(p.perm, flags));
4009                    }
4010                }
4011            }
4012            return new ParceledListSlice<>(out);
4013        }
4014    }
4015
4016    @Override
4017    public PermissionGroupInfo getPermissionGroupInfo(String name, int flags) {
4018        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
4019            return null;
4020        }
4021        // reader
4022        synchronized (mPackages) {
4023            return PackageParser.generatePermissionGroupInfo(
4024                    mPermissionGroups.get(name), flags);
4025        }
4026    }
4027
4028    @Override
4029    public @NonNull ParceledListSlice<PermissionGroupInfo> getAllPermissionGroups(int flags) {
4030        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
4031            return ParceledListSlice.emptyList();
4032        }
4033        // reader
4034        synchronized (mPackages) {
4035            final int N = mPermissionGroups.size();
4036            ArrayList<PermissionGroupInfo> out
4037                    = new ArrayList<PermissionGroupInfo>(N);
4038            for (PackageParser.PermissionGroup pg : mPermissionGroups.values()) {
4039                out.add(PackageParser.generatePermissionGroupInfo(pg, flags));
4040            }
4041            return new ParceledListSlice<>(out);
4042        }
4043    }
4044
4045    private ApplicationInfo generateApplicationInfoFromSettingsLPw(String packageName, int flags,
4046            int uid, int userId) {
4047        if (!sUserManager.exists(userId)) return null;
4048        PackageSetting ps = mSettings.mPackages.get(packageName);
4049        if (ps != null) {
4050            if (filterSharedLibPackageLPr(ps, uid, userId, flags)) {
4051                return null;
4052            }
4053            if (filterAppAccessLPr(ps, uid, userId)) {
4054                return null;
4055            }
4056            if (ps.pkg == null) {
4057                final PackageInfo pInfo = generatePackageInfo(ps, flags, userId);
4058                if (pInfo != null) {
4059                    return pInfo.applicationInfo;
4060                }
4061                return null;
4062            }
4063            ApplicationInfo ai = PackageParser.generateApplicationInfo(ps.pkg, flags,
4064                    ps.readUserState(userId), userId);
4065            if (ai != null) {
4066                rebaseEnabledOverlays(ai, userId);
4067                ai.packageName = resolveExternalPackageNameLPr(ps.pkg);
4068            }
4069            return ai;
4070        }
4071        return null;
4072    }
4073
4074    @Override
4075    public ApplicationInfo getApplicationInfo(String packageName, int flags, int userId) {
4076        if (!sUserManager.exists(userId)) return null;
4077        flags = updateFlagsForApplication(flags, userId, packageName);
4078        enforceCrossUserPermission(Binder.getCallingUid(), userId,
4079                false /* requireFullPermission */, false /* checkShell */, "get application info");
4080
4081        // writer
4082        synchronized (mPackages) {
4083            // Normalize package name to handle renamed packages and static libs
4084            packageName = resolveInternalPackageNameLPr(packageName,
4085                    PackageManager.VERSION_CODE_HIGHEST);
4086
4087            PackageParser.Package p = mPackages.get(packageName);
4088            if (DEBUG_PACKAGE_INFO) Log.v(
4089                    TAG, "getApplicationInfo " + packageName
4090                    + ": " + p);
4091            if (p != null) {
4092                PackageSetting ps = mSettings.mPackages.get(packageName);
4093                if (ps == null) return null;
4094                if (filterSharedLibPackageLPr(ps, Binder.getCallingUid(), userId, flags)) {
4095                    return null;
4096                }
4097                if (filterAppAccessLPr(ps, Binder.getCallingUid(), userId)) {
4098                    return null;
4099                }
4100                // Note: isEnabledLP() does not apply here - always return info
4101                ApplicationInfo ai = PackageParser.generateApplicationInfo(
4102                        p, flags, ps.readUserState(userId), userId);
4103                if (ai != null) {
4104                    rebaseEnabledOverlays(ai, userId);
4105                    ai.packageName = resolveExternalPackageNameLPr(p);
4106                }
4107                return ai;
4108            }
4109            if ("android".equals(packageName)||"system".equals(packageName)) {
4110                return mAndroidApplication;
4111            }
4112            if ((flags & MATCH_KNOWN_PACKAGES) != 0) {
4113                // Already generates the external package name
4114                return generateApplicationInfoFromSettingsLPw(packageName,
4115                        Binder.getCallingUid(), flags, userId);
4116            }
4117        }
4118        return null;
4119    }
4120
4121    private void rebaseEnabledOverlays(@NonNull ApplicationInfo ai, int userId) {
4122        List<String> paths = new ArrayList<>();
4123        ArrayMap<String, ArrayList<String>> userSpecificOverlays =
4124            mEnabledOverlayPaths.get(userId);
4125        if (userSpecificOverlays != null) {
4126            if (!"android".equals(ai.packageName)) {
4127                ArrayList<String> frameworkOverlays = userSpecificOverlays.get("android");
4128                if (frameworkOverlays != null) {
4129                    paths.addAll(frameworkOverlays);
4130                }
4131            }
4132
4133            ArrayList<String> appOverlays = userSpecificOverlays.get(ai.packageName);
4134            if (appOverlays != null) {
4135                paths.addAll(appOverlays);
4136            }
4137        }
4138        ai.resourceDirs = paths.size() > 0 ? paths.toArray(new String[paths.size()]) : null;
4139    }
4140
4141    private String normalizePackageNameLPr(String packageName) {
4142        String normalizedPackageName = mSettings.getRenamedPackageLPr(packageName);
4143        return normalizedPackageName != null ? normalizedPackageName : packageName;
4144    }
4145
4146    @Override
4147    public void deletePreloadsFileCache() {
4148        if (!UserHandle.isSameApp(Binder.getCallingUid(), Process.SYSTEM_UID)) {
4149            throw new SecurityException("Only system or settings may call deletePreloadsFileCache");
4150        }
4151        File dir = Environment.getDataPreloadsFileCacheDirectory();
4152        Slog.i(TAG, "Deleting preloaded file cache " + dir);
4153        FileUtils.deleteContents(dir);
4154    }
4155
4156    @Override
4157    public void freeStorageAndNotify(final String volumeUuid, final long freeStorageSize,
4158            final IPackageDataObserver observer) {
4159        mContext.enforceCallingOrSelfPermission(
4160                android.Manifest.permission.CLEAR_APP_CACHE, null);
4161        mHandler.post(() -> {
4162            boolean success = false;
4163            try {
4164                freeStorage(volumeUuid, freeStorageSize, 0);
4165                success = true;
4166            } catch (IOException e) {
4167                Slog.w(TAG, e);
4168            }
4169            if (observer != null) {
4170                try {
4171                    observer.onRemoveCompleted(null, success);
4172                } catch (RemoteException e) {
4173                    Slog.w(TAG, e);
4174                }
4175            }
4176        });
4177    }
4178
4179    @Override
4180    public void freeStorage(final String volumeUuid, final long freeStorageSize,
4181            final IntentSender pi) {
4182        mContext.enforceCallingOrSelfPermission(
4183                android.Manifest.permission.CLEAR_APP_CACHE, TAG);
4184        mHandler.post(() -> {
4185            boolean success = false;
4186            try {
4187                freeStorage(volumeUuid, freeStorageSize, 0);
4188                success = true;
4189            } catch (IOException e) {
4190                Slog.w(TAG, e);
4191            }
4192            if (pi != null) {
4193                try {
4194                    pi.sendIntent(null, success ? 1 : 0, null, null, null);
4195                } catch (SendIntentException e) {
4196                    Slog.w(TAG, e);
4197                }
4198            }
4199        });
4200    }
4201
4202    /**
4203     * Blocking call to clear various types of cached data across the system
4204     * until the requested bytes are available.
4205     */
4206    public void freeStorage(String volumeUuid, long bytes, int storageFlags) throws IOException {
4207        final StorageManager storage = mContext.getSystemService(StorageManager.class);
4208        final File file = storage.findPathForUuid(volumeUuid);
4209        if (file.getUsableSpace() >= bytes) return;
4210
4211        if (ENABLE_FREE_CACHE_V2) {
4212            final boolean aggressive = (storageFlags
4213                    & StorageManager.FLAG_ALLOCATE_AGGRESSIVE) != 0;
4214            final boolean internalVolume = Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL,
4215                    volumeUuid);
4216
4217            // 1. Pre-flight to determine if we have any chance to succeed
4218            // 2. Consider preloaded data (after 1w honeymoon, unless aggressive)
4219            if (internalVolume && (aggressive || SystemProperties
4220                    .getBoolean("persist.sys.preloads.file_cache_expired", false))) {
4221                deletePreloadsFileCache();
4222                if (file.getUsableSpace() >= bytes) return;
4223            }
4224
4225            // 3. Consider parsed APK data (aggressive only)
4226            if (internalVolume && aggressive) {
4227                FileUtils.deleteContents(mCacheDir);
4228                if (file.getUsableSpace() >= bytes) return;
4229            }
4230
4231            // 4. Consider cached app data (above quotas)
4232            try {
4233                mInstaller.freeCache(volumeUuid, bytes, Installer.FLAG_FREE_CACHE_V2);
4234            } catch (InstallerException ignored) {
4235            }
4236            if (file.getUsableSpace() >= bytes) return;
4237
4238            // 5. Consider shared libraries with refcount=0 and age>2h
4239            // 6. Consider dexopt output (aggressive only)
4240            // 7. Consider ephemeral apps not used in last week
4241
4242            // 8. Consider cached app data (below quotas)
4243            try {
4244                mInstaller.freeCache(volumeUuid, bytes, Installer.FLAG_FREE_CACHE_V2
4245                        | Installer.FLAG_FREE_CACHE_V2_DEFY_QUOTA);
4246            } catch (InstallerException ignored) {
4247            }
4248            if (file.getUsableSpace() >= bytes) return;
4249
4250            // 9. Consider DropBox entries
4251            // 10. Consider ephemeral cookies
4252
4253        } else {
4254            try {
4255                mInstaller.freeCache(volumeUuid, bytes, 0);
4256            } catch (InstallerException ignored) {
4257            }
4258            if (file.getUsableSpace() >= bytes) return;
4259        }
4260
4261        throw new IOException("Failed to free " + bytes + " on storage device at " + file);
4262    }
4263
4264    /**
4265     * Update given flags based on encryption status of current user.
4266     */
4267    private int updateFlags(int flags, int userId) {
4268        if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE
4269                | PackageManager.MATCH_DIRECT_BOOT_AWARE)) != 0) {
4270            // Caller expressed an explicit opinion about what encryption
4271            // aware/unaware components they want to see, so fall through and
4272            // give them what they want
4273        } else {
4274            // Caller expressed no opinion, so match based on user state
4275            if (getUserManagerInternal().isUserUnlockingOrUnlocked(userId)) {
4276                flags |= PackageManager.MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE;
4277            } else {
4278                flags |= PackageManager.MATCH_DIRECT_BOOT_AWARE;
4279            }
4280        }
4281        return flags;
4282    }
4283
4284    private UserManagerInternal getUserManagerInternal() {
4285        if (mUserManagerInternal == null) {
4286            mUserManagerInternal = LocalServices.getService(UserManagerInternal.class);
4287        }
4288        return mUserManagerInternal;
4289    }
4290
4291    private DeviceIdleController.LocalService getDeviceIdleController() {
4292        if (mDeviceIdleController == null) {
4293            mDeviceIdleController =
4294                    LocalServices.getService(DeviceIdleController.LocalService.class);
4295        }
4296        return mDeviceIdleController;
4297    }
4298
4299    /**
4300     * Update given flags when being used to request {@link PackageInfo}.
4301     */
4302    private int updateFlagsForPackage(int flags, int userId, Object cookie) {
4303        final boolean isCallerSystemUser = UserHandle.getCallingUserId() == UserHandle.USER_SYSTEM;
4304        boolean triaged = true;
4305        if ((flags & (PackageManager.GET_ACTIVITIES | PackageManager.GET_RECEIVERS
4306                | PackageManager.GET_SERVICES | PackageManager.GET_PROVIDERS)) != 0) {
4307            // Caller is asking for component details, so they'd better be
4308            // asking for specific encryption matching behavior, or be triaged
4309            if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE
4310                    | PackageManager.MATCH_DIRECT_BOOT_AWARE
4311                    | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) {
4312                triaged = false;
4313            }
4314        }
4315        if ((flags & (PackageManager.MATCH_UNINSTALLED_PACKAGES
4316                | PackageManager.MATCH_SYSTEM_ONLY
4317                | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) {
4318            triaged = false;
4319        }
4320        if ((flags & PackageManager.MATCH_ANY_USER) != 0) {
4321            enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false,
4322                    "MATCH_ANY_USER flag requires INTERACT_ACROSS_USERS permission at "
4323                    + Debug.getCallers(5));
4324        } else if ((flags & PackageManager.MATCH_UNINSTALLED_PACKAGES) != 0 && isCallerSystemUser
4325                && sUserManager.hasManagedProfile(UserHandle.USER_SYSTEM)) {
4326            // If the caller wants all packages and has a restricted profile associated with it,
4327            // then match all users. This is to make sure that launchers that need to access work
4328            // profile apps don't start breaking. TODO: Remove this hack when launchers stop using
4329            // MATCH_UNINSTALLED_PACKAGES to query apps in other profiles. b/31000380
4330            flags |= PackageManager.MATCH_ANY_USER;
4331        }
4332        if (DEBUG_TRIAGED_MISSING && (Binder.getCallingUid() == Process.SYSTEM_UID) && !triaged) {
4333            Log.w(TAG, "Caller hasn't been triaged for missing apps; they asked about " + cookie
4334                    + " with flags 0x" + Integer.toHexString(flags), new Throwable());
4335        }
4336        return updateFlags(flags, userId);
4337    }
4338
4339    /**
4340     * Update given flags when being used to request {@link ApplicationInfo}.
4341     */
4342    private int updateFlagsForApplication(int flags, int userId, Object cookie) {
4343        return updateFlagsForPackage(flags, userId, cookie);
4344    }
4345
4346    /**
4347     * Update given flags when being used to request {@link ComponentInfo}.
4348     */
4349    private int updateFlagsForComponent(int flags, int userId, Object cookie) {
4350        if (cookie instanceof Intent) {
4351            if ((((Intent) cookie).getFlags() & Intent.FLAG_DEBUG_TRIAGED_MISSING) != 0) {
4352                flags |= PackageManager.MATCH_DEBUG_TRIAGED_MISSING;
4353            }
4354        }
4355
4356        boolean triaged = true;
4357        // Caller is asking for component details, so they'd better be
4358        // asking for specific encryption matching behavior, or be triaged
4359        if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE
4360                | PackageManager.MATCH_DIRECT_BOOT_AWARE
4361                | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) {
4362            triaged = false;
4363        }
4364        if (DEBUG_TRIAGED_MISSING && (Binder.getCallingUid() == Process.SYSTEM_UID) && !triaged) {
4365            Log.w(TAG, "Caller hasn't been triaged for missing apps; they asked about " + cookie
4366                    + " with flags 0x" + Integer.toHexString(flags), new Throwable());
4367        }
4368
4369        return updateFlags(flags, userId);
4370    }
4371
4372    /**
4373     * Update given intent when being used to request {@link ResolveInfo}.
4374     */
4375    private Intent updateIntentForResolve(Intent intent) {
4376        if (intent.getSelector() != null) {
4377            intent = intent.getSelector();
4378        }
4379        if (DEBUG_PREFERRED) {
4380            intent.addFlags(Intent.FLAG_DEBUG_LOG_RESOLUTION);
4381        }
4382        return intent;
4383    }
4384
4385    /**
4386     * Update given flags when being used to request {@link ResolveInfo}.
4387     * <p>Instant apps are resolved specially, depending upon context. Minimally,
4388     * {@code}flags{@code} must have the {@link PackageManager#MATCH_INSTANT}
4389     * flag set. However, this flag is only honoured in three circumstances:
4390     * <ul>
4391     * <li>when called from a system process</li>
4392     * <li>when the caller holds the permission {@code android.permission.ACCESS_INSTANT_APPS}</li>
4393     * <li>when resolution occurs to start an activity with a {@code android.intent.action.VIEW}
4394     * action and a {@code android.intent.category.BROWSABLE} category</li>
4395     * </ul>
4396     */
4397    int updateFlagsForResolve(int flags, int userId, Intent intent, int callingUid) {
4398        return updateFlagsForResolve(flags, userId, intent, callingUid,
4399                false /*wantInstantApps*/, false /*onlyExposedExplicitly*/);
4400    }
4401    int updateFlagsForResolve(int flags, int userId, Intent intent, int callingUid,
4402            boolean wantInstantApps) {
4403        return updateFlagsForResolve(flags, userId, intent, callingUid,
4404                wantInstantApps, false /*onlyExposedExplicitly*/);
4405    }
4406    int updateFlagsForResolve(int flags, int userId, Intent intent, int callingUid,
4407            boolean wantInstantApps, boolean onlyExposedExplicitly) {
4408        // Safe mode means we shouldn't match any third-party components
4409        if (mSafeMode) {
4410            flags |= PackageManager.MATCH_SYSTEM_ONLY;
4411        }
4412        if (getInstantAppPackageName(callingUid) != null) {
4413            // But, ephemeral apps see both ephemeral and exposed, non-ephemeral components
4414            if (onlyExposedExplicitly) {
4415                flags |= PackageManager.MATCH_EXPLICITLY_VISIBLE_ONLY;
4416            }
4417            flags |= PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY;
4418            flags |= PackageManager.MATCH_INSTANT;
4419        } else {
4420            final boolean wantMatchInstant = (flags & PackageManager.MATCH_INSTANT) != 0;
4421            final boolean allowMatchInstant =
4422                    (wantInstantApps
4423                            && Intent.ACTION_VIEW.equals(intent.getAction())
4424                            && hasWebURI(intent))
4425                    || (wantMatchInstant && canViewInstantApps(callingUid, userId));
4426            flags &= ~(PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY
4427                    | PackageManager.MATCH_EXPLICITLY_VISIBLE_ONLY);
4428            if (!allowMatchInstant) {
4429                flags &= ~PackageManager.MATCH_INSTANT;
4430            }
4431        }
4432        return updateFlagsForComponent(flags, userId, intent /*cookie*/);
4433    }
4434
4435    private ActivityInfo generateActivityInfo(ActivityInfo ai, int flags, PackageUserState state,
4436            int userId) {
4437        ActivityInfo ret = PackageParser.generateActivityInfo(ai, flags, state, userId);
4438        if (ret != null) {
4439            rebaseEnabledOverlays(ret.applicationInfo, userId);
4440        }
4441        return ret;
4442    }
4443
4444    private ActivityInfo generateActivityInfo(PackageParser.Activity a, int flags,
4445            PackageUserState state, int userId) {
4446        ActivityInfo ai = PackageParser.generateActivityInfo(a, flags, state, userId);
4447        if (ai != null) {
4448            rebaseEnabledOverlays(ai.applicationInfo, userId);
4449        }
4450        return ai;
4451    }
4452
4453    @Override
4454    public ActivityInfo getActivityInfo(ComponentName component, int flags, int userId) {
4455        if (!sUserManager.exists(userId)) return null;
4456        final int callingUid = Binder.getCallingUid();
4457        flags = updateFlagsForComponent(flags, userId, component);
4458        enforceCrossUserPermission(callingUid, userId,
4459                false /* requireFullPermission */, false /* checkShell */, "get activity info");
4460        synchronized (mPackages) {
4461            PackageParser.Activity a = mActivities.mActivities.get(component);
4462
4463            if (DEBUG_PACKAGE_INFO) Log.v(TAG, "getActivityInfo " + component + ": " + a);
4464            if (a != null && mSettings.isEnabledAndMatchLPr(a.info, flags, userId)) {
4465                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
4466                if (ps == null) return null;
4467                if (filterAppAccessLPr(ps, callingUid, component, TYPE_ACTIVITY, userId)) {
4468                    return null;
4469                }
4470                return generateActivityInfo(a, flags, ps.readUserState(userId), userId);
4471            }
4472            if (mResolveComponentName.equals(component)) {
4473                return generateActivityInfo(mResolveActivity, flags, new PackageUserState(),
4474                        userId);
4475            }
4476        }
4477        return null;
4478    }
4479
4480    @Override
4481    public boolean activitySupportsIntent(ComponentName component, Intent intent,
4482            String resolvedType) {
4483        synchronized (mPackages) {
4484            if (component.equals(mResolveComponentName)) {
4485                // The resolver supports EVERYTHING!
4486                return true;
4487            }
4488            final int callingUid = Binder.getCallingUid();
4489            final int callingUserId = UserHandle.getUserId(callingUid);
4490            PackageParser.Activity a = mActivities.mActivities.get(component);
4491            if (a == null) {
4492                return false;
4493            }
4494            PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
4495            if (ps == null) {
4496                return false;
4497            }
4498            if (filterAppAccessLPr(ps, callingUid, component, TYPE_ACTIVITY, callingUserId)) {
4499                return false;
4500            }
4501            for (int i=0; i<a.intents.size(); i++) {
4502                if (a.intents.get(i).match(intent.getAction(), resolvedType, intent.getScheme(),
4503                        intent.getData(), intent.getCategories(), TAG) >= 0) {
4504                    return true;
4505                }
4506            }
4507            return false;
4508        }
4509    }
4510
4511    @Override
4512    public ActivityInfo getReceiverInfo(ComponentName component, int flags, int userId) {
4513        if (!sUserManager.exists(userId)) return null;
4514        final int callingUid = Binder.getCallingUid();
4515        flags = updateFlagsForComponent(flags, userId, component);
4516        enforceCrossUserPermission(callingUid, userId,
4517                false /* requireFullPermission */, false /* checkShell */, "get receiver info");
4518        synchronized (mPackages) {
4519            PackageParser.Activity a = mReceivers.mActivities.get(component);
4520            if (DEBUG_PACKAGE_INFO) Log.v(
4521                TAG, "getReceiverInfo " + component + ": " + a);
4522            if (a != null && mSettings.isEnabledAndMatchLPr(a.info, flags, userId)) {
4523                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
4524                if (ps == null) return null;
4525                if (filterAppAccessLPr(ps, callingUid, component, TYPE_RECEIVER, userId)) {
4526                    return null;
4527                }
4528                return generateActivityInfo(a, flags, ps.readUserState(userId), userId);
4529            }
4530        }
4531        return null;
4532    }
4533
4534    @Override
4535    public ParceledListSlice<SharedLibraryInfo> getSharedLibraries(String packageName,
4536            int flags, int userId) {
4537        if (!sUserManager.exists(userId)) return null;
4538        Preconditions.checkArgumentNonnegative(userId, "userId must be >= 0");
4539        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
4540            return null;
4541        }
4542
4543        flags = updateFlagsForPackage(flags, userId, null);
4544
4545        final boolean canSeeStaticLibraries =
4546                mContext.checkCallingOrSelfPermission(INSTALL_PACKAGES)
4547                        == PERMISSION_GRANTED
4548                || mContext.checkCallingOrSelfPermission(DELETE_PACKAGES)
4549                        == PERMISSION_GRANTED
4550                || canRequestPackageInstallsInternal(packageName,
4551                        PackageManager.MATCH_STATIC_SHARED_LIBRARIES, userId,
4552                        false  /* throwIfPermNotDeclared*/)
4553                || mContext.checkCallingOrSelfPermission(REQUEST_DELETE_PACKAGES)
4554                        == PERMISSION_GRANTED;
4555
4556        synchronized (mPackages) {
4557            List<SharedLibraryInfo> result = null;
4558
4559            final int libCount = mSharedLibraries.size();
4560            for (int i = 0; i < libCount; i++) {
4561                SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.valueAt(i);
4562                if (versionedLib == null) {
4563                    continue;
4564                }
4565
4566                final int versionCount = versionedLib.size();
4567                for (int j = 0; j < versionCount; j++) {
4568                    SharedLibraryInfo libInfo = versionedLib.valueAt(j).info;
4569                    if (!canSeeStaticLibraries && libInfo.isStatic()) {
4570                        break;
4571                    }
4572                    final long identity = Binder.clearCallingIdentity();
4573                    try {
4574                        PackageInfo packageInfo = getPackageInfoVersioned(
4575                                libInfo.getDeclaringPackage(), flags
4576                                        | PackageManager.MATCH_STATIC_SHARED_LIBRARIES, userId);
4577                        if (packageInfo == null) {
4578                            continue;
4579                        }
4580                    } finally {
4581                        Binder.restoreCallingIdentity(identity);
4582                    }
4583
4584                    SharedLibraryInfo resLibInfo = new SharedLibraryInfo(libInfo.getName(),
4585                            libInfo.getVersion(), libInfo.getType(),
4586                            libInfo.getDeclaringPackage(), getPackagesUsingSharedLibraryLPr(libInfo,
4587                            flags, userId));
4588
4589                    if (result == null) {
4590                        result = new ArrayList<>();
4591                    }
4592                    result.add(resLibInfo);
4593                }
4594            }
4595
4596            return result != null ? new ParceledListSlice<>(result) : null;
4597        }
4598    }
4599
4600    private List<VersionedPackage> getPackagesUsingSharedLibraryLPr(
4601            SharedLibraryInfo libInfo, int flags, int userId) {
4602        List<VersionedPackage> versionedPackages = null;
4603        final int packageCount = mSettings.mPackages.size();
4604        for (int i = 0; i < packageCount; i++) {
4605            PackageSetting ps = mSettings.mPackages.valueAt(i);
4606
4607            if (ps == null) {
4608                continue;
4609            }
4610
4611            if (!ps.getUserState().get(userId).isAvailable(flags)) {
4612                continue;
4613            }
4614
4615            final String libName = libInfo.getName();
4616            if (libInfo.isStatic()) {
4617                final int libIdx = ArrayUtils.indexOf(ps.usesStaticLibraries, libName);
4618                if (libIdx < 0) {
4619                    continue;
4620                }
4621                if (ps.usesStaticLibrariesVersions[libIdx] != libInfo.getVersion()) {
4622                    continue;
4623                }
4624                if (versionedPackages == null) {
4625                    versionedPackages = new ArrayList<>();
4626                }
4627                // If the dependent is a static shared lib, use the public package name
4628                String dependentPackageName = ps.name;
4629                if (ps.pkg != null && ps.pkg.applicationInfo.isStaticSharedLibrary()) {
4630                    dependentPackageName = ps.pkg.manifestPackageName;
4631                }
4632                versionedPackages.add(new VersionedPackage(dependentPackageName, ps.versionCode));
4633            } else if (ps.pkg != null) {
4634                if (ArrayUtils.contains(ps.pkg.usesLibraries, libName)
4635                        || ArrayUtils.contains(ps.pkg.usesOptionalLibraries, libName)) {
4636                    if (versionedPackages == null) {
4637                        versionedPackages = new ArrayList<>();
4638                    }
4639                    versionedPackages.add(new VersionedPackage(ps.name, ps.versionCode));
4640                }
4641            }
4642        }
4643
4644        return versionedPackages;
4645    }
4646
4647    @Override
4648    public ServiceInfo getServiceInfo(ComponentName component, int flags, int userId) {
4649        if (!sUserManager.exists(userId)) return null;
4650        final int callingUid = Binder.getCallingUid();
4651        flags = updateFlagsForComponent(flags, userId, component);
4652        enforceCrossUserPermission(callingUid, userId,
4653                false /* requireFullPermission */, false /* checkShell */, "get service info");
4654        synchronized (mPackages) {
4655            PackageParser.Service s = mServices.mServices.get(component);
4656            if (DEBUG_PACKAGE_INFO) Log.v(
4657                TAG, "getServiceInfo " + component + ": " + s);
4658            if (s != null && mSettings.isEnabledAndMatchLPr(s.info, flags, userId)) {
4659                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
4660                if (ps == null) return null;
4661                if (filterAppAccessLPr(ps, callingUid, component, TYPE_SERVICE, userId)) {
4662                    return null;
4663                }
4664                ServiceInfo si = PackageParser.generateServiceInfo(s, flags,
4665                        ps.readUserState(userId), userId);
4666                if (si != null) {
4667                    rebaseEnabledOverlays(si.applicationInfo, userId);
4668                }
4669                return si;
4670            }
4671        }
4672        return null;
4673    }
4674
4675    @Override
4676    public ProviderInfo getProviderInfo(ComponentName component, int flags, int userId) {
4677        if (!sUserManager.exists(userId)) return null;
4678        final int callingUid = Binder.getCallingUid();
4679        flags = updateFlagsForComponent(flags, userId, component);
4680        enforceCrossUserPermission(callingUid, userId,
4681                false /* requireFullPermission */, false /* checkShell */, "get provider info");
4682        synchronized (mPackages) {
4683            PackageParser.Provider p = mProviders.mProviders.get(component);
4684            if (DEBUG_PACKAGE_INFO) Log.v(
4685                TAG, "getProviderInfo " + component + ": " + p);
4686            if (p != null && mSettings.isEnabledAndMatchLPr(p.info, flags, userId)) {
4687                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
4688                if (ps == null) return null;
4689                if (filterAppAccessLPr(ps, callingUid, component, TYPE_PROVIDER, userId)) {
4690                    return null;
4691                }
4692                ProviderInfo pi = PackageParser.generateProviderInfo(p, flags,
4693                        ps.readUserState(userId), userId);
4694                if (pi != null) {
4695                    rebaseEnabledOverlays(pi.applicationInfo, userId);
4696                }
4697                return pi;
4698            }
4699        }
4700        return null;
4701    }
4702
4703    @Override
4704    public String[] getSystemSharedLibraryNames() {
4705        // allow instant applications
4706        synchronized (mPackages) {
4707            Set<String> libs = null;
4708            final int libCount = mSharedLibraries.size();
4709            for (int i = 0; i < libCount; i++) {
4710                SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.valueAt(i);
4711                if (versionedLib == null) {
4712                    continue;
4713                }
4714                final int versionCount = versionedLib.size();
4715                for (int j = 0; j < versionCount; j++) {
4716                    SharedLibraryEntry libEntry = versionedLib.valueAt(j);
4717                    if (!libEntry.info.isStatic()) {
4718                        if (libs == null) {
4719                            libs = new ArraySet<>();
4720                        }
4721                        libs.add(libEntry.info.getName());
4722                        break;
4723                    }
4724                    PackageSetting ps = mSettings.getPackageLPr(libEntry.apk);
4725                    if (ps != null && !filterSharedLibPackageLPr(ps, Binder.getCallingUid(),
4726                            UserHandle.getUserId(Binder.getCallingUid()),
4727                            PackageManager.MATCH_STATIC_SHARED_LIBRARIES)) {
4728                        if (libs == null) {
4729                            libs = new ArraySet<>();
4730                        }
4731                        libs.add(libEntry.info.getName());
4732                        break;
4733                    }
4734                }
4735            }
4736
4737            if (libs != null) {
4738                String[] libsArray = new String[libs.size()];
4739                libs.toArray(libsArray);
4740                return libsArray;
4741            }
4742
4743            return null;
4744        }
4745    }
4746
4747    @Override
4748    public @NonNull String getServicesSystemSharedLibraryPackageName() {
4749        // allow instant applications
4750        synchronized (mPackages) {
4751            return mServicesSystemSharedLibraryPackageName;
4752        }
4753    }
4754
4755    @Override
4756    public @NonNull String getSharedSystemSharedLibraryPackageName() {
4757        // allow instant applications
4758        synchronized (mPackages) {
4759            return mSharedSystemSharedLibraryPackageName;
4760        }
4761    }
4762
4763    private void updateSequenceNumberLP(String packageName, int[] userList) {
4764        for (int i = userList.length - 1; i >= 0; --i) {
4765            final int userId = userList[i];
4766            SparseArray<String> changedPackages = mChangedPackages.get(userId);
4767            if (changedPackages == null) {
4768                changedPackages = new SparseArray<>();
4769                mChangedPackages.put(userId, changedPackages);
4770            }
4771            Map<String, Integer> sequenceNumbers = mChangedPackagesSequenceNumbers.get(userId);
4772            if (sequenceNumbers == null) {
4773                sequenceNumbers = new HashMap<>();
4774                mChangedPackagesSequenceNumbers.put(userId, sequenceNumbers);
4775            }
4776            final Integer sequenceNumber = sequenceNumbers.get(packageName);
4777            if (sequenceNumber != null) {
4778                changedPackages.remove(sequenceNumber);
4779            }
4780            changedPackages.put(mChangedPackagesSequenceNumber, packageName);
4781            sequenceNumbers.put(packageName, mChangedPackagesSequenceNumber);
4782        }
4783        mChangedPackagesSequenceNumber++;
4784    }
4785
4786    @Override
4787    public ChangedPackages getChangedPackages(int sequenceNumber, int userId) {
4788        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
4789            return null;
4790        }
4791        synchronized (mPackages) {
4792            if (sequenceNumber >= mChangedPackagesSequenceNumber) {
4793                return null;
4794            }
4795            final SparseArray<String> changedPackages = mChangedPackages.get(userId);
4796            if (changedPackages == null) {
4797                return null;
4798            }
4799            final List<String> packageNames =
4800                    new ArrayList<>(mChangedPackagesSequenceNumber - sequenceNumber);
4801            for (int i = sequenceNumber; i < mChangedPackagesSequenceNumber; i++) {
4802                final String packageName = changedPackages.get(i);
4803                if (packageName != null) {
4804                    packageNames.add(packageName);
4805                }
4806            }
4807            return packageNames.isEmpty()
4808                    ? null : new ChangedPackages(mChangedPackagesSequenceNumber, packageNames);
4809        }
4810    }
4811
4812    @Override
4813    public @NonNull ParceledListSlice<FeatureInfo> getSystemAvailableFeatures() {
4814        // allow instant applications
4815        ArrayList<FeatureInfo> res;
4816        synchronized (mAvailableFeatures) {
4817            res = new ArrayList<>(mAvailableFeatures.size() + 1);
4818            res.addAll(mAvailableFeatures.values());
4819        }
4820        final FeatureInfo fi = new FeatureInfo();
4821        fi.reqGlEsVersion = SystemProperties.getInt("ro.opengles.version",
4822                FeatureInfo.GL_ES_VERSION_UNDEFINED);
4823        res.add(fi);
4824
4825        return new ParceledListSlice<>(res);
4826    }
4827
4828    @Override
4829    public boolean hasSystemFeature(String name, int version) {
4830        // allow instant applications
4831        synchronized (mAvailableFeatures) {
4832            final FeatureInfo feat = mAvailableFeatures.get(name);
4833            if (feat == null) {
4834                return false;
4835            } else {
4836                return feat.version >= version;
4837            }
4838        }
4839    }
4840
4841    @Override
4842    public int checkPermission(String permName, String pkgName, int userId) {
4843        if (!sUserManager.exists(userId)) {
4844            return PackageManager.PERMISSION_DENIED;
4845        }
4846        final int callingUid = Binder.getCallingUid();
4847
4848        synchronized (mPackages) {
4849            final PackageParser.Package p = mPackages.get(pkgName);
4850            if (p != null && p.mExtras != null) {
4851                final PackageSetting ps = (PackageSetting) p.mExtras;
4852                if (filterAppAccessLPr(ps, callingUid, userId)) {
4853                    return PackageManager.PERMISSION_DENIED;
4854                }
4855                final boolean instantApp = ps.getInstantApp(userId);
4856                final PermissionsState permissionsState = ps.getPermissionsState();
4857                if (permissionsState.hasPermission(permName, userId)) {
4858                    if (instantApp) {
4859                        BasePermission bp = mSettings.mPermissions.get(permName);
4860                        if (bp != null && bp.isInstant()) {
4861                            return PackageManager.PERMISSION_GRANTED;
4862                        }
4863                    } else {
4864                        return PackageManager.PERMISSION_GRANTED;
4865                    }
4866                }
4867                // Special case: ACCESS_FINE_LOCATION permission includes ACCESS_COARSE_LOCATION
4868                if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && permissionsState
4869                        .hasPermission(Manifest.permission.ACCESS_FINE_LOCATION, userId)) {
4870                    return PackageManager.PERMISSION_GRANTED;
4871                }
4872            }
4873        }
4874
4875        return PackageManager.PERMISSION_DENIED;
4876    }
4877
4878    @Override
4879    public int checkUidPermission(String permName, int uid) {
4880        final int callingUid = Binder.getCallingUid();
4881        final int callingUserId = UserHandle.getUserId(callingUid);
4882        final boolean isCallerInstantApp = getInstantAppPackageName(callingUid) != null;
4883        final boolean isUidInstantApp = getInstantAppPackageName(uid) != null;
4884        final int userId = UserHandle.getUserId(uid);
4885        if (!sUserManager.exists(userId)) {
4886            return PackageManager.PERMISSION_DENIED;
4887        }
4888
4889        synchronized (mPackages) {
4890            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
4891            if (obj != null) {
4892                if (obj instanceof SharedUserSetting) {
4893                    if (isCallerInstantApp) {
4894                        return PackageManager.PERMISSION_DENIED;
4895                    }
4896                } else if (obj instanceof PackageSetting) {
4897                    final PackageSetting ps = (PackageSetting) obj;
4898                    if (filterAppAccessLPr(ps, callingUid, callingUserId)) {
4899                        return PackageManager.PERMISSION_DENIED;
4900                    }
4901                }
4902                final SettingBase settingBase = (SettingBase) obj;
4903                final PermissionsState permissionsState = settingBase.getPermissionsState();
4904                if (permissionsState.hasPermission(permName, userId)) {
4905                    if (isUidInstantApp) {
4906                        BasePermission bp = mSettings.mPermissions.get(permName);
4907                        if (bp != null && bp.isInstant()) {
4908                            return PackageManager.PERMISSION_GRANTED;
4909                        }
4910                    } else {
4911                        return PackageManager.PERMISSION_GRANTED;
4912                    }
4913                }
4914                // Special case: ACCESS_FINE_LOCATION permission includes ACCESS_COARSE_LOCATION
4915                if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && permissionsState
4916                        .hasPermission(Manifest.permission.ACCESS_FINE_LOCATION, userId)) {
4917                    return PackageManager.PERMISSION_GRANTED;
4918                }
4919            } else {
4920                ArraySet<String> perms = mSystemPermissions.get(uid);
4921                if (perms != null) {
4922                    if (perms.contains(permName)) {
4923                        return PackageManager.PERMISSION_GRANTED;
4924                    }
4925                    if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && perms
4926                            .contains(Manifest.permission.ACCESS_FINE_LOCATION)) {
4927                        return PackageManager.PERMISSION_GRANTED;
4928                    }
4929                }
4930            }
4931        }
4932
4933        return PackageManager.PERMISSION_DENIED;
4934    }
4935
4936    @Override
4937    public boolean isPermissionRevokedByPolicy(String permission, String packageName, int userId) {
4938        if (UserHandle.getCallingUserId() != userId) {
4939            mContext.enforceCallingPermission(
4940                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
4941                    "isPermissionRevokedByPolicy for user " + userId);
4942        }
4943
4944        if (checkPermission(permission, packageName, userId)
4945                == PackageManager.PERMISSION_GRANTED) {
4946            return false;
4947        }
4948
4949        final int callingUid = Binder.getCallingUid();
4950        if (getInstantAppPackageName(callingUid) != null) {
4951            if (!isCallerSameApp(packageName, callingUid)) {
4952                return false;
4953            }
4954        } else {
4955            if (isInstantApp(packageName, userId)) {
4956                return false;
4957            }
4958        }
4959
4960        final long identity = Binder.clearCallingIdentity();
4961        try {
4962            final int flags = getPermissionFlags(permission, packageName, userId);
4963            return (flags & PackageManager.FLAG_PERMISSION_POLICY_FIXED) != 0;
4964        } finally {
4965            Binder.restoreCallingIdentity(identity);
4966        }
4967    }
4968
4969    @Override
4970    public String getPermissionControllerPackageName() {
4971        synchronized (mPackages) {
4972            return mRequiredInstallerPackage;
4973        }
4974    }
4975
4976    /**
4977     * Checks if the request is from the system or an app that has INTERACT_ACROSS_USERS
4978     * or INTERACT_ACROSS_USERS_FULL permissions, if the userid is not for the caller.
4979     * @param checkShell whether to prevent shell from access if there's a debugging restriction
4980     * @param message the message to log on security exception
4981     */
4982    void enforceCrossUserPermission(int callingUid, int userId, boolean requireFullPermission,
4983            boolean checkShell, String message) {
4984        if (userId < 0) {
4985            throw new IllegalArgumentException("Invalid userId " + userId);
4986        }
4987        if (checkShell) {
4988            enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, userId);
4989        }
4990        if (userId == UserHandle.getUserId(callingUid)) return;
4991        if (callingUid != Process.SYSTEM_UID && callingUid != 0) {
4992            if (requireFullPermission) {
4993                mContext.enforceCallingOrSelfPermission(
4994                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message);
4995            } else {
4996                try {
4997                    mContext.enforceCallingOrSelfPermission(
4998                            android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message);
4999                } catch (SecurityException se) {
5000                    mContext.enforceCallingOrSelfPermission(
5001                            android.Manifest.permission.INTERACT_ACROSS_USERS, message);
5002                }
5003            }
5004        }
5005    }
5006
5007    void enforceShellRestriction(String restriction, int callingUid, int userHandle) {
5008        if (callingUid == Process.SHELL_UID) {
5009            if (userHandle >= 0
5010                    && sUserManager.hasUserRestriction(restriction, userHandle)) {
5011                throw new SecurityException("Shell does not have permission to access user "
5012                        + userHandle);
5013            } else if (userHandle < 0) {
5014                Slog.e(TAG, "Unable to check shell permission for user " + userHandle + "\n\t"
5015                        + Debug.getCallers(3));
5016            }
5017        }
5018    }
5019
5020    private BasePermission findPermissionTreeLP(String permName) {
5021        for(BasePermission bp : mSettings.mPermissionTrees.values()) {
5022            if (permName.startsWith(bp.name) &&
5023                    permName.length() > bp.name.length() &&
5024                    permName.charAt(bp.name.length()) == '.') {
5025                return bp;
5026            }
5027        }
5028        return null;
5029    }
5030
5031    private BasePermission checkPermissionTreeLP(String permName) {
5032        if (permName != null) {
5033            BasePermission bp = findPermissionTreeLP(permName);
5034            if (bp != null) {
5035                if (bp.uid == UserHandle.getAppId(Binder.getCallingUid())) {
5036                    return bp;
5037                }
5038                throw new SecurityException("Calling uid "
5039                        + Binder.getCallingUid()
5040                        + " is not allowed to add to permission tree "
5041                        + bp.name + " owned by uid " + bp.uid);
5042            }
5043        }
5044        throw new SecurityException("No permission tree found for " + permName);
5045    }
5046
5047    static boolean compareStrings(CharSequence s1, CharSequence s2) {
5048        if (s1 == null) {
5049            return s2 == null;
5050        }
5051        if (s2 == null) {
5052            return false;
5053        }
5054        if (s1.getClass() != s2.getClass()) {
5055            return false;
5056        }
5057        return s1.equals(s2);
5058    }
5059
5060    static boolean comparePermissionInfos(PermissionInfo pi1, PermissionInfo pi2) {
5061        if (pi1.icon != pi2.icon) return false;
5062        if (pi1.logo != pi2.logo) return false;
5063        if (pi1.protectionLevel != pi2.protectionLevel) return false;
5064        if (!compareStrings(pi1.name, pi2.name)) return false;
5065        if (!compareStrings(pi1.nonLocalizedLabel, pi2.nonLocalizedLabel)) return false;
5066        // We'll take care of setting this one.
5067        if (!compareStrings(pi1.packageName, pi2.packageName)) return false;
5068        // These are not currently stored in settings.
5069        //if (!compareStrings(pi1.group, pi2.group)) return false;
5070        //if (!compareStrings(pi1.nonLocalizedDescription, pi2.nonLocalizedDescription)) return false;
5071        //if (pi1.labelRes != pi2.labelRes) return false;
5072        //if (pi1.descriptionRes != pi2.descriptionRes) return false;
5073        return true;
5074    }
5075
5076    int permissionInfoFootprint(PermissionInfo info) {
5077        int size = info.name.length();
5078        if (info.nonLocalizedLabel != null) size += info.nonLocalizedLabel.length();
5079        if (info.nonLocalizedDescription != null) size += info.nonLocalizedDescription.length();
5080        return size;
5081    }
5082
5083    int calculateCurrentPermissionFootprintLocked(BasePermission tree) {
5084        int size = 0;
5085        for (BasePermission perm : mSettings.mPermissions.values()) {
5086            if (perm.uid == tree.uid) {
5087                size += perm.name.length() + permissionInfoFootprint(perm.perm.info);
5088            }
5089        }
5090        return size;
5091    }
5092
5093    void enforcePermissionCapLocked(PermissionInfo info, BasePermission tree) {
5094        // We calculate the max size of permissions defined by this uid and throw
5095        // if that plus the size of 'info' would exceed our stated maximum.
5096        if (tree.uid != Process.SYSTEM_UID) {
5097            final int curTreeSize = calculateCurrentPermissionFootprintLocked(tree);
5098            if (curTreeSize + permissionInfoFootprint(info) > MAX_PERMISSION_TREE_FOOTPRINT) {
5099                throw new SecurityException("Permission tree size cap exceeded");
5100            }
5101        }
5102    }
5103
5104    boolean addPermissionLocked(PermissionInfo info, boolean async) {
5105        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
5106            throw new SecurityException("Instant apps can't add permissions");
5107        }
5108        if (info.labelRes == 0 && info.nonLocalizedLabel == null) {
5109            throw new SecurityException("Label must be specified in permission");
5110        }
5111        BasePermission tree = checkPermissionTreeLP(info.name);
5112        BasePermission bp = mSettings.mPermissions.get(info.name);
5113        boolean added = bp == null;
5114        boolean changed = true;
5115        int fixedLevel = PermissionInfo.fixProtectionLevel(info.protectionLevel);
5116        if (added) {
5117            enforcePermissionCapLocked(info, tree);
5118            bp = new BasePermission(info.name, tree.sourcePackage,
5119                    BasePermission.TYPE_DYNAMIC);
5120        } else if (bp.type != BasePermission.TYPE_DYNAMIC) {
5121            throw new SecurityException(
5122                    "Not allowed to modify non-dynamic permission "
5123                    + info.name);
5124        } else {
5125            if (bp.protectionLevel == fixedLevel
5126                    && bp.perm.owner.equals(tree.perm.owner)
5127                    && bp.uid == tree.uid
5128                    && comparePermissionInfos(bp.perm.info, info)) {
5129                changed = false;
5130            }
5131        }
5132        bp.protectionLevel = fixedLevel;
5133        info = new PermissionInfo(info);
5134        info.protectionLevel = fixedLevel;
5135        bp.perm = new PackageParser.Permission(tree.perm.owner, info);
5136        bp.perm.info.packageName = tree.perm.info.packageName;
5137        bp.uid = tree.uid;
5138        if (added) {
5139            mSettings.mPermissions.put(info.name, bp);
5140        }
5141        if (changed) {
5142            if (!async) {
5143                mSettings.writeLPr();
5144            } else {
5145                scheduleWriteSettingsLocked();
5146            }
5147        }
5148        return added;
5149    }
5150
5151    @Override
5152    public boolean addPermission(PermissionInfo info) {
5153        synchronized (mPackages) {
5154            return addPermissionLocked(info, false);
5155        }
5156    }
5157
5158    @Override
5159    public boolean addPermissionAsync(PermissionInfo info) {
5160        synchronized (mPackages) {
5161            return addPermissionLocked(info, true);
5162        }
5163    }
5164
5165    @Override
5166    public void removePermission(String name) {
5167        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
5168            throw new SecurityException("Instant applications don't have access to this method");
5169        }
5170        synchronized (mPackages) {
5171            checkPermissionTreeLP(name);
5172            BasePermission bp = mSettings.mPermissions.get(name);
5173            if (bp != null) {
5174                if (bp.type != BasePermission.TYPE_DYNAMIC) {
5175                    throw new SecurityException(
5176                            "Not allowed to modify non-dynamic permission "
5177                            + name);
5178                }
5179                mSettings.mPermissions.remove(name);
5180                mSettings.writeLPr();
5181            }
5182        }
5183    }
5184
5185    private static void enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(
5186            PackageParser.Package pkg, BasePermission bp) {
5187        int index = pkg.requestedPermissions.indexOf(bp.name);
5188        if (index == -1) {
5189            throw new SecurityException("Package " + pkg.packageName
5190                    + " has not requested permission " + bp.name);
5191        }
5192        if (!bp.isRuntime() && !bp.isDevelopment()) {
5193            throw new SecurityException("Permission " + bp.name
5194                    + " is not a changeable permission type");
5195        }
5196    }
5197
5198    @Override
5199    public void grantRuntimePermission(String packageName, String name, final int userId) {
5200        grantRuntimePermission(packageName, name, userId, false /* Only if not fixed by policy */);
5201    }
5202
5203    private void grantRuntimePermission(String packageName, String name, final int userId,
5204            boolean overridePolicy) {
5205        if (!sUserManager.exists(userId)) {
5206            Log.e(TAG, "No such user:" + userId);
5207            return;
5208        }
5209
5210        mContext.enforceCallingOrSelfPermission(
5211                android.Manifest.permission.GRANT_RUNTIME_PERMISSIONS,
5212                "grantRuntimePermission");
5213
5214        enforceCrossUserPermission(Binder.getCallingUid(), userId,
5215                true /* requireFullPermission */, true /* checkShell */,
5216                "grantRuntimePermission");
5217
5218        final int uid;
5219        final SettingBase sb;
5220
5221        synchronized (mPackages) {
5222            final PackageParser.Package pkg = mPackages.get(packageName);
5223            if (pkg == null) {
5224                throw new IllegalArgumentException("Unknown package: " + packageName);
5225            }
5226
5227            final BasePermission bp = mSettings.mPermissions.get(name);
5228            if (bp == null) {
5229                throw new IllegalArgumentException("Unknown permission: " + name);
5230            }
5231
5232            enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(pkg, bp);
5233
5234            // If a permission review is required for legacy apps we represent
5235            // their permissions as always granted runtime ones since we need
5236            // to keep the review required permission flag per user while an
5237            // install permission's state is shared across all users.
5238            if (mPermissionReviewRequired
5239                    && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M
5240                    && bp.isRuntime()) {
5241                return;
5242            }
5243
5244            uid = UserHandle.getUid(userId, pkg.applicationInfo.uid);
5245            sb = (SettingBase) pkg.mExtras;
5246            if (sb == null) {
5247                throw new IllegalArgumentException("Unknown package: " + packageName);
5248            }
5249
5250            final PermissionsState permissionsState = sb.getPermissionsState();
5251
5252            final int flags = permissionsState.getPermissionFlags(name, userId);
5253            if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) {
5254                throw new SecurityException("Cannot grant system fixed permission "
5255                        + name + " for package " + packageName);
5256            }
5257            if (!overridePolicy && (flags & PackageManager.FLAG_PERMISSION_POLICY_FIXED) != 0) {
5258                throw new SecurityException("Cannot grant policy fixed permission "
5259                        + name + " for package " + packageName);
5260            }
5261
5262            if (bp.isDevelopment()) {
5263                // Development permissions must be handled specially, since they are not
5264                // normal runtime permissions.  For now they apply to all users.
5265                if (permissionsState.grantInstallPermission(bp) !=
5266                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
5267                    scheduleWriteSettingsLocked();
5268                }
5269                return;
5270            }
5271
5272            final PackageSetting ps = mSettings.mPackages.get(packageName);
5273            if (ps.getInstantApp(userId) && !bp.isInstant()) {
5274                throw new SecurityException("Cannot grant non-ephemeral permission"
5275                        + name + " for package " + packageName);
5276            }
5277
5278            if (pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) {
5279                Slog.w(TAG, "Cannot grant runtime permission to a legacy app");
5280                return;
5281            }
5282
5283            final int result = permissionsState.grantRuntimePermission(bp, userId);
5284            switch (result) {
5285                case PermissionsState.PERMISSION_OPERATION_FAILURE: {
5286                    return;
5287                }
5288
5289                case PermissionsState.PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: {
5290                    final int appId = UserHandle.getAppId(pkg.applicationInfo.uid);
5291                    mHandler.post(new Runnable() {
5292                        @Override
5293                        public void run() {
5294                            killUid(appId, userId, KILL_APP_REASON_GIDS_CHANGED);
5295                        }
5296                    });
5297                }
5298                break;
5299            }
5300
5301            if (bp.isRuntime()) {
5302                logPermissionGranted(mContext, name, packageName);
5303            }
5304
5305            mOnPermissionChangeListeners.onPermissionsChanged(uid);
5306
5307            // Not critical if that is lost - app has to request again.
5308            mSettings.writeRuntimePermissionsForUserLPr(userId, false);
5309        }
5310
5311        // Only need to do this if user is initialized. Otherwise it's a new user
5312        // and there are no processes running as the user yet and there's no need
5313        // to make an expensive call to remount processes for the changed permissions.
5314        if (READ_EXTERNAL_STORAGE.equals(name)
5315                || WRITE_EXTERNAL_STORAGE.equals(name)) {
5316            final long token = Binder.clearCallingIdentity();
5317            try {
5318                if (sUserManager.isInitialized(userId)) {
5319                    StorageManagerInternal storageManagerInternal = LocalServices.getService(
5320                            StorageManagerInternal.class);
5321                    storageManagerInternal.onExternalStoragePolicyChanged(uid, packageName);
5322                }
5323            } finally {
5324                Binder.restoreCallingIdentity(token);
5325            }
5326        }
5327    }
5328
5329    @Override
5330    public void revokeRuntimePermission(String packageName, String name, int userId) {
5331        revokeRuntimePermission(packageName, name, userId, false /* Only if not fixed by policy */);
5332    }
5333
5334    private void revokeRuntimePermission(String packageName, String name, int userId,
5335            boolean overridePolicy) {
5336        if (!sUserManager.exists(userId)) {
5337            Log.e(TAG, "No such user:" + userId);
5338            return;
5339        }
5340
5341        mContext.enforceCallingOrSelfPermission(
5342                android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS,
5343                "revokeRuntimePermission");
5344
5345        enforceCrossUserPermission(Binder.getCallingUid(), userId,
5346                true /* requireFullPermission */, true /* checkShell */,
5347                "revokeRuntimePermission");
5348
5349        final int appId;
5350
5351        synchronized (mPackages) {
5352            final PackageParser.Package pkg = mPackages.get(packageName);
5353            if (pkg == null) {
5354                throw new IllegalArgumentException("Unknown package: " + packageName);
5355            }
5356
5357            final BasePermission bp = mSettings.mPermissions.get(name);
5358            if (bp == null) {
5359                throw new IllegalArgumentException("Unknown permission: " + name);
5360            }
5361
5362            enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(pkg, bp);
5363
5364            // If a permission review is required for legacy apps we represent
5365            // their permissions as always granted runtime ones since we need
5366            // to keep the review required permission flag per user while an
5367            // install permission's state is shared across all users.
5368            if (mPermissionReviewRequired
5369                    && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M
5370                    && bp.isRuntime()) {
5371                return;
5372            }
5373
5374            SettingBase sb = (SettingBase) pkg.mExtras;
5375            if (sb == null) {
5376                throw new IllegalArgumentException("Unknown package: " + packageName);
5377            }
5378
5379            final PermissionsState permissionsState = sb.getPermissionsState();
5380
5381            final int flags = permissionsState.getPermissionFlags(name, userId);
5382            if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) {
5383                throw new SecurityException("Cannot revoke system fixed permission "
5384                        + name + " for package " + packageName);
5385            }
5386            if (!overridePolicy && (flags & PackageManager.FLAG_PERMISSION_POLICY_FIXED) != 0) {
5387                throw new SecurityException("Cannot revoke policy fixed permission "
5388                        + name + " for package " + packageName);
5389            }
5390
5391            if (bp.isDevelopment()) {
5392                // Development permissions must be handled specially, since they are not
5393                // normal runtime permissions.  For now they apply to all users.
5394                if (permissionsState.revokeInstallPermission(bp) !=
5395                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
5396                    scheduleWriteSettingsLocked();
5397                }
5398                return;
5399            }
5400
5401            if (permissionsState.revokeRuntimePermission(bp, userId) ==
5402                    PermissionsState.PERMISSION_OPERATION_FAILURE) {
5403                return;
5404            }
5405
5406            if (bp.isRuntime()) {
5407                logPermissionRevoked(mContext, name, packageName);
5408            }
5409
5410            mOnPermissionChangeListeners.onPermissionsChanged(pkg.applicationInfo.uid);
5411
5412            // Critical, after this call app should never have the permission.
5413            mSettings.writeRuntimePermissionsForUserLPr(userId, true);
5414
5415            appId = UserHandle.getAppId(pkg.applicationInfo.uid);
5416        }
5417
5418        killUid(appId, userId, KILL_APP_REASON_PERMISSIONS_REVOKED);
5419    }
5420
5421    /**
5422     * Get the first event id for the permission.
5423     *
5424     * <p>There are four events for each permission: <ul>
5425     *     <li>Request permission: first id + 0</li>
5426     *     <li>Grant permission: first id + 1</li>
5427     *     <li>Request for permission denied: first id + 2</li>
5428     *     <li>Revoke permission: first id + 3</li>
5429     * </ul></p>
5430     *
5431     * @param name name of the permission
5432     *
5433     * @return The first event id for the permission
5434     */
5435    private static int getBaseEventId(@NonNull String name) {
5436        int eventIdIndex = ALL_DANGEROUS_PERMISSIONS.indexOf(name);
5437
5438        if (eventIdIndex == -1) {
5439            if (AppOpsManager.permissionToOpCode(name) == AppOpsManager.OP_NONE
5440                    || "user".equals(Build.TYPE)) {
5441                Log.i(TAG, "Unknown permission " + name);
5442
5443                return MetricsEvent.ACTION_PERMISSION_REQUEST_UNKNOWN;
5444            } else {
5445                // Most likely #ALL_DANGEROUS_PERMISSIONS needs to be updated.
5446                //
5447                // Also update
5448                // - EventLogger#ALL_DANGEROUS_PERMISSIONS
5449                // - metrics_constants.proto
5450                throw new IllegalStateException("Unknown permission " + name);
5451            }
5452        }
5453
5454        return MetricsEvent.ACTION_PERMISSION_REQUEST_READ_CALENDAR + eventIdIndex * 4;
5455    }
5456
5457    /**
5458     * Log that a permission was revoked.
5459     *
5460     * @param context Context of the caller
5461     * @param name name of the permission
5462     * @param packageName package permission if for
5463     */
5464    private static void logPermissionRevoked(@NonNull Context context, @NonNull String name,
5465            @NonNull String packageName) {
5466        MetricsLogger.action(context, getBaseEventId(name) + 3, packageName);
5467    }
5468
5469    /**
5470     * Log that a permission request was granted.
5471     *
5472     * @param context Context of the caller
5473     * @param name name of the permission
5474     * @param packageName package permission if for
5475     */
5476    private static void logPermissionGranted(@NonNull Context context, @NonNull String name,
5477            @NonNull String packageName) {
5478        MetricsLogger.action(context, getBaseEventId(name) + 1, packageName);
5479    }
5480
5481    @Override
5482    public void resetRuntimePermissions() {
5483        mContext.enforceCallingOrSelfPermission(
5484                android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS,
5485                "revokeRuntimePermission");
5486
5487        int callingUid = Binder.getCallingUid();
5488        if (callingUid != Process.SYSTEM_UID && callingUid != 0) {
5489            mContext.enforceCallingOrSelfPermission(
5490                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
5491                    "resetRuntimePermissions");
5492        }
5493
5494        synchronized (mPackages) {
5495            updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL);
5496            for (int userId : UserManagerService.getInstance().getUserIds()) {
5497                final int packageCount = mPackages.size();
5498                for (int i = 0; i < packageCount; i++) {
5499                    PackageParser.Package pkg = mPackages.valueAt(i);
5500                    if (!(pkg.mExtras instanceof PackageSetting)) {
5501                        continue;
5502                    }
5503                    PackageSetting ps = (PackageSetting) pkg.mExtras;
5504                    resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
5505                }
5506            }
5507        }
5508    }
5509
5510    @Override
5511    public int getPermissionFlags(String name, String packageName, int userId) {
5512        if (!sUserManager.exists(userId)) {
5513            return 0;
5514        }
5515
5516        enforceGrantRevokeRuntimePermissionPermissions("getPermissionFlags");
5517
5518        enforceCrossUserPermission(Binder.getCallingUid(), userId,
5519                true /* requireFullPermission */, false /* checkShell */,
5520                "getPermissionFlags");
5521
5522        synchronized (mPackages) {
5523            final PackageParser.Package pkg = mPackages.get(packageName);
5524            if (pkg == null) {
5525                return 0;
5526            }
5527
5528            final BasePermission bp = mSettings.mPermissions.get(name);
5529            if (bp == null) {
5530                return 0;
5531            }
5532
5533            SettingBase sb = (SettingBase) pkg.mExtras;
5534            if (sb == null) {
5535                return 0;
5536            }
5537
5538            PermissionsState permissionsState = sb.getPermissionsState();
5539            return permissionsState.getPermissionFlags(name, userId);
5540        }
5541    }
5542
5543    @Override
5544    public void updatePermissionFlags(String name, String packageName, int flagMask,
5545            int flagValues, int userId) {
5546        if (!sUserManager.exists(userId)) {
5547            return;
5548        }
5549
5550        enforceGrantRevokeRuntimePermissionPermissions("updatePermissionFlags");
5551
5552        enforceCrossUserPermission(Binder.getCallingUid(), userId,
5553                true /* requireFullPermission */, true /* checkShell */,
5554                "updatePermissionFlags");
5555
5556        // Only the system can change these flags and nothing else.
5557        if (getCallingUid() != Process.SYSTEM_UID) {
5558            flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
5559            flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
5560            flagMask &= ~PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT;
5561            flagValues &= ~PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT;
5562            flagValues &= ~PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED;
5563        }
5564
5565        synchronized (mPackages) {
5566            final PackageParser.Package pkg = mPackages.get(packageName);
5567            if (pkg == null) {
5568                throw new IllegalArgumentException("Unknown package: " + packageName);
5569            }
5570
5571            final BasePermission bp = mSettings.mPermissions.get(name);
5572            if (bp == null) {
5573                throw new IllegalArgumentException("Unknown permission: " + name);
5574            }
5575
5576            SettingBase sb = (SettingBase) pkg.mExtras;
5577            if (sb == null) {
5578                throw new IllegalArgumentException("Unknown package: " + packageName);
5579            }
5580
5581            PermissionsState permissionsState = sb.getPermissionsState();
5582
5583            boolean hadState = permissionsState.getRuntimePermissionState(name, userId) != null;
5584
5585            if (permissionsState.updatePermissionFlags(bp, userId, flagMask, flagValues)) {
5586                // Install and runtime permissions are stored in different places,
5587                // so figure out what permission changed and persist the change.
5588                if (permissionsState.getInstallPermissionState(name) != null) {
5589                    scheduleWriteSettingsLocked();
5590                } else if (permissionsState.getRuntimePermissionState(name, userId) != null
5591                        || hadState) {
5592                    mSettings.writeRuntimePermissionsForUserLPr(userId, false);
5593                }
5594            }
5595        }
5596    }
5597
5598    /**
5599     * Update the permission flags for all packages and runtime permissions of a user in order
5600     * to allow device or profile owner to remove POLICY_FIXED.
5601     */
5602    @Override
5603    public void updatePermissionFlagsForAllApps(int flagMask, int flagValues, int userId) {
5604        if (!sUserManager.exists(userId)) {
5605            return;
5606        }
5607
5608        enforceGrantRevokeRuntimePermissionPermissions("updatePermissionFlagsForAllApps");
5609
5610        enforceCrossUserPermission(Binder.getCallingUid(), userId,
5611                true /* requireFullPermission */, true /* checkShell */,
5612                "updatePermissionFlagsForAllApps");
5613
5614        // Only the system can change system fixed flags.
5615        if (getCallingUid() != Process.SYSTEM_UID) {
5616            flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
5617            flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
5618        }
5619
5620        synchronized (mPackages) {
5621            boolean changed = false;
5622            final int packageCount = mPackages.size();
5623            for (int pkgIndex = 0; pkgIndex < packageCount; pkgIndex++) {
5624                final PackageParser.Package pkg = mPackages.valueAt(pkgIndex);
5625                SettingBase sb = (SettingBase) pkg.mExtras;
5626                if (sb == null) {
5627                    continue;
5628                }
5629                PermissionsState permissionsState = sb.getPermissionsState();
5630                changed |= permissionsState.updatePermissionFlagsForAllPermissions(
5631                        userId, flagMask, flagValues);
5632            }
5633            if (changed) {
5634                mSettings.writeRuntimePermissionsForUserLPr(userId, false);
5635            }
5636        }
5637    }
5638
5639    private void enforceGrantRevokeRuntimePermissionPermissions(String message) {
5640        if (mContext.checkCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS)
5641                != PackageManager.PERMISSION_GRANTED
5642            && mContext.checkCallingOrSelfPermission(Manifest.permission.REVOKE_RUNTIME_PERMISSIONS)
5643                != PackageManager.PERMISSION_GRANTED) {
5644            throw new SecurityException(message + " requires "
5645                    + Manifest.permission.GRANT_RUNTIME_PERMISSIONS + " or "
5646                    + Manifest.permission.REVOKE_RUNTIME_PERMISSIONS);
5647        }
5648    }
5649
5650    @Override
5651    public boolean shouldShowRequestPermissionRationale(String permissionName,
5652            String packageName, int userId) {
5653        if (UserHandle.getCallingUserId() != userId) {
5654            mContext.enforceCallingPermission(
5655                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
5656                    "canShowRequestPermissionRationale for user " + userId);
5657        }
5658
5659        final int uid = getPackageUid(packageName, MATCH_DEBUG_TRIAGED_MISSING, userId);
5660        if (UserHandle.getAppId(getCallingUid()) != UserHandle.getAppId(uid)) {
5661            return false;
5662        }
5663
5664        if (checkPermission(permissionName, packageName, userId)
5665                == PackageManager.PERMISSION_GRANTED) {
5666            return false;
5667        }
5668
5669        final int flags;
5670
5671        final long identity = Binder.clearCallingIdentity();
5672        try {
5673            flags = getPermissionFlags(permissionName,
5674                    packageName, userId);
5675        } finally {
5676            Binder.restoreCallingIdentity(identity);
5677        }
5678
5679        final int fixedFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED
5680                | PackageManager.FLAG_PERMISSION_POLICY_FIXED
5681                | PackageManager.FLAG_PERMISSION_USER_FIXED;
5682
5683        if ((flags & fixedFlags) != 0) {
5684            return false;
5685        }
5686
5687        return (flags & PackageManager.FLAG_PERMISSION_USER_SET) != 0;
5688    }
5689
5690    @Override
5691    public void addOnPermissionsChangeListener(IOnPermissionsChangeListener listener) {
5692        mContext.enforceCallingOrSelfPermission(
5693                Manifest.permission.OBSERVE_GRANT_REVOKE_PERMISSIONS,
5694                "addOnPermissionsChangeListener");
5695
5696        synchronized (mPackages) {
5697            mOnPermissionChangeListeners.addListenerLocked(listener);
5698        }
5699    }
5700
5701    @Override
5702    public void removeOnPermissionsChangeListener(IOnPermissionsChangeListener listener) {
5703        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
5704            throw new SecurityException("Instant applications don't have access to this method");
5705        }
5706        synchronized (mPackages) {
5707            mOnPermissionChangeListeners.removeListenerLocked(listener);
5708        }
5709    }
5710
5711    @Override
5712    public boolean isProtectedBroadcast(String actionName) {
5713        // allow instant applications
5714        synchronized (mPackages) {
5715            if (mProtectedBroadcasts.contains(actionName)) {
5716                return true;
5717            } else if (actionName != null) {
5718                // TODO: remove these terrible hacks
5719                if (actionName.startsWith("android.net.netmon.lingerExpired")
5720                        || actionName.startsWith("com.android.server.sip.SipWakeupTimer")
5721                        || actionName.startsWith("com.android.internal.telephony.data-reconnect")
5722                        || actionName.startsWith("android.net.netmon.launchCaptivePortalApp")) {
5723                    return true;
5724                }
5725            }
5726        }
5727        return false;
5728    }
5729
5730    @Override
5731    public int checkSignatures(String pkg1, String pkg2) {
5732        synchronized (mPackages) {
5733            final PackageParser.Package p1 = mPackages.get(pkg1);
5734            final PackageParser.Package p2 = mPackages.get(pkg2);
5735            if (p1 == null || p1.mExtras == null
5736                    || p2 == null || p2.mExtras == null) {
5737                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5738            }
5739            final int callingUid = Binder.getCallingUid();
5740            final int callingUserId = UserHandle.getUserId(callingUid);
5741            final PackageSetting ps1 = (PackageSetting) p1.mExtras;
5742            final PackageSetting ps2 = (PackageSetting) p2.mExtras;
5743            if (filterAppAccessLPr(ps1, callingUid, callingUserId)
5744                    || filterAppAccessLPr(ps2, callingUid, callingUserId)) {
5745                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5746            }
5747            return compareSignatures(p1.mSignatures, p2.mSignatures);
5748        }
5749    }
5750
5751    @Override
5752    public int checkUidSignatures(int uid1, int uid2) {
5753        final int callingUid = Binder.getCallingUid();
5754        final int callingUserId = UserHandle.getUserId(callingUid);
5755        final boolean isCallerInstantApp = getInstantAppPackageName(callingUid) != null;
5756        // Map to base uids.
5757        uid1 = UserHandle.getAppId(uid1);
5758        uid2 = UserHandle.getAppId(uid2);
5759        // reader
5760        synchronized (mPackages) {
5761            Signature[] s1;
5762            Signature[] s2;
5763            Object obj = mSettings.getUserIdLPr(uid1);
5764            if (obj != null) {
5765                if (obj instanceof SharedUserSetting) {
5766                    if (isCallerInstantApp) {
5767                        return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5768                    }
5769                    s1 = ((SharedUserSetting)obj).signatures.mSignatures;
5770                } else if (obj instanceof PackageSetting) {
5771                    final PackageSetting ps = (PackageSetting) obj;
5772                    if (filterAppAccessLPr(ps, callingUid, callingUserId)) {
5773                        return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5774                    }
5775                    s1 = ps.signatures.mSignatures;
5776                } else {
5777                    return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5778                }
5779            } else {
5780                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5781            }
5782            obj = mSettings.getUserIdLPr(uid2);
5783            if (obj != null) {
5784                if (obj instanceof SharedUserSetting) {
5785                    if (isCallerInstantApp) {
5786                        return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5787                    }
5788                    s2 = ((SharedUserSetting)obj).signatures.mSignatures;
5789                } else if (obj instanceof PackageSetting) {
5790                    final PackageSetting ps = (PackageSetting) obj;
5791                    if (filterAppAccessLPr(ps, callingUid, callingUserId)) {
5792                        return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5793                    }
5794                    s2 = ps.signatures.mSignatures;
5795                } else {
5796                    return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5797                }
5798            } else {
5799                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5800            }
5801            return compareSignatures(s1, s2);
5802        }
5803    }
5804
5805    /**
5806     * This method should typically only be used when granting or revoking
5807     * permissions, since the app may immediately restart after this call.
5808     * <p>
5809     * If you're doing surgery on app code/data, use {@link PackageFreezer} to
5810     * guard your work against the app being relaunched.
5811     */
5812    private void killUid(int appId, int userId, String reason) {
5813        final long identity = Binder.clearCallingIdentity();
5814        try {
5815            IActivityManager am = ActivityManager.getService();
5816            if (am != null) {
5817                try {
5818                    am.killUid(appId, userId, reason);
5819                } catch (RemoteException e) {
5820                    /* ignore - same process */
5821                }
5822            }
5823        } finally {
5824            Binder.restoreCallingIdentity(identity);
5825        }
5826    }
5827
5828    /**
5829     * Compares two sets of signatures. Returns:
5830     * <br />
5831     * {@link PackageManager#SIGNATURE_NEITHER_SIGNED}: if both signature sets are null,
5832     * <br />
5833     * {@link PackageManager#SIGNATURE_FIRST_NOT_SIGNED}: if the first signature set is null,
5834     * <br />
5835     * {@link PackageManager#SIGNATURE_SECOND_NOT_SIGNED}: if the second signature set is null,
5836     * <br />
5837     * {@link PackageManager#SIGNATURE_MATCH}: if the two signature sets are identical,
5838     * <br />
5839     * {@link PackageManager#SIGNATURE_NO_MATCH}: if the two signature sets differ.
5840     */
5841    static int compareSignatures(Signature[] s1, Signature[] s2) {
5842        if (s1 == null) {
5843            return s2 == null
5844                    ? PackageManager.SIGNATURE_NEITHER_SIGNED
5845                    : PackageManager.SIGNATURE_FIRST_NOT_SIGNED;
5846        }
5847
5848        if (s2 == null) {
5849            return PackageManager.SIGNATURE_SECOND_NOT_SIGNED;
5850        }
5851
5852        if (s1.length != s2.length) {
5853            return PackageManager.SIGNATURE_NO_MATCH;
5854        }
5855
5856        // Since both signature sets are of size 1, we can compare without HashSets.
5857        if (s1.length == 1) {
5858            return s1[0].equals(s2[0]) ?
5859                    PackageManager.SIGNATURE_MATCH :
5860                    PackageManager.SIGNATURE_NO_MATCH;
5861        }
5862
5863        ArraySet<Signature> set1 = new ArraySet<Signature>();
5864        for (Signature sig : s1) {
5865            set1.add(sig);
5866        }
5867        ArraySet<Signature> set2 = new ArraySet<Signature>();
5868        for (Signature sig : s2) {
5869            set2.add(sig);
5870        }
5871        // Make sure s2 contains all signatures in s1.
5872        if (set1.equals(set2)) {
5873            return PackageManager.SIGNATURE_MATCH;
5874        }
5875        return PackageManager.SIGNATURE_NO_MATCH;
5876    }
5877
5878    /**
5879     * If the database version for this type of package (internal storage or
5880     * external storage) is less than the version where package signatures
5881     * were updated, return true.
5882     */
5883    private boolean isCompatSignatureUpdateNeeded(PackageParser.Package scannedPkg) {
5884        final VersionInfo ver = getSettingsVersionForPackage(scannedPkg);
5885        return ver.databaseVersion < DatabaseVersion.SIGNATURE_END_ENTITY;
5886    }
5887
5888    /**
5889     * Used for backward compatibility to make sure any packages with
5890     * certificate chains get upgraded to the new style. {@code existingSigs}
5891     * will be in the old format (since they were stored on disk from before the
5892     * system upgrade) and {@code scannedSigs} will be in the newer format.
5893     */
5894    private int compareSignaturesCompat(PackageSignatures existingSigs,
5895            PackageParser.Package scannedPkg) {
5896        if (!isCompatSignatureUpdateNeeded(scannedPkg)) {
5897            return PackageManager.SIGNATURE_NO_MATCH;
5898        }
5899
5900        ArraySet<Signature> existingSet = new ArraySet<Signature>();
5901        for (Signature sig : existingSigs.mSignatures) {
5902            existingSet.add(sig);
5903        }
5904        ArraySet<Signature> scannedCompatSet = new ArraySet<Signature>();
5905        for (Signature sig : scannedPkg.mSignatures) {
5906            try {
5907                Signature[] chainSignatures = sig.getChainSignatures();
5908                for (Signature chainSig : chainSignatures) {
5909                    scannedCompatSet.add(chainSig);
5910                }
5911            } catch (CertificateEncodingException e) {
5912                scannedCompatSet.add(sig);
5913            }
5914        }
5915        /*
5916         * Make sure the expanded scanned set contains all signatures in the
5917         * existing one.
5918         */
5919        if (scannedCompatSet.equals(existingSet)) {
5920            // Migrate the old signatures to the new scheme.
5921            existingSigs.assignSignatures(scannedPkg.mSignatures);
5922            // The new KeySets will be re-added later in the scanning process.
5923            synchronized (mPackages) {
5924                mSettings.mKeySetManagerService.removeAppKeySetDataLPw(scannedPkg.packageName);
5925            }
5926            return PackageManager.SIGNATURE_MATCH;
5927        }
5928        return PackageManager.SIGNATURE_NO_MATCH;
5929    }
5930
5931    private boolean isRecoverSignatureUpdateNeeded(PackageParser.Package scannedPkg) {
5932        final VersionInfo ver = getSettingsVersionForPackage(scannedPkg);
5933        return ver.databaseVersion < DatabaseVersion.SIGNATURE_MALFORMED_RECOVER;
5934    }
5935
5936    private int compareSignaturesRecover(PackageSignatures existingSigs,
5937            PackageParser.Package scannedPkg) {
5938        if (!isRecoverSignatureUpdateNeeded(scannedPkg)) {
5939            return PackageManager.SIGNATURE_NO_MATCH;
5940        }
5941
5942        String msg = null;
5943        try {
5944            if (Signature.areEffectiveMatch(existingSigs.mSignatures, scannedPkg.mSignatures)) {
5945                logCriticalInfo(Log.INFO, "Recovered effectively matching certificates for "
5946                        + scannedPkg.packageName);
5947                return PackageManager.SIGNATURE_MATCH;
5948            }
5949        } catch (CertificateException e) {
5950            msg = e.getMessage();
5951        }
5952
5953        logCriticalInfo(Log.INFO,
5954                "Failed to recover certificates for " + scannedPkg.packageName + ": " + msg);
5955        return PackageManager.SIGNATURE_NO_MATCH;
5956    }
5957
5958    @Override
5959    public List<String> getAllPackages() {
5960        final int callingUid = Binder.getCallingUid();
5961        final int callingUserId = UserHandle.getUserId(callingUid);
5962        synchronized (mPackages) {
5963            if (canViewInstantApps(callingUid, callingUserId)) {
5964                return new ArrayList<String>(mPackages.keySet());
5965            }
5966            final String instantAppPkgName = getInstantAppPackageName(callingUid);
5967            final List<String> result = new ArrayList<>();
5968            if (instantAppPkgName != null) {
5969                // caller is an instant application; filter unexposed applications
5970                for (PackageParser.Package pkg : mPackages.values()) {
5971                    if (!pkg.visibleToInstantApps) {
5972                        continue;
5973                    }
5974                    result.add(pkg.packageName);
5975                }
5976            } else {
5977                // caller is a normal application; filter instant applications
5978                for (PackageParser.Package pkg : mPackages.values()) {
5979                    final PackageSetting ps =
5980                            pkg.mExtras != null ? (PackageSetting) pkg.mExtras : null;
5981                    if (ps != null
5982                            && ps.getInstantApp(callingUserId)
5983                            && !mInstantAppRegistry.isInstantAccessGranted(
5984                                    callingUserId, UserHandle.getAppId(callingUid), ps.appId)) {
5985                        continue;
5986                    }
5987                    result.add(pkg.packageName);
5988                }
5989            }
5990            return result;
5991        }
5992    }
5993
5994    @Override
5995    public String[] getPackagesForUid(int uid) {
5996        final int callingUid = Binder.getCallingUid();
5997        final boolean isCallerInstantApp = getInstantAppPackageName(callingUid) != null;
5998        final int userId = UserHandle.getUserId(uid);
5999        uid = UserHandle.getAppId(uid);
6000        // reader
6001        synchronized (mPackages) {
6002            Object obj = mSettings.getUserIdLPr(uid);
6003            if (obj instanceof SharedUserSetting) {
6004                if (isCallerInstantApp) {
6005                    return null;
6006                }
6007                final SharedUserSetting sus = (SharedUserSetting) obj;
6008                final int N = sus.packages.size();
6009                String[] res = new String[N];
6010                final Iterator<PackageSetting> it = sus.packages.iterator();
6011                int i = 0;
6012                while (it.hasNext()) {
6013                    PackageSetting ps = it.next();
6014                    if (ps.getInstalled(userId)) {
6015                        res[i++] = ps.name;
6016                    } else {
6017                        res = ArrayUtils.removeElement(String.class, res, res[i]);
6018                    }
6019                }
6020                return res;
6021            } else if (obj instanceof PackageSetting) {
6022                final PackageSetting ps = (PackageSetting) obj;
6023                if (ps.getInstalled(userId) && !filterAppAccessLPr(ps, callingUid, userId)) {
6024                    return new String[]{ps.name};
6025                }
6026            }
6027        }
6028        return null;
6029    }
6030
6031    @Override
6032    public String getNameForUid(int uid) {
6033        final int callingUid = Binder.getCallingUid();
6034        if (getInstantAppPackageName(callingUid) != null) {
6035            return null;
6036        }
6037        synchronized (mPackages) {
6038            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
6039            if (obj instanceof SharedUserSetting) {
6040                final SharedUserSetting sus = (SharedUserSetting) obj;
6041                return sus.name + ":" + sus.userId;
6042            } else if (obj instanceof PackageSetting) {
6043                final PackageSetting ps = (PackageSetting) obj;
6044                if (filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
6045                    return null;
6046                }
6047                return ps.name;
6048            }
6049        }
6050        return null;
6051    }
6052
6053    @Override
6054    public int getUidForSharedUser(String sharedUserName) {
6055        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
6056            return -1;
6057        }
6058        if (sharedUserName == null) {
6059            return -1;
6060        }
6061        // reader
6062        synchronized (mPackages) {
6063            SharedUserSetting suid;
6064            try {
6065                suid = mSettings.getSharedUserLPw(sharedUserName, 0, 0, false);
6066                if (suid != null) {
6067                    return suid.userId;
6068                }
6069            } catch (PackageManagerException ignore) {
6070                // can't happen, but, still need to catch it
6071            }
6072            return -1;
6073        }
6074    }
6075
6076    @Override
6077    public int getFlagsForUid(int uid) {
6078        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
6079            return 0;
6080        }
6081        synchronized (mPackages) {
6082            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
6083            if (obj instanceof SharedUserSetting) {
6084                final SharedUserSetting sus = (SharedUserSetting) obj;
6085                return sus.pkgFlags;
6086            } else if (obj instanceof PackageSetting) {
6087                final PackageSetting ps = (PackageSetting) obj;
6088                return ps.pkgFlags;
6089            }
6090        }
6091        return 0;
6092    }
6093
6094    @Override
6095    public int getPrivateFlagsForUid(int uid) {
6096        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
6097            return 0;
6098        }
6099        synchronized (mPackages) {
6100            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
6101            if (obj instanceof SharedUserSetting) {
6102                final SharedUserSetting sus = (SharedUserSetting) obj;
6103                return sus.pkgPrivateFlags;
6104            } else if (obj instanceof PackageSetting) {
6105                final PackageSetting ps = (PackageSetting) obj;
6106                return ps.pkgPrivateFlags;
6107            }
6108        }
6109        return 0;
6110    }
6111
6112    @Override
6113    public boolean isUidPrivileged(int uid) {
6114        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
6115            return false;
6116        }
6117        uid = UserHandle.getAppId(uid);
6118        // reader
6119        synchronized (mPackages) {
6120            Object obj = mSettings.getUserIdLPr(uid);
6121            if (obj instanceof SharedUserSetting) {
6122                final SharedUserSetting sus = (SharedUserSetting) obj;
6123                final Iterator<PackageSetting> it = sus.packages.iterator();
6124                while (it.hasNext()) {
6125                    if (it.next().isPrivileged()) {
6126                        return true;
6127                    }
6128                }
6129            } else if (obj instanceof PackageSetting) {
6130                final PackageSetting ps = (PackageSetting) obj;
6131                return ps.isPrivileged();
6132            }
6133        }
6134        return false;
6135    }
6136
6137    @Override
6138    public String[] getAppOpPermissionPackages(String permissionName) {
6139        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
6140            return null;
6141        }
6142        synchronized (mPackages) {
6143            ArraySet<String> pkgs = mAppOpPermissionPackages.get(permissionName);
6144            if (pkgs == null) {
6145                return null;
6146            }
6147            return pkgs.toArray(new String[pkgs.size()]);
6148        }
6149    }
6150
6151    @Override
6152    public ResolveInfo resolveIntent(Intent intent, String resolvedType,
6153            int flags, int userId) {
6154        return resolveIntentInternal(
6155                intent, resolvedType, flags, userId, false /*includeInstantApps*/);
6156    }
6157
6158    private ResolveInfo resolveIntentInternal(Intent intent, String resolvedType,
6159            int flags, int userId, boolean resolveForStart) {
6160        try {
6161            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "resolveIntent");
6162
6163            if (!sUserManager.exists(userId)) return null;
6164            final int callingUid = Binder.getCallingUid();
6165            flags = updateFlagsForResolve(flags, userId, intent, callingUid, resolveForStart);
6166            enforceCrossUserPermission(callingUid, userId,
6167                    false /*requireFullPermission*/, false /*checkShell*/, "resolve intent");
6168
6169            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "queryIntentActivities");
6170            final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType,
6171                    flags, userId, resolveForStart);
6172            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
6173
6174            final ResolveInfo bestChoice =
6175                    chooseBestActivity(intent, resolvedType, flags, query, userId);
6176            return bestChoice;
6177        } finally {
6178            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
6179        }
6180    }
6181
6182    @Override
6183    public ResolveInfo findPersistentPreferredActivity(Intent intent, int userId) {
6184        if (!UserHandle.isSameApp(Binder.getCallingUid(), Process.SYSTEM_UID)) {
6185            throw new SecurityException(
6186                    "findPersistentPreferredActivity can only be run by the system");
6187        }
6188        if (!sUserManager.exists(userId)) {
6189            return null;
6190        }
6191        final int callingUid = Binder.getCallingUid();
6192        intent = updateIntentForResolve(intent);
6193        final String resolvedType = intent.resolveTypeIfNeeded(mContext.getContentResolver());
6194        final int flags = updateFlagsForResolve(
6195                0, userId, intent, callingUid, false /*includeInstantApps*/);
6196        final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags,
6197                userId);
6198        synchronized (mPackages) {
6199            return findPersistentPreferredActivityLP(intent, resolvedType, flags, query, false,
6200                    userId);
6201        }
6202    }
6203
6204    @Override
6205    public void setLastChosenActivity(Intent intent, String resolvedType, int flags,
6206            IntentFilter filter, int match, ComponentName activity) {
6207        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
6208            return;
6209        }
6210        final int userId = UserHandle.getCallingUserId();
6211        if (DEBUG_PREFERRED) {
6212            Log.v(TAG, "setLastChosenActivity intent=" + intent
6213                + " resolvedType=" + resolvedType
6214                + " flags=" + flags
6215                + " filter=" + filter
6216                + " match=" + match
6217                + " activity=" + activity);
6218            filter.dump(new PrintStreamPrinter(System.out), "    ");
6219        }
6220        intent.setComponent(null);
6221        final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags,
6222                userId);
6223        // Find any earlier preferred or last chosen entries and nuke them
6224        findPreferredActivity(intent, resolvedType,
6225                flags, query, 0, false, true, false, userId);
6226        // Add the new activity as the last chosen for this filter
6227        addPreferredActivityInternal(filter, match, null, activity, false, userId,
6228                "Setting last chosen");
6229    }
6230
6231    @Override
6232    public ResolveInfo getLastChosenActivity(Intent intent, String resolvedType, int flags) {
6233        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
6234            return null;
6235        }
6236        final int userId = UserHandle.getCallingUserId();
6237        if (DEBUG_PREFERRED) Log.v(TAG, "Querying last chosen activity for " + intent);
6238        final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags,
6239                userId);
6240        return findPreferredActivity(intent, resolvedType, flags, query, 0,
6241                false, false, false, userId);
6242    }
6243
6244    /**
6245     * Returns whether or not instant apps have been disabled remotely.
6246     */
6247    private boolean isEphemeralDisabled() {
6248        return mEphemeralAppsDisabled;
6249    }
6250
6251    private boolean isInstantAppAllowed(
6252            Intent intent, List<ResolveInfo> resolvedActivities, int userId,
6253            boolean skipPackageCheck) {
6254        if (mInstantAppResolverConnection == null) {
6255            return false;
6256        }
6257        if (mInstantAppInstallerActivity == null) {
6258            return false;
6259        }
6260        if (intent.getComponent() != null) {
6261            return false;
6262        }
6263        if ((intent.getFlags() & Intent.FLAG_IGNORE_EPHEMERAL) != 0) {
6264            return false;
6265        }
6266        if (!skipPackageCheck && intent.getPackage() != null) {
6267            return false;
6268        }
6269        final boolean isWebUri = hasWebURI(intent);
6270        if (!isWebUri || intent.getData().getHost() == null) {
6271            return false;
6272        }
6273        // Deny ephemeral apps if the user chose _ALWAYS or _ALWAYS_ASK for intent resolution.
6274        // Or if there's already an ephemeral app installed that handles the action
6275        synchronized (mPackages) {
6276            final int count = (resolvedActivities == null ? 0 : resolvedActivities.size());
6277            for (int n = 0; n < count; n++) {
6278                final ResolveInfo info = resolvedActivities.get(n);
6279                final String packageName = info.activityInfo.packageName;
6280                final PackageSetting ps = mSettings.mPackages.get(packageName);
6281                if (ps != null) {
6282                    // only check domain verification status if the app is not a browser
6283                    if (!info.handleAllWebDataURI) {
6284                        // Try to get the status from User settings first
6285                        final long packedStatus = getDomainVerificationStatusLPr(ps, userId);
6286                        final int status = (int) (packedStatus >> 32);
6287                        if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS
6288                            || status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) {
6289                            if (DEBUG_EPHEMERAL) {
6290                                Slog.v(TAG, "DENY instant app;"
6291                                    + " pkg: " + packageName + ", status: " + status);
6292                            }
6293                            return false;
6294                        }
6295                    }
6296                    if (ps.getInstantApp(userId)) {
6297                        if (DEBUG_EPHEMERAL) {
6298                            Slog.v(TAG, "DENY instant app installed;"
6299                                    + " pkg: " + packageName);
6300                        }
6301                        return false;
6302                    }
6303                }
6304            }
6305        }
6306        // We've exhausted all ways to deny ephemeral application; let the system look for them.
6307        return true;
6308    }
6309
6310    private void requestInstantAppResolutionPhaseTwo(AuxiliaryResolveInfo responseObj,
6311            Intent origIntent, String resolvedType, String callingPackage,
6312            Bundle verificationBundle, int userId) {
6313        final Message msg = mHandler.obtainMessage(INSTANT_APP_RESOLUTION_PHASE_TWO,
6314                new InstantAppRequest(responseObj, origIntent, resolvedType,
6315                        callingPackage, userId, verificationBundle));
6316        mHandler.sendMessage(msg);
6317    }
6318
6319    private ResolveInfo chooseBestActivity(Intent intent, String resolvedType,
6320            int flags, List<ResolveInfo> query, int userId) {
6321        if (query != null) {
6322            final int N = query.size();
6323            if (N == 1) {
6324                return query.get(0);
6325            } else if (N > 1) {
6326                final boolean debug = ((intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0);
6327                // If there is more than one activity with the same priority,
6328                // then let the user decide between them.
6329                ResolveInfo r0 = query.get(0);
6330                ResolveInfo r1 = query.get(1);
6331                if (DEBUG_INTENT_MATCHING || debug) {
6332                    Slog.v(TAG, r0.activityInfo.name + "=" + r0.priority + " vs "
6333                            + r1.activityInfo.name + "=" + r1.priority);
6334                }
6335                // If the first activity has a higher priority, or a different
6336                // default, then it is always desirable to pick it.
6337                if (r0.priority != r1.priority
6338                        || r0.preferredOrder != r1.preferredOrder
6339                        || r0.isDefault != r1.isDefault) {
6340                    return query.get(0);
6341                }
6342                // If we have saved a preference for a preferred activity for
6343                // this Intent, use that.
6344                ResolveInfo ri = findPreferredActivity(intent, resolvedType,
6345                        flags, query, r0.priority, true, false, debug, userId);
6346                if (ri != null) {
6347                    return ri;
6348                }
6349                // If we have an ephemeral app, use it
6350                for (int i = 0; i < N; i++) {
6351                    ri = query.get(i);
6352                    if (ri.activityInfo.applicationInfo.isInstantApp()) {
6353                        final String packageName = ri.activityInfo.packageName;
6354                        final PackageSetting ps = mSettings.mPackages.get(packageName);
6355                        final long packedStatus = getDomainVerificationStatusLPr(ps, userId);
6356                        final int status = (int)(packedStatus >> 32);
6357                        if (status != INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) {
6358                            return ri;
6359                        }
6360                    }
6361                }
6362                ri = new ResolveInfo(mResolveInfo);
6363                ri.activityInfo = new ActivityInfo(ri.activityInfo);
6364                ri.activityInfo.labelRes = ResolverActivity.getLabelRes(intent.getAction());
6365                // If all of the options come from the same package, show the application's
6366                // label and icon instead of the generic resolver's.
6367                // Some calls like Intent.resolveActivityInfo query the ResolveInfo from here
6368                // and then throw away the ResolveInfo itself, meaning that the caller loses
6369                // the resolvePackageName. Therefore the activityInfo.labelRes above provides
6370                // a fallback for this case; we only set the target package's resources on
6371                // the ResolveInfo, not the ActivityInfo.
6372                final String intentPackage = intent.getPackage();
6373                if (!TextUtils.isEmpty(intentPackage) && allHavePackage(query, intentPackage)) {
6374                    final ApplicationInfo appi = query.get(0).activityInfo.applicationInfo;
6375                    ri.resolvePackageName = intentPackage;
6376                    if (userNeedsBadging(userId)) {
6377                        ri.noResourceId = true;
6378                    } else {
6379                        ri.icon = appi.icon;
6380                    }
6381                    ri.iconResourceId = appi.icon;
6382                    ri.labelRes = appi.labelRes;
6383                }
6384                ri.activityInfo.applicationInfo = new ApplicationInfo(
6385                        ri.activityInfo.applicationInfo);
6386                if (userId != 0) {
6387                    ri.activityInfo.applicationInfo.uid = UserHandle.getUid(userId,
6388                            UserHandle.getAppId(ri.activityInfo.applicationInfo.uid));
6389                }
6390                // Make sure that the resolver is displayable in car mode
6391                if (ri.activityInfo.metaData == null) ri.activityInfo.metaData = new Bundle();
6392                ri.activityInfo.metaData.putBoolean(Intent.METADATA_DOCK_HOME, true);
6393                return ri;
6394            }
6395        }
6396        return null;
6397    }
6398
6399    /**
6400     * Return true if the given list is not empty and all of its contents have
6401     * an activityInfo with the given package name.
6402     */
6403    private boolean allHavePackage(List<ResolveInfo> list, String packageName) {
6404        if (ArrayUtils.isEmpty(list)) {
6405            return false;
6406        }
6407        for (int i = 0, N = list.size(); i < N; i++) {
6408            final ResolveInfo ri = list.get(i);
6409            final ActivityInfo ai = ri != null ? ri.activityInfo : null;
6410            if (ai == null || !packageName.equals(ai.packageName)) {
6411                return false;
6412            }
6413        }
6414        return true;
6415    }
6416
6417    private ResolveInfo findPersistentPreferredActivityLP(Intent intent, String resolvedType,
6418            int flags, List<ResolveInfo> query, boolean debug, int userId) {
6419        final int N = query.size();
6420        PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities
6421                .get(userId);
6422        // Get the list of persistent preferred activities that handle the intent
6423        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for presistent preferred activities...");
6424        List<PersistentPreferredActivity> pprefs = ppir != null
6425                ? ppir.queryIntent(intent, resolvedType,
6426                        (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0,
6427                        userId)
6428                : null;
6429        if (pprefs != null && pprefs.size() > 0) {
6430            final int M = pprefs.size();
6431            for (int i=0; i<M; i++) {
6432                final PersistentPreferredActivity ppa = pprefs.get(i);
6433                if (DEBUG_PREFERRED || debug) {
6434                    Slog.v(TAG, "Checking PersistentPreferredActivity ds="
6435                            + (ppa.countDataSchemes() > 0 ? ppa.getDataScheme(0) : "<none>")
6436                            + "\n  component=" + ppa.mComponent);
6437                    ppa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
6438                }
6439                final ActivityInfo ai = getActivityInfo(ppa.mComponent,
6440                        flags | MATCH_DISABLED_COMPONENTS, userId);
6441                if (DEBUG_PREFERRED || debug) {
6442                    Slog.v(TAG, "Found persistent preferred activity:");
6443                    if (ai != null) {
6444                        ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
6445                    } else {
6446                        Slog.v(TAG, "  null");
6447                    }
6448                }
6449                if (ai == null) {
6450                    // This previously registered persistent preferred activity
6451                    // component is no longer known. Ignore it and do NOT remove it.
6452                    continue;
6453                }
6454                for (int j=0; j<N; j++) {
6455                    final ResolveInfo ri = query.get(j);
6456                    if (!ri.activityInfo.applicationInfo.packageName
6457                            .equals(ai.applicationInfo.packageName)) {
6458                        continue;
6459                    }
6460                    if (!ri.activityInfo.name.equals(ai.name)) {
6461                        continue;
6462                    }
6463                    //  Found a persistent preference that can handle the intent.
6464                    if (DEBUG_PREFERRED || debug) {
6465                        Slog.v(TAG, "Returning persistent preferred activity: " +
6466                                ri.activityInfo.packageName + "/" + ri.activityInfo.name);
6467                    }
6468                    return ri;
6469                }
6470            }
6471        }
6472        return null;
6473    }
6474
6475    // TODO: handle preferred activities missing while user has amnesia
6476    ResolveInfo findPreferredActivity(Intent intent, String resolvedType, int flags,
6477            List<ResolveInfo> query, int priority, boolean always,
6478            boolean removeMatches, boolean debug, int userId) {
6479        if (!sUserManager.exists(userId)) return null;
6480        final int callingUid = Binder.getCallingUid();
6481        flags = updateFlagsForResolve(
6482                flags, userId, intent, callingUid, false /*includeInstantApps*/);
6483        intent = updateIntentForResolve(intent);
6484        // writer
6485        synchronized (mPackages) {
6486            // Try to find a matching persistent preferred activity.
6487            ResolveInfo pri = findPersistentPreferredActivityLP(intent, resolvedType, flags, query,
6488                    debug, userId);
6489
6490            // If a persistent preferred activity matched, use it.
6491            if (pri != null) {
6492                return pri;
6493            }
6494
6495            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
6496            // Get the list of preferred activities that handle the intent
6497            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for preferred activities...");
6498            List<PreferredActivity> prefs = pir != null
6499                    ? pir.queryIntent(intent, resolvedType,
6500                            (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0,
6501                            userId)
6502                    : null;
6503            if (prefs != null && prefs.size() > 0) {
6504                boolean changed = false;
6505                try {
6506                    // First figure out how good the original match set is.
6507                    // We will only allow preferred activities that came
6508                    // from the same match quality.
6509                    int match = 0;
6510
6511                    if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Figuring out best match...");
6512
6513                    final int N = query.size();
6514                    for (int j=0; j<N; j++) {
6515                        final ResolveInfo ri = query.get(j);
6516                        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Match for " + ri.activityInfo
6517                                + ": 0x" + Integer.toHexString(match));
6518                        if (ri.match > match) {
6519                            match = ri.match;
6520                        }
6521                    }
6522
6523                    if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Best match: 0x"
6524                            + Integer.toHexString(match));
6525
6526                    match &= IntentFilter.MATCH_CATEGORY_MASK;
6527                    final int M = prefs.size();
6528                    for (int i=0; i<M; i++) {
6529                        final PreferredActivity pa = prefs.get(i);
6530                        if (DEBUG_PREFERRED || debug) {
6531                            Slog.v(TAG, "Checking PreferredActivity ds="
6532                                    + (pa.countDataSchemes() > 0 ? pa.getDataScheme(0) : "<none>")
6533                                    + "\n  component=" + pa.mPref.mComponent);
6534                            pa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
6535                        }
6536                        if (pa.mPref.mMatch != match) {
6537                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping bad match "
6538                                    + Integer.toHexString(pa.mPref.mMatch));
6539                            continue;
6540                        }
6541                        // If it's not an "always" type preferred activity and that's what we're
6542                        // looking for, skip it.
6543                        if (always && !pa.mPref.mAlways) {
6544                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping mAlways=false entry");
6545                            continue;
6546                        }
6547                        final ActivityInfo ai = getActivityInfo(
6548                                pa.mPref.mComponent, flags | MATCH_DISABLED_COMPONENTS
6549                                        | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
6550                                userId);
6551                        if (DEBUG_PREFERRED || debug) {
6552                            Slog.v(TAG, "Found preferred activity:");
6553                            if (ai != null) {
6554                                ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
6555                            } else {
6556                                Slog.v(TAG, "  null");
6557                            }
6558                        }
6559                        if (ai == null) {
6560                            // This previously registered preferred activity
6561                            // component is no longer known.  Most likely an update
6562                            // to the app was installed and in the new version this
6563                            // component no longer exists.  Clean it up by removing
6564                            // it from the preferred activities list, and skip it.
6565                            Slog.w(TAG, "Removing dangling preferred activity: "
6566                                    + pa.mPref.mComponent);
6567                            pir.removeFilter(pa);
6568                            changed = true;
6569                            continue;
6570                        }
6571                        for (int j=0; j<N; j++) {
6572                            final ResolveInfo ri = query.get(j);
6573                            if (!ri.activityInfo.applicationInfo.packageName
6574                                    .equals(ai.applicationInfo.packageName)) {
6575                                continue;
6576                            }
6577                            if (!ri.activityInfo.name.equals(ai.name)) {
6578                                continue;
6579                            }
6580
6581                            if (removeMatches) {
6582                                pir.removeFilter(pa);
6583                                changed = true;
6584                                if (DEBUG_PREFERRED) {
6585                                    Slog.v(TAG, "Removing match " + pa.mPref.mComponent);
6586                                }
6587                                break;
6588                            }
6589
6590                            // Okay we found a previously set preferred or last chosen app.
6591                            // If the result set is different from when this
6592                            // was created, we need to clear it and re-ask the
6593                            // user their preference, if we're looking for an "always" type entry.
6594                            if (always && !pa.mPref.sameSet(query)) {
6595                                Slog.i(TAG, "Result set changed, dropping preferred activity for "
6596                                        + intent + " type " + resolvedType);
6597                                if (DEBUG_PREFERRED) {
6598                                    Slog.v(TAG, "Removing preferred activity since set changed "
6599                                            + pa.mPref.mComponent);
6600                                }
6601                                pir.removeFilter(pa);
6602                                // Re-add the filter as a "last chosen" entry (!always)
6603                                PreferredActivity lastChosen = new PreferredActivity(
6604                                        pa, pa.mPref.mMatch, null, pa.mPref.mComponent, false);
6605                                pir.addFilter(lastChosen);
6606                                changed = true;
6607                                return null;
6608                            }
6609
6610                            // Yay! Either the set matched or we're looking for the last chosen
6611                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Returning preferred activity: "
6612                                    + ri.activityInfo.packageName + "/" + ri.activityInfo.name);
6613                            return ri;
6614                        }
6615                    }
6616                } finally {
6617                    if (changed) {
6618                        if (DEBUG_PREFERRED) {
6619                            Slog.v(TAG, "Preferred activity bookkeeping changed; writing restrictions");
6620                        }
6621                        scheduleWritePackageRestrictionsLocked(userId);
6622                    }
6623                }
6624            }
6625        }
6626        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "No preferred activity to return");
6627        return null;
6628    }
6629
6630    /*
6631     * Returns if intent can be forwarded from the sourceUserId to the targetUserId
6632     */
6633    @Override
6634    public boolean canForwardTo(Intent intent, String resolvedType, int sourceUserId,
6635            int targetUserId) {
6636        mContext.enforceCallingOrSelfPermission(
6637                android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
6638        List<CrossProfileIntentFilter> matches =
6639                getMatchingCrossProfileIntentFilters(intent, resolvedType, sourceUserId);
6640        if (matches != null) {
6641            int size = matches.size();
6642            for (int i = 0; i < size; i++) {
6643                if (matches.get(i).getTargetUserId() == targetUserId) return true;
6644            }
6645        }
6646        if (hasWebURI(intent)) {
6647            // cross-profile app linking works only towards the parent.
6648            final int callingUid = Binder.getCallingUid();
6649            final UserInfo parent = getProfileParent(sourceUserId);
6650            synchronized(mPackages) {
6651                int flags = updateFlagsForResolve(0, parent.id, intent, callingUid,
6652                        false /*includeInstantApps*/);
6653                CrossProfileDomainInfo xpDomainInfo = getCrossProfileDomainPreferredLpr(
6654                        intent, resolvedType, flags, sourceUserId, parent.id);
6655                return xpDomainInfo != null;
6656            }
6657        }
6658        return false;
6659    }
6660
6661    private UserInfo getProfileParent(int userId) {
6662        final long identity = Binder.clearCallingIdentity();
6663        try {
6664            return sUserManager.getProfileParent(userId);
6665        } finally {
6666            Binder.restoreCallingIdentity(identity);
6667        }
6668    }
6669
6670    private List<CrossProfileIntentFilter> getMatchingCrossProfileIntentFilters(Intent intent,
6671            String resolvedType, int userId) {
6672        CrossProfileIntentResolver resolver = mSettings.mCrossProfileIntentResolvers.get(userId);
6673        if (resolver != null) {
6674            return resolver.queryIntent(intent, resolvedType, false /*defaultOnly*/, userId);
6675        }
6676        return null;
6677    }
6678
6679    @Override
6680    public @NonNull ParceledListSlice<ResolveInfo> queryIntentActivities(Intent intent,
6681            String resolvedType, int flags, int userId) {
6682        try {
6683            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "queryIntentActivities");
6684
6685            return new ParceledListSlice<>(
6686                    queryIntentActivitiesInternal(intent, resolvedType, flags, userId));
6687        } finally {
6688            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
6689        }
6690    }
6691
6692    /**
6693     * Returns the package name of the calling Uid if it's an instant app. If it isn't
6694     * instant, returns {@code null}.
6695     */
6696    private String getInstantAppPackageName(int callingUid) {
6697        synchronized (mPackages) {
6698            // If the caller is an isolated app use the owner's uid for the lookup.
6699            if (Process.isIsolated(callingUid)) {
6700                callingUid = mIsolatedOwners.get(callingUid);
6701            }
6702            final int appId = UserHandle.getAppId(callingUid);
6703            final Object obj = mSettings.getUserIdLPr(appId);
6704            if (obj instanceof PackageSetting) {
6705                final PackageSetting ps = (PackageSetting) obj;
6706                final boolean isInstantApp = ps.getInstantApp(UserHandle.getUserId(callingUid));
6707                return isInstantApp ? ps.pkg.packageName : null;
6708            }
6709        }
6710        return null;
6711    }
6712
6713    private @NonNull List<ResolveInfo> queryIntentActivitiesInternal(Intent intent,
6714            String resolvedType, int flags, int userId) {
6715        return queryIntentActivitiesInternal(intent, resolvedType, flags, userId, false);
6716    }
6717
6718    private @NonNull List<ResolveInfo> queryIntentActivitiesInternal(Intent intent,
6719            String resolvedType, int flags, int userId, boolean resolveForStart) {
6720        if (!sUserManager.exists(userId)) return Collections.emptyList();
6721        final int callingUid = Binder.getCallingUid();
6722        final String instantAppPkgName = getInstantAppPackageName(callingUid);
6723        enforceCrossUserPermission(callingUid, userId,
6724                false /* requireFullPermission */, false /* checkShell */,
6725                "query intent activities");
6726        final String pkgName = intent.getPackage();
6727        ComponentName comp = intent.getComponent();
6728        if (comp == null) {
6729            if (intent.getSelector() != null) {
6730                intent = intent.getSelector();
6731                comp = intent.getComponent();
6732            }
6733        }
6734
6735        flags = updateFlagsForResolve(flags, userId, intent, callingUid, resolveForStart,
6736                comp != null || pkgName != null /*onlyExposedExplicitly*/);
6737        if (comp != null) {
6738            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
6739            final ActivityInfo ai = getActivityInfo(comp, flags, userId);
6740            if (ai != null) {
6741                // When specifying an explicit component, we prevent the activity from being
6742                // used when either 1) the calling package is normal and the activity is within
6743                // an ephemeral application or 2) the calling package is ephemeral and the
6744                // activity is not visible to ephemeral applications.
6745                final boolean matchInstantApp =
6746                        (flags & PackageManager.MATCH_INSTANT) != 0;
6747                final boolean matchVisibleToInstantAppOnly =
6748                        (flags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
6749                final boolean matchExplicitlyVisibleOnly =
6750                        (flags & PackageManager.MATCH_EXPLICITLY_VISIBLE_ONLY) != 0;
6751                final boolean isCallerInstantApp =
6752                        instantAppPkgName != null;
6753                final boolean isTargetSameInstantApp =
6754                        comp.getPackageName().equals(instantAppPkgName);
6755                final boolean isTargetInstantApp =
6756                        (ai.applicationInfo.privateFlags
6757                                & ApplicationInfo.PRIVATE_FLAG_INSTANT) != 0;
6758                final boolean isTargetVisibleToInstantApp =
6759                        (ai.flags & ActivityInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0;
6760                final boolean isTargetExplicitlyVisibleToInstantApp =
6761                        isTargetVisibleToInstantApp
6762                        && (ai.flags & ActivityInfo.FLAG_IMPLICITLY_VISIBLE_TO_INSTANT_APP) == 0;
6763                final boolean isTargetHiddenFromInstantApp =
6764                        !isTargetVisibleToInstantApp
6765                        || (matchExplicitlyVisibleOnly && !isTargetExplicitlyVisibleToInstantApp);
6766                final boolean blockResolution =
6767                        !isTargetSameInstantApp
6768                        && ((!matchInstantApp && !isCallerInstantApp && isTargetInstantApp)
6769                                || (matchVisibleToInstantAppOnly && isCallerInstantApp
6770                                        && isTargetHiddenFromInstantApp));
6771                if (!blockResolution) {
6772                    final ResolveInfo ri = new ResolveInfo();
6773                    ri.activityInfo = ai;
6774                    list.add(ri);
6775                }
6776            }
6777            return applyPostResolutionFilter(list, instantAppPkgName);
6778        }
6779
6780        // reader
6781        boolean sortResult = false;
6782        boolean addEphemeral = false;
6783        List<ResolveInfo> result;
6784        final boolean ephemeralDisabled = isEphemeralDisabled();
6785        synchronized (mPackages) {
6786            if (pkgName == null) {
6787                List<CrossProfileIntentFilter> matchingFilters =
6788                        getMatchingCrossProfileIntentFilters(intent, resolvedType, userId);
6789                // Check for results that need to skip the current profile.
6790                ResolveInfo xpResolveInfo  = querySkipCurrentProfileIntents(matchingFilters, intent,
6791                        resolvedType, flags, userId);
6792                if (xpResolveInfo != null) {
6793                    List<ResolveInfo> xpResult = new ArrayList<ResolveInfo>(1);
6794                    xpResult.add(xpResolveInfo);
6795                    return applyPostResolutionFilter(
6796                            filterIfNotSystemUser(xpResult, userId), instantAppPkgName);
6797                }
6798
6799                // Check for results in the current profile.
6800                result = filterIfNotSystemUser(mActivities.queryIntent(
6801                        intent, resolvedType, flags, userId), userId);
6802                addEphemeral = !ephemeralDisabled
6803                        && isInstantAppAllowed(intent, result, userId, false /*skipPackageCheck*/);
6804                // Check for cross profile results.
6805                boolean hasNonNegativePriorityResult = hasNonNegativePriority(result);
6806                xpResolveInfo = queryCrossProfileIntents(
6807                        matchingFilters, intent, resolvedType, flags, userId,
6808                        hasNonNegativePriorityResult);
6809                if (xpResolveInfo != null && isUserEnabled(xpResolveInfo.targetUserId)) {
6810                    boolean isVisibleToUser = filterIfNotSystemUser(
6811                            Collections.singletonList(xpResolveInfo), userId).size() > 0;
6812                    if (isVisibleToUser) {
6813                        result.add(xpResolveInfo);
6814                        sortResult = true;
6815                    }
6816                }
6817                if (hasWebURI(intent)) {
6818                    CrossProfileDomainInfo xpDomainInfo = null;
6819                    final UserInfo parent = getProfileParent(userId);
6820                    if (parent != null) {
6821                        xpDomainInfo = getCrossProfileDomainPreferredLpr(intent, resolvedType,
6822                                flags, userId, parent.id);
6823                    }
6824                    if (xpDomainInfo != null) {
6825                        if (xpResolveInfo != null) {
6826                            // If we didn't remove it, the cross-profile ResolveInfo would be twice
6827                            // in the result.
6828                            result.remove(xpResolveInfo);
6829                        }
6830                        if (result.size() == 0 && !addEphemeral) {
6831                            // No result in current profile, but found candidate in parent user.
6832                            // And we are not going to add emphemeral app, so we can return the
6833                            // result straight away.
6834                            result.add(xpDomainInfo.resolveInfo);
6835                            return applyPostResolutionFilter(result, instantAppPkgName);
6836                        }
6837                    } else if (result.size() <= 1 && !addEphemeral) {
6838                        // No result in parent user and <= 1 result in current profile, and we
6839                        // are not going to add emphemeral app, so we can return the result without
6840                        // further processing.
6841                        return applyPostResolutionFilter(result, instantAppPkgName);
6842                    }
6843                    // We have more than one candidate (combining results from current and parent
6844                    // profile), so we need filtering and sorting.
6845                    result = filterCandidatesWithDomainPreferredActivitiesLPr(
6846                            intent, flags, result, xpDomainInfo, userId);
6847                    sortResult = true;
6848                }
6849            } else {
6850                final PackageParser.Package pkg = mPackages.get(pkgName);
6851                result = null;
6852                if (pkg != null) {
6853                    result = filterIfNotSystemUser(
6854                            mActivities.queryIntentForPackage(
6855                                    intent, resolvedType, flags, pkg.activities, userId),
6856                            userId);
6857                }
6858                if (result == null || result.size() == 0) {
6859                    // the caller wants to resolve for a particular package; however, there
6860                    // were no installed results, so, try to find an ephemeral result
6861                    addEphemeral = !ephemeralDisabled
6862                            && isInstantAppAllowed(
6863                                    intent, null /*result*/, userId, true /*skipPackageCheck*/);
6864                    if (result == null) {
6865                        result = new ArrayList<>();
6866                    }
6867                }
6868            }
6869        }
6870        if (addEphemeral) {
6871            result = maybeAddInstantAppInstaller(result, intent, resolvedType, flags, userId);
6872        }
6873        if (sortResult) {
6874            Collections.sort(result, mResolvePrioritySorter);
6875        }
6876        return applyPostResolutionFilter(result, instantAppPkgName);
6877    }
6878
6879    private List<ResolveInfo> maybeAddInstantAppInstaller(List<ResolveInfo> result, Intent intent,
6880            String resolvedType, int flags, int userId) {
6881        // first, check to see if we've got an instant app already installed
6882        final boolean alreadyResolvedLocally = (flags & PackageManager.MATCH_INSTANT) != 0;
6883        ResolveInfo localInstantApp = null;
6884        boolean blockResolution = false;
6885        if (!alreadyResolvedLocally) {
6886            final List<ResolveInfo> instantApps = mActivities.queryIntent(intent, resolvedType,
6887                    flags
6888                        | PackageManager.GET_RESOLVED_FILTER
6889                        | PackageManager.MATCH_INSTANT
6890                        | PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY,
6891                    userId);
6892            for (int i = instantApps.size() - 1; i >= 0; --i) {
6893                final ResolveInfo info = instantApps.get(i);
6894                final String packageName = info.activityInfo.packageName;
6895                final PackageSetting ps = mSettings.mPackages.get(packageName);
6896                if (ps.getInstantApp(userId)) {
6897                    final long packedStatus = getDomainVerificationStatusLPr(ps, userId);
6898                    final int status = (int)(packedStatus >> 32);
6899                    final int linkGeneration = (int)(packedStatus & 0xFFFFFFFF);
6900                    if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
6901                        // there's a local instant application installed, but, the user has
6902                        // chosen to never use it; skip resolution and don't acknowledge
6903                        // an instant application is even available
6904                        if (DEBUG_EPHEMERAL) {
6905                            Slog.v(TAG, "Instant app marked to never run; pkg: " + packageName);
6906                        }
6907                        blockResolution = true;
6908                        break;
6909                    } else {
6910                        // we have a locally installed instant application; skip resolution
6911                        // but acknowledge there's an instant application available
6912                        if (DEBUG_EPHEMERAL) {
6913                            Slog.v(TAG, "Found installed instant app; pkg: " + packageName);
6914                        }
6915                        localInstantApp = info;
6916                        break;
6917                    }
6918                }
6919            }
6920        }
6921        // no app installed, let's see if one's available
6922        AuxiliaryResolveInfo auxiliaryResponse = null;
6923        if (!blockResolution) {
6924            if (localInstantApp == null) {
6925                // we don't have an instant app locally, resolve externally
6926                Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "resolveEphemeral");
6927                final InstantAppRequest requestObject = new InstantAppRequest(
6928                        null /*responseObj*/, intent /*origIntent*/, resolvedType,
6929                        null /*callingPackage*/, userId, null /*verificationBundle*/);
6930                auxiliaryResponse =
6931                        InstantAppResolver.doInstantAppResolutionPhaseOne(
6932                                mContext, mInstantAppResolverConnection, requestObject);
6933                Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
6934            } else {
6935                // we have an instant application locally, but, we can't admit that since
6936                // callers shouldn't be able to determine prior browsing. create a dummy
6937                // auxiliary response so the downstream code behaves as if there's an
6938                // instant application available externally. when it comes time to start
6939                // the instant application, we'll do the right thing.
6940                final ApplicationInfo ai = localInstantApp.activityInfo.applicationInfo;
6941                auxiliaryResponse = new AuxiliaryResolveInfo(
6942                        ai.packageName, null /*splitName*/, ai.versionCode, null /*failureIntent*/);
6943            }
6944        }
6945        if (auxiliaryResponse != null) {
6946            if (DEBUG_EPHEMERAL) {
6947                Slog.v(TAG, "Adding ephemeral installer to the ResolveInfo list");
6948            }
6949            final ResolveInfo ephemeralInstaller = new ResolveInfo(mInstantAppInstallerInfo);
6950            final PackageSetting ps =
6951                    mSettings.mPackages.get(mInstantAppInstallerActivity.packageName);
6952            if (ps != null) {
6953                ephemeralInstaller.activityInfo = PackageParser.generateActivityInfo(
6954                        mInstantAppInstallerActivity, 0, ps.readUserState(userId), userId);
6955                ephemeralInstaller.activityInfo.launchToken = auxiliaryResponse.token;
6956                ephemeralInstaller.auxiliaryInfo = auxiliaryResponse;
6957                // make sure this resolver is the default
6958                ephemeralInstaller.isDefault = true;
6959                ephemeralInstaller.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART
6960                        | IntentFilter.MATCH_ADJUSTMENT_NORMAL;
6961                // add a non-generic filter
6962                ephemeralInstaller.filter = new IntentFilter(intent.getAction());
6963                ephemeralInstaller.filter.addDataPath(
6964                        intent.getData().getPath(), PatternMatcher.PATTERN_LITERAL);
6965                ephemeralInstaller.isInstantAppAvailable = true;
6966                result.add(ephemeralInstaller);
6967            }
6968        }
6969        return result;
6970    }
6971
6972    private static class CrossProfileDomainInfo {
6973        /* ResolveInfo for IntentForwarderActivity to send the intent to the other profile */
6974        ResolveInfo resolveInfo;
6975        /* Best domain verification status of the activities found in the other profile */
6976        int bestDomainVerificationStatus;
6977    }
6978
6979    private CrossProfileDomainInfo getCrossProfileDomainPreferredLpr(Intent intent,
6980            String resolvedType, int flags, int sourceUserId, int parentUserId) {
6981        if (!sUserManager.hasUserRestriction(UserManager.ALLOW_PARENT_PROFILE_APP_LINKING,
6982                sourceUserId)) {
6983            return null;
6984        }
6985        List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent,
6986                resolvedType, flags, parentUserId);
6987
6988        if (resultTargetUser == null || resultTargetUser.isEmpty()) {
6989            return null;
6990        }
6991        CrossProfileDomainInfo result = null;
6992        int size = resultTargetUser.size();
6993        for (int i = 0; i < size; i++) {
6994            ResolveInfo riTargetUser = resultTargetUser.get(i);
6995            // Intent filter verification is only for filters that specify a host. So don't return
6996            // those that handle all web uris.
6997            if (riTargetUser.handleAllWebDataURI) {
6998                continue;
6999            }
7000            String packageName = riTargetUser.activityInfo.packageName;
7001            PackageSetting ps = mSettings.mPackages.get(packageName);
7002            if (ps == null) {
7003                continue;
7004            }
7005            long verificationState = getDomainVerificationStatusLPr(ps, parentUserId);
7006            int status = (int)(verificationState >> 32);
7007            if (result == null) {
7008                result = new CrossProfileDomainInfo();
7009                result.resolveInfo = createForwardingResolveInfoUnchecked(new IntentFilter(),
7010                        sourceUserId, parentUserId);
7011                result.bestDomainVerificationStatus = status;
7012            } else {
7013                result.bestDomainVerificationStatus = bestDomainVerificationStatus(status,
7014                        result.bestDomainVerificationStatus);
7015            }
7016        }
7017        // Don't consider matches with status NEVER across profiles.
7018        if (result != null && result.bestDomainVerificationStatus
7019                == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
7020            return null;
7021        }
7022        return result;
7023    }
7024
7025    /**
7026     * Verification statuses are ordered from the worse to the best, except for
7027     * INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER, which is the worse.
7028     */
7029    private int bestDomainVerificationStatus(int status1, int status2) {
7030        if (status1 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
7031            return status2;
7032        }
7033        if (status2 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
7034            return status1;
7035        }
7036        return (int) MathUtils.max(status1, status2);
7037    }
7038
7039    private boolean isUserEnabled(int userId) {
7040        long callingId = Binder.clearCallingIdentity();
7041        try {
7042            UserInfo userInfo = sUserManager.getUserInfo(userId);
7043            return userInfo != null && userInfo.isEnabled();
7044        } finally {
7045            Binder.restoreCallingIdentity(callingId);
7046        }
7047    }
7048
7049    /**
7050     * Filter out activities with systemUserOnly flag set, when current user is not System.
7051     *
7052     * @return filtered list
7053     */
7054    private List<ResolveInfo> filterIfNotSystemUser(List<ResolveInfo> resolveInfos, int userId) {
7055        if (userId == UserHandle.USER_SYSTEM) {
7056            return resolveInfos;
7057        }
7058        for (int i = resolveInfos.size() - 1; i >= 0; i--) {
7059            ResolveInfo info = resolveInfos.get(i);
7060            if ((info.activityInfo.flags & ActivityInfo.FLAG_SYSTEM_USER_ONLY) != 0) {
7061                resolveInfos.remove(i);
7062            }
7063        }
7064        return resolveInfos;
7065    }
7066
7067    /**
7068     * Filters out ephemeral activities.
7069     * <p>When resolving for an ephemeral app, only activities that 1) are defined in the
7070     * ephemeral app or 2) marked with {@code visibleToEphemeral} are returned.
7071     *
7072     * @param resolveInfos The pre-filtered list of resolved activities
7073     * @param ephemeralPkgName The ephemeral package name. If {@code null}, no filtering
7074     *          is performed.
7075     * @return A filtered list of resolved activities.
7076     */
7077    private List<ResolveInfo> applyPostResolutionFilter(List<ResolveInfo> resolveInfos,
7078            String ephemeralPkgName) {
7079        // TODO: When adding on-demand split support for non-instant apps, remove this check
7080        // and always apply post filtering
7081        if (ephemeralPkgName == null) {
7082            return resolveInfos;
7083        }
7084        for (int i = resolveInfos.size() - 1; i >= 0; i--) {
7085            final ResolveInfo info = resolveInfos.get(i);
7086            final boolean isEphemeralApp = info.activityInfo.applicationInfo.isInstantApp();
7087            // allow activities that are defined in the provided package
7088            if (isEphemeralApp && ephemeralPkgName.equals(info.activityInfo.packageName)) {
7089                if (info.activityInfo.splitName != null
7090                        && !ArrayUtils.contains(info.activityInfo.applicationInfo.splitNames,
7091                                info.activityInfo.splitName)) {
7092                    // requested activity is defined in a split that hasn't been installed yet.
7093                    // add the installer to the resolve list
7094                    if (DEBUG_EPHEMERAL) {
7095                        Slog.v(TAG, "Adding ephemeral installer to the ResolveInfo list");
7096                    }
7097                    final ResolveInfo installerInfo = new ResolveInfo(mInstantAppInstallerInfo);
7098                    installerInfo.auxiliaryInfo = new AuxiliaryResolveInfo(
7099                            info.activityInfo.packageName, info.activityInfo.splitName,
7100                            info.activityInfo.applicationInfo.versionCode, null /*failureIntent*/);
7101                    // make sure this resolver is the default
7102                    installerInfo.isDefault = true;
7103                    installerInfo.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART
7104                            | IntentFilter.MATCH_ADJUSTMENT_NORMAL;
7105                    // add a non-generic filter
7106                    installerInfo.filter = new IntentFilter();
7107                    // load resources from the correct package
7108                    installerInfo.resolvePackageName = info.getComponentInfo().packageName;
7109                    resolveInfos.set(i, installerInfo);
7110                }
7111                continue;
7112            }
7113            // allow activities that have been explicitly exposed to ephemeral apps
7114            if (!isEphemeralApp
7115                    && ((info.activityInfo.flags & ActivityInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0)) {
7116                continue;
7117            }
7118            resolveInfos.remove(i);
7119        }
7120        return resolveInfos;
7121    }
7122
7123    /**
7124     * @param resolveInfos list of resolve infos in descending priority order
7125     * @return if the list contains a resolve info with non-negative priority
7126     */
7127    private boolean hasNonNegativePriority(List<ResolveInfo> resolveInfos) {
7128        return resolveInfos.size() > 0 && resolveInfos.get(0).priority >= 0;
7129    }
7130
7131    private static boolean hasWebURI(Intent intent) {
7132        if (intent.getData() == null) {
7133            return false;
7134        }
7135        final String scheme = intent.getScheme();
7136        if (TextUtils.isEmpty(scheme)) {
7137            return false;
7138        }
7139        return scheme.equals(IntentFilter.SCHEME_HTTP) || scheme.equals(IntentFilter.SCHEME_HTTPS);
7140    }
7141
7142    private List<ResolveInfo> filterCandidatesWithDomainPreferredActivitiesLPr(Intent intent,
7143            int matchFlags, List<ResolveInfo> candidates, CrossProfileDomainInfo xpDomainInfo,
7144            int userId) {
7145        final boolean debug = (intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0;
7146
7147        if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) {
7148            Slog.v(TAG, "Filtering results with preferred activities. Candidates count: " +
7149                    candidates.size());
7150        }
7151
7152        ArrayList<ResolveInfo> result = new ArrayList<ResolveInfo>();
7153        ArrayList<ResolveInfo> alwaysList = new ArrayList<ResolveInfo>();
7154        ArrayList<ResolveInfo> undefinedList = new ArrayList<ResolveInfo>();
7155        ArrayList<ResolveInfo> alwaysAskList = new ArrayList<ResolveInfo>();
7156        ArrayList<ResolveInfo> neverList = new ArrayList<ResolveInfo>();
7157        ArrayList<ResolveInfo> matchAllList = new ArrayList<ResolveInfo>();
7158
7159        synchronized (mPackages) {
7160            final int count = candidates.size();
7161            // First, try to use linked apps. Partition the candidates into four lists:
7162            // one for the final results, one for the "do not use ever", one for "undefined status"
7163            // and finally one for "browser app type".
7164            for (int n=0; n<count; n++) {
7165                ResolveInfo info = candidates.get(n);
7166                String packageName = info.activityInfo.packageName;
7167                PackageSetting ps = mSettings.mPackages.get(packageName);
7168                if (ps != null) {
7169                    // Add to the special match all list (Browser use case)
7170                    if (info.handleAllWebDataURI) {
7171                        matchAllList.add(info);
7172                        continue;
7173                    }
7174                    // Try to get the status from User settings first
7175                    long packedStatus = getDomainVerificationStatusLPr(ps, userId);
7176                    int status = (int)(packedStatus >> 32);
7177                    int linkGeneration = (int)(packedStatus & 0xFFFFFFFF);
7178                    if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS) {
7179                        if (DEBUG_DOMAIN_VERIFICATION || debug) {
7180                            Slog.i(TAG, "  + always: " + info.activityInfo.packageName
7181                                    + " : linkgen=" + linkGeneration);
7182                        }
7183                        // Use link-enabled generation as preferredOrder, i.e.
7184                        // prefer newly-enabled over earlier-enabled.
7185                        info.preferredOrder = linkGeneration;
7186                        alwaysList.add(info);
7187                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
7188                        if (DEBUG_DOMAIN_VERIFICATION || debug) {
7189                            Slog.i(TAG, "  + never: " + info.activityInfo.packageName);
7190                        }
7191                        neverList.add(info);
7192                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) {
7193                        if (DEBUG_DOMAIN_VERIFICATION || debug) {
7194                            Slog.i(TAG, "  + always-ask: " + info.activityInfo.packageName);
7195                        }
7196                        alwaysAskList.add(info);
7197                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED ||
7198                            status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK) {
7199                        if (DEBUG_DOMAIN_VERIFICATION || debug) {
7200                            Slog.i(TAG, "  + ask: " + info.activityInfo.packageName);
7201                        }
7202                        undefinedList.add(info);
7203                    }
7204                }
7205            }
7206
7207            // We'll want to include browser possibilities in a few cases
7208            boolean includeBrowser = false;
7209
7210            // First try to add the "always" resolution(s) for the current user, if any
7211            if (alwaysList.size() > 0) {
7212                result.addAll(alwaysList);
7213            } else {
7214                // Add all undefined apps as we want them to appear in the disambiguation dialog.
7215                result.addAll(undefinedList);
7216                // Maybe add one for the other profile.
7217                if (xpDomainInfo != null && (
7218                        xpDomainInfo.bestDomainVerificationStatus
7219                        != INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER)) {
7220                    result.add(xpDomainInfo.resolveInfo);
7221                }
7222                includeBrowser = true;
7223            }
7224
7225            // The presence of any 'always ask' alternatives means we'll also offer browsers.
7226            // If there were 'always' entries their preferred order has been set, so we also
7227            // back that off to make the alternatives equivalent
7228            if (alwaysAskList.size() > 0) {
7229                for (ResolveInfo i : result) {
7230                    i.preferredOrder = 0;
7231                }
7232                result.addAll(alwaysAskList);
7233                includeBrowser = true;
7234            }
7235
7236            if (includeBrowser) {
7237                // Also add browsers (all of them or only the default one)
7238                if (DEBUG_DOMAIN_VERIFICATION) {
7239                    Slog.v(TAG, "   ...including browsers in candidate set");
7240                }
7241                if ((matchFlags & MATCH_ALL) != 0) {
7242                    result.addAll(matchAllList);
7243                } else {
7244                    // Browser/generic handling case.  If there's a default browser, go straight
7245                    // to that (but only if there is no other higher-priority match).
7246                    final String defaultBrowserPackageName = getDefaultBrowserPackageName(userId);
7247                    int maxMatchPrio = 0;
7248                    ResolveInfo defaultBrowserMatch = null;
7249                    final int numCandidates = matchAllList.size();
7250                    for (int n = 0; n < numCandidates; n++) {
7251                        ResolveInfo info = matchAllList.get(n);
7252                        // track the highest overall match priority...
7253                        if (info.priority > maxMatchPrio) {
7254                            maxMatchPrio = info.priority;
7255                        }
7256                        // ...and the highest-priority default browser match
7257                        if (info.activityInfo.packageName.equals(defaultBrowserPackageName)) {
7258                            if (defaultBrowserMatch == null
7259                                    || (defaultBrowserMatch.priority < info.priority)) {
7260                                if (debug) {
7261                                    Slog.v(TAG, "Considering default browser match " + info);
7262                                }
7263                                defaultBrowserMatch = info;
7264                            }
7265                        }
7266                    }
7267                    if (defaultBrowserMatch != null
7268                            && defaultBrowserMatch.priority >= maxMatchPrio
7269                            && !TextUtils.isEmpty(defaultBrowserPackageName))
7270                    {
7271                        if (debug) {
7272                            Slog.v(TAG, "Default browser match " + defaultBrowserMatch);
7273                        }
7274                        result.add(defaultBrowserMatch);
7275                    } else {
7276                        result.addAll(matchAllList);
7277                    }
7278                }
7279
7280                // If there is nothing selected, add all candidates and remove the ones that the user
7281                // has explicitly put into the INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER state
7282                if (result.size() == 0) {
7283                    result.addAll(candidates);
7284                    result.removeAll(neverList);
7285                }
7286            }
7287        }
7288        if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) {
7289            Slog.v(TAG, "Filtered results with preferred activities. New candidates count: " +
7290                    result.size());
7291            for (ResolveInfo info : result) {
7292                Slog.v(TAG, "  + " + info.activityInfo);
7293            }
7294        }
7295        return result;
7296    }
7297
7298    // Returns a packed value as a long:
7299    //
7300    // high 'int'-sized word: link status: undefined/ask/never/always.
7301    // low 'int'-sized word: relative priority among 'always' results.
7302    private long getDomainVerificationStatusLPr(PackageSetting ps, int userId) {
7303        long result = ps.getDomainVerificationStatusForUser(userId);
7304        // if none available, get the master status
7305        if (result >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) {
7306            if (ps.getIntentFilterVerificationInfo() != null) {
7307                result = ((long)ps.getIntentFilterVerificationInfo().getStatus()) << 32;
7308            }
7309        }
7310        return result;
7311    }
7312
7313    private ResolveInfo querySkipCurrentProfileIntents(
7314            List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType,
7315            int flags, int sourceUserId) {
7316        if (matchingFilters != null) {
7317            int size = matchingFilters.size();
7318            for (int i = 0; i < size; i ++) {
7319                CrossProfileIntentFilter filter = matchingFilters.get(i);
7320                if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0) {
7321                    // Checking if there are activities in the target user that can handle the
7322                    // intent.
7323                    ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent,
7324                            resolvedType, flags, sourceUserId);
7325                    if (resolveInfo != null) {
7326                        return resolveInfo;
7327                    }
7328                }
7329            }
7330        }
7331        return null;
7332    }
7333
7334    // Return matching ResolveInfo in target user if any.
7335    private ResolveInfo queryCrossProfileIntents(
7336            List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType,
7337            int flags, int sourceUserId, boolean matchInCurrentProfile) {
7338        if (matchingFilters != null) {
7339            // Two {@link CrossProfileIntentFilter}s can have the same targetUserId and
7340            // match the same intent. For performance reasons, it is better not to
7341            // run queryIntent twice for the same userId
7342            SparseBooleanArray alreadyTriedUserIds = new SparseBooleanArray();
7343            int size = matchingFilters.size();
7344            for (int i = 0; i < size; i++) {
7345                CrossProfileIntentFilter filter = matchingFilters.get(i);
7346                int targetUserId = filter.getTargetUserId();
7347                boolean skipCurrentProfile =
7348                        (filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0;
7349                boolean skipCurrentProfileIfNoMatchFound =
7350                        (filter.getFlags() & PackageManager.ONLY_IF_NO_MATCH_FOUND) != 0;
7351                if (!skipCurrentProfile && !alreadyTriedUserIds.get(targetUserId)
7352                        && (!skipCurrentProfileIfNoMatchFound || !matchInCurrentProfile)) {
7353                    // Checking if there are activities in the target user that can handle the
7354                    // intent.
7355                    ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent,
7356                            resolvedType, flags, sourceUserId);
7357                    if (resolveInfo != null) return resolveInfo;
7358                    alreadyTriedUserIds.put(targetUserId, true);
7359                }
7360            }
7361        }
7362        return null;
7363    }
7364
7365    /**
7366     * If the filter's target user can handle the intent and is enabled: returns a ResolveInfo that
7367     * will forward the intent to the filter's target user.
7368     * Otherwise, returns null.
7369     */
7370    private ResolveInfo createForwardingResolveInfo(CrossProfileIntentFilter filter, Intent intent,
7371            String resolvedType, int flags, int sourceUserId) {
7372        int targetUserId = filter.getTargetUserId();
7373        List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent,
7374                resolvedType, flags, targetUserId);
7375        if (resultTargetUser != null && isUserEnabled(targetUserId)) {
7376            // If all the matches in the target profile are suspended, return null.
7377            for (int i = resultTargetUser.size() - 1; i >= 0; i--) {
7378                if ((resultTargetUser.get(i).activityInfo.applicationInfo.flags
7379                        & ApplicationInfo.FLAG_SUSPENDED) == 0) {
7380                    return createForwardingResolveInfoUnchecked(filter, sourceUserId,
7381                            targetUserId);
7382                }
7383            }
7384        }
7385        return null;
7386    }
7387
7388    private ResolveInfo createForwardingResolveInfoUnchecked(IntentFilter filter,
7389            int sourceUserId, int targetUserId) {
7390        ResolveInfo forwardingResolveInfo = new ResolveInfo();
7391        long ident = Binder.clearCallingIdentity();
7392        boolean targetIsProfile;
7393        try {
7394            targetIsProfile = sUserManager.getUserInfo(targetUserId).isManagedProfile();
7395        } finally {
7396            Binder.restoreCallingIdentity(ident);
7397        }
7398        String className;
7399        if (targetIsProfile) {
7400            className = FORWARD_INTENT_TO_MANAGED_PROFILE;
7401        } else {
7402            className = FORWARD_INTENT_TO_PARENT;
7403        }
7404        ComponentName forwardingActivityComponentName = new ComponentName(
7405                mAndroidApplication.packageName, className);
7406        ActivityInfo forwardingActivityInfo = getActivityInfo(forwardingActivityComponentName, 0,
7407                sourceUserId);
7408        if (!targetIsProfile) {
7409            forwardingActivityInfo.showUserIcon = targetUserId;
7410            forwardingResolveInfo.noResourceId = true;
7411        }
7412        forwardingResolveInfo.activityInfo = forwardingActivityInfo;
7413        forwardingResolveInfo.priority = 0;
7414        forwardingResolveInfo.preferredOrder = 0;
7415        forwardingResolveInfo.match = 0;
7416        forwardingResolveInfo.isDefault = true;
7417        forwardingResolveInfo.filter = filter;
7418        forwardingResolveInfo.targetUserId = targetUserId;
7419        return forwardingResolveInfo;
7420    }
7421
7422    @Override
7423    public @NonNull ParceledListSlice<ResolveInfo> queryIntentActivityOptions(ComponentName caller,
7424            Intent[] specifics, String[] specificTypes, Intent intent,
7425            String resolvedType, int flags, int userId) {
7426        return new ParceledListSlice<>(queryIntentActivityOptionsInternal(caller, specifics,
7427                specificTypes, intent, resolvedType, flags, userId));
7428    }
7429
7430    private @NonNull List<ResolveInfo> queryIntentActivityOptionsInternal(ComponentName caller,
7431            Intent[] specifics, String[] specificTypes, Intent intent,
7432            String resolvedType, int flags, int userId) {
7433        if (!sUserManager.exists(userId)) return Collections.emptyList();
7434        final int callingUid = Binder.getCallingUid();
7435        flags = updateFlagsForResolve(flags, userId, intent, callingUid,
7436                false /*includeInstantApps*/);
7437        enforceCrossUserPermission(callingUid, userId,
7438                false /*requireFullPermission*/, false /*checkShell*/,
7439                "query intent activity options");
7440        final String resultsAction = intent.getAction();
7441
7442        final List<ResolveInfo> results = queryIntentActivitiesInternal(intent, resolvedType, flags
7443                | PackageManager.GET_RESOLVED_FILTER, userId);
7444
7445        if (DEBUG_INTENT_MATCHING) {
7446            Log.v(TAG, "Query " + intent + ": " + results);
7447        }
7448
7449        int specificsPos = 0;
7450        int N;
7451
7452        // todo: note that the algorithm used here is O(N^2).  This
7453        // isn't a problem in our current environment, but if we start running
7454        // into situations where we have more than 5 or 10 matches then this
7455        // should probably be changed to something smarter...
7456
7457        // First we go through and resolve each of the specific items
7458        // that were supplied, taking care of removing any corresponding
7459        // duplicate items in the generic resolve list.
7460        if (specifics != null) {
7461            for (int i=0; i<specifics.length; i++) {
7462                final Intent sintent = specifics[i];
7463                if (sintent == null) {
7464                    continue;
7465                }
7466
7467                if (DEBUG_INTENT_MATCHING) {
7468                    Log.v(TAG, "Specific #" + i + ": " + sintent);
7469                }
7470
7471                String action = sintent.getAction();
7472                if (resultsAction != null && resultsAction.equals(action)) {
7473                    // If this action was explicitly requested, then don't
7474                    // remove things that have it.
7475                    action = null;
7476                }
7477
7478                ResolveInfo ri = null;
7479                ActivityInfo ai = null;
7480
7481                ComponentName comp = sintent.getComponent();
7482                if (comp == null) {
7483                    ri = resolveIntent(
7484                        sintent,
7485                        specificTypes != null ? specificTypes[i] : null,
7486                            flags, userId);
7487                    if (ri == null) {
7488                        continue;
7489                    }
7490                    if (ri == mResolveInfo) {
7491                        // ACK!  Must do something better with this.
7492                    }
7493                    ai = ri.activityInfo;
7494                    comp = new ComponentName(ai.applicationInfo.packageName,
7495                            ai.name);
7496                } else {
7497                    ai = getActivityInfo(comp, flags, userId);
7498                    if (ai == null) {
7499                        continue;
7500                    }
7501                }
7502
7503                // Look for any generic query activities that are duplicates
7504                // of this specific one, and remove them from the results.
7505                if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Specific #" + i + ": " + ai);
7506                N = results.size();
7507                int j;
7508                for (j=specificsPos; j<N; j++) {
7509                    ResolveInfo sri = results.get(j);
7510                    if ((sri.activityInfo.name.equals(comp.getClassName())
7511                            && sri.activityInfo.applicationInfo.packageName.equals(
7512                                    comp.getPackageName()))
7513                        || (action != null && sri.filter.matchAction(action))) {
7514                        results.remove(j);
7515                        if (DEBUG_INTENT_MATCHING) Log.v(
7516                            TAG, "Removing duplicate item from " + j
7517                            + " due to specific " + specificsPos);
7518                        if (ri == null) {
7519                            ri = sri;
7520                        }
7521                        j--;
7522                        N--;
7523                    }
7524                }
7525
7526                // Add this specific item to its proper place.
7527                if (ri == null) {
7528                    ri = new ResolveInfo();
7529                    ri.activityInfo = ai;
7530                }
7531                results.add(specificsPos, ri);
7532                ri.specificIndex = i;
7533                specificsPos++;
7534            }
7535        }
7536
7537        // Now we go through the remaining generic results and remove any
7538        // duplicate actions that are found here.
7539        N = results.size();
7540        for (int i=specificsPos; i<N-1; i++) {
7541            final ResolveInfo rii = results.get(i);
7542            if (rii.filter == null) {
7543                continue;
7544            }
7545
7546            // Iterate over all of the actions of this result's intent
7547            // filter...  typically this should be just one.
7548            final Iterator<String> it = rii.filter.actionsIterator();
7549            if (it == null) {
7550                continue;
7551            }
7552            while (it.hasNext()) {
7553                final String action = it.next();
7554                if (resultsAction != null && resultsAction.equals(action)) {
7555                    // If this action was explicitly requested, then don't
7556                    // remove things that have it.
7557                    continue;
7558                }
7559                for (int j=i+1; j<N; j++) {
7560                    final ResolveInfo rij = results.get(j);
7561                    if (rij.filter != null && rij.filter.hasAction(action)) {
7562                        results.remove(j);
7563                        if (DEBUG_INTENT_MATCHING) Log.v(
7564                            TAG, "Removing duplicate item from " + j
7565                            + " due to action " + action + " at " + i);
7566                        j--;
7567                        N--;
7568                    }
7569                }
7570            }
7571
7572            // If the caller didn't request filter information, drop it now
7573            // so we don't have to marshall/unmarshall it.
7574            if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
7575                rii.filter = null;
7576            }
7577        }
7578
7579        // Filter out the caller activity if so requested.
7580        if (caller != null) {
7581            N = results.size();
7582            for (int i=0; i<N; i++) {
7583                ActivityInfo ainfo = results.get(i).activityInfo;
7584                if (caller.getPackageName().equals(ainfo.applicationInfo.packageName)
7585                        && caller.getClassName().equals(ainfo.name)) {
7586                    results.remove(i);
7587                    break;
7588                }
7589            }
7590        }
7591
7592        // If the caller didn't request filter information,
7593        // drop them now so we don't have to
7594        // marshall/unmarshall it.
7595        if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
7596            N = results.size();
7597            for (int i=0; i<N; i++) {
7598                results.get(i).filter = null;
7599            }
7600        }
7601
7602        if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Result: " + results);
7603        return results;
7604    }
7605
7606    @Override
7607    public @NonNull ParceledListSlice<ResolveInfo> queryIntentReceivers(Intent intent,
7608            String resolvedType, int flags, int userId) {
7609        return new ParceledListSlice<>(
7610                queryIntentReceiversInternal(intent, resolvedType, flags, userId));
7611    }
7612
7613    private @NonNull List<ResolveInfo> queryIntentReceiversInternal(Intent intent,
7614            String resolvedType, int flags, int userId) {
7615        if (!sUserManager.exists(userId)) return Collections.emptyList();
7616        final int callingUid = Binder.getCallingUid();
7617        final String instantAppPkgName = getInstantAppPackageName(callingUid);
7618        flags = updateFlagsForResolve(flags, userId, intent, callingUid,
7619                false /*includeInstantApps*/);
7620        ComponentName comp = intent.getComponent();
7621        if (comp == null) {
7622            if (intent.getSelector() != null) {
7623                intent = intent.getSelector();
7624                comp = intent.getComponent();
7625            }
7626        }
7627        if (comp != null) {
7628            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
7629            final ActivityInfo ai = getReceiverInfo(comp, flags, userId);
7630            if (ai != null) {
7631                // When specifying an explicit component, we prevent the activity from being
7632                // used when either 1) the calling package is normal and the activity is within
7633                // an instant application or 2) the calling package is ephemeral and the
7634                // activity is not visible to instant applications.
7635                final boolean matchInstantApp =
7636                        (flags & PackageManager.MATCH_INSTANT) != 0;
7637                final boolean matchVisibleToInstantAppOnly =
7638                        (flags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
7639                final boolean matchExplicitlyVisibleOnly =
7640                        (flags & PackageManager.MATCH_EXPLICITLY_VISIBLE_ONLY) != 0;
7641                final boolean isCallerInstantApp =
7642                        instantAppPkgName != null;
7643                final boolean isTargetSameInstantApp =
7644                        comp.getPackageName().equals(instantAppPkgName);
7645                final boolean isTargetInstantApp =
7646                        (ai.applicationInfo.privateFlags
7647                                & ApplicationInfo.PRIVATE_FLAG_INSTANT) != 0;
7648                final boolean isTargetVisibleToInstantApp =
7649                        (ai.flags & ActivityInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0;
7650                final boolean isTargetExplicitlyVisibleToInstantApp =
7651                        isTargetVisibleToInstantApp
7652                        && (ai.flags & ActivityInfo.FLAG_IMPLICITLY_VISIBLE_TO_INSTANT_APP) == 0;
7653                final boolean isTargetHiddenFromInstantApp =
7654                        !isTargetVisibleToInstantApp
7655                        || (matchExplicitlyVisibleOnly && !isTargetExplicitlyVisibleToInstantApp);
7656                final boolean blockResolution =
7657                        !isTargetSameInstantApp
7658                        && ((!matchInstantApp && !isCallerInstantApp && isTargetInstantApp)
7659                                || (matchVisibleToInstantAppOnly && isCallerInstantApp
7660                                        && isTargetHiddenFromInstantApp));
7661                if (!blockResolution) {
7662                    ResolveInfo ri = new ResolveInfo();
7663                    ri.activityInfo = ai;
7664                    list.add(ri);
7665                }
7666            }
7667            return applyPostResolutionFilter(list, instantAppPkgName);
7668        }
7669
7670        // reader
7671        synchronized (mPackages) {
7672            String pkgName = intent.getPackage();
7673            if (pkgName == null) {
7674                final List<ResolveInfo> result =
7675                        mReceivers.queryIntent(intent, resolvedType, flags, userId);
7676                return applyPostResolutionFilter(result, instantAppPkgName);
7677            }
7678            final PackageParser.Package pkg = mPackages.get(pkgName);
7679            if (pkg != null) {
7680                final List<ResolveInfo> result = mReceivers.queryIntentForPackage(
7681                        intent, resolvedType, flags, pkg.receivers, userId);
7682                return applyPostResolutionFilter(result, instantAppPkgName);
7683            }
7684            return Collections.emptyList();
7685        }
7686    }
7687
7688    @Override
7689    public ResolveInfo resolveService(Intent intent, String resolvedType, int flags, int userId) {
7690        final int callingUid = Binder.getCallingUid();
7691        return resolveServiceInternal(intent, resolvedType, flags, userId, callingUid);
7692    }
7693
7694    private ResolveInfo resolveServiceInternal(Intent intent, String resolvedType, int flags,
7695            int userId, int callingUid) {
7696        if (!sUserManager.exists(userId)) return null;
7697        flags = updateFlagsForResolve(
7698                flags, userId, intent, callingUid, false /*includeInstantApps*/);
7699        List<ResolveInfo> query = queryIntentServicesInternal(
7700                intent, resolvedType, flags, userId, callingUid, false /*includeInstantApps*/);
7701        if (query != null) {
7702            if (query.size() >= 1) {
7703                // If there is more than one service with the same priority,
7704                // just arbitrarily pick the first one.
7705                return query.get(0);
7706            }
7707        }
7708        return null;
7709    }
7710
7711    @Override
7712    public @NonNull ParceledListSlice<ResolveInfo> queryIntentServices(Intent intent,
7713            String resolvedType, int flags, int userId) {
7714        final int callingUid = Binder.getCallingUid();
7715        return new ParceledListSlice<>(queryIntentServicesInternal(
7716                intent, resolvedType, flags, userId, callingUid, false /*includeInstantApps*/));
7717    }
7718
7719    private @NonNull List<ResolveInfo> queryIntentServicesInternal(Intent intent,
7720            String resolvedType, int flags, int userId, int callingUid,
7721            boolean includeInstantApps) {
7722        if (!sUserManager.exists(userId)) return Collections.emptyList();
7723        final String instantAppPkgName = getInstantAppPackageName(callingUid);
7724        flags = updateFlagsForResolve(flags, userId, intent, callingUid, includeInstantApps);
7725        ComponentName comp = intent.getComponent();
7726        if (comp == null) {
7727            if (intent.getSelector() != null) {
7728                intent = intent.getSelector();
7729                comp = intent.getComponent();
7730            }
7731        }
7732        if (comp != null) {
7733            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
7734            final ServiceInfo si = getServiceInfo(comp, flags, userId);
7735            if (si != null) {
7736                // When specifying an explicit component, we prevent the service from being
7737                // used when either 1) the service is in an instant application and the
7738                // caller is not the same instant application or 2) the calling package is
7739                // ephemeral and the activity is not visible to ephemeral applications.
7740                final boolean matchInstantApp =
7741                        (flags & PackageManager.MATCH_INSTANT) != 0;
7742                final boolean matchVisibleToInstantAppOnly =
7743                        (flags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
7744                final boolean isCallerInstantApp =
7745                        instantAppPkgName != null;
7746                final boolean isTargetSameInstantApp =
7747                        comp.getPackageName().equals(instantAppPkgName);
7748                final boolean isTargetInstantApp =
7749                        (si.applicationInfo.privateFlags
7750                                & ApplicationInfo.PRIVATE_FLAG_INSTANT) != 0;
7751                final boolean isTargetHiddenFromInstantApp =
7752                        (si.flags & ServiceInfo.FLAG_VISIBLE_TO_INSTANT_APP) == 0;
7753                final boolean blockResolution =
7754                        !isTargetSameInstantApp
7755                        && ((!matchInstantApp && !isCallerInstantApp && isTargetInstantApp)
7756                                || (matchVisibleToInstantAppOnly && isCallerInstantApp
7757                                        && isTargetHiddenFromInstantApp));
7758                if (!blockResolution) {
7759                    final ResolveInfo ri = new ResolveInfo();
7760                    ri.serviceInfo = si;
7761                    list.add(ri);
7762                }
7763            }
7764            return list;
7765        }
7766
7767        // reader
7768        synchronized (mPackages) {
7769            String pkgName = intent.getPackage();
7770            if (pkgName == null) {
7771                return applyPostServiceResolutionFilter(
7772                        mServices.queryIntent(intent, resolvedType, flags, userId),
7773                        instantAppPkgName);
7774            }
7775            final PackageParser.Package pkg = mPackages.get(pkgName);
7776            if (pkg != null) {
7777                return applyPostServiceResolutionFilter(
7778                        mServices.queryIntentForPackage(intent, resolvedType, flags, pkg.services,
7779                                userId),
7780                        instantAppPkgName);
7781            }
7782            return Collections.emptyList();
7783        }
7784    }
7785
7786    private List<ResolveInfo> applyPostServiceResolutionFilter(List<ResolveInfo> resolveInfos,
7787            String instantAppPkgName) {
7788        // TODO: When adding on-demand split support for non-instant apps, remove this check
7789        // and always apply post filtering
7790        if (instantAppPkgName == null) {
7791            return resolveInfos;
7792        }
7793        for (int i = resolveInfos.size() - 1; i >= 0; i--) {
7794            final ResolveInfo info = resolveInfos.get(i);
7795            final boolean isEphemeralApp = info.serviceInfo.applicationInfo.isInstantApp();
7796            // allow services that are defined in the provided package
7797            if (isEphemeralApp && instantAppPkgName.equals(info.serviceInfo.packageName)) {
7798                if (info.serviceInfo.splitName != null
7799                        && !ArrayUtils.contains(info.serviceInfo.applicationInfo.splitNames,
7800                                info.serviceInfo.splitName)) {
7801                    // requested service is defined in a split that hasn't been installed yet.
7802                    // add the installer to the resolve list
7803                    if (DEBUG_EPHEMERAL) {
7804                        Slog.v(TAG, "Adding ephemeral installer to the ResolveInfo list");
7805                    }
7806                    final ResolveInfo installerInfo = new ResolveInfo(mInstantAppInstallerInfo);
7807                    installerInfo.auxiliaryInfo = new AuxiliaryResolveInfo(
7808                            info.serviceInfo.packageName, info.serviceInfo.splitName,
7809                            info.serviceInfo.applicationInfo.versionCode, null /*failureIntent*/);
7810                    // make sure this resolver is the default
7811                    installerInfo.isDefault = true;
7812                    installerInfo.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART
7813                            | IntentFilter.MATCH_ADJUSTMENT_NORMAL;
7814                    // add a non-generic filter
7815                    installerInfo.filter = new IntentFilter();
7816                    // load resources from the correct package
7817                    installerInfo.resolvePackageName = info.getComponentInfo().packageName;
7818                    resolveInfos.set(i, installerInfo);
7819                }
7820                continue;
7821            }
7822            // allow services that have been explicitly exposed to ephemeral apps
7823            if (!isEphemeralApp
7824                    && ((info.serviceInfo.flags & ServiceInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0)) {
7825                continue;
7826            }
7827            resolveInfos.remove(i);
7828        }
7829        return resolveInfos;
7830    }
7831
7832    @Override
7833    public @NonNull ParceledListSlice<ResolveInfo> queryIntentContentProviders(Intent intent,
7834            String resolvedType, int flags, int userId) {
7835        return new ParceledListSlice<>(
7836                queryIntentContentProvidersInternal(intent, resolvedType, flags, userId));
7837    }
7838
7839    private @NonNull List<ResolveInfo> queryIntentContentProvidersInternal(
7840            Intent intent, String resolvedType, int flags, int userId) {
7841        if (!sUserManager.exists(userId)) return Collections.emptyList();
7842        final int callingUid = Binder.getCallingUid();
7843        final String instantAppPkgName = getInstantAppPackageName(callingUid);
7844        flags = updateFlagsForResolve(flags, userId, intent, callingUid,
7845                false /*includeInstantApps*/);
7846        ComponentName comp = intent.getComponent();
7847        if (comp == null) {
7848            if (intent.getSelector() != null) {
7849                intent = intent.getSelector();
7850                comp = intent.getComponent();
7851            }
7852        }
7853        if (comp != null) {
7854            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
7855            final ProviderInfo pi = getProviderInfo(comp, flags, userId);
7856            if (pi != null) {
7857                // When specifying an explicit component, we prevent the provider from being
7858                // used when either 1) the provider is in an instant application and the
7859                // caller is not the same instant application or 2) the calling package is an
7860                // instant application and the provider is not visible to instant applications.
7861                final boolean matchInstantApp =
7862                        (flags & PackageManager.MATCH_INSTANT) != 0;
7863                final boolean matchVisibleToInstantAppOnly =
7864                        (flags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
7865                final boolean isCallerInstantApp =
7866                        instantAppPkgName != null;
7867                final boolean isTargetSameInstantApp =
7868                        comp.getPackageName().equals(instantAppPkgName);
7869                final boolean isTargetInstantApp =
7870                        (pi.applicationInfo.privateFlags
7871                                & ApplicationInfo.PRIVATE_FLAG_INSTANT) != 0;
7872                final boolean isTargetHiddenFromInstantApp =
7873                        (pi.flags & ProviderInfo.FLAG_VISIBLE_TO_INSTANT_APP) == 0;
7874                final boolean blockResolution =
7875                        !isTargetSameInstantApp
7876                        && ((!matchInstantApp && !isCallerInstantApp && isTargetInstantApp)
7877                                || (matchVisibleToInstantAppOnly && isCallerInstantApp
7878                                        && isTargetHiddenFromInstantApp));
7879                if (!blockResolution) {
7880                    final ResolveInfo ri = new ResolveInfo();
7881                    ri.providerInfo = pi;
7882                    list.add(ri);
7883                }
7884            }
7885            return list;
7886        }
7887
7888        // reader
7889        synchronized (mPackages) {
7890            String pkgName = intent.getPackage();
7891            if (pkgName == null) {
7892                return applyPostContentProviderResolutionFilter(
7893                        mProviders.queryIntent(intent, resolvedType, flags, userId),
7894                        instantAppPkgName);
7895            }
7896            final PackageParser.Package pkg = mPackages.get(pkgName);
7897            if (pkg != null) {
7898                return applyPostContentProviderResolutionFilter(
7899                        mProviders.queryIntentForPackage(
7900                        intent, resolvedType, flags, pkg.providers, userId),
7901                        instantAppPkgName);
7902            }
7903            return Collections.emptyList();
7904        }
7905    }
7906
7907    private List<ResolveInfo> applyPostContentProviderResolutionFilter(
7908            List<ResolveInfo> resolveInfos, String instantAppPkgName) {
7909        // TODO: When adding on-demand split support for non-instant applications, remove
7910        // this check and always apply post filtering
7911        if (instantAppPkgName == null) {
7912            return resolveInfos;
7913        }
7914        for (int i = resolveInfos.size() - 1; i >= 0; i--) {
7915            final ResolveInfo info = resolveInfos.get(i);
7916            final boolean isEphemeralApp = info.providerInfo.applicationInfo.isInstantApp();
7917            // allow providers that are defined in the provided package
7918            if (isEphemeralApp && instantAppPkgName.equals(info.providerInfo.packageName)) {
7919                if (info.providerInfo.splitName != null
7920                        && !ArrayUtils.contains(info.providerInfo.applicationInfo.splitNames,
7921                                info.providerInfo.splitName)) {
7922                    // requested provider is defined in a split that hasn't been installed yet.
7923                    // add the installer to the resolve list
7924                    if (DEBUG_EPHEMERAL) {
7925                        Slog.v(TAG, "Adding ephemeral installer to the ResolveInfo list");
7926                    }
7927                    final ResolveInfo installerInfo = new ResolveInfo(mInstantAppInstallerInfo);
7928                    installerInfo.auxiliaryInfo = new AuxiliaryResolveInfo(
7929                            info.providerInfo.packageName, info.providerInfo.splitName,
7930                            info.providerInfo.applicationInfo.versionCode, null /*failureIntent*/);
7931                    // make sure this resolver is the default
7932                    installerInfo.isDefault = true;
7933                    installerInfo.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART
7934                            | IntentFilter.MATCH_ADJUSTMENT_NORMAL;
7935                    // add a non-generic filter
7936                    installerInfo.filter = new IntentFilter();
7937                    // load resources from the correct package
7938                    installerInfo.resolvePackageName = info.getComponentInfo().packageName;
7939                    resolveInfos.set(i, installerInfo);
7940                }
7941                continue;
7942            }
7943            // allow providers that have been explicitly exposed to instant applications
7944            if (!isEphemeralApp
7945                    && ((info.providerInfo.flags & ProviderInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0)) {
7946                continue;
7947            }
7948            resolveInfos.remove(i);
7949        }
7950        return resolveInfos;
7951    }
7952
7953    @Override
7954    public ParceledListSlice<PackageInfo> getInstalledPackages(int flags, int userId) {
7955        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
7956            return ParceledListSlice.emptyList();
7957        }
7958        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
7959        flags = updateFlagsForPackage(flags, userId, null);
7960        final boolean listUninstalled = (flags & MATCH_KNOWN_PACKAGES) != 0;
7961        enforceCrossUserPermission(Binder.getCallingUid(), userId,
7962                true /* requireFullPermission */, false /* checkShell */,
7963                "get installed packages");
7964
7965        // writer
7966        synchronized (mPackages) {
7967            ArrayList<PackageInfo> list;
7968            if (listUninstalled) {
7969                list = new ArrayList<>(mSettings.mPackages.size());
7970                for (PackageSetting ps : mSettings.mPackages.values()) {
7971                    if (filterSharedLibPackageLPr(ps, Binder.getCallingUid(), userId, flags)) {
7972                        continue;
7973                    }
7974                    final PackageInfo pi = generatePackageInfo(ps, flags, userId);
7975                    if (pi != null) {
7976                        list.add(pi);
7977                    }
7978                }
7979            } else {
7980                list = new ArrayList<>(mPackages.size());
7981                for (PackageParser.Package p : mPackages.values()) {
7982                    if (filterSharedLibPackageLPr((PackageSetting) p.mExtras,
7983                            Binder.getCallingUid(), userId, flags)) {
7984                        continue;
7985                    }
7986                    final PackageInfo pi = generatePackageInfo((PackageSetting)
7987                            p.mExtras, flags, userId);
7988                    if (pi != null) {
7989                        list.add(pi);
7990                    }
7991                }
7992            }
7993
7994            return new ParceledListSlice<>(list);
7995        }
7996    }
7997
7998    private void addPackageHoldingPermissions(ArrayList<PackageInfo> list, PackageSetting ps,
7999            String[] permissions, boolean[] tmp, int flags, int userId) {
8000        int numMatch = 0;
8001        final PermissionsState permissionsState = ps.getPermissionsState();
8002        for (int i=0; i<permissions.length; i++) {
8003            final String permission = permissions[i];
8004            if (permissionsState.hasPermission(permission, userId)) {
8005                tmp[i] = true;
8006                numMatch++;
8007            } else {
8008                tmp[i] = false;
8009            }
8010        }
8011        if (numMatch == 0) {
8012            return;
8013        }
8014        final PackageInfo pi = generatePackageInfo(ps, flags, userId);
8015
8016        // The above might return null in cases of uninstalled apps or install-state
8017        // skew across users/profiles.
8018        if (pi != null) {
8019            if ((flags&PackageManager.GET_PERMISSIONS) == 0) {
8020                if (numMatch == permissions.length) {
8021                    pi.requestedPermissions = permissions;
8022                } else {
8023                    pi.requestedPermissions = new String[numMatch];
8024                    numMatch = 0;
8025                    for (int i=0; i<permissions.length; i++) {
8026                        if (tmp[i]) {
8027                            pi.requestedPermissions[numMatch] = permissions[i];
8028                            numMatch++;
8029                        }
8030                    }
8031                }
8032            }
8033            list.add(pi);
8034        }
8035    }
8036
8037    @Override
8038    public ParceledListSlice<PackageInfo> getPackagesHoldingPermissions(
8039            String[] permissions, int flags, int userId) {
8040        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
8041        flags = updateFlagsForPackage(flags, userId, permissions);
8042        enforceCrossUserPermission(Binder.getCallingUid(), userId,
8043                true /* requireFullPermission */, false /* checkShell */,
8044                "get packages holding permissions");
8045        final boolean listUninstalled = (flags & MATCH_KNOWN_PACKAGES) != 0;
8046
8047        // writer
8048        synchronized (mPackages) {
8049            ArrayList<PackageInfo> list = new ArrayList<PackageInfo>();
8050            boolean[] tmpBools = new boolean[permissions.length];
8051            if (listUninstalled) {
8052                for (PackageSetting ps : mSettings.mPackages.values()) {
8053                    addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags,
8054                            userId);
8055                }
8056            } else {
8057                for (PackageParser.Package pkg : mPackages.values()) {
8058                    PackageSetting ps = (PackageSetting)pkg.mExtras;
8059                    if (ps != null) {
8060                        addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags,
8061                                userId);
8062                    }
8063                }
8064            }
8065
8066            return new ParceledListSlice<PackageInfo>(list);
8067        }
8068    }
8069
8070    @Override
8071    public ParceledListSlice<ApplicationInfo> getInstalledApplications(int flags, int userId) {
8072        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
8073            return ParceledListSlice.emptyList();
8074        }
8075        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
8076        flags = updateFlagsForApplication(flags, userId, null);
8077        final boolean listUninstalled = (flags & MATCH_KNOWN_PACKAGES) != 0;
8078
8079        // writer
8080        synchronized (mPackages) {
8081            ArrayList<ApplicationInfo> list;
8082            if (listUninstalled) {
8083                list = new ArrayList<>(mSettings.mPackages.size());
8084                for (PackageSetting ps : mSettings.mPackages.values()) {
8085                    ApplicationInfo ai;
8086                    int effectiveFlags = flags;
8087                    if (ps.isSystem()) {
8088                        effectiveFlags |= PackageManager.MATCH_ANY_USER;
8089                    }
8090                    if (ps.pkg != null) {
8091                        if (filterSharedLibPackageLPr(ps, Binder.getCallingUid(), userId, flags)) {
8092                            continue;
8093                        }
8094                        ai = PackageParser.generateApplicationInfo(ps.pkg, effectiveFlags,
8095                                ps.readUserState(userId), userId);
8096                        if (ai != null) {
8097                            rebaseEnabledOverlays(ai, userId);
8098                            ai.packageName = resolveExternalPackageNameLPr(ps.pkg);
8099                        }
8100                    } else {
8101                        // Shared lib filtering done in generateApplicationInfoFromSettingsLPw
8102                        // and already converts to externally visible package name
8103                        ai = generateApplicationInfoFromSettingsLPw(ps.name,
8104                                Binder.getCallingUid(), effectiveFlags, userId);
8105                    }
8106                    if (ai != null) {
8107                        list.add(ai);
8108                    }
8109                }
8110            } else {
8111                list = new ArrayList<>(mPackages.size());
8112                for (PackageParser.Package p : mPackages.values()) {
8113                    if (p.mExtras != null) {
8114                        PackageSetting ps = (PackageSetting) p.mExtras;
8115                        if (filterSharedLibPackageLPr(ps, Binder.getCallingUid(), userId, flags)) {
8116                            continue;
8117                        }
8118                        ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags,
8119                                ps.readUserState(userId), userId);
8120                        if (ai != null) {
8121                            rebaseEnabledOverlays(ai, userId);
8122                            ai.packageName = resolveExternalPackageNameLPr(p);
8123                            list.add(ai);
8124                        }
8125                    }
8126                }
8127            }
8128
8129            return new ParceledListSlice<>(list);
8130        }
8131    }
8132
8133    @Override
8134    public ParceledListSlice<InstantAppInfo> getInstantApps(int userId) {
8135        if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) {
8136            return null;
8137        }
8138        mContext.enforceCallingOrSelfPermission(Manifest.permission.ACCESS_INSTANT_APPS,
8139                "getEphemeralApplications");
8140        enforceCrossUserPermission(Binder.getCallingUid(), userId,
8141                true /* requireFullPermission */, false /* checkShell */,
8142                "getEphemeralApplications");
8143        synchronized (mPackages) {
8144            List<InstantAppInfo> instantApps = mInstantAppRegistry
8145                    .getInstantAppsLPr(userId);
8146            if (instantApps != null) {
8147                return new ParceledListSlice<>(instantApps);
8148            }
8149        }
8150        return null;
8151    }
8152
8153    @Override
8154    public boolean isInstantApp(String packageName, int userId) {
8155        enforceCrossUserPermission(Binder.getCallingUid(), userId,
8156                true /* requireFullPermission */, false /* checkShell */,
8157                "isInstantApp");
8158        if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) {
8159            return false;
8160        }
8161        int callingUid = Binder.getCallingUid();
8162        if (Process.isIsolated(callingUid)) {
8163            callingUid = mIsolatedOwners.get(callingUid);
8164        }
8165
8166        synchronized (mPackages) {
8167            final PackageSetting ps = mSettings.mPackages.get(packageName);
8168            PackageParser.Package pkg = mPackages.get(packageName);
8169            final boolean returnAllowed =
8170                    ps != null
8171                    && (isCallerSameApp(packageName, callingUid)
8172                            || canViewInstantApps(callingUid, userId)
8173                            || mInstantAppRegistry.isInstantAccessGranted(
8174                                    userId, UserHandle.getAppId(callingUid), ps.appId));
8175            if (returnAllowed) {
8176                return ps.getInstantApp(userId);
8177            }
8178        }
8179        return false;
8180    }
8181
8182    @Override
8183    public byte[] getInstantAppCookie(String packageName, int userId) {
8184        if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) {
8185            return null;
8186        }
8187
8188        enforceCrossUserPermission(Binder.getCallingUid(), userId,
8189                true /* requireFullPermission */, false /* checkShell */,
8190                "getInstantAppCookie");
8191        if (!isCallerSameApp(packageName, Binder.getCallingUid())) {
8192            return null;
8193        }
8194        synchronized (mPackages) {
8195            return mInstantAppRegistry.getInstantAppCookieLPw(
8196                    packageName, userId);
8197        }
8198    }
8199
8200    @Override
8201    public boolean setInstantAppCookie(String packageName, byte[] cookie, int userId) {
8202        if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) {
8203            return true;
8204        }
8205
8206        enforceCrossUserPermission(Binder.getCallingUid(), userId,
8207                true /* requireFullPermission */, true /* checkShell */,
8208                "setInstantAppCookie");
8209        if (!isCallerSameApp(packageName, Binder.getCallingUid())) {
8210            return false;
8211        }
8212        synchronized (mPackages) {
8213            return mInstantAppRegistry.setInstantAppCookieLPw(
8214                    packageName, cookie, userId);
8215        }
8216    }
8217
8218    @Override
8219    public Bitmap getInstantAppIcon(String packageName, int userId) {
8220        if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) {
8221            return null;
8222        }
8223
8224        mContext.enforceCallingOrSelfPermission(Manifest.permission.ACCESS_INSTANT_APPS,
8225                "getInstantAppIcon");
8226
8227        enforceCrossUserPermission(Binder.getCallingUid(), userId,
8228                true /* requireFullPermission */, false /* checkShell */,
8229                "getInstantAppIcon");
8230
8231        synchronized (mPackages) {
8232            return mInstantAppRegistry.getInstantAppIconLPw(
8233                    packageName, userId);
8234        }
8235    }
8236
8237    private boolean isCallerSameApp(String packageName, int uid) {
8238        PackageParser.Package pkg = mPackages.get(packageName);
8239        return pkg != null
8240                && UserHandle.getAppId(uid) == pkg.applicationInfo.uid;
8241    }
8242
8243    @Override
8244    public @NonNull ParceledListSlice<ApplicationInfo> getPersistentApplications(int flags) {
8245        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
8246            return ParceledListSlice.emptyList();
8247        }
8248        return new ParceledListSlice<>(getPersistentApplicationsInternal(flags));
8249    }
8250
8251    private @NonNull List<ApplicationInfo> getPersistentApplicationsInternal(int flags) {
8252        final ArrayList<ApplicationInfo> finalList = new ArrayList<ApplicationInfo>();
8253
8254        // reader
8255        synchronized (mPackages) {
8256            final Iterator<PackageParser.Package> i = mPackages.values().iterator();
8257            final int userId = UserHandle.getCallingUserId();
8258            while (i.hasNext()) {
8259                final PackageParser.Package p = i.next();
8260                if (p.applicationInfo == null) continue;
8261
8262                final boolean matchesUnaware = ((flags & MATCH_DIRECT_BOOT_UNAWARE) != 0)
8263                        && !p.applicationInfo.isDirectBootAware();
8264                final boolean matchesAware = ((flags & MATCH_DIRECT_BOOT_AWARE) != 0)
8265                        && p.applicationInfo.isDirectBootAware();
8266
8267                if ((p.applicationInfo.flags & ApplicationInfo.FLAG_PERSISTENT) != 0
8268                        && (!mSafeMode || isSystemApp(p))
8269                        && (matchesUnaware || matchesAware)) {
8270                    PackageSetting ps = mSettings.mPackages.get(p.packageName);
8271                    if (ps != null) {
8272                        ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags,
8273                                ps.readUserState(userId), userId);
8274                        if (ai != null) {
8275                            rebaseEnabledOverlays(ai, userId);
8276                            finalList.add(ai);
8277                        }
8278                    }
8279                }
8280            }
8281        }
8282
8283        return finalList;
8284    }
8285
8286    @Override
8287    public ProviderInfo resolveContentProvider(String name, int flags, int userId) {
8288        if (!sUserManager.exists(userId)) return null;
8289        flags = updateFlagsForComponent(flags, userId, name);
8290        final String instantAppPkgName = getInstantAppPackageName(Binder.getCallingUid());
8291        // reader
8292        synchronized (mPackages) {
8293            final PackageParser.Provider provider = mProvidersByAuthority.get(name);
8294            PackageSetting ps = provider != null
8295                    ? mSettings.mPackages.get(provider.owner.packageName)
8296                    : null;
8297            if (ps != null) {
8298                final boolean isInstantApp = ps.getInstantApp(userId);
8299                // normal application; filter out instant application provider
8300                if (instantAppPkgName == null && isInstantApp) {
8301                    return null;
8302                }
8303                // instant application; filter out other instant applications
8304                if (instantAppPkgName != null
8305                        && isInstantApp
8306                        && !provider.owner.packageName.equals(instantAppPkgName)) {
8307                    return null;
8308                }
8309                // instant application; filter out non-exposed provider
8310                if (instantAppPkgName != null
8311                        && !isInstantApp
8312                        && (provider.info.flags & ProviderInfo.FLAG_VISIBLE_TO_INSTANT_APP) == 0) {
8313                    return null;
8314                }
8315                // provider not enabled
8316                if (!mSettings.isEnabledAndMatchLPr(provider.info, flags, userId)) {
8317                    return null;
8318                }
8319                return PackageParser.generateProviderInfo(
8320                        provider, flags, ps.readUserState(userId), userId);
8321            }
8322            return null;
8323        }
8324    }
8325
8326    /**
8327     * @deprecated
8328     */
8329    @Deprecated
8330    public void querySyncProviders(List<String> outNames, List<ProviderInfo> outInfo) {
8331        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
8332            return;
8333        }
8334        // reader
8335        synchronized (mPackages) {
8336            final Iterator<Map.Entry<String, PackageParser.Provider>> i = mProvidersByAuthority
8337                    .entrySet().iterator();
8338            final int userId = UserHandle.getCallingUserId();
8339            while (i.hasNext()) {
8340                Map.Entry<String, PackageParser.Provider> entry = i.next();
8341                PackageParser.Provider p = entry.getValue();
8342                PackageSetting ps = mSettings.mPackages.get(p.owner.packageName);
8343
8344                if (ps != null && p.syncable
8345                        && (!mSafeMode || (p.info.applicationInfo.flags
8346                                &ApplicationInfo.FLAG_SYSTEM) != 0)) {
8347                    ProviderInfo info = PackageParser.generateProviderInfo(p, 0,
8348                            ps.readUserState(userId), userId);
8349                    if (info != null) {
8350                        outNames.add(entry.getKey());
8351                        outInfo.add(info);
8352                    }
8353                }
8354            }
8355        }
8356    }
8357
8358    @Override
8359    public @NonNull ParceledListSlice<ProviderInfo> queryContentProviders(String processName,
8360            int uid, int flags, String metaDataKey) {
8361        final int callingUid = Binder.getCallingUid();
8362        final int userId = processName != null ? UserHandle.getUserId(uid)
8363                : UserHandle.getCallingUserId();
8364        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
8365        flags = updateFlagsForComponent(flags, userId, processName);
8366        ArrayList<ProviderInfo> finalList = null;
8367        // reader
8368        synchronized (mPackages) {
8369            final Iterator<PackageParser.Provider> i = mProviders.mProviders.values().iterator();
8370            while (i.hasNext()) {
8371                final PackageParser.Provider p = i.next();
8372                PackageSetting ps = mSettings.mPackages.get(p.owner.packageName);
8373                if (ps != null && p.info.authority != null
8374                        && (processName == null
8375                                || (p.info.processName.equals(processName)
8376                                        && UserHandle.isSameApp(p.info.applicationInfo.uid, uid)))
8377                        && mSettings.isEnabledAndMatchLPr(p.info, flags, userId)) {
8378
8379                    // See PM.queryContentProviders()'s javadoc for why we have the metaData
8380                    // parameter.
8381                    if (metaDataKey != null
8382                            && (p.metaData == null || !p.metaData.containsKey(metaDataKey))) {
8383                        continue;
8384                    }
8385                    final ComponentName component =
8386                            new ComponentName(p.info.packageName, p.info.name);
8387                    if (filterAppAccessLPr(ps, callingUid, component, TYPE_PROVIDER, userId)) {
8388                        continue;
8389                    }
8390                    if (finalList == null) {
8391                        finalList = new ArrayList<ProviderInfo>(3);
8392                    }
8393                    ProviderInfo info = PackageParser.generateProviderInfo(p, flags,
8394                            ps.readUserState(userId), userId);
8395                    if (info != null) {
8396                        finalList.add(info);
8397                    }
8398                }
8399            }
8400        }
8401
8402        if (finalList != null) {
8403            Collections.sort(finalList, mProviderInitOrderSorter);
8404            return new ParceledListSlice<ProviderInfo>(finalList);
8405        }
8406
8407        return ParceledListSlice.emptyList();
8408    }
8409
8410    @Override
8411    public InstrumentationInfo getInstrumentationInfo(ComponentName component, int flags) {
8412        // reader
8413        synchronized (mPackages) {
8414            final int callingUid = Binder.getCallingUid();
8415            final int callingUserId = UserHandle.getUserId(callingUid);
8416            final PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
8417            if (ps == null) return null;
8418            if (filterAppAccessLPr(ps, callingUid, component, TYPE_UNKNOWN, callingUserId)) {
8419                return null;
8420            }
8421            final PackageParser.Instrumentation i = mInstrumentation.get(component);
8422            return PackageParser.generateInstrumentationInfo(i, flags);
8423        }
8424    }
8425
8426    @Override
8427    public @NonNull ParceledListSlice<InstrumentationInfo> queryInstrumentation(
8428            String targetPackage, int flags) {
8429        final int callingUid = Binder.getCallingUid();
8430        final int callingUserId = UserHandle.getUserId(callingUid);
8431        final PackageSetting ps = mSettings.mPackages.get(targetPackage);
8432        if (filterAppAccessLPr(ps, callingUid, callingUserId)) {
8433            return ParceledListSlice.emptyList();
8434        }
8435        return new ParceledListSlice<>(queryInstrumentationInternal(targetPackage, flags));
8436    }
8437
8438    private @NonNull List<InstrumentationInfo> queryInstrumentationInternal(String targetPackage,
8439            int flags) {
8440        ArrayList<InstrumentationInfo> finalList = new ArrayList<InstrumentationInfo>();
8441
8442        // reader
8443        synchronized (mPackages) {
8444            final Iterator<PackageParser.Instrumentation> i = mInstrumentation.values().iterator();
8445            while (i.hasNext()) {
8446                final PackageParser.Instrumentation p = i.next();
8447                if (targetPackage == null
8448                        || targetPackage.equals(p.info.targetPackage)) {
8449                    InstrumentationInfo ii = PackageParser.generateInstrumentationInfo(p,
8450                            flags);
8451                    if (ii != null) {
8452                        finalList.add(ii);
8453                    }
8454                }
8455            }
8456        }
8457
8458        return finalList;
8459    }
8460
8461    private void scanDirTracedLI(File dir, final int parseFlags, int scanFlags, long currentTime) {
8462        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanDir [" + dir.getAbsolutePath() + "]");
8463        try {
8464            scanDirLI(dir, parseFlags, scanFlags, currentTime);
8465        } finally {
8466            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
8467        }
8468    }
8469
8470    private void scanDirLI(File dir, int parseFlags, int scanFlags, long currentTime) {
8471        final File[] files = dir.listFiles();
8472        if (ArrayUtils.isEmpty(files)) {
8473            Log.d(TAG, "No files in app dir " + dir);
8474            return;
8475        }
8476
8477        if (DEBUG_PACKAGE_SCANNING) {
8478            Log.d(TAG, "Scanning app dir " + dir + " scanFlags=" + scanFlags
8479                    + " flags=0x" + Integer.toHexString(parseFlags));
8480        }
8481        ParallelPackageParser parallelPackageParser = new ParallelPackageParser(
8482                mSeparateProcesses, mOnlyCore, mMetrics, mCacheDir,
8483                mParallelPackageParserCallback);
8484
8485        // Submit files for parsing in parallel
8486        int fileCount = 0;
8487        for (File file : files) {
8488            final boolean isPackage = (isApkFile(file) || file.isDirectory())
8489                    && !PackageInstallerService.isStageName(file.getName());
8490            if (!isPackage) {
8491                // Ignore entries which are not packages
8492                continue;
8493            }
8494            parallelPackageParser.submit(file, parseFlags);
8495            fileCount++;
8496        }
8497
8498        // Process results one by one
8499        for (; fileCount > 0; fileCount--) {
8500            ParallelPackageParser.ParseResult parseResult = parallelPackageParser.take();
8501            Throwable throwable = parseResult.throwable;
8502            int errorCode = PackageManager.INSTALL_SUCCEEDED;
8503
8504            if (throwable == null) {
8505                // Static shared libraries have synthetic package names
8506                if (parseResult.pkg.applicationInfo.isStaticSharedLibrary()) {
8507                    renameStaticSharedLibraryPackage(parseResult.pkg);
8508                }
8509                try {
8510                    if (errorCode == PackageManager.INSTALL_SUCCEEDED) {
8511                        scanPackageLI(parseResult.pkg, parseResult.scanFile, parseFlags, scanFlags,
8512                                currentTime, null);
8513                    }
8514                } catch (PackageManagerException e) {
8515                    errorCode = e.error;
8516                    Slog.w(TAG, "Failed to scan " + parseResult.scanFile + ": " + e.getMessage());
8517                }
8518            } else if (throwable instanceof PackageParser.PackageParserException) {
8519                PackageParser.PackageParserException e = (PackageParser.PackageParserException)
8520                        throwable;
8521                errorCode = e.error;
8522                Slog.w(TAG, "Failed to parse " + parseResult.scanFile + ": " + e.getMessage());
8523            } else {
8524                throw new IllegalStateException("Unexpected exception occurred while parsing "
8525                        + parseResult.scanFile, throwable);
8526            }
8527
8528            // Delete invalid userdata apps
8529            if ((parseFlags & PackageParser.PARSE_IS_SYSTEM) == 0 &&
8530                    errorCode == PackageManager.INSTALL_FAILED_INVALID_APK) {
8531                logCriticalInfo(Log.WARN,
8532                        "Deleting invalid package at " + parseResult.scanFile);
8533                removeCodePathLI(parseResult.scanFile);
8534            }
8535        }
8536        parallelPackageParser.close();
8537    }
8538
8539    private static File getSettingsProblemFile() {
8540        File dataDir = Environment.getDataDirectory();
8541        File systemDir = new File(dataDir, "system");
8542        File fname = new File(systemDir, "uiderrors.txt");
8543        return fname;
8544    }
8545
8546    static void reportSettingsProblem(int priority, String msg) {
8547        logCriticalInfo(priority, msg);
8548    }
8549
8550    public static void logCriticalInfo(int priority, String msg) {
8551        Slog.println(priority, TAG, msg);
8552        EventLogTags.writePmCriticalInfo(msg);
8553        try {
8554            File fname = getSettingsProblemFile();
8555            FileOutputStream out = new FileOutputStream(fname, true);
8556            PrintWriter pw = new FastPrintWriter(out);
8557            SimpleDateFormat formatter = new SimpleDateFormat();
8558            String dateString = formatter.format(new Date(System.currentTimeMillis()));
8559            pw.println(dateString + ": " + msg);
8560            pw.close();
8561            FileUtils.setPermissions(
8562                    fname.toString(),
8563                    FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IROTH,
8564                    -1, -1);
8565        } catch (java.io.IOException e) {
8566        }
8567    }
8568
8569    private long getLastModifiedTime(PackageParser.Package pkg, File srcFile) {
8570        if (srcFile.isDirectory()) {
8571            final File baseFile = new File(pkg.baseCodePath);
8572            long maxModifiedTime = baseFile.lastModified();
8573            if (pkg.splitCodePaths != null) {
8574                for (int i = pkg.splitCodePaths.length - 1; i >=0; --i) {
8575                    final File splitFile = new File(pkg.splitCodePaths[i]);
8576                    maxModifiedTime = Math.max(maxModifiedTime, splitFile.lastModified());
8577                }
8578            }
8579            return maxModifiedTime;
8580        }
8581        return srcFile.lastModified();
8582    }
8583
8584    private void collectCertificatesLI(PackageSetting ps, PackageParser.Package pkg, File srcFile,
8585            final int policyFlags) throws PackageManagerException {
8586        // When upgrading from pre-N MR1, verify the package time stamp using the package
8587        // directory and not the APK file.
8588        final long lastModifiedTime = mIsPreNMR1Upgrade
8589                ? new File(pkg.codePath).lastModified() : getLastModifiedTime(pkg, srcFile);
8590        if (ps != null
8591                && ps.codePath.equals(srcFile)
8592                && ps.timeStamp == lastModifiedTime
8593                && !isCompatSignatureUpdateNeeded(pkg)
8594                && !isRecoverSignatureUpdateNeeded(pkg)) {
8595            long mSigningKeySetId = ps.keySetData.getProperSigningKeySet();
8596            KeySetManagerService ksms = mSettings.mKeySetManagerService;
8597            ArraySet<PublicKey> signingKs;
8598            synchronized (mPackages) {
8599                signingKs = ksms.getPublicKeysFromKeySetLPr(mSigningKeySetId);
8600            }
8601            if (ps.signatures.mSignatures != null
8602                    && ps.signatures.mSignatures.length != 0
8603                    && signingKs != null) {
8604                // Optimization: reuse the existing cached certificates
8605                // if the package appears to be unchanged.
8606                pkg.mSignatures = ps.signatures.mSignatures;
8607                pkg.mSigningKeys = signingKs;
8608                return;
8609            }
8610
8611            Slog.w(TAG, "PackageSetting for " + ps.name
8612                    + " is missing signatures.  Collecting certs again to recover them.");
8613        } else {
8614            Slog.i(TAG, srcFile.toString() + " changed; collecting certs");
8615        }
8616
8617        try {
8618            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "collectCertificates");
8619            PackageParser.collectCertificates(pkg, policyFlags);
8620        } catch (PackageParserException e) {
8621            throw PackageManagerException.from(e);
8622        } finally {
8623            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
8624        }
8625    }
8626
8627    /**
8628     *  Traces a package scan.
8629     *  @see #scanPackageLI(File, int, int, long, UserHandle)
8630     */
8631    private PackageParser.Package scanPackageTracedLI(File scanFile, final int parseFlags,
8632            int scanFlags, long currentTime, UserHandle user) throws PackageManagerException {
8633        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage [" + scanFile.toString() + "]");
8634        try {
8635            return scanPackageLI(scanFile, parseFlags, scanFlags, currentTime, user);
8636        } finally {
8637            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
8638        }
8639    }
8640
8641    /**
8642     *  Scans a package and returns the newly parsed package.
8643     *  Returns {@code null} in case of errors and the error code is stored in mLastScanError
8644     */
8645    private PackageParser.Package scanPackageLI(File scanFile, int parseFlags, int scanFlags,
8646            long currentTime, UserHandle user) throws PackageManagerException {
8647        if (DEBUG_INSTALL) Slog.d(TAG, "Parsing: " + scanFile);
8648        PackageParser pp = new PackageParser();
8649        pp.setSeparateProcesses(mSeparateProcesses);
8650        pp.setOnlyCoreApps(mOnlyCore);
8651        pp.setDisplayMetrics(mMetrics);
8652        pp.setCallback(mPackageParserCallback);
8653
8654        if ((scanFlags & SCAN_TRUSTED_OVERLAY) != 0) {
8655            parseFlags |= PackageParser.PARSE_TRUSTED_OVERLAY;
8656        }
8657
8658        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "parsePackage");
8659        final PackageParser.Package pkg;
8660        try {
8661            pkg = pp.parsePackage(scanFile, parseFlags);
8662        } catch (PackageParserException e) {
8663            throw PackageManagerException.from(e);
8664        } finally {
8665            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
8666        }
8667
8668        // Static shared libraries have synthetic package names
8669        if (pkg.applicationInfo.isStaticSharedLibrary()) {
8670            renameStaticSharedLibraryPackage(pkg);
8671        }
8672
8673        return scanPackageLI(pkg, scanFile, parseFlags, scanFlags, currentTime, user);
8674    }
8675
8676    /**
8677     *  Scans a package and returns the newly parsed package.
8678     *  @throws PackageManagerException on a parse error.
8679     */
8680    private PackageParser.Package scanPackageLI(PackageParser.Package pkg, File scanFile,
8681            final int policyFlags, int scanFlags, long currentTime, @Nullable UserHandle user)
8682            throws PackageManagerException {
8683        // If the package has children and this is the first dive in the function
8684        // we scan the package with the SCAN_CHECK_ONLY flag set to see whether all
8685        // packages (parent and children) would be successfully scanned before the
8686        // actual scan since scanning mutates internal state and we want to atomically
8687        // install the package and its children.
8688        if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
8689            if (pkg.childPackages != null && pkg.childPackages.size() > 0) {
8690                scanFlags |= SCAN_CHECK_ONLY;
8691            }
8692        } else {
8693            scanFlags &= ~SCAN_CHECK_ONLY;
8694        }
8695
8696        // Scan the parent
8697        PackageParser.Package scannedPkg = scanPackageInternalLI(pkg, scanFile, policyFlags,
8698                scanFlags, currentTime, user);
8699
8700        // Scan the children
8701        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
8702        for (int i = 0; i < childCount; i++) {
8703            PackageParser.Package childPackage = pkg.childPackages.get(i);
8704            scanPackageInternalLI(childPackage, scanFile, policyFlags, scanFlags,
8705                    currentTime, user);
8706        }
8707
8708
8709        if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
8710            return scanPackageLI(pkg, scanFile, policyFlags, scanFlags, currentTime, user);
8711        }
8712
8713        return scannedPkg;
8714    }
8715
8716    /**
8717     *  Scans a package and returns the newly parsed package.
8718     *  @throws PackageManagerException on a parse error.
8719     */
8720    private PackageParser.Package scanPackageInternalLI(PackageParser.Package pkg, File scanFile,
8721            int policyFlags, int scanFlags, long currentTime, @Nullable UserHandle user)
8722            throws PackageManagerException {
8723        PackageSetting ps = null;
8724        PackageSetting updatedPkg;
8725        // reader
8726        synchronized (mPackages) {
8727            // Look to see if we already know about this package.
8728            String oldName = mSettings.getRenamedPackageLPr(pkg.packageName);
8729            if (pkg.mOriginalPackages != null && pkg.mOriginalPackages.contains(oldName)) {
8730                // This package has been renamed to its original name.  Let's
8731                // use that.
8732                ps = mSettings.getPackageLPr(oldName);
8733            }
8734            // If there was no original package, see one for the real package name.
8735            if (ps == null) {
8736                ps = mSettings.getPackageLPr(pkg.packageName);
8737            }
8738            // Check to see if this package could be hiding/updating a system
8739            // package.  Must look for it either under the original or real
8740            // package name depending on our state.
8741            updatedPkg = mSettings.getDisabledSystemPkgLPr(ps != null ? ps.name : pkg.packageName);
8742            if (DEBUG_INSTALL && updatedPkg != null) Slog.d(TAG, "updatedPkg = " + updatedPkg);
8743
8744            // If this is a package we don't know about on the system partition, we
8745            // may need to remove disabled child packages on the system partition
8746            // or may need to not add child packages if the parent apk is updated
8747            // on the data partition and no longer defines this child package.
8748            if ((policyFlags & PackageParser.PARSE_IS_SYSTEM) != 0) {
8749                // If this is a parent package for an updated system app and this system
8750                // app got an OTA update which no longer defines some of the child packages
8751                // we have to prune them from the disabled system packages.
8752                PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(pkg.packageName);
8753                if (disabledPs != null) {
8754                    final int scannedChildCount = (pkg.childPackages != null)
8755                            ? pkg.childPackages.size() : 0;
8756                    final int disabledChildCount = disabledPs.childPackageNames != null
8757                            ? disabledPs.childPackageNames.size() : 0;
8758                    for (int i = 0; i < disabledChildCount; i++) {
8759                        String disabledChildPackageName = disabledPs.childPackageNames.get(i);
8760                        boolean disabledPackageAvailable = false;
8761                        for (int j = 0; j < scannedChildCount; j++) {
8762                            PackageParser.Package childPkg = pkg.childPackages.get(j);
8763                            if (childPkg.packageName.equals(disabledChildPackageName)) {
8764                                disabledPackageAvailable = true;
8765                                break;
8766                            }
8767                         }
8768                         if (!disabledPackageAvailable) {
8769                             mSettings.removeDisabledSystemPackageLPw(disabledChildPackageName);
8770                         }
8771                    }
8772                }
8773            }
8774        }
8775
8776        boolean updatedPkgBetter = false;
8777        // First check if this is a system package that may involve an update
8778        if (updatedPkg != null && (policyFlags & PackageParser.PARSE_IS_SYSTEM) != 0) {
8779            // If new package is not located in "/system/priv-app" (e.g. due to an OTA),
8780            // it needs to drop FLAG_PRIVILEGED.
8781            if (locationIsPrivileged(scanFile)) {
8782                updatedPkg.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
8783            } else {
8784                updatedPkg.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
8785            }
8786
8787            if (ps != null && !ps.codePath.equals(scanFile)) {
8788                // The path has changed from what was last scanned...  check the
8789                // version of the new path against what we have stored to determine
8790                // what to do.
8791                if (DEBUG_INSTALL) Slog.d(TAG, "Path changing from " + ps.codePath);
8792                if (pkg.mVersionCode <= ps.versionCode) {
8793                    // The system package has been updated and the code path does not match
8794                    // Ignore entry. Skip it.
8795                    if (DEBUG_INSTALL) Slog.i(TAG, "Package " + ps.name + " at " + scanFile
8796                            + " ignored: updated version " + ps.versionCode
8797                            + " better than this " + pkg.mVersionCode);
8798                    if (!updatedPkg.codePath.equals(scanFile)) {
8799                        Slog.w(PackageManagerService.TAG, "Code path for hidden system pkg "
8800                                + ps.name + " changing from " + updatedPkg.codePathString
8801                                + " to " + scanFile);
8802                        updatedPkg.codePath = scanFile;
8803                        updatedPkg.codePathString = scanFile.toString();
8804                        updatedPkg.resourcePath = scanFile;
8805                        updatedPkg.resourcePathString = scanFile.toString();
8806                    }
8807                    updatedPkg.pkg = pkg;
8808                    updatedPkg.versionCode = pkg.mVersionCode;
8809
8810                    // Update the disabled system child packages to point to the package too.
8811                    final int childCount = updatedPkg.childPackageNames != null
8812                            ? updatedPkg.childPackageNames.size() : 0;
8813                    for (int i = 0; i < childCount; i++) {
8814                        String childPackageName = updatedPkg.childPackageNames.get(i);
8815                        PackageSetting updatedChildPkg = mSettings.getDisabledSystemPkgLPr(
8816                                childPackageName);
8817                        if (updatedChildPkg != null) {
8818                            updatedChildPkg.pkg = pkg;
8819                            updatedChildPkg.versionCode = pkg.mVersionCode;
8820                        }
8821                    }
8822
8823                    throw new PackageManagerException(Log.WARN, "Package " + ps.name + " at "
8824                            + scanFile + " ignored: updated version " + ps.versionCode
8825                            + " better than this " + pkg.mVersionCode);
8826                } else {
8827                    // The current app on the system partition is better than
8828                    // what we have updated to on the data partition; switch
8829                    // back to the system partition version.
8830                    // At this point, its safely assumed that package installation for
8831                    // apps in system partition will go through. If not there won't be a working
8832                    // version of the app
8833                    // writer
8834                    synchronized (mPackages) {
8835                        // Just remove the loaded entries from package lists.
8836                        mPackages.remove(ps.name);
8837                    }
8838
8839                    logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile
8840                            + " reverting from " + ps.codePathString
8841                            + ": new version " + pkg.mVersionCode
8842                            + " better than installed " + ps.versionCode);
8843
8844                    InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
8845                            ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
8846                    synchronized (mInstallLock) {
8847                        args.cleanUpResourcesLI();
8848                    }
8849                    synchronized (mPackages) {
8850                        mSettings.enableSystemPackageLPw(ps.name);
8851                    }
8852                    updatedPkgBetter = true;
8853                }
8854            }
8855        }
8856
8857        if (updatedPkg != null) {
8858            // An updated system app will not have the PARSE_IS_SYSTEM flag set
8859            // initially
8860            policyFlags |= PackageParser.PARSE_IS_SYSTEM;
8861
8862            // An updated privileged app will not have the PARSE_IS_PRIVILEGED
8863            // flag set initially
8864            if ((updatedPkg.pkgPrivateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0) {
8865                policyFlags |= PackageParser.PARSE_IS_PRIVILEGED;
8866            }
8867        }
8868
8869        // Verify certificates against what was last scanned
8870        collectCertificatesLI(ps, pkg, scanFile, policyFlags);
8871
8872        /*
8873         * A new system app appeared, but we already had a non-system one of the
8874         * same name installed earlier.
8875         */
8876        boolean shouldHideSystemApp = false;
8877        if (updatedPkg == null && ps != null
8878                && (policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0 && !isSystemApp(ps)) {
8879            /*
8880             * Check to make sure the signatures match first. If they don't,
8881             * wipe the installed application and its data.
8882             */
8883            if (compareSignatures(ps.signatures.mSignatures, pkg.mSignatures)
8884                    != PackageManager.SIGNATURE_MATCH) {
8885                logCriticalInfo(Log.WARN, "Package " + ps.name + " appeared on system, but"
8886                        + " signatures don't match existing userdata copy; removing");
8887                try (PackageFreezer freezer = freezePackage(pkg.packageName,
8888                        "scanPackageInternalLI")) {
8889                    deletePackageLIF(pkg.packageName, null, true, null, 0, null, false, null);
8890                }
8891                ps = null;
8892            } else {
8893                /*
8894                 * If the newly-added system app is an older version than the
8895                 * already installed version, hide it. It will be scanned later
8896                 * and re-added like an update.
8897                 */
8898                if (pkg.mVersionCode <= ps.versionCode) {
8899                    shouldHideSystemApp = true;
8900                    logCriticalInfo(Log.INFO, "Package " + ps.name + " appeared at " + scanFile
8901                            + " but new version " + pkg.mVersionCode + " better than installed "
8902                            + ps.versionCode + "; hiding system");
8903                } else {
8904                    /*
8905                     * The newly found system app is a newer version that the
8906                     * one previously installed. Simply remove the
8907                     * already-installed application and replace it with our own
8908                     * while keeping the application data.
8909                     */
8910                    logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile
8911                            + " reverting from " + ps.codePathString + ": new version "
8912                            + pkg.mVersionCode + " better than installed " + ps.versionCode);
8913                    InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
8914                            ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
8915                    synchronized (mInstallLock) {
8916                        args.cleanUpResourcesLI();
8917                    }
8918                }
8919            }
8920        }
8921
8922        // The apk is forward locked (not public) if its code and resources
8923        // are kept in different files. (except for app in either system or
8924        // vendor path).
8925        // TODO grab this value from PackageSettings
8926        if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
8927            if (ps != null && !ps.codePath.equals(ps.resourcePath)) {
8928                policyFlags |= PackageParser.PARSE_FORWARD_LOCK;
8929            }
8930        }
8931
8932        // TODO: extend to support forward-locked splits
8933        String resourcePath = null;
8934        String baseResourcePath = null;
8935        if ((policyFlags & PackageParser.PARSE_FORWARD_LOCK) != 0 && !updatedPkgBetter) {
8936            if (ps != null && ps.resourcePathString != null) {
8937                resourcePath = ps.resourcePathString;
8938                baseResourcePath = ps.resourcePathString;
8939            } else {
8940                // Should not happen at all. Just log an error.
8941                Slog.e(TAG, "Resource path not set for package " + pkg.packageName);
8942            }
8943        } else {
8944            resourcePath = pkg.codePath;
8945            baseResourcePath = pkg.baseCodePath;
8946        }
8947
8948        // Set application objects path explicitly.
8949        pkg.setApplicationVolumeUuid(pkg.volumeUuid);
8950        pkg.setApplicationInfoCodePath(pkg.codePath);
8951        pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
8952        pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
8953        pkg.setApplicationInfoResourcePath(resourcePath);
8954        pkg.setApplicationInfoBaseResourcePath(baseResourcePath);
8955        pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
8956
8957        final int userId = ((user == null) ? 0 : user.getIdentifier());
8958        if (ps != null && ps.getInstantApp(userId)) {
8959            scanFlags |= SCAN_AS_INSTANT_APP;
8960        }
8961
8962        // Note that we invoke the following method only if we are about to unpack an application
8963        PackageParser.Package scannedPkg = scanPackageLI(pkg, policyFlags, scanFlags
8964                | SCAN_UPDATE_SIGNATURE, currentTime, user);
8965
8966        /*
8967         * If the system app should be overridden by a previously installed
8968         * data, hide the system app now and let the /data/app scan pick it up
8969         * again.
8970         */
8971        if (shouldHideSystemApp) {
8972            synchronized (mPackages) {
8973                mSettings.disableSystemPackageLPw(pkg.packageName, true);
8974            }
8975        }
8976
8977        return scannedPkg;
8978    }
8979
8980    private void renameStaticSharedLibraryPackage(PackageParser.Package pkg) {
8981        // Derive the new package synthetic package name
8982        pkg.setPackageName(pkg.packageName + STATIC_SHARED_LIB_DELIMITER
8983                + pkg.staticSharedLibVersion);
8984    }
8985
8986    private static String fixProcessName(String defProcessName,
8987            String processName) {
8988        if (processName == null) {
8989            return defProcessName;
8990        }
8991        return processName;
8992    }
8993
8994    private void verifySignaturesLP(PackageSetting pkgSetting, PackageParser.Package pkg)
8995            throws PackageManagerException {
8996        if (pkgSetting.signatures.mSignatures != null) {
8997            // Already existing package. Make sure signatures match
8998            boolean match = compareSignatures(pkgSetting.signatures.mSignatures, pkg.mSignatures)
8999                    == PackageManager.SIGNATURE_MATCH;
9000            if (!match) {
9001                match = compareSignaturesCompat(pkgSetting.signatures, pkg)
9002                        == PackageManager.SIGNATURE_MATCH;
9003            }
9004            if (!match) {
9005                match = compareSignaturesRecover(pkgSetting.signatures, pkg)
9006                        == PackageManager.SIGNATURE_MATCH;
9007            }
9008            if (!match) {
9009                throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package "
9010                        + pkg.packageName + " signatures do not match the "
9011                        + "previously installed version; ignoring!");
9012            }
9013        }
9014
9015        // Check for shared user signatures
9016        if (pkgSetting.sharedUser != null && pkgSetting.sharedUser.signatures.mSignatures != null) {
9017            // Already existing package. Make sure signatures match
9018            boolean match = compareSignatures(pkgSetting.sharedUser.signatures.mSignatures,
9019                    pkg.mSignatures) == PackageManager.SIGNATURE_MATCH;
9020            if (!match) {
9021                match = compareSignaturesCompat(pkgSetting.sharedUser.signatures, pkg)
9022                        == PackageManager.SIGNATURE_MATCH;
9023            }
9024            if (!match) {
9025                match = compareSignaturesRecover(pkgSetting.sharedUser.signatures, pkg)
9026                        == PackageManager.SIGNATURE_MATCH;
9027            }
9028            if (!match) {
9029                throw new PackageManagerException(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE,
9030                        "Package " + pkg.packageName
9031                        + " has no signatures that match those in shared user "
9032                        + pkgSetting.sharedUser.name + "; ignoring!");
9033            }
9034        }
9035    }
9036
9037    /**
9038     * Enforces that only the system UID or root's UID can call a method exposed
9039     * via Binder.
9040     *
9041     * @param message used as message if SecurityException is thrown
9042     * @throws SecurityException if the caller is not system or root
9043     */
9044    private static final void enforceSystemOrRoot(String message) {
9045        final int uid = Binder.getCallingUid();
9046        if (uid != Process.SYSTEM_UID && uid != Process.ROOT_UID) {
9047            throw new SecurityException(message);
9048        }
9049    }
9050
9051    @Override
9052    public void performFstrimIfNeeded() {
9053        enforceSystemOrRoot("Only the system can request fstrim");
9054
9055        // Before everything else, see whether we need to fstrim.
9056        try {
9057            IStorageManager sm = PackageHelper.getStorageManager();
9058            if (sm != null) {
9059                boolean doTrim = false;
9060                final long interval = android.provider.Settings.Global.getLong(
9061                        mContext.getContentResolver(),
9062                        android.provider.Settings.Global.FSTRIM_MANDATORY_INTERVAL,
9063                        DEFAULT_MANDATORY_FSTRIM_INTERVAL);
9064                if (interval > 0) {
9065                    final long timeSinceLast = System.currentTimeMillis() - sm.lastMaintenance();
9066                    if (timeSinceLast > interval) {
9067                        doTrim = true;
9068                        Slog.w(TAG, "No disk maintenance in " + timeSinceLast
9069                                + "; running immediately");
9070                    }
9071                }
9072                if (doTrim) {
9073                    final boolean dexOptDialogShown;
9074                    synchronized (mPackages) {
9075                        dexOptDialogShown = mDexOptDialogShown;
9076                    }
9077                    if (!isFirstBoot() && dexOptDialogShown) {
9078                        try {
9079                            ActivityManager.getService().showBootMessage(
9080                                    mContext.getResources().getString(
9081                                            R.string.android_upgrading_fstrim), true);
9082                        } catch (RemoteException e) {
9083                        }
9084                    }
9085                    sm.runMaintenance();
9086                }
9087            } else {
9088                Slog.e(TAG, "storageManager service unavailable!");
9089            }
9090        } catch (RemoteException e) {
9091            // Can't happen; StorageManagerService is local
9092        }
9093    }
9094
9095    @Override
9096    public void updatePackagesIfNeeded() {
9097        enforceSystemOrRoot("Only the system can request package update");
9098
9099        // We need to re-extract after an OTA.
9100        boolean causeUpgrade = isUpgrade();
9101
9102        // First boot or factory reset.
9103        // Note: we also handle devices that are upgrading to N right now as if it is their
9104        //       first boot, as they do not have profile data.
9105        boolean causeFirstBoot = isFirstBoot() || mIsPreNUpgrade;
9106
9107        // We need to re-extract after a pruned cache, as AoT-ed files will be out of date.
9108        boolean causePrunedCache = VMRuntime.didPruneDalvikCache();
9109
9110        if (!causeUpgrade && !causeFirstBoot && !causePrunedCache) {
9111            return;
9112        }
9113
9114        List<PackageParser.Package> pkgs;
9115        synchronized (mPackages) {
9116            pkgs = PackageManagerServiceUtils.getPackagesForDexopt(mPackages.values(), this);
9117        }
9118
9119        final long startTime = System.nanoTime();
9120        final int[] stats = performDexOptUpgrade(pkgs, mIsPreNUpgrade /* showDialog */,
9121                    getCompilerFilterForReason(causeFirstBoot ? REASON_FIRST_BOOT : REASON_BOOT));
9122
9123        final int elapsedTimeSeconds =
9124                (int) TimeUnit.NANOSECONDS.toSeconds(System.nanoTime() - startTime);
9125
9126        MetricsLogger.histogram(mContext, "opt_dialog_num_dexopted", stats[0]);
9127        MetricsLogger.histogram(mContext, "opt_dialog_num_skipped", stats[1]);
9128        MetricsLogger.histogram(mContext, "opt_dialog_num_failed", stats[2]);
9129        MetricsLogger.histogram(mContext, "opt_dialog_num_total", getOptimizablePackages().size());
9130        MetricsLogger.histogram(mContext, "opt_dialog_time_s", elapsedTimeSeconds);
9131    }
9132
9133    /**
9134     * Performs dexopt on the set of packages in {@code packages} and returns an int array
9135     * containing statistics about the invocation. The array consists of three elements,
9136     * which are (in order) {@code numberOfPackagesOptimized}, {@code numberOfPackagesSkipped}
9137     * and {@code numberOfPackagesFailed}.
9138     */
9139    private int[] performDexOptUpgrade(List<PackageParser.Package> pkgs, boolean showDialog,
9140            String compilerFilter) {
9141
9142        int numberOfPackagesVisited = 0;
9143        int numberOfPackagesOptimized = 0;
9144        int numberOfPackagesSkipped = 0;
9145        int numberOfPackagesFailed = 0;
9146        final int numberOfPackagesToDexopt = pkgs.size();
9147
9148        for (PackageParser.Package pkg : pkgs) {
9149            numberOfPackagesVisited++;
9150
9151            if (!PackageDexOptimizer.canOptimizePackage(pkg)) {
9152                if (DEBUG_DEXOPT) {
9153                    Log.i(TAG, "Skipping update of of non-optimizable app " + pkg.packageName);
9154                }
9155                numberOfPackagesSkipped++;
9156                continue;
9157            }
9158
9159            if (DEBUG_DEXOPT) {
9160                Log.i(TAG, "Updating app " + numberOfPackagesVisited + " of " +
9161                        numberOfPackagesToDexopt + ": " + pkg.packageName);
9162            }
9163
9164            if (showDialog) {
9165                try {
9166                    ActivityManager.getService().showBootMessage(
9167                            mContext.getResources().getString(R.string.android_upgrading_apk,
9168                                    numberOfPackagesVisited, numberOfPackagesToDexopt), true);
9169                } catch (RemoteException e) {
9170                }
9171                synchronized (mPackages) {
9172                    mDexOptDialogShown = true;
9173                }
9174            }
9175
9176            // If the OTA updates a system app which was previously preopted to a non-preopted state
9177            // the app might end up being verified at runtime. That's because by default the apps
9178            // are verify-profile but for preopted apps there's no profile.
9179            // Do a hacky check to ensure that if we have no profiles (a reasonable indication
9180            // that before the OTA the app was preopted) the app gets compiled with a non-profile
9181            // filter (by default 'quicken').
9182            // Note that at this stage unused apps are already filtered.
9183            if (isSystemApp(pkg) &&
9184                    DexFile.isProfileGuidedCompilerFilter(compilerFilter) &&
9185                    !Environment.getReferenceProfile(pkg.packageName).exists()) {
9186                compilerFilter = getNonProfileGuidedCompilerFilter(compilerFilter);
9187            }
9188
9189            // checkProfiles is false to avoid merging profiles during boot which
9190            // might interfere with background compilation (b/28612421).
9191            // Unfortunately this will also means that "pm.dexopt.boot=speed-profile" will
9192            // behave differently than "pm.dexopt.bg-dexopt=speed-profile" but that's a
9193            // trade-off worth doing to save boot time work.
9194            int dexOptStatus = performDexOptTraced(pkg.packageName,
9195                    false /* checkProfiles */,
9196                    compilerFilter,
9197                    false /* force */);
9198            switch (dexOptStatus) {
9199                case PackageDexOptimizer.DEX_OPT_PERFORMED:
9200                    numberOfPackagesOptimized++;
9201                    break;
9202                case PackageDexOptimizer.DEX_OPT_SKIPPED:
9203                    numberOfPackagesSkipped++;
9204                    break;
9205                case PackageDexOptimizer.DEX_OPT_FAILED:
9206                    numberOfPackagesFailed++;
9207                    break;
9208                default:
9209                    Log.e(TAG, "Unexpected dexopt return code " + dexOptStatus);
9210                    break;
9211            }
9212        }
9213
9214        return new int[] { numberOfPackagesOptimized, numberOfPackagesSkipped,
9215                numberOfPackagesFailed };
9216    }
9217
9218    @Override
9219    public void notifyPackageUse(String packageName, int reason) {
9220        synchronized (mPackages) {
9221            final int callingUid = Binder.getCallingUid();
9222            final int callingUserId = UserHandle.getUserId(callingUid);
9223            if (getInstantAppPackageName(callingUid) != null) {
9224                if (!isCallerSameApp(packageName, callingUid)) {
9225                    return;
9226                }
9227            } else {
9228                if (isInstantApp(packageName, callingUserId)) {
9229                    return;
9230                }
9231            }
9232            final PackageParser.Package p = mPackages.get(packageName);
9233            if (p == null) {
9234                return;
9235            }
9236            p.mLastPackageUsageTimeInMills[reason] = System.currentTimeMillis();
9237        }
9238    }
9239
9240    @Override
9241    public void notifyDexLoad(String loadingPackageName, List<String> dexPaths, String loaderIsa) {
9242        int userId = UserHandle.getCallingUserId();
9243        ApplicationInfo ai = getApplicationInfo(loadingPackageName, /*flags*/ 0, userId);
9244        if (ai == null) {
9245            Slog.w(TAG, "Loading a package that does not exist for the calling user. package="
9246                + loadingPackageName + ", user=" + userId);
9247            return;
9248        }
9249        mDexManager.notifyDexLoad(ai, dexPaths, loaderIsa, userId);
9250    }
9251
9252    @Override
9253    public boolean performDexOpt(String packageName,
9254            boolean checkProfiles, int compileReason, boolean force) {
9255        return performDexOptWithStatus(packageName, checkProfiles, compileReason, force) !=
9256                PackageDexOptimizer.DEX_OPT_FAILED;
9257    }
9258
9259    /**
9260     * Perform dexopt on the given package and return one of following result:
9261     *  {@link PackageDexOptimizer#DEX_OPT_SKIPPED}
9262     *  {@link PackageDexOptimizer#DEX_OPT_PERFORMED}
9263     *  {@link PackageDexOptimizer#DEX_OPT_FAILED}
9264     */
9265    /* package */ int performDexOptWithStatus(String packageName,
9266            boolean checkProfiles, int compileReason, boolean force) {
9267        return performDexOptTraced(packageName, checkProfiles,
9268                getCompilerFilterForReason(compileReason), force);
9269    }
9270
9271    @Override
9272    public boolean performDexOptMode(String packageName,
9273            boolean checkProfiles, String targetCompilerFilter, boolean force) {
9274        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
9275            return false;
9276        }
9277        int dexOptStatus = performDexOptTraced(packageName, checkProfiles,
9278                targetCompilerFilter, force);
9279        return dexOptStatus != PackageDexOptimizer.DEX_OPT_FAILED;
9280    }
9281
9282    private int performDexOptTraced(String packageName,
9283                boolean checkProfiles, String targetCompilerFilter, boolean force) {
9284        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt");
9285        try {
9286            return performDexOptInternal(packageName, checkProfiles,
9287                    targetCompilerFilter, force);
9288        } finally {
9289            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
9290        }
9291    }
9292
9293    // Run dexopt on a given package. Returns true if dexopt did not fail, i.e.
9294    // if the package can now be considered up to date for the given filter.
9295    private int performDexOptInternal(String packageName,
9296                boolean checkProfiles, String targetCompilerFilter, boolean force) {
9297        PackageParser.Package p;
9298        synchronized (mPackages) {
9299            p = mPackages.get(packageName);
9300            if (p == null) {
9301                // Package could not be found. Report failure.
9302                return PackageDexOptimizer.DEX_OPT_FAILED;
9303            }
9304            mPackageUsage.maybeWriteAsync(mPackages);
9305            mCompilerStats.maybeWriteAsync();
9306        }
9307        long callingId = Binder.clearCallingIdentity();
9308        try {
9309            synchronized (mInstallLock) {
9310                return performDexOptInternalWithDependenciesLI(p, checkProfiles,
9311                        targetCompilerFilter, force);
9312            }
9313        } finally {
9314            Binder.restoreCallingIdentity(callingId);
9315        }
9316    }
9317
9318    public ArraySet<String> getOptimizablePackages() {
9319        ArraySet<String> pkgs = new ArraySet<String>();
9320        synchronized (mPackages) {
9321            for (PackageParser.Package p : mPackages.values()) {
9322                if (PackageDexOptimizer.canOptimizePackage(p)) {
9323                    pkgs.add(p.packageName);
9324                }
9325            }
9326        }
9327        return pkgs;
9328    }
9329
9330    private int performDexOptInternalWithDependenciesLI(PackageParser.Package p,
9331            boolean checkProfiles, String targetCompilerFilter,
9332            boolean force) {
9333        // Select the dex optimizer based on the force parameter.
9334        // Note: The force option is rarely used (cmdline input for testing, mostly), so it's OK to
9335        //       allocate an object here.
9336        PackageDexOptimizer pdo = force
9337                ? new PackageDexOptimizer.ForcedUpdatePackageDexOptimizer(mPackageDexOptimizer)
9338                : mPackageDexOptimizer;
9339
9340        // Dexopt all dependencies first. Note: we ignore the return value and march on
9341        // on errors.
9342        // Note that we are going to call performDexOpt on those libraries as many times as
9343        // they are referenced in packages. When we do a batch of performDexOpt (for example
9344        // at boot, or background job), the passed 'targetCompilerFilter' stays the same,
9345        // and the first package that uses the library will dexopt it. The
9346        // others will see that the compiled code for the library is up to date.
9347        Collection<PackageParser.Package> deps = findSharedNonSystemLibraries(p);
9348        final String[] instructionSets = getAppDexInstructionSets(p.applicationInfo);
9349        if (!deps.isEmpty()) {
9350            for (PackageParser.Package depPackage : deps) {
9351                // TODO: Analyze and investigate if we (should) profile libraries.
9352                pdo.performDexOpt(depPackage, null /* sharedLibraries */, instructionSets,
9353                        false /* checkProfiles */,
9354                        targetCompilerFilter,
9355                        getOrCreateCompilerPackageStats(depPackage),
9356                        true /* isUsedByOtherApps */);
9357            }
9358        }
9359        return pdo.performDexOpt(p, p.usesLibraryFiles, instructionSets, checkProfiles,
9360                targetCompilerFilter, getOrCreateCompilerPackageStats(p),
9361                mDexManager.isUsedByOtherApps(p.packageName));
9362    }
9363
9364    // Performs dexopt on the used secondary dex files belonging to the given package.
9365    // Returns true if all dex files were process successfully (which could mean either dexopt or
9366    // skip). Returns false if any of the files caused errors.
9367    @Override
9368    public boolean performDexOptSecondary(String packageName, String compilerFilter,
9369            boolean force) {
9370        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
9371            return false;
9372        }
9373        mDexManager.reconcileSecondaryDexFiles(packageName);
9374        return mDexManager.dexoptSecondaryDex(packageName, compilerFilter, force);
9375    }
9376
9377    public boolean performDexOptSecondary(String packageName, int compileReason,
9378            boolean force) {
9379        return mDexManager.dexoptSecondaryDex(packageName, compileReason, force);
9380    }
9381
9382    /**
9383     * Reconcile the information we have about the secondary dex files belonging to
9384     * {@code packagName} and the actual dex files. For all dex files that were
9385     * deleted, update the internal records and delete the generated oat files.
9386     */
9387    @Override
9388    public void reconcileSecondaryDexFiles(String packageName) {
9389        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
9390            return;
9391        }
9392        mDexManager.reconcileSecondaryDexFiles(packageName);
9393    }
9394
9395    // TODO(calin): this is only needed for BackgroundDexOptService. Find a cleaner way to inject
9396    // a reference there.
9397    /*package*/ DexManager getDexManager() {
9398        return mDexManager;
9399    }
9400
9401    /**
9402     * Execute the background dexopt job immediately.
9403     */
9404    @Override
9405    public boolean runBackgroundDexoptJob() {
9406        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
9407            return false;
9408        }
9409        return BackgroundDexOptService.runIdleOptimizationsNow(this, mContext);
9410    }
9411
9412    List<PackageParser.Package> findSharedNonSystemLibraries(PackageParser.Package p) {
9413        if (p.usesLibraries != null || p.usesOptionalLibraries != null
9414                || p.usesStaticLibraries != null) {
9415            ArrayList<PackageParser.Package> retValue = new ArrayList<>();
9416            Set<String> collectedNames = new HashSet<>();
9417            findSharedNonSystemLibrariesRecursive(p, retValue, collectedNames);
9418
9419            retValue.remove(p);
9420
9421            return retValue;
9422        } else {
9423            return Collections.emptyList();
9424        }
9425    }
9426
9427    private void findSharedNonSystemLibrariesRecursive(PackageParser.Package p,
9428            ArrayList<PackageParser.Package> collected, Set<String> collectedNames) {
9429        if (!collectedNames.contains(p.packageName)) {
9430            collectedNames.add(p.packageName);
9431            collected.add(p);
9432
9433            if (p.usesLibraries != null) {
9434                findSharedNonSystemLibrariesRecursive(p.usesLibraries,
9435                        null, collected, collectedNames);
9436            }
9437            if (p.usesOptionalLibraries != null) {
9438                findSharedNonSystemLibrariesRecursive(p.usesOptionalLibraries,
9439                        null, collected, collectedNames);
9440            }
9441            if (p.usesStaticLibraries != null) {
9442                findSharedNonSystemLibrariesRecursive(p.usesStaticLibraries,
9443                        p.usesStaticLibrariesVersions, collected, collectedNames);
9444            }
9445        }
9446    }
9447
9448    private void findSharedNonSystemLibrariesRecursive(ArrayList<String> libs, int[] versions,
9449            ArrayList<PackageParser.Package> collected, Set<String> collectedNames) {
9450        final int libNameCount = libs.size();
9451        for (int i = 0; i < libNameCount; i++) {
9452            String libName = libs.get(i);
9453            int version = (versions != null && versions.length == libNameCount)
9454                    ? versions[i] : PackageManager.VERSION_CODE_HIGHEST;
9455            PackageParser.Package libPkg = findSharedNonSystemLibrary(libName, version);
9456            if (libPkg != null) {
9457                findSharedNonSystemLibrariesRecursive(libPkg, collected, collectedNames);
9458            }
9459        }
9460    }
9461
9462    private PackageParser.Package findSharedNonSystemLibrary(String name, int version) {
9463        synchronized (mPackages) {
9464            SharedLibraryEntry libEntry = getSharedLibraryEntryLPr(name, version);
9465            if (libEntry != null) {
9466                return mPackages.get(libEntry.apk);
9467            }
9468            return null;
9469        }
9470    }
9471
9472    private SharedLibraryEntry getSharedLibraryEntryLPr(String name, int version) {
9473        SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(name);
9474        if (versionedLib == null) {
9475            return null;
9476        }
9477        return versionedLib.get(version);
9478    }
9479
9480    private SharedLibraryEntry getLatestSharedLibraVersionLPr(PackageParser.Package pkg) {
9481        SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(
9482                pkg.staticSharedLibName);
9483        if (versionedLib == null) {
9484            return null;
9485        }
9486        int previousLibVersion = -1;
9487        final int versionCount = versionedLib.size();
9488        for (int i = 0; i < versionCount; i++) {
9489            final int libVersion = versionedLib.keyAt(i);
9490            if (libVersion < pkg.staticSharedLibVersion) {
9491                previousLibVersion = Math.max(previousLibVersion, libVersion);
9492            }
9493        }
9494        if (previousLibVersion >= 0) {
9495            return versionedLib.get(previousLibVersion);
9496        }
9497        return null;
9498    }
9499
9500    public void shutdown() {
9501        mPackageUsage.writeNow(mPackages);
9502        mCompilerStats.writeNow();
9503    }
9504
9505    @Override
9506    public void dumpProfiles(String packageName) {
9507        PackageParser.Package pkg;
9508        synchronized (mPackages) {
9509            pkg = mPackages.get(packageName);
9510            if (pkg == null) {
9511                throw new IllegalArgumentException("Unknown package: " + packageName);
9512            }
9513        }
9514        /* Only the shell, root, or the app user should be able to dump profiles. */
9515        int callingUid = Binder.getCallingUid();
9516        if (callingUid != Process.SHELL_UID &&
9517            callingUid != Process.ROOT_UID &&
9518            callingUid != pkg.applicationInfo.uid) {
9519            throw new SecurityException("dumpProfiles");
9520        }
9521
9522        synchronized (mInstallLock) {
9523            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dump profiles");
9524            final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid);
9525            try {
9526                List<String> allCodePaths = pkg.getAllCodePathsExcludingResourceOnly();
9527                String codePaths = TextUtils.join(";", allCodePaths);
9528                mInstaller.dumpProfiles(sharedGid, packageName, codePaths);
9529            } catch (InstallerException e) {
9530                Slog.w(TAG, "Failed to dump profiles", e);
9531            }
9532            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
9533        }
9534    }
9535
9536    @Override
9537    public void forceDexOpt(String packageName) {
9538        enforceSystemOrRoot("forceDexOpt");
9539
9540        PackageParser.Package pkg;
9541        synchronized (mPackages) {
9542            pkg = mPackages.get(packageName);
9543            if (pkg == null) {
9544                throw new IllegalArgumentException("Unknown package: " + packageName);
9545            }
9546        }
9547
9548        synchronized (mInstallLock) {
9549            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt");
9550
9551            // Whoever is calling forceDexOpt wants a compiled package.
9552            // Don't use profiles since that may cause compilation to be skipped.
9553            final int res = performDexOptInternalWithDependenciesLI(pkg,
9554                    false /* checkProfiles */, getDefaultCompilerFilter(),
9555                    true /* force */);
9556
9557            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
9558            if (res != PackageDexOptimizer.DEX_OPT_PERFORMED) {
9559                throw new IllegalStateException("Failed to dexopt: " + res);
9560            }
9561        }
9562    }
9563
9564    private boolean verifyPackageUpdateLPr(PackageSetting oldPkg, PackageParser.Package newPkg) {
9565        if ((oldPkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) {
9566            Slog.w(TAG, "Unable to update from " + oldPkg.name
9567                    + " to " + newPkg.packageName
9568                    + ": old package not in system partition");
9569            return false;
9570        } else if (mPackages.get(oldPkg.name) != null) {
9571            Slog.w(TAG, "Unable to update from " + oldPkg.name
9572                    + " to " + newPkg.packageName
9573                    + ": old package still exists");
9574            return false;
9575        }
9576        return true;
9577    }
9578
9579    void removeCodePathLI(File codePath) {
9580        if (codePath.isDirectory()) {
9581            try {
9582                mInstaller.rmPackageDir(codePath.getAbsolutePath());
9583            } catch (InstallerException e) {
9584                Slog.w(TAG, "Failed to remove code path", e);
9585            }
9586        } else {
9587            codePath.delete();
9588        }
9589    }
9590
9591    private int[] resolveUserIds(int userId) {
9592        return (userId == UserHandle.USER_ALL) ? sUserManager.getUserIds() : new int[] { userId };
9593    }
9594
9595    private void clearAppDataLIF(PackageParser.Package pkg, int userId, int flags) {
9596        if (pkg == null) {
9597            Slog.wtf(TAG, "Package was null!", new Throwable());
9598            return;
9599        }
9600        clearAppDataLeafLIF(pkg, userId, flags);
9601        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
9602        for (int i = 0; i < childCount; i++) {
9603            clearAppDataLeafLIF(pkg.childPackages.get(i), userId, flags);
9604        }
9605    }
9606
9607    private void clearAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) {
9608        final PackageSetting ps;
9609        synchronized (mPackages) {
9610            ps = mSettings.mPackages.get(pkg.packageName);
9611        }
9612        for (int realUserId : resolveUserIds(userId)) {
9613            final long ceDataInode = (ps != null) ? ps.getCeDataInode(realUserId) : 0;
9614            try {
9615                mInstaller.clearAppData(pkg.volumeUuid, pkg.packageName, realUserId, flags,
9616                        ceDataInode);
9617            } catch (InstallerException e) {
9618                Slog.w(TAG, String.valueOf(e));
9619            }
9620        }
9621    }
9622
9623    private void destroyAppDataLIF(PackageParser.Package pkg, int userId, int flags) {
9624        if (pkg == null) {
9625            Slog.wtf(TAG, "Package was null!", new Throwable());
9626            return;
9627        }
9628        destroyAppDataLeafLIF(pkg, userId, flags);
9629        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
9630        for (int i = 0; i < childCount; i++) {
9631            destroyAppDataLeafLIF(pkg.childPackages.get(i), userId, flags);
9632        }
9633    }
9634
9635    private void destroyAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) {
9636        final PackageSetting ps;
9637        synchronized (mPackages) {
9638            ps = mSettings.mPackages.get(pkg.packageName);
9639        }
9640        for (int realUserId : resolveUserIds(userId)) {
9641            final long ceDataInode = (ps != null) ? ps.getCeDataInode(realUserId) : 0;
9642            try {
9643                mInstaller.destroyAppData(pkg.volumeUuid, pkg.packageName, realUserId, flags,
9644                        ceDataInode);
9645            } catch (InstallerException e) {
9646                Slog.w(TAG, String.valueOf(e));
9647            }
9648            mDexManager.notifyPackageDataDestroyed(pkg.packageName, userId);
9649        }
9650    }
9651
9652    private void destroyAppProfilesLIF(PackageParser.Package pkg, int userId) {
9653        if (pkg == null) {
9654            Slog.wtf(TAG, "Package was null!", new Throwable());
9655            return;
9656        }
9657        destroyAppProfilesLeafLIF(pkg);
9658        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
9659        for (int i = 0; i < childCount; i++) {
9660            destroyAppProfilesLeafLIF(pkg.childPackages.get(i));
9661        }
9662    }
9663
9664    private void destroyAppProfilesLeafLIF(PackageParser.Package pkg) {
9665        try {
9666            mInstaller.destroyAppProfiles(pkg.packageName);
9667        } catch (InstallerException e) {
9668            Slog.w(TAG, String.valueOf(e));
9669        }
9670    }
9671
9672    private void clearAppProfilesLIF(PackageParser.Package pkg, int userId) {
9673        if (pkg == null) {
9674            Slog.wtf(TAG, "Package was null!", new Throwable());
9675            return;
9676        }
9677        clearAppProfilesLeafLIF(pkg);
9678        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
9679        for (int i = 0; i < childCount; i++) {
9680            clearAppProfilesLeafLIF(pkg.childPackages.get(i));
9681        }
9682    }
9683
9684    private void clearAppProfilesLeafLIF(PackageParser.Package pkg) {
9685        try {
9686            mInstaller.clearAppProfiles(pkg.packageName);
9687        } catch (InstallerException e) {
9688            Slog.w(TAG, String.valueOf(e));
9689        }
9690    }
9691
9692    private void setInstallAndUpdateTime(PackageParser.Package pkg, long firstInstallTime,
9693            long lastUpdateTime) {
9694        // Set parent install/update time
9695        PackageSetting ps = (PackageSetting) pkg.mExtras;
9696        if (ps != null) {
9697            ps.firstInstallTime = firstInstallTime;
9698            ps.lastUpdateTime = lastUpdateTime;
9699        }
9700        // Set children install/update time
9701        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
9702        for (int i = 0; i < childCount; i++) {
9703            PackageParser.Package childPkg = pkg.childPackages.get(i);
9704            ps = (PackageSetting) childPkg.mExtras;
9705            if (ps != null) {
9706                ps.firstInstallTime = firstInstallTime;
9707                ps.lastUpdateTime = lastUpdateTime;
9708            }
9709        }
9710    }
9711
9712    private void addSharedLibraryLPr(ArraySet<String> usesLibraryFiles, SharedLibraryEntry file,
9713            PackageParser.Package changingLib) {
9714        if (file.path != null) {
9715            usesLibraryFiles.add(file.path);
9716            return;
9717        }
9718        PackageParser.Package p = mPackages.get(file.apk);
9719        if (changingLib != null && changingLib.packageName.equals(file.apk)) {
9720            // If we are doing this while in the middle of updating a library apk,
9721            // then we need to make sure to use that new apk for determining the
9722            // dependencies here.  (We haven't yet finished committing the new apk
9723            // to the package manager state.)
9724            if (p == null || p.packageName.equals(changingLib.packageName)) {
9725                p = changingLib;
9726            }
9727        }
9728        if (p != null) {
9729            usesLibraryFiles.addAll(p.getAllCodePaths());
9730            if (p.usesLibraryFiles != null) {
9731                Collections.addAll(usesLibraryFiles, p.usesLibraryFiles);
9732            }
9733        }
9734    }
9735
9736    private void updateSharedLibrariesLPr(PackageParser.Package pkg,
9737            PackageParser.Package changingLib) throws PackageManagerException {
9738        if (pkg == null) {
9739            return;
9740        }
9741        ArraySet<String> usesLibraryFiles = null;
9742        if (pkg.usesLibraries != null) {
9743            usesLibraryFiles = addSharedLibrariesLPw(pkg.usesLibraries,
9744                    null, null, pkg.packageName, changingLib, true, null);
9745        }
9746        if (pkg.usesStaticLibraries != null) {
9747            usesLibraryFiles = addSharedLibrariesLPw(pkg.usesStaticLibraries,
9748                    pkg.usesStaticLibrariesVersions, pkg.usesStaticLibrariesCertDigests,
9749                    pkg.packageName, changingLib, true, usesLibraryFiles);
9750        }
9751        if (pkg.usesOptionalLibraries != null) {
9752            usesLibraryFiles = addSharedLibrariesLPw(pkg.usesOptionalLibraries,
9753                    null, null, pkg.packageName, changingLib, false, usesLibraryFiles);
9754        }
9755        if (!ArrayUtils.isEmpty(usesLibraryFiles)) {
9756            pkg.usesLibraryFiles = usesLibraryFiles.toArray(new String[usesLibraryFiles.size()]);
9757        } else {
9758            pkg.usesLibraryFiles = null;
9759        }
9760    }
9761
9762    private ArraySet<String> addSharedLibrariesLPw(@NonNull List<String> requestedLibraries,
9763            @Nullable int[] requiredVersions, @Nullable String[] requiredCertDigests,
9764            @NonNull String packageName, @Nullable PackageParser.Package changingLib,
9765            boolean required, @Nullable ArraySet<String> outUsedLibraries)
9766            throws PackageManagerException {
9767        final int libCount = requestedLibraries.size();
9768        for (int i = 0; i < libCount; i++) {
9769            final String libName = requestedLibraries.get(i);
9770            final int libVersion = requiredVersions != null ? requiredVersions[i]
9771                    : SharedLibraryInfo.VERSION_UNDEFINED;
9772            final SharedLibraryEntry libEntry = getSharedLibraryEntryLPr(libName, libVersion);
9773            if (libEntry == null) {
9774                if (required) {
9775                    throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY,
9776                            "Package " + packageName + " requires unavailable shared library "
9777                                    + libName + "; failing!");
9778                } else if (DEBUG_SHARED_LIBRARIES) {
9779                    Slog.i(TAG, "Package " + packageName
9780                            + " desires unavailable shared library "
9781                            + libName + "; ignoring!");
9782                }
9783            } else {
9784                if (requiredVersions != null && requiredCertDigests != null) {
9785                    if (libEntry.info.getVersion() != requiredVersions[i]) {
9786                        throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY,
9787                            "Package " + packageName + " requires unavailable static shared"
9788                                    + " library " + libName + " version "
9789                                    + libEntry.info.getVersion() + "; failing!");
9790                    }
9791
9792                    PackageParser.Package libPkg = mPackages.get(libEntry.apk);
9793                    if (libPkg == null) {
9794                        throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY,
9795                                "Package " + packageName + " requires unavailable static shared"
9796                                        + " library; failing!");
9797                    }
9798
9799                    String expectedCertDigest = requiredCertDigests[i];
9800                    String libCertDigest = PackageUtils.computeCertSha256Digest(
9801                                libPkg.mSignatures[0]);
9802                    if (!libCertDigest.equalsIgnoreCase(expectedCertDigest)) {
9803                        throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY,
9804                                "Package " + packageName + " requires differently signed" +
9805                                        " static shared library; failing!");
9806                    }
9807                }
9808
9809                if (outUsedLibraries == null) {
9810                    outUsedLibraries = new ArraySet<>();
9811                }
9812                addSharedLibraryLPr(outUsedLibraries, libEntry, changingLib);
9813            }
9814        }
9815        return outUsedLibraries;
9816    }
9817
9818    private static boolean hasString(List<String> list, List<String> which) {
9819        if (list == null) {
9820            return false;
9821        }
9822        for (int i=list.size()-1; i>=0; i--) {
9823            for (int j=which.size()-1; j>=0; j--) {
9824                if (which.get(j).equals(list.get(i))) {
9825                    return true;
9826                }
9827            }
9828        }
9829        return false;
9830    }
9831
9832    private ArrayList<PackageParser.Package> updateAllSharedLibrariesLPw(
9833            PackageParser.Package changingPkg) {
9834        ArrayList<PackageParser.Package> res = null;
9835        for (PackageParser.Package pkg : mPackages.values()) {
9836            if (changingPkg != null
9837                    && !hasString(pkg.usesLibraries, changingPkg.libraryNames)
9838                    && !hasString(pkg.usesOptionalLibraries, changingPkg.libraryNames)
9839                    && !ArrayUtils.contains(pkg.usesStaticLibraries,
9840                            changingPkg.staticSharedLibName)) {
9841                return null;
9842            }
9843            if (res == null) {
9844                res = new ArrayList<>();
9845            }
9846            res.add(pkg);
9847            try {
9848                updateSharedLibrariesLPr(pkg, changingPkg);
9849            } catch (PackageManagerException e) {
9850                // If a system app update or an app and a required lib missing we
9851                // delete the package and for updated system apps keep the data as
9852                // it is better for the user to reinstall than to be in an limbo
9853                // state. Also libs disappearing under an app should never happen
9854                // - just in case.
9855                if (!pkg.isSystemApp() || pkg.isUpdatedSystemApp()) {
9856                    final int flags = pkg.isUpdatedSystemApp()
9857                            ? PackageManager.DELETE_KEEP_DATA : 0;
9858                    deletePackageLIF(pkg.packageName, null, true, sUserManager.getUserIds(),
9859                            flags , null, true, null);
9860                }
9861                Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
9862            }
9863        }
9864        return res;
9865    }
9866
9867    /**
9868     * Derive the value of the {@code cpuAbiOverride} based on the provided
9869     * value and an optional stored value from the package settings.
9870     */
9871    private static String deriveAbiOverride(String abiOverride, PackageSetting settings) {
9872        String cpuAbiOverride = null;
9873
9874        if (NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(abiOverride)) {
9875            cpuAbiOverride = null;
9876        } else if (abiOverride != null) {
9877            cpuAbiOverride = abiOverride;
9878        } else if (settings != null) {
9879            cpuAbiOverride = settings.cpuAbiOverrideString;
9880        }
9881
9882        return cpuAbiOverride;
9883    }
9884
9885    private PackageParser.Package scanPackageTracedLI(PackageParser.Package pkg,
9886            final int policyFlags, int scanFlags, long currentTime, @Nullable UserHandle user)
9887                    throws PackageManagerException {
9888        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage");
9889        // If the package has children and this is the first dive in the function
9890        // we recursively scan the package with the SCAN_CHECK_ONLY flag set to see
9891        // whether all packages (parent and children) would be successfully scanned
9892        // before the actual scan since scanning mutates internal state and we want
9893        // to atomically install the package and its children.
9894        if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
9895            if (pkg.childPackages != null && pkg.childPackages.size() > 0) {
9896                scanFlags |= SCAN_CHECK_ONLY;
9897            }
9898        } else {
9899            scanFlags &= ~SCAN_CHECK_ONLY;
9900        }
9901
9902        final PackageParser.Package scannedPkg;
9903        try {
9904            // Scan the parent
9905            scannedPkg = scanPackageLI(pkg, policyFlags, scanFlags, currentTime, user);
9906            // Scan the children
9907            final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
9908            for (int i = 0; i < childCount; i++) {
9909                PackageParser.Package childPkg = pkg.childPackages.get(i);
9910                scanPackageLI(childPkg, policyFlags,
9911                        scanFlags, currentTime, user);
9912            }
9913        } finally {
9914            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
9915        }
9916
9917        if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
9918            return scanPackageTracedLI(pkg, policyFlags, scanFlags, currentTime, user);
9919        }
9920
9921        return scannedPkg;
9922    }
9923
9924    private PackageParser.Package scanPackageLI(PackageParser.Package pkg, final int policyFlags,
9925            int scanFlags, long currentTime, @Nullable UserHandle user)
9926                    throws PackageManagerException {
9927        boolean success = false;
9928        try {
9929            final PackageParser.Package res = scanPackageDirtyLI(pkg, policyFlags, scanFlags,
9930                    currentTime, user);
9931            success = true;
9932            return res;
9933        } finally {
9934            if (!success && (scanFlags & SCAN_DELETE_DATA_ON_FAILURES) != 0) {
9935                // DELETE_DATA_ON_FAILURES is only used by frozen paths
9936                destroyAppDataLIF(pkg, UserHandle.USER_ALL,
9937                        StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
9938                destroyAppProfilesLIF(pkg, UserHandle.USER_ALL);
9939            }
9940        }
9941    }
9942
9943    /**
9944     * Returns {@code true} if the given file contains code. Otherwise {@code false}.
9945     */
9946    private static boolean apkHasCode(String fileName) {
9947        StrictJarFile jarFile = null;
9948        try {
9949            jarFile = new StrictJarFile(fileName,
9950                    false /*verify*/, false /*signatureSchemeRollbackProtectionsEnforced*/);
9951            return jarFile.findEntry("classes.dex") != null;
9952        } catch (IOException ignore) {
9953        } finally {
9954            try {
9955                if (jarFile != null) {
9956                    jarFile.close();
9957                }
9958            } catch (IOException ignore) {}
9959        }
9960        return false;
9961    }
9962
9963    /**
9964     * Enforces code policy for the package. This ensures that if an APK has
9965     * declared hasCode="true" in its manifest that the APK actually contains
9966     * code.
9967     *
9968     * @throws PackageManagerException If bytecode could not be found when it should exist
9969     */
9970    private static void assertCodePolicy(PackageParser.Package pkg)
9971            throws PackageManagerException {
9972        final boolean shouldHaveCode =
9973                (pkg.applicationInfo.flags & ApplicationInfo.FLAG_HAS_CODE) != 0;
9974        if (shouldHaveCode && !apkHasCode(pkg.baseCodePath)) {
9975            throw new PackageManagerException(INSTALL_FAILED_INVALID_APK,
9976                    "Package " + pkg.baseCodePath + " code is missing");
9977        }
9978
9979        if (!ArrayUtils.isEmpty(pkg.splitCodePaths)) {
9980            for (int i = 0; i < pkg.splitCodePaths.length; i++) {
9981                final boolean splitShouldHaveCode =
9982                        (pkg.splitFlags[i] & ApplicationInfo.FLAG_HAS_CODE) != 0;
9983                if (splitShouldHaveCode && !apkHasCode(pkg.splitCodePaths[i])) {
9984                    throw new PackageManagerException(INSTALL_FAILED_INVALID_APK,
9985                            "Package " + pkg.splitCodePaths[i] + " code is missing");
9986                }
9987            }
9988        }
9989    }
9990
9991    private PackageParser.Package scanPackageDirtyLI(PackageParser.Package pkg,
9992            final int policyFlags, final int scanFlags, long currentTime, @Nullable UserHandle user)
9993                    throws PackageManagerException {
9994        if (DEBUG_PACKAGE_SCANNING) {
9995            if ((policyFlags & PackageParser.PARSE_CHATTY) != 0)
9996                Log.d(TAG, "Scanning package " + pkg.packageName);
9997        }
9998
9999        applyPolicy(pkg, policyFlags);
10000
10001        assertPackageIsValid(pkg, policyFlags, scanFlags);
10002
10003        // Initialize package source and resource directories
10004        final File scanFile = new File(pkg.codePath);
10005        final File destCodeFile = new File(pkg.applicationInfo.getCodePath());
10006        final File destResourceFile = new File(pkg.applicationInfo.getResourcePath());
10007
10008        SharedUserSetting suid = null;
10009        PackageSetting pkgSetting = null;
10010
10011        // Getting the package setting may have a side-effect, so if we
10012        // are only checking if scan would succeed, stash a copy of the
10013        // old setting to restore at the end.
10014        PackageSetting nonMutatedPs = null;
10015
10016        // We keep references to the derived CPU Abis from settings in oder to reuse
10017        // them in the case where we're not upgrading or booting for the first time.
10018        String primaryCpuAbiFromSettings = null;
10019        String secondaryCpuAbiFromSettings = null;
10020
10021        // writer
10022        synchronized (mPackages) {
10023            if (pkg.mSharedUserId != null) {
10024                // SIDE EFFECTS; may potentially allocate a new shared user
10025                suid = mSettings.getSharedUserLPw(
10026                        pkg.mSharedUserId, 0 /*pkgFlags*/, 0 /*pkgPrivateFlags*/, true /*create*/);
10027                if (DEBUG_PACKAGE_SCANNING) {
10028                    if ((policyFlags & PackageParser.PARSE_CHATTY) != 0)
10029                        Log.d(TAG, "Shared UserID " + pkg.mSharedUserId + " (uid=" + suid.userId
10030                                + "): packages=" + suid.packages);
10031                }
10032            }
10033
10034            // Check if we are renaming from an original package name.
10035            PackageSetting origPackage = null;
10036            String realName = null;
10037            if (pkg.mOriginalPackages != null) {
10038                // This package may need to be renamed to a previously
10039                // installed name.  Let's check on that...
10040                final String renamed = mSettings.getRenamedPackageLPr(pkg.mRealPackage);
10041                if (pkg.mOriginalPackages.contains(renamed)) {
10042                    // This package had originally been installed as the
10043                    // original name, and we have already taken care of
10044                    // transitioning to the new one.  Just update the new
10045                    // one to continue using the old name.
10046                    realName = pkg.mRealPackage;
10047                    if (!pkg.packageName.equals(renamed)) {
10048                        // Callers into this function may have already taken
10049                        // care of renaming the package; only do it here if
10050                        // it is not already done.
10051                        pkg.setPackageName(renamed);
10052                    }
10053                } else {
10054                    for (int i=pkg.mOriginalPackages.size()-1; i>=0; i--) {
10055                        if ((origPackage = mSettings.getPackageLPr(
10056                                pkg.mOriginalPackages.get(i))) != null) {
10057                            // We do have the package already installed under its
10058                            // original name...  should we use it?
10059                            if (!verifyPackageUpdateLPr(origPackage, pkg)) {
10060                                // New package is not compatible with original.
10061                                origPackage = null;
10062                                continue;
10063                            } else if (origPackage.sharedUser != null) {
10064                                // Make sure uid is compatible between packages.
10065                                if (!origPackage.sharedUser.name.equals(pkg.mSharedUserId)) {
10066                                    Slog.w(TAG, "Unable to migrate data from " + origPackage.name
10067                                            + " to " + pkg.packageName + ": old uid "
10068                                            + origPackage.sharedUser.name
10069                                            + " differs from " + pkg.mSharedUserId);
10070                                    origPackage = null;
10071                                    continue;
10072                                }
10073                                // TODO: Add case when shared user id is added [b/28144775]
10074                            } else {
10075                                if (DEBUG_UPGRADE) Log.v(TAG, "Renaming new package "
10076                                        + pkg.packageName + " to old name " + origPackage.name);
10077                            }
10078                            break;
10079                        }
10080                    }
10081                }
10082            }
10083
10084            if (mTransferedPackages.contains(pkg.packageName)) {
10085                Slog.w(TAG, "Package " + pkg.packageName
10086                        + " was transferred to another, but its .apk remains");
10087            }
10088
10089            // See comments in nonMutatedPs declaration
10090            if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
10091                PackageSetting foundPs = mSettings.getPackageLPr(pkg.packageName);
10092                if (foundPs != null) {
10093                    nonMutatedPs = new PackageSetting(foundPs);
10094                }
10095            }
10096
10097            if ((scanFlags & SCAN_FIRST_BOOT_OR_UPGRADE) == 0) {
10098                PackageSetting foundPs = mSettings.getPackageLPr(pkg.packageName);
10099                if (foundPs != null) {
10100                    primaryCpuAbiFromSettings = foundPs.primaryCpuAbiString;
10101                    secondaryCpuAbiFromSettings = foundPs.secondaryCpuAbiString;
10102                }
10103            }
10104
10105            pkgSetting = mSettings.getPackageLPr(pkg.packageName);
10106            if (pkgSetting != null && pkgSetting.sharedUser != suid) {
10107                PackageManagerService.reportSettingsProblem(Log.WARN,
10108                        "Package " + pkg.packageName + " shared user changed from "
10109                                + (pkgSetting.sharedUser != null
10110                                        ? pkgSetting.sharedUser.name : "<nothing>")
10111                                + " to "
10112                                + (suid != null ? suid.name : "<nothing>")
10113                                + "; replacing with new");
10114                pkgSetting = null;
10115            }
10116            final PackageSetting oldPkgSetting =
10117                    pkgSetting == null ? null : new PackageSetting(pkgSetting);
10118            final PackageSetting disabledPkgSetting =
10119                    mSettings.getDisabledSystemPkgLPr(pkg.packageName);
10120
10121            String[] usesStaticLibraries = null;
10122            if (pkg.usesStaticLibraries != null) {
10123                usesStaticLibraries = new String[pkg.usesStaticLibraries.size()];
10124                pkg.usesStaticLibraries.toArray(usesStaticLibraries);
10125            }
10126
10127            if (pkgSetting == null) {
10128                final String parentPackageName = (pkg.parentPackage != null)
10129                        ? pkg.parentPackage.packageName : null;
10130                final boolean instantApp = (scanFlags & SCAN_AS_INSTANT_APP) != 0;
10131                // REMOVE SharedUserSetting from method; update in a separate call
10132                pkgSetting = Settings.createNewSetting(pkg.packageName, origPackage,
10133                        disabledPkgSetting, realName, suid, destCodeFile, destResourceFile,
10134                        pkg.applicationInfo.nativeLibraryRootDir, pkg.applicationInfo.primaryCpuAbi,
10135                        pkg.applicationInfo.secondaryCpuAbi, pkg.mVersionCode,
10136                        pkg.applicationInfo.flags, pkg.applicationInfo.privateFlags, user,
10137                        true /*allowInstall*/, instantApp, parentPackageName,
10138                        pkg.getChildPackageNames(), UserManagerService.getInstance(),
10139                        usesStaticLibraries, pkg.usesStaticLibrariesVersions);
10140                // SIDE EFFECTS; updates system state; move elsewhere
10141                if (origPackage != null) {
10142                    mSettings.addRenamedPackageLPw(pkg.packageName, origPackage.name);
10143                }
10144                mSettings.addUserToSettingLPw(pkgSetting);
10145            } else {
10146                // REMOVE SharedUserSetting from method; update in a separate call.
10147                //
10148                // TODO(narayan): This update is bogus. nativeLibraryDir & primaryCpuAbi,
10149                // secondaryCpuAbi are not known at this point so we always update them
10150                // to null here, only to reset them at a later point.
10151                Settings.updatePackageSetting(pkgSetting, disabledPkgSetting, suid, destCodeFile,
10152                        pkg.applicationInfo.nativeLibraryDir, pkg.applicationInfo.primaryCpuAbi,
10153                        pkg.applicationInfo.secondaryCpuAbi, pkg.applicationInfo.flags,
10154                        pkg.applicationInfo.privateFlags, pkg.getChildPackageNames(),
10155                        UserManagerService.getInstance(), usesStaticLibraries,
10156                        pkg.usesStaticLibrariesVersions);
10157            }
10158            // SIDE EFFECTS; persists system state to files on disk; move elsewhere
10159            mSettings.writeUserRestrictionsLPw(pkgSetting, oldPkgSetting);
10160
10161            // SIDE EFFECTS; modifies system state; move elsewhere
10162            if (pkgSetting.origPackage != null) {
10163                // If we are first transitioning from an original package,
10164                // fix up the new package's name now.  We need to do this after
10165                // looking up the package under its new name, so getPackageLP
10166                // can take care of fiddling things correctly.
10167                pkg.setPackageName(origPackage.name);
10168
10169                // File a report about this.
10170                String msg = "New package " + pkgSetting.realName
10171                        + " renamed to replace old package " + pkgSetting.name;
10172                reportSettingsProblem(Log.WARN, msg);
10173
10174                // Make a note of it.
10175                if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
10176                    mTransferedPackages.add(origPackage.name);
10177                }
10178
10179                // No longer need to retain this.
10180                pkgSetting.origPackage = null;
10181            }
10182
10183            // SIDE EFFECTS; modifies system state; move elsewhere
10184            if ((scanFlags & SCAN_CHECK_ONLY) == 0 && realName != null) {
10185                // Make a note of it.
10186                mTransferedPackages.add(pkg.packageName);
10187            }
10188
10189            if (mSettings.isDisabledSystemPackageLPr(pkg.packageName)) {
10190                pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
10191            }
10192
10193            if ((scanFlags & SCAN_BOOTING) == 0
10194                    && (policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
10195                // Check all shared libraries and map to their actual file path.
10196                // We only do this here for apps not on a system dir, because those
10197                // are the only ones that can fail an install due to this.  We
10198                // will take care of the system apps by updating all of their
10199                // library paths after the scan is done. Also during the initial
10200                // scan don't update any libs as we do this wholesale after all
10201                // apps are scanned to avoid dependency based scanning.
10202                updateSharedLibrariesLPr(pkg, null);
10203            }
10204
10205            if (mFoundPolicyFile) {
10206                SELinuxMMAC.assignSeInfoValue(pkg);
10207            }
10208            pkg.applicationInfo.uid = pkgSetting.appId;
10209            pkg.mExtras = pkgSetting;
10210
10211
10212            // Static shared libs have same package with different versions where
10213            // we internally use a synthetic package name to allow multiple versions
10214            // of the same package, therefore we need to compare signatures against
10215            // the package setting for the latest library version.
10216            PackageSetting signatureCheckPs = pkgSetting;
10217            if (pkg.applicationInfo.isStaticSharedLibrary()) {
10218                SharedLibraryEntry libraryEntry = getLatestSharedLibraVersionLPr(pkg);
10219                if (libraryEntry != null) {
10220                    signatureCheckPs = mSettings.getPackageLPr(libraryEntry.apk);
10221                }
10222            }
10223
10224            if (shouldCheckUpgradeKeySetLP(signatureCheckPs, scanFlags)) {
10225                if (checkUpgradeKeySetLP(signatureCheckPs, pkg)) {
10226                    // We just determined the app is signed correctly, so bring
10227                    // over the latest parsed certs.
10228                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
10229                } else {
10230                    if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
10231                        throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
10232                                "Package " + pkg.packageName + " upgrade keys do not match the "
10233                                + "previously installed version");
10234                    } else {
10235                        pkgSetting.signatures.mSignatures = pkg.mSignatures;
10236                        String msg = "System package " + pkg.packageName
10237                                + " signature changed; retaining data.";
10238                        reportSettingsProblem(Log.WARN, msg);
10239                    }
10240                }
10241            } else {
10242                try {
10243                    // SIDE EFFECTS; compareSignaturesCompat() changes KeysetManagerService
10244                    verifySignaturesLP(signatureCheckPs, pkg);
10245                    // We just determined the app is signed correctly, so bring
10246                    // over the latest parsed certs.
10247                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
10248                } catch (PackageManagerException e) {
10249                    if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
10250                        throw e;
10251                    }
10252                    // The signature has changed, but this package is in the system
10253                    // image...  let's recover!
10254                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
10255                    // However...  if this package is part of a shared user, but it
10256                    // doesn't match the signature of the shared user, let's fail.
10257                    // What this means is that you can't change the signatures
10258                    // associated with an overall shared user, which doesn't seem all
10259                    // that unreasonable.
10260                    if (signatureCheckPs.sharedUser != null) {
10261                        if (compareSignatures(signatureCheckPs.sharedUser.signatures.mSignatures,
10262                                pkg.mSignatures) != PackageManager.SIGNATURE_MATCH) {
10263                            throw new PackageManagerException(
10264                                    INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES,
10265                                    "Signature mismatch for shared user: "
10266                                            + pkgSetting.sharedUser);
10267                        }
10268                    }
10269                    // File a report about this.
10270                    String msg = "System package " + pkg.packageName
10271                            + " signature changed; retaining data.";
10272                    reportSettingsProblem(Log.WARN, msg);
10273                }
10274            }
10275
10276            if ((scanFlags & SCAN_CHECK_ONLY) == 0 && pkg.mAdoptPermissions != null) {
10277                // This package wants to adopt ownership of permissions from
10278                // another package.
10279                for (int i = pkg.mAdoptPermissions.size() - 1; i >= 0; i--) {
10280                    final String origName = pkg.mAdoptPermissions.get(i);
10281                    final PackageSetting orig = mSettings.getPackageLPr(origName);
10282                    if (orig != null) {
10283                        if (verifyPackageUpdateLPr(orig, pkg)) {
10284                            Slog.i(TAG, "Adopting permissions from " + origName + " to "
10285                                    + pkg.packageName);
10286                            // SIDE EFFECTS; updates permissions system state; move elsewhere
10287                            mSettings.transferPermissionsLPw(origName, pkg.packageName);
10288                        }
10289                    }
10290                }
10291            }
10292        }
10293
10294        pkg.applicationInfo.processName = fixProcessName(
10295                pkg.applicationInfo.packageName,
10296                pkg.applicationInfo.processName);
10297
10298        if (pkg != mPlatformPackage) {
10299            // Get all of our default paths setup
10300            pkg.applicationInfo.initForUser(UserHandle.USER_SYSTEM);
10301        }
10302
10303        final String cpuAbiOverride = deriveAbiOverride(pkg.cpuAbiOverride, pkgSetting);
10304
10305        if ((scanFlags & SCAN_NEW_INSTALL) == 0) {
10306            if ((scanFlags & SCAN_FIRST_BOOT_OR_UPGRADE) != 0) {
10307                Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "derivePackageAbi");
10308                derivePackageAbi(
10309                        pkg, scanFile, cpuAbiOverride, true /*extractLibs*/, mAppLib32InstallDir);
10310                Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
10311
10312                // Some system apps still use directory structure for native libraries
10313                // in which case we might end up not detecting abi solely based on apk
10314                // structure. Try to detect abi based on directory structure.
10315                if (isSystemApp(pkg) && !pkg.isUpdatedSystemApp() &&
10316                        pkg.applicationInfo.primaryCpuAbi == null) {
10317                    setBundledAppAbisAndRoots(pkg, pkgSetting);
10318                    setNativeLibraryPaths(pkg, mAppLib32InstallDir);
10319                }
10320            } else {
10321                // This is not a first boot or an upgrade, don't bother deriving the
10322                // ABI during the scan. Instead, trust the value that was stored in the
10323                // package setting.
10324                pkg.applicationInfo.primaryCpuAbi = primaryCpuAbiFromSettings;
10325                pkg.applicationInfo.secondaryCpuAbi = secondaryCpuAbiFromSettings;
10326
10327                setNativeLibraryPaths(pkg, mAppLib32InstallDir);
10328
10329                if (DEBUG_ABI_SELECTION) {
10330                    Slog.i(TAG, "Using ABIS and native lib paths from settings : " +
10331                        pkg.packageName + " " + pkg.applicationInfo.primaryCpuAbi + ", " +
10332                        pkg.applicationInfo.secondaryCpuAbi);
10333                }
10334            }
10335        } else {
10336            if ((scanFlags & SCAN_MOVE) != 0) {
10337                // We haven't run dex-opt for this move (since we've moved the compiled output too)
10338                // but we already have this packages package info in the PackageSetting. We just
10339                // use that and derive the native library path based on the new codepath.
10340                pkg.applicationInfo.primaryCpuAbi = pkgSetting.primaryCpuAbiString;
10341                pkg.applicationInfo.secondaryCpuAbi = pkgSetting.secondaryCpuAbiString;
10342            }
10343
10344            // Set native library paths again. For moves, the path will be updated based on the
10345            // ABIs we've determined above. For non-moves, the path will be updated based on the
10346            // ABIs we determined during compilation, but the path will depend on the final
10347            // package path (after the rename away from the stage path).
10348            setNativeLibraryPaths(pkg, mAppLib32InstallDir);
10349        }
10350
10351        // This is a special case for the "system" package, where the ABI is
10352        // dictated by the zygote configuration (and init.rc). We should keep track
10353        // of this ABI so that we can deal with "normal" applications that run under
10354        // the same UID correctly.
10355        if (mPlatformPackage == pkg) {
10356            pkg.applicationInfo.primaryCpuAbi = VMRuntime.getRuntime().is64Bit() ?
10357                    Build.SUPPORTED_64_BIT_ABIS[0] : Build.SUPPORTED_32_BIT_ABIS[0];
10358        }
10359
10360        // If there's a mismatch between the abi-override in the package setting
10361        // and the abiOverride specified for the install. Warn about this because we
10362        // would've already compiled the app without taking the package setting into
10363        // account.
10364        if ((scanFlags & SCAN_NO_DEX) == 0 && (scanFlags & SCAN_NEW_INSTALL) != 0) {
10365            if (cpuAbiOverride == null && pkgSetting.cpuAbiOverrideString != null) {
10366                Slog.w(TAG, "Ignoring persisted ABI override " + cpuAbiOverride +
10367                        " for package " + pkg.packageName);
10368            }
10369        }
10370
10371        pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi;
10372        pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi;
10373        pkgSetting.cpuAbiOverrideString = cpuAbiOverride;
10374
10375        // Copy the derived override back to the parsed package, so that we can
10376        // update the package settings accordingly.
10377        pkg.cpuAbiOverride = cpuAbiOverride;
10378
10379        if (DEBUG_ABI_SELECTION) {
10380            Slog.d(TAG, "Resolved nativeLibraryRoot for " + pkg.applicationInfo.packageName
10381                    + " to root=" + pkg.applicationInfo.nativeLibraryRootDir + ", isa="
10382                    + pkg.applicationInfo.nativeLibraryRootRequiresIsa);
10383        }
10384
10385        // Push the derived path down into PackageSettings so we know what to
10386        // clean up at uninstall time.
10387        pkgSetting.legacyNativeLibraryPathString = pkg.applicationInfo.nativeLibraryRootDir;
10388
10389        if (DEBUG_ABI_SELECTION) {
10390            Log.d(TAG, "Abis for package[" + pkg.packageName + "] are" +
10391                    " primary=" + pkg.applicationInfo.primaryCpuAbi +
10392                    " secondary=" + pkg.applicationInfo.secondaryCpuAbi);
10393        }
10394
10395        // SIDE EFFECTS; removes DEX files from disk; move elsewhere
10396        if ((scanFlags & SCAN_BOOTING) == 0 && pkgSetting.sharedUser != null) {
10397            // We don't do this here during boot because we can do it all
10398            // at once after scanning all existing packages.
10399            //
10400            // We also do this *before* we perform dexopt on this package, so that
10401            // we can avoid redundant dexopts, and also to make sure we've got the
10402            // code and package path correct.
10403            adjustCpuAbisForSharedUserLPw(pkgSetting.sharedUser.packages, pkg);
10404        }
10405
10406        if (mFactoryTest && pkg.requestedPermissions.contains(
10407                android.Manifest.permission.FACTORY_TEST)) {
10408            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_FACTORY_TEST;
10409        }
10410
10411        if (isSystemApp(pkg)) {
10412            pkgSetting.isOrphaned = true;
10413        }
10414
10415        // Take care of first install / last update times.
10416        final long scanFileTime = getLastModifiedTime(pkg, scanFile);
10417        if (currentTime != 0) {
10418            if (pkgSetting.firstInstallTime == 0) {
10419                pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = currentTime;
10420            } else if ((scanFlags & SCAN_UPDATE_TIME) != 0) {
10421                pkgSetting.lastUpdateTime = currentTime;
10422            }
10423        } else if (pkgSetting.firstInstallTime == 0) {
10424            // We need *something*.  Take time time stamp of the file.
10425            pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = scanFileTime;
10426        } else if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0) {
10427            if (scanFileTime != pkgSetting.timeStamp) {
10428                // A package on the system image has changed; consider this
10429                // to be an update.
10430                pkgSetting.lastUpdateTime = scanFileTime;
10431            }
10432        }
10433        pkgSetting.setTimeStamp(scanFileTime);
10434
10435        if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
10436            if (nonMutatedPs != null) {
10437                synchronized (mPackages) {
10438                    mSettings.mPackages.put(nonMutatedPs.name, nonMutatedPs);
10439                }
10440            }
10441        } else {
10442            final int userId = user == null ? 0 : user.getIdentifier();
10443            // Modify state for the given package setting
10444            commitPackageSettings(pkg, pkgSetting, user, scanFlags,
10445                    (policyFlags & PackageParser.PARSE_CHATTY) != 0 /*chatty*/);
10446            if (pkgSetting.getInstantApp(userId)) {
10447                mInstantAppRegistry.addInstantAppLPw(userId, pkgSetting.appId);
10448            }
10449        }
10450        return pkg;
10451    }
10452
10453    /**
10454     * Applies policy to the parsed package based upon the given policy flags.
10455     * Ensures the package is in a good state.
10456     * <p>
10457     * Implementation detail: This method must NOT have any side effect. It would
10458     * ideally be static, but, it requires locks to read system state.
10459     */
10460    private void applyPolicy(PackageParser.Package pkg, int policyFlags) {
10461        if ((policyFlags&PackageParser.PARSE_IS_SYSTEM) != 0) {
10462            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_SYSTEM;
10463            if (pkg.applicationInfo.isDirectBootAware()) {
10464                // we're direct boot aware; set for all components
10465                for (PackageParser.Service s : pkg.services) {
10466                    s.info.encryptionAware = s.info.directBootAware = true;
10467                }
10468                for (PackageParser.Provider p : pkg.providers) {
10469                    p.info.encryptionAware = p.info.directBootAware = true;
10470                }
10471                for (PackageParser.Activity a : pkg.activities) {
10472                    a.info.encryptionAware = a.info.directBootAware = true;
10473                }
10474                for (PackageParser.Activity r : pkg.receivers) {
10475                    r.info.encryptionAware = r.info.directBootAware = true;
10476                }
10477            }
10478        } else {
10479            // Only allow system apps to be flagged as core apps.
10480            pkg.coreApp = false;
10481            // clear flags not applicable to regular apps
10482            pkg.applicationInfo.privateFlags &=
10483                    ~ApplicationInfo.PRIVATE_FLAG_DEFAULT_TO_DEVICE_PROTECTED_STORAGE;
10484            pkg.applicationInfo.privateFlags &=
10485                    ~ApplicationInfo.PRIVATE_FLAG_DIRECT_BOOT_AWARE;
10486        }
10487        pkg.mTrustedOverlay = (policyFlags&PackageParser.PARSE_TRUSTED_OVERLAY) != 0;
10488
10489        if ((policyFlags&PackageParser.PARSE_IS_PRIVILEGED) != 0) {
10490            pkg.applicationInfo.privateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
10491        }
10492
10493        if (!isSystemApp(pkg)) {
10494            // Only system apps can use these features.
10495            pkg.mOriginalPackages = null;
10496            pkg.mRealPackage = null;
10497            pkg.mAdoptPermissions = null;
10498        }
10499    }
10500
10501    /**
10502     * Asserts the parsed package is valid according to the given policy. If the
10503     * package is invalid, for whatever reason, throws {@link PackageManagerException}.
10504     * <p>
10505     * Implementation detail: This method must NOT have any side effects. It would
10506     * ideally be static, but, it requires locks to read system state.
10507     *
10508     * @throws PackageManagerException If the package fails any of the validation checks
10509     */
10510    private void assertPackageIsValid(PackageParser.Package pkg, int policyFlags, int scanFlags)
10511            throws PackageManagerException {
10512        if ((policyFlags & PackageParser.PARSE_ENFORCE_CODE) != 0) {
10513            assertCodePolicy(pkg);
10514        }
10515
10516        if (pkg.applicationInfo.getCodePath() == null ||
10517                pkg.applicationInfo.getResourcePath() == null) {
10518            // Bail out. The resource and code paths haven't been set.
10519            throw new PackageManagerException(INSTALL_FAILED_INVALID_APK,
10520                    "Code and resource paths haven't been set correctly");
10521        }
10522
10523        // Make sure we're not adding any bogus keyset info
10524        KeySetManagerService ksms = mSettings.mKeySetManagerService;
10525        ksms.assertScannedPackageValid(pkg);
10526
10527        synchronized (mPackages) {
10528            // The special "android" package can only be defined once
10529            if (pkg.packageName.equals("android")) {
10530                if (mAndroidApplication != null) {
10531                    Slog.w(TAG, "*************************************************");
10532                    Slog.w(TAG, "Core android package being redefined.  Skipping.");
10533                    Slog.w(TAG, " codePath=" + pkg.codePath);
10534                    Slog.w(TAG, "*************************************************");
10535                    throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE,
10536                            "Core android package being redefined.  Skipping.");
10537                }
10538            }
10539
10540            // A package name must be unique; don't allow duplicates
10541            if (mPackages.containsKey(pkg.packageName)) {
10542                throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE,
10543                        "Application package " + pkg.packageName
10544                        + " already installed.  Skipping duplicate.");
10545            }
10546
10547            if (pkg.applicationInfo.isStaticSharedLibrary()) {
10548                // Static libs have a synthetic package name containing the version
10549                // but we still want the base name to be unique.
10550                if (mPackages.containsKey(pkg.manifestPackageName)) {
10551                    throw new PackageManagerException(
10552                            "Duplicate static shared lib provider package");
10553                }
10554
10555                // Static shared libraries should have at least O target SDK
10556                if (pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.O) {
10557                    throw new PackageManagerException(
10558                            "Packages declaring static-shared libs must target O SDK or higher");
10559                }
10560
10561                // Package declaring static a shared lib cannot be instant apps
10562                if ((scanFlags & SCAN_AS_INSTANT_APP) != 0) {
10563                    throw new PackageManagerException(
10564                            "Packages declaring static-shared libs cannot be instant apps");
10565                }
10566
10567                // Package declaring static a shared lib cannot be renamed since the package
10568                // name is synthetic and apps can't code around package manager internals.
10569                if (!ArrayUtils.isEmpty(pkg.mOriginalPackages)) {
10570                    throw new PackageManagerException(
10571                            "Packages declaring static-shared libs cannot be renamed");
10572                }
10573
10574                // Package declaring static a shared lib cannot declare child packages
10575                if (!ArrayUtils.isEmpty(pkg.childPackages)) {
10576                    throw new PackageManagerException(
10577                            "Packages declaring static-shared libs cannot have child packages");
10578                }
10579
10580                // Package declaring static a shared lib cannot declare dynamic libs
10581                if (!ArrayUtils.isEmpty(pkg.libraryNames)) {
10582                    throw new PackageManagerException(
10583                            "Packages declaring static-shared libs cannot declare dynamic libs");
10584                }
10585
10586                // Package declaring static a shared lib cannot declare shared users
10587                if (pkg.mSharedUserId != null) {
10588                    throw new PackageManagerException(
10589                            "Packages declaring static-shared libs cannot declare shared users");
10590                }
10591
10592                // Static shared libs cannot declare activities
10593                if (!pkg.activities.isEmpty()) {
10594                    throw new PackageManagerException(
10595                            "Static shared libs cannot declare activities");
10596                }
10597
10598                // Static shared libs cannot declare services
10599                if (!pkg.services.isEmpty()) {
10600                    throw new PackageManagerException(
10601                            "Static shared libs cannot declare services");
10602                }
10603
10604                // Static shared libs cannot declare providers
10605                if (!pkg.providers.isEmpty()) {
10606                    throw new PackageManagerException(
10607                            "Static shared libs cannot declare content providers");
10608                }
10609
10610                // Static shared libs cannot declare receivers
10611                if (!pkg.receivers.isEmpty()) {
10612                    throw new PackageManagerException(
10613                            "Static shared libs cannot declare broadcast receivers");
10614                }
10615
10616                // Static shared libs cannot declare permission groups
10617                if (!pkg.permissionGroups.isEmpty()) {
10618                    throw new PackageManagerException(
10619                            "Static shared libs cannot declare permission groups");
10620                }
10621
10622                // Static shared libs cannot declare permissions
10623                if (!pkg.permissions.isEmpty()) {
10624                    throw new PackageManagerException(
10625                            "Static shared libs cannot declare permissions");
10626                }
10627
10628                // Static shared libs cannot declare protected broadcasts
10629                if (pkg.protectedBroadcasts != null) {
10630                    throw new PackageManagerException(
10631                            "Static shared libs cannot declare protected broadcasts");
10632                }
10633
10634                // Static shared libs cannot be overlay targets
10635                if (pkg.mOverlayTarget != null) {
10636                    throw new PackageManagerException(
10637                            "Static shared libs cannot be overlay targets");
10638                }
10639
10640                // The version codes must be ordered as lib versions
10641                int minVersionCode = Integer.MIN_VALUE;
10642                int maxVersionCode = Integer.MAX_VALUE;
10643
10644                SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(
10645                        pkg.staticSharedLibName);
10646                if (versionedLib != null) {
10647                    final int versionCount = versionedLib.size();
10648                    for (int i = 0; i < versionCount; i++) {
10649                        SharedLibraryInfo libInfo = versionedLib.valueAt(i).info;
10650                        // TODO: We will change version code to long, so in the new API it is long
10651                        final int libVersionCode = (int) libInfo.getDeclaringPackage()
10652                                .getVersionCode();
10653                        if (libInfo.getVersion() <  pkg.staticSharedLibVersion) {
10654                            minVersionCode = Math.max(minVersionCode, libVersionCode + 1);
10655                        } else if (libInfo.getVersion() >  pkg.staticSharedLibVersion) {
10656                            maxVersionCode = Math.min(maxVersionCode, libVersionCode - 1);
10657                        } else {
10658                            minVersionCode = maxVersionCode = libVersionCode;
10659                            break;
10660                        }
10661                    }
10662                }
10663                if (pkg.mVersionCode < minVersionCode || pkg.mVersionCode > maxVersionCode) {
10664                    throw new PackageManagerException("Static shared"
10665                            + " lib version codes must be ordered as lib versions");
10666                }
10667            }
10668
10669            // Only privileged apps and updated privileged apps can add child packages.
10670            if (pkg.childPackages != null && !pkg.childPackages.isEmpty()) {
10671                if ((policyFlags & PARSE_IS_PRIVILEGED) == 0) {
10672                    throw new PackageManagerException("Only privileged apps can add child "
10673                            + "packages. Ignoring package " + pkg.packageName);
10674                }
10675                final int childCount = pkg.childPackages.size();
10676                for (int i = 0; i < childCount; i++) {
10677                    PackageParser.Package childPkg = pkg.childPackages.get(i);
10678                    if (mSettings.hasOtherDisabledSystemPkgWithChildLPr(pkg.packageName,
10679                            childPkg.packageName)) {
10680                        throw new PackageManagerException("Can't override child of "
10681                                + "another disabled app. Ignoring package " + pkg.packageName);
10682                    }
10683                }
10684            }
10685
10686            // If we're only installing presumed-existing packages, require that the
10687            // scanned APK is both already known and at the path previously established
10688            // for it.  Previously unknown packages we pick up normally, but if we have an
10689            // a priori expectation about this package's install presence, enforce it.
10690            // With a singular exception for new system packages. When an OTA contains
10691            // a new system package, we allow the codepath to change from a system location
10692            // to the user-installed location. If we don't allow this change, any newer,
10693            // user-installed version of the application will be ignored.
10694            if ((scanFlags & SCAN_REQUIRE_KNOWN) != 0) {
10695                if (mExpectingBetter.containsKey(pkg.packageName)) {
10696                    logCriticalInfo(Log.WARN,
10697                            "Relax SCAN_REQUIRE_KNOWN requirement for package " + pkg.packageName);
10698                } else {
10699                    PackageSetting known = mSettings.getPackageLPr(pkg.packageName);
10700                    if (known != null) {
10701                        if (DEBUG_PACKAGE_SCANNING) {
10702                            Log.d(TAG, "Examining " + pkg.codePath
10703                                    + " and requiring known paths " + known.codePathString
10704                                    + " & " + known.resourcePathString);
10705                        }
10706                        if (!pkg.applicationInfo.getCodePath().equals(known.codePathString)
10707                                || !pkg.applicationInfo.getResourcePath().equals(
10708                                        known.resourcePathString)) {
10709                            throw new PackageManagerException(INSTALL_FAILED_PACKAGE_CHANGED,
10710                                    "Application package " + pkg.packageName
10711                                    + " found at " + pkg.applicationInfo.getCodePath()
10712                                    + " but expected at " + known.codePathString
10713                                    + "; ignoring.");
10714                        }
10715                    }
10716                }
10717            }
10718
10719            // Verify that this new package doesn't have any content providers
10720            // that conflict with existing packages.  Only do this if the
10721            // package isn't already installed, since we don't want to break
10722            // things that are installed.
10723            if ((scanFlags & SCAN_NEW_INSTALL) != 0) {
10724                final int N = pkg.providers.size();
10725                int i;
10726                for (i=0; i<N; i++) {
10727                    PackageParser.Provider p = pkg.providers.get(i);
10728                    if (p.info.authority != null) {
10729                        String names[] = p.info.authority.split(";");
10730                        for (int j = 0; j < names.length; j++) {
10731                            if (mProvidersByAuthority.containsKey(names[j])) {
10732                                PackageParser.Provider other = mProvidersByAuthority.get(names[j]);
10733                                final String otherPackageName =
10734                                        ((other != null && other.getComponentName() != null) ?
10735                                                other.getComponentName().getPackageName() : "?");
10736                                throw new PackageManagerException(
10737                                        INSTALL_FAILED_CONFLICTING_PROVIDER,
10738                                        "Can't install because provider name " + names[j]
10739                                                + " (in package " + pkg.applicationInfo.packageName
10740                                                + ") is already used by " + otherPackageName);
10741                            }
10742                        }
10743                    }
10744                }
10745            }
10746        }
10747    }
10748
10749    private boolean addSharedLibraryLPw(String path, String apk, String name, int version,
10750            int type, String declaringPackageName, int declaringVersionCode) {
10751        SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(name);
10752        if (versionedLib == null) {
10753            versionedLib = new SparseArray<>();
10754            mSharedLibraries.put(name, versionedLib);
10755            if (type == SharedLibraryInfo.TYPE_STATIC) {
10756                mStaticLibsByDeclaringPackage.put(declaringPackageName, versionedLib);
10757            }
10758        } else if (versionedLib.indexOfKey(version) >= 0) {
10759            return false;
10760        }
10761        SharedLibraryEntry libEntry = new SharedLibraryEntry(path, apk, name,
10762                version, type, declaringPackageName, declaringVersionCode);
10763        versionedLib.put(version, libEntry);
10764        return true;
10765    }
10766
10767    private boolean removeSharedLibraryLPw(String name, int version) {
10768        SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(name);
10769        if (versionedLib == null) {
10770            return false;
10771        }
10772        final int libIdx = versionedLib.indexOfKey(version);
10773        if (libIdx < 0) {
10774            return false;
10775        }
10776        SharedLibraryEntry libEntry = versionedLib.valueAt(libIdx);
10777        versionedLib.remove(version);
10778        if (versionedLib.size() <= 0) {
10779            mSharedLibraries.remove(name);
10780            if (libEntry.info.getType() == SharedLibraryInfo.TYPE_STATIC) {
10781                mStaticLibsByDeclaringPackage.remove(libEntry.info.getDeclaringPackage()
10782                        .getPackageName());
10783            }
10784        }
10785        return true;
10786    }
10787
10788    /**
10789     * Adds a scanned package to the system. When this method is finished, the package will
10790     * be available for query, resolution, etc...
10791     */
10792    private void commitPackageSettings(PackageParser.Package pkg, PackageSetting pkgSetting,
10793            UserHandle user, int scanFlags, boolean chatty) throws PackageManagerException {
10794        final String pkgName = pkg.packageName;
10795        if (mCustomResolverComponentName != null &&
10796                mCustomResolverComponentName.getPackageName().equals(pkg.packageName)) {
10797            setUpCustomResolverActivity(pkg);
10798        }
10799
10800        if (pkg.packageName.equals("android")) {
10801            synchronized (mPackages) {
10802                if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
10803                    // Set up information for our fall-back user intent resolution activity.
10804                    mPlatformPackage = pkg;
10805                    pkg.mVersionCode = mSdkVersion;
10806                    mAndroidApplication = pkg.applicationInfo;
10807                    if (!mResolverReplaced) {
10808                        mResolveActivity.applicationInfo = mAndroidApplication;
10809                        mResolveActivity.name = ResolverActivity.class.getName();
10810                        mResolveActivity.packageName = mAndroidApplication.packageName;
10811                        mResolveActivity.processName = "system:ui";
10812                        mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
10813                        mResolveActivity.documentLaunchMode = ActivityInfo.DOCUMENT_LAUNCH_NEVER;
10814                        mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS;
10815                        mResolveActivity.theme = R.style.Theme_Material_Dialog_Alert;
10816                        mResolveActivity.exported = true;
10817                        mResolveActivity.enabled = true;
10818                        mResolveActivity.resizeMode = ActivityInfo.RESIZE_MODE_RESIZEABLE;
10819                        mResolveActivity.configChanges = ActivityInfo.CONFIG_SCREEN_SIZE
10820                                | ActivityInfo.CONFIG_SMALLEST_SCREEN_SIZE
10821                                | ActivityInfo.CONFIG_SCREEN_LAYOUT
10822                                | ActivityInfo.CONFIG_ORIENTATION
10823                                | ActivityInfo.CONFIG_KEYBOARD
10824                                | ActivityInfo.CONFIG_KEYBOARD_HIDDEN;
10825                        mResolveInfo.activityInfo = mResolveActivity;
10826                        mResolveInfo.priority = 0;
10827                        mResolveInfo.preferredOrder = 0;
10828                        mResolveInfo.match = 0;
10829                        mResolveComponentName = new ComponentName(
10830                                mAndroidApplication.packageName, mResolveActivity.name);
10831                    }
10832                }
10833            }
10834        }
10835
10836        ArrayList<PackageParser.Package> clientLibPkgs = null;
10837        // writer
10838        synchronized (mPackages) {
10839            boolean hasStaticSharedLibs = false;
10840
10841            // Any app can add new static shared libraries
10842            if (pkg.staticSharedLibName != null) {
10843                // Static shared libs don't allow renaming as they have synthetic package
10844                // names to allow install of multiple versions, so use name from manifest.
10845                if (addSharedLibraryLPw(null, pkg.packageName, pkg.staticSharedLibName,
10846                        pkg.staticSharedLibVersion, SharedLibraryInfo.TYPE_STATIC,
10847                        pkg.manifestPackageName, pkg.mVersionCode)) {
10848                    hasStaticSharedLibs = true;
10849                } else {
10850                    Slog.w(TAG, "Package " + pkg.packageName + " library "
10851                                + pkg.staticSharedLibName + " already exists; skipping");
10852                }
10853                // Static shared libs cannot be updated once installed since they
10854                // use synthetic package name which includes the version code, so
10855                // not need to update other packages's shared lib dependencies.
10856            }
10857
10858            if (!hasStaticSharedLibs
10859                    && (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
10860                // Only system apps can add new dynamic shared libraries.
10861                if (pkg.libraryNames != null) {
10862                    for (int i = 0; i < pkg.libraryNames.size(); i++) {
10863                        String name = pkg.libraryNames.get(i);
10864                        boolean allowed = false;
10865                        if (pkg.isUpdatedSystemApp()) {
10866                            // New library entries can only be added through the
10867                            // system image.  This is important to get rid of a lot
10868                            // of nasty edge cases: for example if we allowed a non-
10869                            // system update of the app to add a library, then uninstalling
10870                            // the update would make the library go away, and assumptions
10871                            // we made such as through app install filtering would now
10872                            // have allowed apps on the device which aren't compatible
10873                            // with it.  Better to just have the restriction here, be
10874                            // conservative, and create many fewer cases that can negatively
10875                            // impact the user experience.
10876                            final PackageSetting sysPs = mSettings
10877                                    .getDisabledSystemPkgLPr(pkg.packageName);
10878                            if (sysPs.pkg != null && sysPs.pkg.libraryNames != null) {
10879                                for (int j = 0; j < sysPs.pkg.libraryNames.size(); j++) {
10880                                    if (name.equals(sysPs.pkg.libraryNames.get(j))) {
10881                                        allowed = true;
10882                                        break;
10883                                    }
10884                                }
10885                            }
10886                        } else {
10887                            allowed = true;
10888                        }
10889                        if (allowed) {
10890                            if (!addSharedLibraryLPw(null, pkg.packageName, name,
10891                                    SharedLibraryInfo.VERSION_UNDEFINED,
10892                                    SharedLibraryInfo.TYPE_DYNAMIC,
10893                                    pkg.packageName, pkg.mVersionCode)) {
10894                                Slog.w(TAG, "Package " + pkg.packageName + " library "
10895                                        + name + " already exists; skipping");
10896                            }
10897                        } else {
10898                            Slog.w(TAG, "Package " + pkg.packageName + " declares lib "
10899                                    + name + " that is not declared on system image; skipping");
10900                        }
10901                    }
10902
10903                    if ((scanFlags & SCAN_BOOTING) == 0) {
10904                        // If we are not booting, we need to update any applications
10905                        // that are clients of our shared library.  If we are booting,
10906                        // this will all be done once the scan is complete.
10907                        clientLibPkgs = updateAllSharedLibrariesLPw(pkg);
10908                    }
10909                }
10910            }
10911        }
10912
10913        if ((scanFlags & SCAN_BOOTING) != 0) {
10914            // No apps can run during boot scan, so they don't need to be frozen
10915        } else if ((scanFlags & SCAN_DONT_KILL_APP) != 0) {
10916            // Caller asked to not kill app, so it's probably not frozen
10917        } else if ((scanFlags & SCAN_IGNORE_FROZEN) != 0) {
10918            // Caller asked us to ignore frozen check for some reason; they
10919            // probably didn't know the package name
10920        } else {
10921            // We're doing major surgery on this package, so it better be frozen
10922            // right now to keep it from launching
10923            checkPackageFrozen(pkgName);
10924        }
10925
10926        // Also need to kill any apps that are dependent on the library.
10927        if (clientLibPkgs != null) {
10928            for (int i=0; i<clientLibPkgs.size(); i++) {
10929                PackageParser.Package clientPkg = clientLibPkgs.get(i);
10930                killApplication(clientPkg.applicationInfo.packageName,
10931                        clientPkg.applicationInfo.uid, "update lib");
10932            }
10933        }
10934
10935        // writer
10936        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings");
10937
10938        synchronized (mPackages) {
10939            // We don't expect installation to fail beyond this point
10940
10941            // Add the new setting to mSettings
10942            mSettings.insertPackageSettingLPw(pkgSetting, pkg);
10943            // Add the new setting to mPackages
10944            mPackages.put(pkg.applicationInfo.packageName, pkg);
10945            // Make sure we don't accidentally delete its data.
10946            final Iterator<PackageCleanItem> iter = mSettings.mPackagesToBeCleaned.iterator();
10947            while (iter.hasNext()) {
10948                PackageCleanItem item = iter.next();
10949                if (pkgName.equals(item.packageName)) {
10950                    iter.remove();
10951                }
10952            }
10953
10954            // Add the package's KeySets to the global KeySetManagerService
10955            KeySetManagerService ksms = mSettings.mKeySetManagerService;
10956            ksms.addScannedPackageLPw(pkg);
10957
10958            int N = pkg.providers.size();
10959            StringBuilder r = null;
10960            int i;
10961            for (i=0; i<N; i++) {
10962                PackageParser.Provider p = pkg.providers.get(i);
10963                p.info.processName = fixProcessName(pkg.applicationInfo.processName,
10964                        p.info.processName);
10965                mProviders.addProvider(p);
10966                p.syncable = p.info.isSyncable;
10967                if (p.info.authority != null) {
10968                    String names[] = p.info.authority.split(";");
10969                    p.info.authority = null;
10970                    for (int j = 0; j < names.length; j++) {
10971                        if (j == 1 && p.syncable) {
10972                            // We only want the first authority for a provider to possibly be
10973                            // syncable, so if we already added this provider using a different
10974                            // authority clear the syncable flag. We copy the provider before
10975                            // changing it because the mProviders object contains a reference
10976                            // to a provider that we don't want to change.
10977                            // Only do this for the second authority since the resulting provider
10978                            // object can be the same for all future authorities for this provider.
10979                            p = new PackageParser.Provider(p);
10980                            p.syncable = false;
10981                        }
10982                        if (!mProvidersByAuthority.containsKey(names[j])) {
10983                            mProvidersByAuthority.put(names[j], p);
10984                            if (p.info.authority == null) {
10985                                p.info.authority = names[j];
10986                            } else {
10987                                p.info.authority = p.info.authority + ";" + names[j];
10988                            }
10989                            if (DEBUG_PACKAGE_SCANNING) {
10990                                if (chatty)
10991                                    Log.d(TAG, "Registered content provider: " + names[j]
10992                                            + ", className = " + p.info.name + ", isSyncable = "
10993                                            + p.info.isSyncable);
10994                            }
10995                        } else {
10996                            PackageParser.Provider other = mProvidersByAuthority.get(names[j]);
10997                            Slog.w(TAG, "Skipping provider name " + names[j] +
10998                                    " (in package " + pkg.applicationInfo.packageName +
10999                                    "): name already used by "
11000                                    + ((other != null && other.getComponentName() != null)
11001                                            ? other.getComponentName().getPackageName() : "?"));
11002                        }
11003                    }
11004                }
11005                if (chatty) {
11006                    if (r == null) {
11007                        r = new StringBuilder(256);
11008                    } else {
11009                        r.append(' ');
11010                    }
11011                    r.append(p.info.name);
11012                }
11013            }
11014            if (r != null) {
11015                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Providers: " + r);
11016            }
11017
11018            N = pkg.services.size();
11019            r = null;
11020            for (i=0; i<N; i++) {
11021                PackageParser.Service s = pkg.services.get(i);
11022                s.info.processName = fixProcessName(pkg.applicationInfo.processName,
11023                        s.info.processName);
11024                mServices.addService(s);
11025                if (chatty) {
11026                    if (r == null) {
11027                        r = new StringBuilder(256);
11028                    } else {
11029                        r.append(' ');
11030                    }
11031                    r.append(s.info.name);
11032                }
11033            }
11034            if (r != null) {
11035                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Services: " + r);
11036            }
11037
11038            N = pkg.receivers.size();
11039            r = null;
11040            for (i=0; i<N; i++) {
11041                PackageParser.Activity a = pkg.receivers.get(i);
11042                a.info.processName = fixProcessName(pkg.applicationInfo.processName,
11043                        a.info.processName);
11044                mReceivers.addActivity(a, "receiver");
11045                if (chatty) {
11046                    if (r == null) {
11047                        r = new StringBuilder(256);
11048                    } else {
11049                        r.append(' ');
11050                    }
11051                    r.append(a.info.name);
11052                }
11053            }
11054            if (r != null) {
11055                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Receivers: " + r);
11056            }
11057
11058            N = pkg.activities.size();
11059            r = null;
11060            for (i=0; i<N; i++) {
11061                PackageParser.Activity a = pkg.activities.get(i);
11062                a.info.processName = fixProcessName(pkg.applicationInfo.processName,
11063                        a.info.processName);
11064                mActivities.addActivity(a, "activity");
11065                if (chatty) {
11066                    if (r == null) {
11067                        r = new StringBuilder(256);
11068                    } else {
11069                        r.append(' ');
11070                    }
11071                    r.append(a.info.name);
11072                }
11073            }
11074            if (r != null) {
11075                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Activities: " + r);
11076            }
11077
11078            N = pkg.permissionGroups.size();
11079            r = null;
11080            for (i=0; i<N; i++) {
11081                PackageParser.PermissionGroup pg = pkg.permissionGroups.get(i);
11082                PackageParser.PermissionGroup cur = mPermissionGroups.get(pg.info.name);
11083                final String curPackageName = cur == null ? null : cur.info.packageName;
11084                // Dont allow ephemeral apps to define new permission groups.
11085                if ((scanFlags & SCAN_AS_INSTANT_APP) != 0) {
11086                    Slog.w(TAG, "Permission group " + pg.info.name + " from package "
11087                            + pg.info.packageName
11088                            + " ignored: instant apps cannot define new permission groups.");
11089                    continue;
11090                }
11091                final boolean isPackageUpdate = pg.info.packageName.equals(curPackageName);
11092                if (cur == null || isPackageUpdate) {
11093                    mPermissionGroups.put(pg.info.name, pg);
11094                    if (chatty) {
11095                        if (r == null) {
11096                            r = new StringBuilder(256);
11097                        } else {
11098                            r.append(' ');
11099                        }
11100                        if (isPackageUpdate) {
11101                            r.append("UPD:");
11102                        }
11103                        r.append(pg.info.name);
11104                    }
11105                } else {
11106                    Slog.w(TAG, "Permission group " + pg.info.name + " from package "
11107                            + pg.info.packageName + " ignored: original from "
11108                            + cur.info.packageName);
11109                    if (chatty) {
11110                        if (r == null) {
11111                            r = new StringBuilder(256);
11112                        } else {
11113                            r.append(' ');
11114                        }
11115                        r.append("DUP:");
11116                        r.append(pg.info.name);
11117                    }
11118                }
11119            }
11120            if (r != null) {
11121                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Permission Groups: " + r);
11122            }
11123
11124            N = pkg.permissions.size();
11125            r = null;
11126            for (i=0; i<N; i++) {
11127                PackageParser.Permission p = pkg.permissions.get(i);
11128
11129                // Dont allow ephemeral apps to define new permissions.
11130                if ((scanFlags & SCAN_AS_INSTANT_APP) != 0) {
11131                    Slog.w(TAG, "Permission " + p.info.name + " from package "
11132                            + p.info.packageName
11133                            + " ignored: instant apps cannot define new permissions.");
11134                    continue;
11135                }
11136
11137                // Assume by default that we did not install this permission into the system.
11138                p.info.flags &= ~PermissionInfo.FLAG_INSTALLED;
11139
11140                // Now that permission groups have a special meaning, we ignore permission
11141                // groups for legacy apps to prevent unexpected behavior. In particular,
11142                // permissions for one app being granted to someone just because they happen
11143                // to be in a group defined by another app (before this had no implications).
11144                if (pkg.applicationInfo.targetSdkVersion > Build.VERSION_CODES.LOLLIPOP_MR1) {
11145                    p.group = mPermissionGroups.get(p.info.group);
11146                    // Warn for a permission in an unknown group.
11147                    if (DEBUG_PERMISSIONS && p.info.group != null && p.group == null) {
11148                        Slog.i(TAG, "Permission " + p.info.name + " from package "
11149                                + p.info.packageName + " in an unknown group " + p.info.group);
11150                    }
11151                }
11152
11153                ArrayMap<String, BasePermission> permissionMap =
11154                        p.tree ? mSettings.mPermissionTrees
11155                                : mSettings.mPermissions;
11156                BasePermission bp = permissionMap.get(p.info.name);
11157
11158                // Allow system apps to redefine non-system permissions
11159                if (bp != null && !Objects.equals(bp.sourcePackage, p.info.packageName)) {
11160                    final boolean currentOwnerIsSystem = (bp.perm != null
11161                            && isSystemApp(bp.perm.owner));
11162                    if (isSystemApp(p.owner)) {
11163                        if (bp.type == BasePermission.TYPE_BUILTIN && bp.perm == null) {
11164                            // It's a built-in permission and no owner, take ownership now
11165                            bp.packageSetting = pkgSetting;
11166                            bp.perm = p;
11167                            bp.uid = pkg.applicationInfo.uid;
11168                            bp.sourcePackage = p.info.packageName;
11169                            p.info.flags |= PermissionInfo.FLAG_INSTALLED;
11170                        } else if (!currentOwnerIsSystem) {
11171                            String msg = "New decl " + p.owner + " of permission  "
11172                                    + p.info.name + " is system; overriding " + bp.sourcePackage;
11173                            reportSettingsProblem(Log.WARN, msg);
11174                            bp = null;
11175                        }
11176                    }
11177                }
11178
11179                if (bp == null) {
11180                    bp = new BasePermission(p.info.name, p.info.packageName,
11181                            BasePermission.TYPE_NORMAL);
11182                    permissionMap.put(p.info.name, bp);
11183                }
11184
11185                if (bp.perm == null) {
11186                    if (bp.sourcePackage == null
11187                            || bp.sourcePackage.equals(p.info.packageName)) {
11188                        BasePermission tree = findPermissionTreeLP(p.info.name);
11189                        if (tree == null
11190                                || tree.sourcePackage.equals(p.info.packageName)) {
11191                            bp.packageSetting = pkgSetting;
11192                            bp.perm = p;
11193                            bp.uid = pkg.applicationInfo.uid;
11194                            bp.sourcePackage = p.info.packageName;
11195                            p.info.flags |= PermissionInfo.FLAG_INSTALLED;
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                        } else {
11205                            Slog.w(TAG, "Permission " + p.info.name + " from package "
11206                                    + p.info.packageName + " ignored: base tree "
11207                                    + tree.name + " is from package "
11208                                    + tree.sourcePackage);
11209                        }
11210                    } else {
11211                        Slog.w(TAG, "Permission " + p.info.name + " from package "
11212                                + p.info.packageName + " ignored: original from "
11213                                + bp.sourcePackage);
11214                    }
11215                } else if (chatty) {
11216                    if (r == null) {
11217                        r = new StringBuilder(256);
11218                    } else {
11219                        r.append(' ');
11220                    }
11221                    r.append("DUP:");
11222                    r.append(p.info.name);
11223                }
11224                if (bp.perm == p) {
11225                    bp.protectionLevel = p.info.protectionLevel;
11226                }
11227            }
11228
11229            if (r != null) {
11230                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Permissions: " + r);
11231            }
11232
11233            N = pkg.instrumentation.size();
11234            r = null;
11235            for (i=0; i<N; i++) {
11236                PackageParser.Instrumentation a = pkg.instrumentation.get(i);
11237                a.info.packageName = pkg.applicationInfo.packageName;
11238                a.info.sourceDir = pkg.applicationInfo.sourceDir;
11239                a.info.publicSourceDir = pkg.applicationInfo.publicSourceDir;
11240                a.info.splitNames = pkg.splitNames;
11241                a.info.splitSourceDirs = pkg.applicationInfo.splitSourceDirs;
11242                a.info.splitPublicSourceDirs = pkg.applicationInfo.splitPublicSourceDirs;
11243                a.info.splitDependencies = pkg.applicationInfo.splitDependencies;
11244                a.info.dataDir = pkg.applicationInfo.dataDir;
11245                a.info.deviceProtectedDataDir = pkg.applicationInfo.deviceProtectedDataDir;
11246                a.info.credentialProtectedDataDir = pkg.applicationInfo.credentialProtectedDataDir;
11247                a.info.nativeLibraryDir = pkg.applicationInfo.nativeLibraryDir;
11248                a.info.secondaryNativeLibraryDir = pkg.applicationInfo.secondaryNativeLibraryDir;
11249                mInstrumentation.put(a.getComponentName(), a);
11250                if (chatty) {
11251                    if (r == null) {
11252                        r = new StringBuilder(256);
11253                    } else {
11254                        r.append(' ');
11255                    }
11256                    r.append(a.info.name);
11257                }
11258            }
11259            if (r != null) {
11260                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Instrumentation: " + r);
11261            }
11262
11263            if (pkg.protectedBroadcasts != null) {
11264                N = pkg.protectedBroadcasts.size();
11265                for (i=0; i<N; i++) {
11266                    mProtectedBroadcasts.add(pkg.protectedBroadcasts.get(i));
11267                }
11268            }
11269        }
11270
11271        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
11272    }
11273
11274    /**
11275     * Derive the ABI of a non-system package located at {@code scanFile}. This information
11276     * is derived purely on the basis of the contents of {@code scanFile} and
11277     * {@code cpuAbiOverride}.
11278     *
11279     * If {@code extractLibs} is true, native libraries are extracted from the app if required.
11280     */
11281    private static void derivePackageAbi(PackageParser.Package pkg, File scanFile,
11282                                 String cpuAbiOverride, boolean extractLibs,
11283                                 File appLib32InstallDir)
11284            throws PackageManagerException {
11285        // Give ourselves some initial paths; we'll come back for another
11286        // pass once we've determined ABI below.
11287        setNativeLibraryPaths(pkg, appLib32InstallDir);
11288
11289        // We would never need to extract libs for forward-locked and external packages,
11290        // since the container service will do it for us. We shouldn't attempt to
11291        // extract libs from system app when it was not updated.
11292        if (pkg.isForwardLocked() || pkg.applicationInfo.isExternalAsec() ||
11293                (isSystemApp(pkg) && !pkg.isUpdatedSystemApp())) {
11294            extractLibs = false;
11295        }
11296
11297        final String nativeLibraryRootStr = pkg.applicationInfo.nativeLibraryRootDir;
11298        final boolean useIsaSpecificSubdirs = pkg.applicationInfo.nativeLibraryRootRequiresIsa;
11299
11300        NativeLibraryHelper.Handle handle = null;
11301        try {
11302            handle = NativeLibraryHelper.Handle.create(pkg);
11303            // TODO(multiArch): This can be null for apps that didn't go through the
11304            // usual installation process. We can calculate it again, like we
11305            // do during install time.
11306            //
11307            // TODO(multiArch): Why do we need to rescan ASEC apps again ? It seems totally
11308            // unnecessary.
11309            final File nativeLibraryRoot = new File(nativeLibraryRootStr);
11310
11311            // Null out the abis so that they can be recalculated.
11312            pkg.applicationInfo.primaryCpuAbi = null;
11313            pkg.applicationInfo.secondaryCpuAbi = null;
11314            if (isMultiArch(pkg.applicationInfo)) {
11315                // Warn if we've set an abiOverride for multi-lib packages..
11316                // By definition, we need to copy both 32 and 64 bit libraries for
11317                // such packages.
11318                if (pkg.cpuAbiOverride != null
11319                        && !NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(pkg.cpuAbiOverride)) {
11320                    Slog.w(TAG, "Ignoring abiOverride for multi arch application.");
11321                }
11322
11323                int abi32 = PackageManager.NO_NATIVE_LIBRARIES;
11324                int abi64 = PackageManager.NO_NATIVE_LIBRARIES;
11325                if (Build.SUPPORTED_32_BIT_ABIS.length > 0) {
11326                    if (extractLibs) {
11327                        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyNativeBinaries");
11328                        abi32 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
11329                                nativeLibraryRoot, Build.SUPPORTED_32_BIT_ABIS,
11330                                useIsaSpecificSubdirs);
11331                    } else {
11332                        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "findSupportedAbi");
11333                        abi32 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_32_BIT_ABIS);
11334                    }
11335                    Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
11336                }
11337
11338                maybeThrowExceptionForMultiArchCopy(
11339                        "Error unpackaging 32 bit native libs for multiarch app.", abi32);
11340
11341                if (Build.SUPPORTED_64_BIT_ABIS.length > 0) {
11342                    if (extractLibs) {
11343                        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyNativeBinaries");
11344                        abi64 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
11345                                nativeLibraryRoot, Build.SUPPORTED_64_BIT_ABIS,
11346                                useIsaSpecificSubdirs);
11347                    } else {
11348                        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "findSupportedAbi");
11349                        abi64 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_64_BIT_ABIS);
11350                    }
11351                    Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
11352                }
11353
11354                maybeThrowExceptionForMultiArchCopy(
11355                        "Error unpackaging 64 bit native libs for multiarch app.", abi64);
11356
11357                if (abi64 >= 0) {
11358                    pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[abi64];
11359                }
11360
11361                if (abi32 >= 0) {
11362                    final String abi = Build.SUPPORTED_32_BIT_ABIS[abi32];
11363                    if (abi64 >= 0) {
11364                        if (pkg.use32bitAbi) {
11365                            pkg.applicationInfo.secondaryCpuAbi = pkg.applicationInfo.primaryCpuAbi;
11366                            pkg.applicationInfo.primaryCpuAbi = abi;
11367                        } else {
11368                            pkg.applicationInfo.secondaryCpuAbi = abi;
11369                        }
11370                    } else {
11371                        pkg.applicationInfo.primaryCpuAbi = abi;
11372                    }
11373                }
11374
11375            } else {
11376                String[] abiList = (cpuAbiOverride != null) ?
11377                        new String[] { cpuAbiOverride } : Build.SUPPORTED_ABIS;
11378
11379                // Enable gross and lame hacks for apps that are built with old
11380                // SDK tools. We must scan their APKs for renderscript bitcode and
11381                // not launch them if it's present. Don't bother checking on devices
11382                // that don't have 64 bit support.
11383                boolean needsRenderScriptOverride = false;
11384                if (Build.SUPPORTED_64_BIT_ABIS.length > 0 && cpuAbiOverride == null &&
11385                        NativeLibraryHelper.hasRenderscriptBitcode(handle)) {
11386                    abiList = Build.SUPPORTED_32_BIT_ABIS;
11387                    needsRenderScriptOverride = true;
11388                }
11389
11390                final int copyRet;
11391                if (extractLibs) {
11392                    Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyNativeBinaries");
11393                    copyRet = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
11394                            nativeLibraryRoot, abiList, useIsaSpecificSubdirs);
11395                } else {
11396                    Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "findSupportedAbi");
11397                    copyRet = NativeLibraryHelper.findSupportedAbi(handle, abiList);
11398                }
11399                Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
11400
11401                if (copyRet < 0 && copyRet != PackageManager.NO_NATIVE_LIBRARIES) {
11402                    throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR,
11403                            "Error unpackaging native libs for app, errorCode=" + copyRet);
11404                }
11405
11406                if (copyRet >= 0) {
11407                    pkg.applicationInfo.primaryCpuAbi = abiList[copyRet];
11408                } else if (copyRet == PackageManager.NO_NATIVE_LIBRARIES && cpuAbiOverride != null) {
11409                    pkg.applicationInfo.primaryCpuAbi = cpuAbiOverride;
11410                } else if (needsRenderScriptOverride) {
11411                    pkg.applicationInfo.primaryCpuAbi = abiList[0];
11412                }
11413            }
11414        } catch (IOException ioe) {
11415            Slog.e(TAG, "Unable to get canonical file " + ioe.toString());
11416        } finally {
11417            IoUtils.closeQuietly(handle);
11418        }
11419
11420        // Now that we've calculated the ABIs and determined if it's an internal app,
11421        // we will go ahead and populate the nativeLibraryPath.
11422        setNativeLibraryPaths(pkg, appLib32InstallDir);
11423    }
11424
11425    /**
11426     * Adjusts ABIs for a set of packages belonging to a shared user so that they all match.
11427     * i.e, so that all packages can be run inside a single process if required.
11428     *
11429     * Optionally, callers can pass in a parsed package via {@code newPackage} in which case
11430     * this function will either try and make the ABI for all packages in {@code packagesForUser}
11431     * match {@code scannedPackage} or will update the ABI of {@code scannedPackage} to match
11432     * the ABI selected for {@code packagesForUser}. This variant is used when installing or
11433     * updating a package that belongs to a shared user.
11434     *
11435     * NOTE: We currently only match for the primary CPU abi string. Matching the secondary
11436     * adds unnecessary complexity.
11437     */
11438    private void adjustCpuAbisForSharedUserLPw(Set<PackageSetting> packagesForUser,
11439            PackageParser.Package scannedPackage) {
11440        String requiredInstructionSet = null;
11441        if (scannedPackage != null && scannedPackage.applicationInfo.primaryCpuAbi != null) {
11442            requiredInstructionSet = VMRuntime.getInstructionSet(
11443                     scannedPackage.applicationInfo.primaryCpuAbi);
11444        }
11445
11446        PackageSetting requirer = null;
11447        for (PackageSetting ps : packagesForUser) {
11448            // If packagesForUser contains scannedPackage, we skip it. This will happen
11449            // when scannedPackage is an update of an existing package. Without this check,
11450            // we will never be able to change the ABI of any package belonging to a shared
11451            // user, even if it's compatible with other packages.
11452            if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) {
11453                if (ps.primaryCpuAbiString == null) {
11454                    continue;
11455                }
11456
11457                final String instructionSet = VMRuntime.getInstructionSet(ps.primaryCpuAbiString);
11458                if (requiredInstructionSet != null && !instructionSet.equals(requiredInstructionSet)) {
11459                    // We have a mismatch between instruction sets (say arm vs arm64) warn about
11460                    // this but there's not much we can do.
11461                    String errorMessage = "Instruction set mismatch, "
11462                            + ((requirer == null) ? "[caller]" : requirer)
11463                            + " requires " + requiredInstructionSet + " whereas " + ps
11464                            + " requires " + instructionSet;
11465                    Slog.w(TAG, errorMessage);
11466                }
11467
11468                if (requiredInstructionSet == null) {
11469                    requiredInstructionSet = instructionSet;
11470                    requirer = ps;
11471                }
11472            }
11473        }
11474
11475        if (requiredInstructionSet != null) {
11476            String adjustedAbi;
11477            if (requirer != null) {
11478                // requirer != null implies that either scannedPackage was null or that scannedPackage
11479                // did not require an ABI, in which case we have to adjust scannedPackage to match
11480                // the ABI of the set (which is the same as requirer's ABI)
11481                adjustedAbi = requirer.primaryCpuAbiString;
11482                if (scannedPackage != null) {
11483                    scannedPackage.applicationInfo.primaryCpuAbi = adjustedAbi;
11484                }
11485            } else {
11486                // requirer == null implies that we're updating all ABIs in the set to
11487                // match scannedPackage.
11488                adjustedAbi =  scannedPackage.applicationInfo.primaryCpuAbi;
11489            }
11490
11491            for (PackageSetting ps : packagesForUser) {
11492                if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) {
11493                    if (ps.primaryCpuAbiString != null) {
11494                        continue;
11495                    }
11496
11497                    ps.primaryCpuAbiString = adjustedAbi;
11498                    if (ps.pkg != null && ps.pkg.applicationInfo != null &&
11499                            !TextUtils.equals(adjustedAbi, ps.pkg.applicationInfo.primaryCpuAbi)) {
11500                        ps.pkg.applicationInfo.primaryCpuAbi = adjustedAbi;
11501                        if (DEBUG_ABI_SELECTION) {
11502                            Slog.i(TAG, "Adjusting ABI for " + ps.name + " to " + adjustedAbi
11503                                    + " (requirer="
11504                                    + (requirer != null ? requirer.pkg : "null")
11505                                    + ", scannedPackage="
11506                                    + (scannedPackage != null ? scannedPackage : "null")
11507                                    + ")");
11508                        }
11509                        try {
11510                            mInstaller.rmdex(ps.codePathString,
11511                                    getDexCodeInstructionSet(getPreferredInstructionSet()));
11512                        } catch (InstallerException ignored) {
11513                        }
11514                    }
11515                }
11516            }
11517        }
11518    }
11519
11520    private void setUpCustomResolverActivity(PackageParser.Package pkg) {
11521        synchronized (mPackages) {
11522            mResolverReplaced = true;
11523            // Set up information for custom user intent resolution activity.
11524            mResolveActivity.applicationInfo = pkg.applicationInfo;
11525            mResolveActivity.name = mCustomResolverComponentName.getClassName();
11526            mResolveActivity.packageName = pkg.applicationInfo.packageName;
11527            mResolveActivity.processName = pkg.applicationInfo.packageName;
11528            mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
11529            mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS |
11530                    ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS;
11531            mResolveActivity.theme = 0;
11532            mResolveActivity.exported = true;
11533            mResolveActivity.enabled = true;
11534            mResolveInfo.activityInfo = mResolveActivity;
11535            mResolveInfo.priority = 0;
11536            mResolveInfo.preferredOrder = 0;
11537            mResolveInfo.match = 0;
11538            mResolveComponentName = mCustomResolverComponentName;
11539            Slog.i(TAG, "Replacing default ResolverActivity with custom activity: " +
11540                    mResolveComponentName);
11541        }
11542    }
11543
11544    private void setUpInstantAppInstallerActivityLP(ActivityInfo installerActivity) {
11545        if (installerActivity == null) {
11546            if (DEBUG_EPHEMERAL) {
11547                Slog.d(TAG, "Clear ephemeral installer activity");
11548            }
11549            mInstantAppInstallerActivity = null;
11550            return;
11551        }
11552
11553        if (DEBUG_EPHEMERAL) {
11554            Slog.d(TAG, "Set ephemeral installer activity: "
11555                    + installerActivity.getComponentName());
11556        }
11557        // Set up information for ephemeral installer activity
11558        mInstantAppInstallerActivity = installerActivity;
11559        mInstantAppInstallerActivity.flags |= ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS
11560                | ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS;
11561        mInstantAppInstallerActivity.exported = true;
11562        mInstantAppInstallerActivity.enabled = true;
11563        mInstantAppInstallerInfo.activityInfo = mInstantAppInstallerActivity;
11564        mInstantAppInstallerInfo.priority = 0;
11565        mInstantAppInstallerInfo.preferredOrder = 1;
11566        mInstantAppInstallerInfo.isDefault = true;
11567        mInstantAppInstallerInfo.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART
11568                | IntentFilter.MATCH_ADJUSTMENT_NORMAL;
11569    }
11570
11571    private static String calculateBundledApkRoot(final String codePathString) {
11572        final File codePath = new File(codePathString);
11573        final File codeRoot;
11574        if (FileUtils.contains(Environment.getRootDirectory(), codePath)) {
11575            codeRoot = Environment.getRootDirectory();
11576        } else if (FileUtils.contains(Environment.getOemDirectory(), codePath)) {
11577            codeRoot = Environment.getOemDirectory();
11578        } else if (FileUtils.contains(Environment.getVendorDirectory(), codePath)) {
11579            codeRoot = Environment.getVendorDirectory();
11580        } else {
11581            // Unrecognized code path; take its top real segment as the apk root:
11582            // e.g. /something/app/blah.apk => /something
11583            try {
11584                File f = codePath.getCanonicalFile();
11585                File parent = f.getParentFile();    // non-null because codePath is a file
11586                File tmp;
11587                while ((tmp = parent.getParentFile()) != null) {
11588                    f = parent;
11589                    parent = tmp;
11590                }
11591                codeRoot = f;
11592                Slog.w(TAG, "Unrecognized code path "
11593                        + codePath + " - using " + codeRoot);
11594            } catch (IOException e) {
11595                // Can't canonicalize the code path -- shenanigans?
11596                Slog.w(TAG, "Can't canonicalize code path " + codePath);
11597                return Environment.getRootDirectory().getPath();
11598            }
11599        }
11600        return codeRoot.getPath();
11601    }
11602
11603    /**
11604     * Derive and set the location of native libraries for the given package,
11605     * which varies depending on where and how the package was installed.
11606     */
11607    private static void setNativeLibraryPaths(PackageParser.Package pkg, File appLib32InstallDir) {
11608        final ApplicationInfo info = pkg.applicationInfo;
11609        final String codePath = pkg.codePath;
11610        final File codeFile = new File(codePath);
11611        final boolean bundledApp = info.isSystemApp() && !info.isUpdatedSystemApp();
11612        final boolean asecApp = info.isForwardLocked() || info.isExternalAsec();
11613
11614        info.nativeLibraryRootDir = null;
11615        info.nativeLibraryRootRequiresIsa = false;
11616        info.nativeLibraryDir = null;
11617        info.secondaryNativeLibraryDir = null;
11618
11619        if (isApkFile(codeFile)) {
11620            // Monolithic install
11621            if (bundledApp) {
11622                // If "/system/lib64/apkname" exists, assume that is the per-package
11623                // native library directory to use; otherwise use "/system/lib/apkname".
11624                final String apkRoot = calculateBundledApkRoot(info.sourceDir);
11625                final boolean is64Bit = VMRuntime.is64BitInstructionSet(
11626                        getPrimaryInstructionSet(info));
11627
11628                // This is a bundled system app so choose the path based on the ABI.
11629                // if it's a 64 bit abi, use lib64 otherwise use lib32. Note that this
11630                // is just the default path.
11631                final String apkName = deriveCodePathName(codePath);
11632                final String libDir = is64Bit ? LIB64_DIR_NAME : LIB_DIR_NAME;
11633                info.nativeLibraryRootDir = Environment.buildPath(new File(apkRoot), libDir,
11634                        apkName).getAbsolutePath();
11635
11636                if (info.secondaryCpuAbi != null) {
11637                    final String secondaryLibDir = is64Bit ? LIB_DIR_NAME : LIB64_DIR_NAME;
11638                    info.secondaryNativeLibraryDir = Environment.buildPath(new File(apkRoot),
11639                            secondaryLibDir, apkName).getAbsolutePath();
11640                }
11641            } else if (asecApp) {
11642                info.nativeLibraryRootDir = new File(codeFile.getParentFile(), LIB_DIR_NAME)
11643                        .getAbsolutePath();
11644            } else {
11645                final String apkName = deriveCodePathName(codePath);
11646                info.nativeLibraryRootDir = new File(appLib32InstallDir, apkName)
11647                        .getAbsolutePath();
11648            }
11649
11650            info.nativeLibraryRootRequiresIsa = false;
11651            info.nativeLibraryDir = info.nativeLibraryRootDir;
11652        } else {
11653            // Cluster install
11654            info.nativeLibraryRootDir = new File(codeFile, LIB_DIR_NAME).getAbsolutePath();
11655            info.nativeLibraryRootRequiresIsa = true;
11656
11657            info.nativeLibraryDir = new File(info.nativeLibraryRootDir,
11658                    getPrimaryInstructionSet(info)).getAbsolutePath();
11659
11660            if (info.secondaryCpuAbi != null) {
11661                info.secondaryNativeLibraryDir = new File(info.nativeLibraryRootDir,
11662                        VMRuntime.getInstructionSet(info.secondaryCpuAbi)).getAbsolutePath();
11663            }
11664        }
11665    }
11666
11667    /**
11668     * Calculate the abis and roots for a bundled app. These can uniquely
11669     * be determined from the contents of the system partition, i.e whether
11670     * it contains 64 or 32 bit shared libraries etc. We do not validate any
11671     * of this information, and instead assume that the system was built
11672     * sensibly.
11673     */
11674    private static void setBundledAppAbisAndRoots(PackageParser.Package pkg,
11675                                           PackageSetting pkgSetting) {
11676        final String apkName = deriveCodePathName(pkg.applicationInfo.getCodePath());
11677
11678        // If "/system/lib64/apkname" exists, assume that is the per-package
11679        // native library directory to use; otherwise use "/system/lib/apkname".
11680        final String apkRoot = calculateBundledApkRoot(pkg.applicationInfo.sourceDir);
11681        setBundledAppAbi(pkg, apkRoot, apkName);
11682        // pkgSetting might be null during rescan following uninstall of updates
11683        // to a bundled app, so accommodate that possibility.  The settings in
11684        // that case will be established later from the parsed package.
11685        //
11686        // If the settings aren't null, sync them up with what we've just derived.
11687        // note that apkRoot isn't stored in the package settings.
11688        if (pkgSetting != null) {
11689            pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi;
11690            pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi;
11691        }
11692    }
11693
11694    /**
11695     * Deduces the ABI of a bundled app and sets the relevant fields on the
11696     * parsed pkg object.
11697     *
11698     * @param apkRoot the root of the installed apk, something like {@code /system} or {@code /oem}
11699     *        under which system libraries are installed.
11700     * @param apkName the name of the installed package.
11701     */
11702    private static void setBundledAppAbi(PackageParser.Package pkg, String apkRoot, String apkName) {
11703        final File codeFile = new File(pkg.codePath);
11704
11705        final boolean has64BitLibs;
11706        final boolean has32BitLibs;
11707        if (isApkFile(codeFile)) {
11708            // Monolithic install
11709            has64BitLibs = (new File(apkRoot, new File(LIB64_DIR_NAME, apkName).getPath())).exists();
11710            has32BitLibs = (new File(apkRoot, new File(LIB_DIR_NAME, apkName).getPath())).exists();
11711        } else {
11712            // Cluster install
11713            final File rootDir = new File(codeFile, LIB_DIR_NAME);
11714            if (!ArrayUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS)
11715                    && !TextUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS[0])) {
11716                final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_64_BIT_ABIS[0]);
11717                has64BitLibs = (new File(rootDir, isa)).exists();
11718            } else {
11719                has64BitLibs = false;
11720            }
11721            if (!ArrayUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS)
11722                    && !TextUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS[0])) {
11723                final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_32_BIT_ABIS[0]);
11724                has32BitLibs = (new File(rootDir, isa)).exists();
11725            } else {
11726                has32BitLibs = false;
11727            }
11728        }
11729
11730        if (has64BitLibs && !has32BitLibs) {
11731            // The package has 64 bit libs, but not 32 bit libs. Its primary
11732            // ABI should be 64 bit. We can safely assume here that the bundled
11733            // native libraries correspond to the most preferred ABI in the list.
11734
11735            pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
11736            pkg.applicationInfo.secondaryCpuAbi = null;
11737        } else if (has32BitLibs && !has64BitLibs) {
11738            // The package has 32 bit libs but not 64 bit libs. Its primary
11739            // ABI should be 32 bit.
11740
11741            pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
11742            pkg.applicationInfo.secondaryCpuAbi = null;
11743        } else if (has32BitLibs && has64BitLibs) {
11744            // The application has both 64 and 32 bit bundled libraries. We check
11745            // here that the app declares multiArch support, and warn if it doesn't.
11746            //
11747            // We will be lenient here and record both ABIs. The primary will be the
11748            // ABI that's higher on the list, i.e, a device that's configured to prefer
11749            // 64 bit apps will see a 64 bit primary ABI,
11750
11751            if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_MULTIARCH) == 0) {
11752                Slog.e(TAG, "Package " + pkg + " has multiple bundled libs, but is not multiarch.");
11753            }
11754
11755            if (VMRuntime.is64BitInstructionSet(getPreferredInstructionSet())) {
11756                pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
11757                pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
11758            } else {
11759                pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
11760                pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
11761            }
11762        } else {
11763            pkg.applicationInfo.primaryCpuAbi = null;
11764            pkg.applicationInfo.secondaryCpuAbi = null;
11765        }
11766    }
11767
11768    private void killApplication(String pkgName, int appId, String reason) {
11769        killApplication(pkgName, appId, UserHandle.USER_ALL, reason);
11770    }
11771
11772    private void killApplication(String pkgName, int appId, int userId, String reason) {
11773        // Request the ActivityManager to kill the process(only for existing packages)
11774        // so that we do not end up in a confused state while the user is still using the older
11775        // version of the application while the new one gets installed.
11776        final long token = Binder.clearCallingIdentity();
11777        try {
11778            IActivityManager am = ActivityManager.getService();
11779            if (am != null) {
11780                try {
11781                    am.killApplication(pkgName, appId, userId, reason);
11782                } catch (RemoteException e) {
11783                }
11784            }
11785        } finally {
11786            Binder.restoreCallingIdentity(token);
11787        }
11788    }
11789
11790    private void removePackageLI(PackageParser.Package pkg, boolean chatty) {
11791        // Remove the parent package setting
11792        PackageSetting ps = (PackageSetting) pkg.mExtras;
11793        if (ps != null) {
11794            removePackageLI(ps, chatty);
11795        }
11796        // Remove the child package setting
11797        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
11798        for (int i = 0; i < childCount; i++) {
11799            PackageParser.Package childPkg = pkg.childPackages.get(i);
11800            ps = (PackageSetting) childPkg.mExtras;
11801            if (ps != null) {
11802                removePackageLI(ps, chatty);
11803            }
11804        }
11805    }
11806
11807    void removePackageLI(PackageSetting ps, boolean chatty) {
11808        if (DEBUG_INSTALL) {
11809            if (chatty)
11810                Log.d(TAG, "Removing package " + ps.name);
11811        }
11812
11813        // writer
11814        synchronized (mPackages) {
11815            mPackages.remove(ps.name);
11816            final PackageParser.Package pkg = ps.pkg;
11817            if (pkg != null) {
11818                cleanPackageDataStructuresLILPw(pkg, chatty);
11819            }
11820        }
11821    }
11822
11823    void removeInstalledPackageLI(PackageParser.Package pkg, boolean chatty) {
11824        if (DEBUG_INSTALL) {
11825            if (chatty)
11826                Log.d(TAG, "Removing package " + pkg.applicationInfo.packageName);
11827        }
11828
11829        // writer
11830        synchronized (mPackages) {
11831            // Remove the parent package
11832            mPackages.remove(pkg.applicationInfo.packageName);
11833            cleanPackageDataStructuresLILPw(pkg, chatty);
11834
11835            // Remove the child packages
11836            final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
11837            for (int i = 0; i < childCount; i++) {
11838                PackageParser.Package childPkg = pkg.childPackages.get(i);
11839                mPackages.remove(childPkg.applicationInfo.packageName);
11840                cleanPackageDataStructuresLILPw(childPkg, chatty);
11841            }
11842        }
11843    }
11844
11845    void cleanPackageDataStructuresLILPw(PackageParser.Package pkg, boolean chatty) {
11846        int N = pkg.providers.size();
11847        StringBuilder r = null;
11848        int i;
11849        for (i=0; i<N; i++) {
11850            PackageParser.Provider p = pkg.providers.get(i);
11851            mProviders.removeProvider(p);
11852            if (p.info.authority == null) {
11853
11854                /* There was another ContentProvider with this authority when
11855                 * this app was installed so this authority is null,
11856                 * Ignore it as we don't have to unregister the provider.
11857                 */
11858                continue;
11859            }
11860            String names[] = p.info.authority.split(";");
11861            for (int j = 0; j < names.length; j++) {
11862                if (mProvidersByAuthority.get(names[j]) == p) {
11863                    mProvidersByAuthority.remove(names[j]);
11864                    if (DEBUG_REMOVE) {
11865                        if (chatty)
11866                            Log.d(TAG, "Unregistered content provider: " + names[j]
11867                                    + ", className = " + p.info.name + ", isSyncable = "
11868                                    + p.info.isSyncable);
11869                    }
11870                }
11871            }
11872            if (DEBUG_REMOVE && chatty) {
11873                if (r == null) {
11874                    r = new StringBuilder(256);
11875                } else {
11876                    r.append(' ');
11877                }
11878                r.append(p.info.name);
11879            }
11880        }
11881        if (r != null) {
11882            if (DEBUG_REMOVE) Log.d(TAG, "  Providers: " + r);
11883        }
11884
11885        N = pkg.services.size();
11886        r = null;
11887        for (i=0; i<N; i++) {
11888            PackageParser.Service s = pkg.services.get(i);
11889            mServices.removeService(s);
11890            if (chatty) {
11891                if (r == null) {
11892                    r = new StringBuilder(256);
11893                } else {
11894                    r.append(' ');
11895                }
11896                r.append(s.info.name);
11897            }
11898        }
11899        if (r != null) {
11900            if (DEBUG_REMOVE) Log.d(TAG, "  Services: " + r);
11901        }
11902
11903        N = pkg.receivers.size();
11904        r = null;
11905        for (i=0; i<N; i++) {
11906            PackageParser.Activity a = pkg.receivers.get(i);
11907            mReceivers.removeActivity(a, "receiver");
11908            if (DEBUG_REMOVE && chatty) {
11909                if (r == null) {
11910                    r = new StringBuilder(256);
11911                } else {
11912                    r.append(' ');
11913                }
11914                r.append(a.info.name);
11915            }
11916        }
11917        if (r != null) {
11918            if (DEBUG_REMOVE) Log.d(TAG, "  Receivers: " + r);
11919        }
11920
11921        N = pkg.activities.size();
11922        r = null;
11923        for (i=0; i<N; i++) {
11924            PackageParser.Activity a = pkg.activities.get(i);
11925            mActivities.removeActivity(a, "activity");
11926            if (DEBUG_REMOVE && chatty) {
11927                if (r == null) {
11928                    r = new StringBuilder(256);
11929                } else {
11930                    r.append(' ');
11931                }
11932                r.append(a.info.name);
11933            }
11934        }
11935        if (r != null) {
11936            if (DEBUG_REMOVE) Log.d(TAG, "  Activities: " + r);
11937        }
11938
11939        N = pkg.permissions.size();
11940        r = null;
11941        for (i=0; i<N; i++) {
11942            PackageParser.Permission p = pkg.permissions.get(i);
11943            BasePermission bp = mSettings.mPermissions.get(p.info.name);
11944            if (bp == null) {
11945                bp = mSettings.mPermissionTrees.get(p.info.name);
11946            }
11947            if (bp != null && bp.perm == p) {
11948                bp.perm = null;
11949                if (DEBUG_REMOVE && chatty) {
11950                    if (r == null) {
11951                        r = new StringBuilder(256);
11952                    } else {
11953                        r.append(' ');
11954                    }
11955                    r.append(p.info.name);
11956                }
11957            }
11958            if ((p.info.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
11959                ArraySet<String> appOpPkgs = mAppOpPermissionPackages.get(p.info.name);
11960                if (appOpPkgs != null) {
11961                    appOpPkgs.remove(pkg.packageName);
11962                }
11963            }
11964        }
11965        if (r != null) {
11966            if (DEBUG_REMOVE) Log.d(TAG, "  Permissions: " + r);
11967        }
11968
11969        N = pkg.requestedPermissions.size();
11970        r = null;
11971        for (i=0; i<N; i++) {
11972            String perm = pkg.requestedPermissions.get(i);
11973            BasePermission bp = mSettings.mPermissions.get(perm);
11974            if (bp != null && (bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
11975                ArraySet<String> appOpPkgs = mAppOpPermissionPackages.get(perm);
11976                if (appOpPkgs != null) {
11977                    appOpPkgs.remove(pkg.packageName);
11978                    if (appOpPkgs.isEmpty()) {
11979                        mAppOpPermissionPackages.remove(perm);
11980                    }
11981                }
11982            }
11983        }
11984        if (r != null) {
11985            if (DEBUG_REMOVE) Log.d(TAG, "  Permissions: " + r);
11986        }
11987
11988        N = pkg.instrumentation.size();
11989        r = null;
11990        for (i=0; i<N; i++) {
11991            PackageParser.Instrumentation a = pkg.instrumentation.get(i);
11992            mInstrumentation.remove(a.getComponentName());
11993            if (DEBUG_REMOVE && chatty) {
11994                if (r == null) {
11995                    r = new StringBuilder(256);
11996                } else {
11997                    r.append(' ');
11998                }
11999                r.append(a.info.name);
12000            }
12001        }
12002        if (r != null) {
12003            if (DEBUG_REMOVE) Log.d(TAG, "  Instrumentation: " + r);
12004        }
12005
12006        r = null;
12007        if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) {
12008            // Only system apps can hold shared libraries.
12009            if (pkg.libraryNames != null) {
12010                for (i = 0; i < pkg.libraryNames.size(); i++) {
12011                    String name = pkg.libraryNames.get(i);
12012                    if (removeSharedLibraryLPw(name, 0)) {
12013                        if (DEBUG_REMOVE && chatty) {
12014                            if (r == null) {
12015                                r = new StringBuilder(256);
12016                            } else {
12017                                r.append(' ');
12018                            }
12019                            r.append(name);
12020                        }
12021                    }
12022                }
12023            }
12024        }
12025
12026        r = null;
12027
12028        // Any package can hold static shared libraries.
12029        if (pkg.staticSharedLibName != null) {
12030            if (removeSharedLibraryLPw(pkg.staticSharedLibName, pkg.staticSharedLibVersion)) {
12031                if (DEBUG_REMOVE && chatty) {
12032                    if (r == null) {
12033                        r = new StringBuilder(256);
12034                    } else {
12035                        r.append(' ');
12036                    }
12037                    r.append(pkg.staticSharedLibName);
12038                }
12039            }
12040        }
12041
12042        if (r != null) {
12043            if (DEBUG_REMOVE) Log.d(TAG, "  Libraries: " + r);
12044        }
12045    }
12046
12047    private static boolean hasPermission(PackageParser.Package pkgInfo, String perm) {
12048        for (int i=pkgInfo.permissions.size()-1; i>=0; i--) {
12049            if (pkgInfo.permissions.get(i).info.name.equals(perm)) {
12050                return true;
12051            }
12052        }
12053        return false;
12054    }
12055
12056    static final int UPDATE_PERMISSIONS_ALL = 1<<0;
12057    static final int UPDATE_PERMISSIONS_REPLACE_PKG = 1<<1;
12058    static final int UPDATE_PERMISSIONS_REPLACE_ALL = 1<<2;
12059
12060    private void updatePermissionsLPw(PackageParser.Package pkg, int flags) {
12061        // Update the parent permissions
12062        updatePermissionsLPw(pkg.packageName, pkg, flags);
12063        // Update the child permissions
12064        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
12065        for (int i = 0; i < childCount; i++) {
12066            PackageParser.Package childPkg = pkg.childPackages.get(i);
12067            updatePermissionsLPw(childPkg.packageName, childPkg, flags);
12068        }
12069    }
12070
12071    private void updatePermissionsLPw(String changingPkg, PackageParser.Package pkgInfo,
12072            int flags) {
12073        final String volumeUuid = (pkgInfo != null) ? getVolumeUuidForPackage(pkgInfo) : null;
12074        updatePermissionsLPw(changingPkg, pkgInfo, volumeUuid, flags);
12075    }
12076
12077    private void updatePermissionsLPw(String changingPkg,
12078            PackageParser.Package pkgInfo, String replaceVolumeUuid, int flags) {
12079        // Make sure there are no dangling permission trees.
12080        Iterator<BasePermission> it = mSettings.mPermissionTrees.values().iterator();
12081        while (it.hasNext()) {
12082            final BasePermission bp = it.next();
12083            if (bp.packageSetting == null) {
12084                // We may not yet have parsed the package, so just see if
12085                // we still know about its settings.
12086                bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage);
12087            }
12088            if (bp.packageSetting == null) {
12089                Slog.w(TAG, "Removing dangling permission tree: " + bp.name
12090                        + " from package " + bp.sourcePackage);
12091                it.remove();
12092            } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) {
12093                if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) {
12094                    Slog.i(TAG, "Removing old permission tree: " + bp.name
12095                            + " from package " + bp.sourcePackage);
12096                    flags |= UPDATE_PERMISSIONS_ALL;
12097                    it.remove();
12098                }
12099            }
12100        }
12101
12102        // Make sure all dynamic permissions have been assigned to a package,
12103        // and make sure there are no dangling permissions.
12104        it = mSettings.mPermissions.values().iterator();
12105        while (it.hasNext()) {
12106            final BasePermission bp = it.next();
12107            if (bp.type == BasePermission.TYPE_DYNAMIC) {
12108                if (DEBUG_SETTINGS) Log.v(TAG, "Dynamic permission: name="
12109                        + bp.name + " pkg=" + bp.sourcePackage
12110                        + " info=" + bp.pendingInfo);
12111                if (bp.packageSetting == null && bp.pendingInfo != null) {
12112                    final BasePermission tree = findPermissionTreeLP(bp.name);
12113                    if (tree != null && tree.perm != null) {
12114                        bp.packageSetting = tree.packageSetting;
12115                        bp.perm = new PackageParser.Permission(tree.perm.owner,
12116                                new PermissionInfo(bp.pendingInfo));
12117                        bp.perm.info.packageName = tree.perm.info.packageName;
12118                        bp.perm.info.name = bp.name;
12119                        bp.uid = tree.uid;
12120                    }
12121                }
12122            }
12123            if (bp.packageSetting == null) {
12124                // We may not yet have parsed the package, so just see if
12125                // we still know about its settings.
12126                bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage);
12127            }
12128            if (bp.packageSetting == null) {
12129                Slog.w(TAG, "Removing dangling permission: " + bp.name
12130                        + " from package " + bp.sourcePackage);
12131                it.remove();
12132            } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) {
12133                if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) {
12134                    Slog.i(TAG, "Removing old permission: " + bp.name
12135                            + " from package " + bp.sourcePackage);
12136                    flags |= UPDATE_PERMISSIONS_ALL;
12137                    it.remove();
12138                }
12139            }
12140        }
12141
12142        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "grantPermissions");
12143        // Now update the permissions for all packages, in particular
12144        // replace the granted permissions of the system packages.
12145        if ((flags&UPDATE_PERMISSIONS_ALL) != 0) {
12146            for (PackageParser.Package pkg : mPackages.values()) {
12147                if (pkg != pkgInfo) {
12148                    // Only replace for packages on requested volume
12149                    final String volumeUuid = getVolumeUuidForPackage(pkg);
12150                    final boolean replace = ((flags & UPDATE_PERMISSIONS_REPLACE_ALL) != 0)
12151                            && Objects.equals(replaceVolumeUuid, volumeUuid);
12152                    grantPermissionsLPw(pkg, replace, changingPkg);
12153                }
12154            }
12155        }
12156
12157        if (pkgInfo != null) {
12158            // Only replace for packages on requested volume
12159            final String volumeUuid = getVolumeUuidForPackage(pkgInfo);
12160            final boolean replace = ((flags & UPDATE_PERMISSIONS_REPLACE_PKG) != 0)
12161                    && Objects.equals(replaceVolumeUuid, volumeUuid);
12162            grantPermissionsLPw(pkgInfo, replace, changingPkg);
12163        }
12164        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
12165    }
12166
12167    private void grantPermissionsLPw(PackageParser.Package pkg, boolean replace,
12168            String packageOfInterest) {
12169        // IMPORTANT: There are two types of permissions: install and runtime.
12170        // Install time permissions are granted when the app is installed to
12171        // all device users and users added in the future. Runtime permissions
12172        // are granted at runtime explicitly to specific users. Normal and signature
12173        // protected permissions are install time permissions. Dangerous permissions
12174        // are install permissions if the app's target SDK is Lollipop MR1 or older,
12175        // otherwise they are runtime permissions. This function does not manage
12176        // runtime permissions except for the case an app targeting Lollipop MR1
12177        // being upgraded to target a newer SDK, in which case dangerous permissions
12178        // are transformed from install time to runtime ones.
12179
12180        final PackageSetting ps = (PackageSetting) pkg.mExtras;
12181        if (ps == null) {
12182            return;
12183        }
12184
12185        PermissionsState permissionsState = ps.getPermissionsState();
12186        PermissionsState origPermissions = permissionsState;
12187
12188        final int[] currentUserIds = UserManagerService.getInstance().getUserIds();
12189
12190        boolean runtimePermissionsRevoked = false;
12191        int[] changedRuntimePermissionUserIds = EMPTY_INT_ARRAY;
12192
12193        boolean changedInstallPermission = false;
12194
12195        if (replace) {
12196            ps.installPermissionsFixed = false;
12197            if (!ps.isSharedUser()) {
12198                origPermissions = new PermissionsState(permissionsState);
12199                permissionsState.reset();
12200            } else {
12201                // We need to know only about runtime permission changes since the
12202                // calling code always writes the install permissions state but
12203                // the runtime ones are written only if changed. The only cases of
12204                // changed runtime permissions here are promotion of an install to
12205                // runtime and revocation of a runtime from a shared user.
12206                changedRuntimePermissionUserIds = revokeUnusedSharedUserPermissionsLPw(
12207                        ps.sharedUser, UserManagerService.getInstance().getUserIds());
12208                if (!ArrayUtils.isEmpty(changedRuntimePermissionUserIds)) {
12209                    runtimePermissionsRevoked = true;
12210                }
12211            }
12212        }
12213
12214        permissionsState.setGlobalGids(mGlobalGids);
12215
12216        final int N = pkg.requestedPermissions.size();
12217        for (int i=0; i<N; i++) {
12218            final String name = pkg.requestedPermissions.get(i);
12219            final BasePermission bp = mSettings.mPermissions.get(name);
12220            final boolean appSupportsRuntimePermissions = pkg.applicationInfo.targetSdkVersion
12221                    >= Build.VERSION_CODES.M;
12222
12223            if (DEBUG_INSTALL) {
12224                Log.i(TAG, "Package " + pkg.packageName + " checking " + name + ": " + bp);
12225            }
12226
12227            if (bp == null || bp.packageSetting == null) {
12228                if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) {
12229                    if (DEBUG_PERMISSIONS) {
12230                        Slog.i(TAG, "Unknown permission " + name
12231                                + " in package " + pkg.packageName);
12232                    }
12233                }
12234                continue;
12235            }
12236
12237
12238            // Limit ephemeral apps to ephemeral allowed permissions.
12239            if (pkg.applicationInfo.isInstantApp() && !bp.isInstant()) {
12240                if (DEBUG_PERMISSIONS) {
12241                    Log.i(TAG, "Denying non-ephemeral permission " + bp.name + " for package "
12242                            + pkg.packageName);
12243                }
12244                continue;
12245            }
12246
12247            if (bp.isRuntimeOnly() && !appSupportsRuntimePermissions) {
12248                if (DEBUG_PERMISSIONS) {
12249                    Log.i(TAG, "Denying runtime-only permission " + bp.name + " for package "
12250                            + pkg.packageName);
12251                }
12252                continue;
12253            }
12254
12255            final String perm = bp.name;
12256            boolean allowedSig = false;
12257            int grant = GRANT_DENIED;
12258
12259            // Keep track of app op permissions.
12260            if ((bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
12261                ArraySet<String> pkgs = mAppOpPermissionPackages.get(bp.name);
12262                if (pkgs == null) {
12263                    pkgs = new ArraySet<>();
12264                    mAppOpPermissionPackages.put(bp.name, pkgs);
12265                }
12266                pkgs.add(pkg.packageName);
12267            }
12268
12269            final int level = bp.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE;
12270            switch (level) {
12271                case PermissionInfo.PROTECTION_NORMAL: {
12272                    // For all apps normal permissions are install time ones.
12273                    grant = GRANT_INSTALL;
12274                } break;
12275
12276                case PermissionInfo.PROTECTION_DANGEROUS: {
12277                    // If a permission review is required for legacy apps we represent
12278                    // their permissions as always granted runtime ones since we need
12279                    // to keep the review required permission flag per user while an
12280                    // install permission's state is shared across all users.
12281                    if (!appSupportsRuntimePermissions && !mPermissionReviewRequired) {
12282                        // For legacy apps dangerous permissions are install time ones.
12283                        grant = GRANT_INSTALL;
12284                    } else if (origPermissions.hasInstallPermission(bp.name)) {
12285                        // For legacy apps that became modern, install becomes runtime.
12286                        grant = GRANT_UPGRADE;
12287                    } else if (mPromoteSystemApps
12288                            && isSystemApp(ps)
12289                            && mExistingSystemPackages.contains(ps.name)) {
12290                        // For legacy system apps, install becomes runtime.
12291                        // We cannot check hasInstallPermission() for system apps since those
12292                        // permissions were granted implicitly and not persisted pre-M.
12293                        grant = GRANT_UPGRADE;
12294                    } else {
12295                        // For modern apps keep runtime permissions unchanged.
12296                        grant = GRANT_RUNTIME;
12297                    }
12298                } break;
12299
12300                case PermissionInfo.PROTECTION_SIGNATURE: {
12301                    // For all apps signature permissions are install time ones.
12302                    allowedSig = grantSignaturePermission(perm, pkg, bp, origPermissions);
12303                    if (allowedSig) {
12304                        grant = GRANT_INSTALL;
12305                    }
12306                } break;
12307            }
12308
12309            if (DEBUG_PERMISSIONS) {
12310                Slog.i(TAG, "Granting permission " + perm + " to package " + pkg.packageName);
12311            }
12312
12313            if (grant != GRANT_DENIED) {
12314                if (!isSystemApp(ps) && ps.installPermissionsFixed) {
12315                    // If this is an existing, non-system package, then
12316                    // we can't add any new permissions to it.
12317                    if (!allowedSig && !origPermissions.hasInstallPermission(perm)) {
12318                        // Except...  if this is a permission that was added
12319                        // to the platform (note: need to only do this when
12320                        // updating the platform).
12321                        if (!isNewPlatformPermissionForPackage(perm, pkg)) {
12322                            grant = GRANT_DENIED;
12323                        }
12324                    }
12325                }
12326
12327                switch (grant) {
12328                    case GRANT_INSTALL: {
12329                        // Revoke this as runtime permission to handle the case of
12330                        // a runtime permission being downgraded to an install one.
12331                        // Also in permission review mode we keep dangerous permissions
12332                        // for legacy apps
12333                        for (int userId : UserManagerService.getInstance().getUserIds()) {
12334                            if (origPermissions.getRuntimePermissionState(
12335                                    bp.name, userId) != null) {
12336                                // Revoke the runtime permission and clear the flags.
12337                                origPermissions.revokeRuntimePermission(bp, userId);
12338                                origPermissions.updatePermissionFlags(bp, userId,
12339                                      PackageManager.MASK_PERMISSION_FLAGS, 0);
12340                                // If we revoked a permission permission, we have to write.
12341                                changedRuntimePermissionUserIds = ArrayUtils.appendInt(
12342                                        changedRuntimePermissionUserIds, userId);
12343                            }
12344                        }
12345                        // Grant an install permission.
12346                        if (permissionsState.grantInstallPermission(bp) !=
12347                                PermissionsState.PERMISSION_OPERATION_FAILURE) {
12348                            changedInstallPermission = true;
12349                        }
12350                    } break;
12351
12352                    case GRANT_RUNTIME: {
12353                        // Grant previously granted runtime permissions.
12354                        for (int userId : UserManagerService.getInstance().getUserIds()) {
12355                            PermissionState permissionState = origPermissions
12356                                    .getRuntimePermissionState(bp.name, userId);
12357                            int flags = permissionState != null
12358                                    ? permissionState.getFlags() : 0;
12359                            if (origPermissions.hasRuntimePermission(bp.name, userId)) {
12360                                // Don't propagate the permission in a permission review mode if
12361                                // the former was revoked, i.e. marked to not propagate on upgrade.
12362                                // Note that in a permission review mode install permissions are
12363                                // represented as constantly granted runtime ones since we need to
12364                                // keep a per user state associated with the permission. Also the
12365                                // revoke on upgrade flag is no longer applicable and is reset.
12366                                final boolean revokeOnUpgrade = (flags & PackageManager
12367                                        .FLAG_PERMISSION_REVOKE_ON_UPGRADE) != 0;
12368                                if (revokeOnUpgrade) {
12369                                    flags &= ~PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE;
12370                                    // Since we changed the flags, we have to write.
12371                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
12372                                            changedRuntimePermissionUserIds, userId);
12373                                }
12374                                if (!mPermissionReviewRequired || !revokeOnUpgrade) {
12375                                    if (permissionsState.grantRuntimePermission(bp, userId) ==
12376                                            PermissionsState.PERMISSION_OPERATION_FAILURE) {
12377                                        // If we cannot put the permission as it was,
12378                                        // we have to write.
12379                                        changedRuntimePermissionUserIds = ArrayUtils.appendInt(
12380                                                changedRuntimePermissionUserIds, userId);
12381                                    }
12382                                }
12383
12384                                // If the app supports runtime permissions no need for a review.
12385                                if (mPermissionReviewRequired
12386                                        && appSupportsRuntimePermissions
12387                                        && (flags & PackageManager
12388                                                .FLAG_PERMISSION_REVIEW_REQUIRED) != 0) {
12389                                    flags &= ~PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED;
12390                                    // Since we changed the flags, we have to write.
12391                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
12392                                            changedRuntimePermissionUserIds, userId);
12393                                }
12394                            } else if (mPermissionReviewRequired
12395                                    && !appSupportsRuntimePermissions) {
12396                                // For legacy apps that need a permission review, every new
12397                                // runtime permission is granted but it is pending a review.
12398                                // We also need to review only platform defined runtime
12399                                // permissions as these are the only ones the platform knows
12400                                // how to disable the API to simulate revocation as legacy
12401                                // apps don't expect to run with revoked permissions.
12402                                if (PLATFORM_PACKAGE_NAME.equals(bp.sourcePackage)) {
12403                                    if ((flags & FLAG_PERMISSION_REVIEW_REQUIRED) == 0) {
12404                                        flags |= FLAG_PERMISSION_REVIEW_REQUIRED;
12405                                        // We changed the flags, hence have to write.
12406                                        changedRuntimePermissionUserIds = ArrayUtils.appendInt(
12407                                                changedRuntimePermissionUserIds, userId);
12408                                    }
12409                                }
12410                                if (permissionsState.grantRuntimePermission(bp, userId)
12411                                        != PermissionsState.PERMISSION_OPERATION_FAILURE) {
12412                                    // We changed the permission, hence have to write.
12413                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
12414                                            changedRuntimePermissionUserIds, userId);
12415                                }
12416                            }
12417                            // Propagate the permission flags.
12418                            permissionsState.updatePermissionFlags(bp, userId, flags, flags);
12419                        }
12420                    } break;
12421
12422                    case GRANT_UPGRADE: {
12423                        // Grant runtime permissions for a previously held install permission.
12424                        PermissionState permissionState = origPermissions
12425                                .getInstallPermissionState(bp.name);
12426                        final int flags = permissionState != null ? permissionState.getFlags() : 0;
12427
12428                        if (origPermissions.revokeInstallPermission(bp)
12429                                != PermissionsState.PERMISSION_OPERATION_FAILURE) {
12430                            // We will be transferring the permission flags, so clear them.
12431                            origPermissions.updatePermissionFlags(bp, UserHandle.USER_ALL,
12432                                    PackageManager.MASK_PERMISSION_FLAGS, 0);
12433                            changedInstallPermission = true;
12434                        }
12435
12436                        // If the permission is not to be promoted to runtime we ignore it and
12437                        // also its other flags as they are not applicable to install permissions.
12438                        if ((flags & PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE) == 0) {
12439                            for (int userId : currentUserIds) {
12440                                if (permissionsState.grantRuntimePermission(bp, userId) !=
12441                                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
12442                                    // Transfer the permission flags.
12443                                    permissionsState.updatePermissionFlags(bp, userId,
12444                                            flags, flags);
12445                                    // If we granted the permission, we have to write.
12446                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
12447                                            changedRuntimePermissionUserIds, userId);
12448                                }
12449                            }
12450                        }
12451                    } break;
12452
12453                    default: {
12454                        if (packageOfInterest == null
12455                                || packageOfInterest.equals(pkg.packageName)) {
12456                            if (DEBUG_PERMISSIONS) {
12457                                Slog.i(TAG, "Not granting permission " + perm
12458                                        + " to package " + pkg.packageName
12459                                        + " because it was previously installed without");
12460                            }
12461                        }
12462                    } break;
12463                }
12464            } else {
12465                if (permissionsState.revokeInstallPermission(bp) !=
12466                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
12467                    // Also drop the permission flags.
12468                    permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL,
12469                            PackageManager.MASK_PERMISSION_FLAGS, 0);
12470                    changedInstallPermission = true;
12471                    Slog.i(TAG, "Un-granting permission " + perm
12472                            + " from package " + pkg.packageName
12473                            + " (protectionLevel=" + bp.protectionLevel
12474                            + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
12475                            + ")");
12476                } else if ((bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) == 0) {
12477                    // Don't print warning for app op permissions, since it is fine for them
12478                    // not to be granted, there is a UI for the user to decide.
12479                    if (DEBUG_PERMISSIONS
12480                            && (packageOfInterest == null
12481                                    || packageOfInterest.equals(pkg.packageName))) {
12482                        Slog.i(TAG, "Not granting permission " + perm
12483                                + " to package " + pkg.packageName
12484                                + " (protectionLevel=" + bp.protectionLevel
12485                                + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
12486                                + ")");
12487                    }
12488                }
12489            }
12490        }
12491
12492        if ((changedInstallPermission || replace) && !ps.installPermissionsFixed &&
12493                !isSystemApp(ps) || isUpdatedSystemApp(ps)){
12494            // This is the first that we have heard about this package, so the
12495            // permissions we have now selected are fixed until explicitly
12496            // changed.
12497            ps.installPermissionsFixed = true;
12498        }
12499
12500        // Persist the runtime permissions state for users with changes. If permissions
12501        // were revoked because no app in the shared user declares them we have to
12502        // write synchronously to avoid losing runtime permissions state.
12503        for (int userId : changedRuntimePermissionUserIds) {
12504            mSettings.writeRuntimePermissionsForUserLPr(userId, runtimePermissionsRevoked);
12505        }
12506    }
12507
12508    private boolean isNewPlatformPermissionForPackage(String perm, PackageParser.Package pkg) {
12509        boolean allowed = false;
12510        final int NP = PackageParser.NEW_PERMISSIONS.length;
12511        for (int ip=0; ip<NP; ip++) {
12512            final PackageParser.NewPermissionInfo npi
12513                    = PackageParser.NEW_PERMISSIONS[ip];
12514            if (npi.name.equals(perm)
12515                    && pkg.applicationInfo.targetSdkVersion < npi.sdkVersion) {
12516                allowed = true;
12517                Log.i(TAG, "Auto-granting " + perm + " to old pkg "
12518                        + pkg.packageName);
12519                break;
12520            }
12521        }
12522        return allowed;
12523    }
12524
12525    private boolean grantSignaturePermission(String perm, PackageParser.Package pkg,
12526            BasePermission bp, PermissionsState origPermissions) {
12527        boolean privilegedPermission = (bp.protectionLevel
12528                & PermissionInfo.PROTECTION_FLAG_PRIVILEGED) != 0;
12529        boolean privappPermissionsDisable =
12530                RoSystemProperties.CONTROL_PRIVAPP_PERMISSIONS_DISABLE;
12531        boolean platformPermission = PLATFORM_PACKAGE_NAME.equals(bp.sourcePackage);
12532        boolean platformPackage = PLATFORM_PACKAGE_NAME.equals(pkg.packageName);
12533        if (!privappPermissionsDisable && privilegedPermission && pkg.isPrivilegedApp()
12534                && !platformPackage && platformPermission) {
12535            ArraySet<String> wlPermissions = SystemConfig.getInstance()
12536                    .getPrivAppPermissions(pkg.packageName);
12537            boolean whitelisted = wlPermissions != null && wlPermissions.contains(perm);
12538            if (!whitelisted) {
12539                Slog.w(TAG, "Privileged permission " + perm + " for package "
12540                        + pkg.packageName + " - not in privapp-permissions whitelist");
12541                // Only report violations for apps on system image
12542                if (!mSystemReady && !pkg.isUpdatedSystemApp()) {
12543                    if (mPrivappPermissionsViolations == null) {
12544                        mPrivappPermissionsViolations = new ArraySet<>();
12545                    }
12546                    mPrivappPermissionsViolations.add(pkg.packageName + ": " + perm);
12547                }
12548                if (RoSystemProperties.CONTROL_PRIVAPP_PERMISSIONS_ENFORCE) {
12549                    return false;
12550                }
12551            }
12552        }
12553        boolean allowed = (compareSignatures(
12554                bp.packageSetting.signatures.mSignatures, pkg.mSignatures)
12555                        == PackageManager.SIGNATURE_MATCH)
12556                || (compareSignatures(mPlatformPackage.mSignatures, pkg.mSignatures)
12557                        == PackageManager.SIGNATURE_MATCH);
12558        if (!allowed && privilegedPermission) {
12559            if (isSystemApp(pkg)) {
12560                // For updated system applications, a system permission
12561                // is granted only if it had been defined by the original application.
12562                if (pkg.isUpdatedSystemApp()) {
12563                    final PackageSetting sysPs = mSettings
12564                            .getDisabledSystemPkgLPr(pkg.packageName);
12565                    if (sysPs != null && sysPs.getPermissionsState().hasInstallPermission(perm)) {
12566                        // If the original was granted this permission, we take
12567                        // that grant decision as read and propagate it to the
12568                        // update.
12569                        if (sysPs.isPrivileged()) {
12570                            allowed = true;
12571                        }
12572                    } else {
12573                        // The system apk may have been updated with an older
12574                        // version of the one on the data partition, but which
12575                        // granted a new system permission that it didn't have
12576                        // before.  In this case we do want to allow the app to
12577                        // now get the new permission if the ancestral apk is
12578                        // privileged to get it.
12579                        if (sysPs != null && sysPs.pkg != null && sysPs.isPrivileged()) {
12580                            for (int j = 0; j < sysPs.pkg.requestedPermissions.size(); j++) {
12581                                if (perm.equals(sysPs.pkg.requestedPermissions.get(j))) {
12582                                    allowed = true;
12583                                    break;
12584                                }
12585                            }
12586                        }
12587                        // Also if a privileged parent package on the system image or any of
12588                        // its children requested a privileged permission, the updated child
12589                        // packages can also get the permission.
12590                        if (pkg.parentPackage != null) {
12591                            final PackageSetting disabledSysParentPs = mSettings
12592                                    .getDisabledSystemPkgLPr(pkg.parentPackage.packageName);
12593                            if (disabledSysParentPs != null && disabledSysParentPs.pkg != null
12594                                    && disabledSysParentPs.isPrivileged()) {
12595                                if (isPackageRequestingPermission(disabledSysParentPs.pkg, perm)) {
12596                                    allowed = true;
12597                                } else if (disabledSysParentPs.pkg.childPackages != null) {
12598                                    final int count = disabledSysParentPs.pkg.childPackages.size();
12599                                    for (int i = 0; i < count; i++) {
12600                                        PackageParser.Package disabledSysChildPkg =
12601                                                disabledSysParentPs.pkg.childPackages.get(i);
12602                                        if (isPackageRequestingPermission(disabledSysChildPkg,
12603                                                perm)) {
12604                                            allowed = true;
12605                                            break;
12606                                        }
12607                                    }
12608                                }
12609                            }
12610                        }
12611                    }
12612                } else {
12613                    allowed = isPrivilegedApp(pkg);
12614                }
12615            }
12616        }
12617        if (!allowed) {
12618            if (!allowed && (bp.protectionLevel
12619                    & PermissionInfo.PROTECTION_FLAG_PRE23) != 0
12620                    && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) {
12621                // If this was a previously normal/dangerous permission that got moved
12622                // to a system permission as part of the runtime permission redesign, then
12623                // we still want to blindly grant it to old apps.
12624                allowed = true;
12625            }
12626            if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_INSTALLER) != 0
12627                    && pkg.packageName.equals(mRequiredInstallerPackage)) {
12628                // If this permission is to be granted to the system installer and
12629                // this app is an installer, then it gets the permission.
12630                allowed = true;
12631            }
12632            if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_VERIFIER) != 0
12633                    && pkg.packageName.equals(mRequiredVerifierPackage)) {
12634                // If this permission is to be granted to the system verifier and
12635                // this app is a verifier, then it gets the permission.
12636                allowed = true;
12637            }
12638            if (!allowed && (bp.protectionLevel
12639                    & PermissionInfo.PROTECTION_FLAG_PREINSTALLED) != 0
12640                    && isSystemApp(pkg)) {
12641                // Any pre-installed system app is allowed to get this permission.
12642                allowed = true;
12643            }
12644            if (!allowed && (bp.protectionLevel
12645                    & PermissionInfo.PROTECTION_FLAG_DEVELOPMENT) != 0) {
12646                // For development permissions, a development permission
12647                // is granted only if it was already granted.
12648                allowed = origPermissions.hasInstallPermission(perm);
12649            }
12650            if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_SETUP) != 0
12651                    && pkg.packageName.equals(mSetupWizardPackage)) {
12652                // If this permission is to be granted to the system setup wizard and
12653                // this app is a setup wizard, then it gets the permission.
12654                allowed = true;
12655            }
12656        }
12657        return allowed;
12658    }
12659
12660    private boolean isPackageRequestingPermission(PackageParser.Package pkg, String permission) {
12661        final int permCount = pkg.requestedPermissions.size();
12662        for (int j = 0; j < permCount; j++) {
12663            String requestedPermission = pkg.requestedPermissions.get(j);
12664            if (permission.equals(requestedPermission)) {
12665                return true;
12666            }
12667        }
12668        return false;
12669    }
12670
12671    final class ActivityIntentResolver
12672            extends IntentResolver<PackageParser.ActivityIntentInfo, ResolveInfo> {
12673        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
12674                boolean defaultOnly, int userId) {
12675            if (!sUserManager.exists(userId)) return null;
12676            mFlags = (defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0);
12677            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
12678        }
12679
12680        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
12681                int userId) {
12682            if (!sUserManager.exists(userId)) return null;
12683            mFlags = flags;
12684            return super.queryIntent(intent, resolvedType,
12685                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0,
12686                    userId);
12687        }
12688
12689        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
12690                int flags, ArrayList<PackageParser.Activity> packageActivities, int userId) {
12691            if (!sUserManager.exists(userId)) return null;
12692            if (packageActivities == null) {
12693                return null;
12694            }
12695            mFlags = flags;
12696            final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0;
12697            final int N = packageActivities.size();
12698            ArrayList<PackageParser.ActivityIntentInfo[]> listCut =
12699                new ArrayList<PackageParser.ActivityIntentInfo[]>(N);
12700
12701            ArrayList<PackageParser.ActivityIntentInfo> intentFilters;
12702            for (int i = 0; i < N; ++i) {
12703                intentFilters = packageActivities.get(i).intents;
12704                if (intentFilters != null && intentFilters.size() > 0) {
12705                    PackageParser.ActivityIntentInfo[] array =
12706                            new PackageParser.ActivityIntentInfo[intentFilters.size()];
12707                    intentFilters.toArray(array);
12708                    listCut.add(array);
12709                }
12710            }
12711            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
12712        }
12713
12714        /**
12715         * Finds a privileged activity that matches the specified activity names.
12716         */
12717        private PackageParser.Activity findMatchingActivity(
12718                List<PackageParser.Activity> activityList, ActivityInfo activityInfo) {
12719            for (PackageParser.Activity sysActivity : activityList) {
12720                if (sysActivity.info.name.equals(activityInfo.name)) {
12721                    return sysActivity;
12722                }
12723                if (sysActivity.info.name.equals(activityInfo.targetActivity)) {
12724                    return sysActivity;
12725                }
12726                if (sysActivity.info.targetActivity != null) {
12727                    if (sysActivity.info.targetActivity.equals(activityInfo.name)) {
12728                        return sysActivity;
12729                    }
12730                    if (sysActivity.info.targetActivity.equals(activityInfo.targetActivity)) {
12731                        return sysActivity;
12732                    }
12733                }
12734            }
12735            return null;
12736        }
12737
12738        public class IterGenerator<E> {
12739            public Iterator<E> generate(ActivityIntentInfo info) {
12740                return null;
12741            }
12742        }
12743
12744        public class ActionIterGenerator extends IterGenerator<String> {
12745            @Override
12746            public Iterator<String> generate(ActivityIntentInfo info) {
12747                return info.actionsIterator();
12748            }
12749        }
12750
12751        public class CategoriesIterGenerator extends IterGenerator<String> {
12752            @Override
12753            public Iterator<String> generate(ActivityIntentInfo info) {
12754                return info.categoriesIterator();
12755            }
12756        }
12757
12758        public class SchemesIterGenerator extends IterGenerator<String> {
12759            @Override
12760            public Iterator<String> generate(ActivityIntentInfo info) {
12761                return info.schemesIterator();
12762            }
12763        }
12764
12765        public class AuthoritiesIterGenerator extends IterGenerator<IntentFilter.AuthorityEntry> {
12766            @Override
12767            public Iterator<IntentFilter.AuthorityEntry> generate(ActivityIntentInfo info) {
12768                return info.authoritiesIterator();
12769            }
12770        }
12771
12772        /**
12773         * <em>WARNING</em> for performance reasons, the passed in intentList WILL BE
12774         * MODIFIED. Do not pass in a list that should not be changed.
12775         */
12776        private <T> void getIntentListSubset(List<ActivityIntentInfo> intentList,
12777                IterGenerator<T> generator, Iterator<T> searchIterator) {
12778            // loop through the set of actions; every one must be found in the intent filter
12779            while (searchIterator.hasNext()) {
12780                // we must have at least one filter in the list to consider a match
12781                if (intentList.size() == 0) {
12782                    break;
12783                }
12784
12785                final T searchAction = searchIterator.next();
12786
12787                // loop through the set of intent filters
12788                final Iterator<ActivityIntentInfo> intentIter = intentList.iterator();
12789                while (intentIter.hasNext()) {
12790                    final ActivityIntentInfo intentInfo = intentIter.next();
12791                    boolean selectionFound = false;
12792
12793                    // loop through the intent filter's selection criteria; at least one
12794                    // of them must match the searched criteria
12795                    final Iterator<T> intentSelectionIter = generator.generate(intentInfo);
12796                    while (intentSelectionIter != null && intentSelectionIter.hasNext()) {
12797                        final T intentSelection = intentSelectionIter.next();
12798                        if (intentSelection != null && intentSelection.equals(searchAction)) {
12799                            selectionFound = true;
12800                            break;
12801                        }
12802                    }
12803
12804                    // the selection criteria wasn't found in this filter's set; this filter
12805                    // is not a potential match
12806                    if (!selectionFound) {
12807                        intentIter.remove();
12808                    }
12809                }
12810            }
12811        }
12812
12813        private boolean isProtectedAction(ActivityIntentInfo filter) {
12814            final Iterator<String> actionsIter = filter.actionsIterator();
12815            while (actionsIter != null && actionsIter.hasNext()) {
12816                final String filterAction = actionsIter.next();
12817                if (PROTECTED_ACTIONS.contains(filterAction)) {
12818                    return true;
12819                }
12820            }
12821            return false;
12822        }
12823
12824        /**
12825         * Adjusts the priority of the given intent filter according to policy.
12826         * <p>
12827         * <ul>
12828         * <li>The priority for non privileged applications is capped to '0'</li>
12829         * <li>The priority for protected actions on privileged applications is capped to '0'</li>
12830         * <li>The priority for unbundled updates to privileged applications is capped to the
12831         *      priority defined on the system partition</li>
12832         * </ul>
12833         * <p>
12834         * <em>NOTE:</em> There is one exception. For security reasons, the setup wizard is
12835         * allowed to obtain any priority on any action.
12836         */
12837        private void adjustPriority(
12838                List<PackageParser.Activity> systemActivities, ActivityIntentInfo intent) {
12839            // nothing to do; priority is fine as-is
12840            if (intent.getPriority() <= 0) {
12841                return;
12842            }
12843
12844            final ActivityInfo activityInfo = intent.activity.info;
12845            final ApplicationInfo applicationInfo = activityInfo.applicationInfo;
12846
12847            final boolean privilegedApp =
12848                    ((applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0);
12849            if (!privilegedApp) {
12850                // non-privileged applications can never define a priority >0
12851                if (DEBUG_FILTERS) {
12852                    Slog.i(TAG, "Non-privileged app; cap priority to 0;"
12853                            + " package: " + applicationInfo.packageName
12854                            + " activity: " + intent.activity.className
12855                            + " origPrio: " + intent.getPriority());
12856                }
12857                intent.setPriority(0);
12858                return;
12859            }
12860
12861            if (systemActivities == null) {
12862                // the system package is not disabled; we're parsing the system partition
12863                if (isProtectedAction(intent)) {
12864                    if (mDeferProtectedFilters) {
12865                        // We can't deal with these just yet. No component should ever obtain a
12866                        // >0 priority for a protected actions, with ONE exception -- the setup
12867                        // wizard. The setup wizard, however, cannot be known until we're able to
12868                        // query it for the category CATEGORY_SETUP_WIZARD. Which we can't do
12869                        // until all intent filters have been processed. Chicken, meet egg.
12870                        // Let the filter temporarily have a high priority and rectify the
12871                        // priorities after all system packages have been scanned.
12872                        mProtectedFilters.add(intent);
12873                        if (DEBUG_FILTERS) {
12874                            Slog.i(TAG, "Protected action; save for later;"
12875                                    + " package: " + applicationInfo.packageName
12876                                    + " activity: " + intent.activity.className
12877                                    + " origPrio: " + intent.getPriority());
12878                        }
12879                        return;
12880                    } else {
12881                        if (DEBUG_FILTERS && mSetupWizardPackage == null) {
12882                            Slog.i(TAG, "No setup wizard;"
12883                                + " All protected intents capped to priority 0");
12884                        }
12885                        if (intent.activity.info.packageName.equals(mSetupWizardPackage)) {
12886                            if (DEBUG_FILTERS) {
12887                                Slog.i(TAG, "Found setup wizard;"
12888                                    + " allow priority " + intent.getPriority() + ";"
12889                                    + " package: " + intent.activity.info.packageName
12890                                    + " activity: " + intent.activity.className
12891                                    + " priority: " + intent.getPriority());
12892                            }
12893                            // setup wizard gets whatever it wants
12894                            return;
12895                        }
12896                        if (DEBUG_FILTERS) {
12897                            Slog.i(TAG, "Protected action; cap priority to 0;"
12898                                    + " package: " + intent.activity.info.packageName
12899                                    + " activity: " + intent.activity.className
12900                                    + " origPrio: " + intent.getPriority());
12901                        }
12902                        intent.setPriority(0);
12903                        return;
12904                    }
12905                }
12906                // privileged apps on the system image get whatever priority they request
12907                return;
12908            }
12909
12910            // privileged app unbundled update ... try to find the same activity
12911            final PackageParser.Activity foundActivity =
12912                    findMatchingActivity(systemActivities, activityInfo);
12913            if (foundActivity == null) {
12914                // this is a new activity; it cannot obtain >0 priority
12915                if (DEBUG_FILTERS) {
12916                    Slog.i(TAG, "New activity; cap priority to 0;"
12917                            + " package: " + applicationInfo.packageName
12918                            + " activity: " + intent.activity.className
12919                            + " origPrio: " + intent.getPriority());
12920                }
12921                intent.setPriority(0);
12922                return;
12923            }
12924
12925            // found activity, now check for filter equivalence
12926
12927            // a shallow copy is enough; we modify the list, not its contents
12928            final List<ActivityIntentInfo> intentListCopy =
12929                    new ArrayList<>(foundActivity.intents);
12930            final List<ActivityIntentInfo> foundFilters = findFilters(intent);
12931
12932            // find matching action subsets
12933            final Iterator<String> actionsIterator = intent.actionsIterator();
12934            if (actionsIterator != null) {
12935                getIntentListSubset(
12936                        intentListCopy, new ActionIterGenerator(), actionsIterator);
12937                if (intentListCopy.size() == 0) {
12938                    // no more intents to match; we're not equivalent
12939                    if (DEBUG_FILTERS) {
12940                        Slog.i(TAG, "Mismatched action; cap priority to 0;"
12941                                + " package: " + applicationInfo.packageName
12942                                + " activity: " + intent.activity.className
12943                                + " origPrio: " + intent.getPriority());
12944                    }
12945                    intent.setPriority(0);
12946                    return;
12947                }
12948            }
12949
12950            // find matching category subsets
12951            final Iterator<String> categoriesIterator = intent.categoriesIterator();
12952            if (categoriesIterator != null) {
12953                getIntentListSubset(intentListCopy, new CategoriesIterGenerator(),
12954                        categoriesIterator);
12955                if (intentListCopy.size() == 0) {
12956                    // no more intents to match; we're not equivalent
12957                    if (DEBUG_FILTERS) {
12958                        Slog.i(TAG, "Mismatched category; cap priority to 0;"
12959                                + " package: " + applicationInfo.packageName
12960                                + " activity: " + intent.activity.className
12961                                + " origPrio: " + intent.getPriority());
12962                    }
12963                    intent.setPriority(0);
12964                    return;
12965                }
12966            }
12967
12968            // find matching schemes subsets
12969            final Iterator<String> schemesIterator = intent.schemesIterator();
12970            if (schemesIterator != null) {
12971                getIntentListSubset(intentListCopy, new SchemesIterGenerator(),
12972                        schemesIterator);
12973                if (intentListCopy.size() == 0) {
12974                    // no more intents to match; we're not equivalent
12975                    if (DEBUG_FILTERS) {
12976                        Slog.i(TAG, "Mismatched scheme; cap priority to 0;"
12977                                + " package: " + applicationInfo.packageName
12978                                + " activity: " + intent.activity.className
12979                                + " origPrio: " + intent.getPriority());
12980                    }
12981                    intent.setPriority(0);
12982                    return;
12983                }
12984            }
12985
12986            // find matching authorities subsets
12987            final Iterator<IntentFilter.AuthorityEntry>
12988                    authoritiesIterator = intent.authoritiesIterator();
12989            if (authoritiesIterator != null) {
12990                getIntentListSubset(intentListCopy,
12991                        new AuthoritiesIterGenerator(),
12992                        authoritiesIterator);
12993                if (intentListCopy.size() == 0) {
12994                    // no more intents to match; we're not equivalent
12995                    if (DEBUG_FILTERS) {
12996                        Slog.i(TAG, "Mismatched authority; cap priority to 0;"
12997                                + " package: " + applicationInfo.packageName
12998                                + " activity: " + intent.activity.className
12999                                + " origPrio: " + intent.getPriority());
13000                    }
13001                    intent.setPriority(0);
13002                    return;
13003                }
13004            }
13005
13006            // we found matching filter(s); app gets the max priority of all intents
13007            int cappedPriority = 0;
13008            for (int i = intentListCopy.size() - 1; i >= 0; --i) {
13009                cappedPriority = Math.max(cappedPriority, intentListCopy.get(i).getPriority());
13010            }
13011            if (intent.getPriority() > cappedPriority) {
13012                if (DEBUG_FILTERS) {
13013                    Slog.i(TAG, "Found matching filter(s);"
13014                            + " cap priority to " + cappedPriority + ";"
13015                            + " package: " + applicationInfo.packageName
13016                            + " activity: " + intent.activity.className
13017                            + " origPrio: " + intent.getPriority());
13018                }
13019                intent.setPriority(cappedPriority);
13020                return;
13021            }
13022            // all this for nothing; the requested priority was <= what was on the system
13023        }
13024
13025        public final void addActivity(PackageParser.Activity a, String type) {
13026            mActivities.put(a.getComponentName(), a);
13027            if (DEBUG_SHOW_INFO)
13028                Log.v(
13029                TAG, "  " + type + " " +
13030                (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":");
13031            if (DEBUG_SHOW_INFO)
13032                Log.v(TAG, "    Class=" + a.info.name);
13033            final int NI = a.intents.size();
13034            for (int j=0; j<NI; j++) {
13035                PackageParser.ActivityIntentInfo intent = a.intents.get(j);
13036                if ("activity".equals(type)) {
13037                    final PackageSetting ps =
13038                            mSettings.getDisabledSystemPkgLPr(intent.activity.info.packageName);
13039                    final List<PackageParser.Activity> systemActivities =
13040                            ps != null && ps.pkg != null ? ps.pkg.activities : null;
13041                    adjustPriority(systemActivities, intent);
13042                }
13043                if (DEBUG_SHOW_INFO) {
13044                    Log.v(TAG, "    IntentFilter:");
13045                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
13046                }
13047                if (!intent.debugCheck()) {
13048                    Log.w(TAG, "==> For Activity " + a.info.name);
13049                }
13050                addFilter(intent);
13051            }
13052        }
13053
13054        public final void removeActivity(PackageParser.Activity a, String type) {
13055            mActivities.remove(a.getComponentName());
13056            if (DEBUG_SHOW_INFO) {
13057                Log.v(TAG, "  " + type + " "
13058                        + (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel
13059                                : a.info.name) + ":");
13060                Log.v(TAG, "    Class=" + a.info.name);
13061            }
13062            final int NI = a.intents.size();
13063            for (int j=0; j<NI; j++) {
13064                PackageParser.ActivityIntentInfo intent = a.intents.get(j);
13065                if (DEBUG_SHOW_INFO) {
13066                    Log.v(TAG, "    IntentFilter:");
13067                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
13068                }
13069                removeFilter(intent);
13070            }
13071        }
13072
13073        @Override
13074        protected boolean allowFilterResult(
13075                PackageParser.ActivityIntentInfo filter, List<ResolveInfo> dest) {
13076            ActivityInfo filterAi = filter.activity.info;
13077            for (int i=dest.size()-1; i>=0; i--) {
13078                ActivityInfo destAi = dest.get(i).activityInfo;
13079                if (destAi.name == filterAi.name
13080                        && destAi.packageName == filterAi.packageName) {
13081                    return false;
13082                }
13083            }
13084            return true;
13085        }
13086
13087        @Override
13088        protected ActivityIntentInfo[] newArray(int size) {
13089            return new ActivityIntentInfo[size];
13090        }
13091
13092        @Override
13093        protected boolean isFilterStopped(PackageParser.ActivityIntentInfo filter, int userId) {
13094            if (!sUserManager.exists(userId)) return true;
13095            PackageParser.Package p = filter.activity.owner;
13096            if (p != null) {
13097                PackageSetting ps = (PackageSetting)p.mExtras;
13098                if (ps != null) {
13099                    // System apps are never considered stopped for purposes of
13100                    // filtering, because there may be no way for the user to
13101                    // actually re-launch them.
13102                    return (ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0
13103                            && ps.getStopped(userId);
13104                }
13105            }
13106            return false;
13107        }
13108
13109        @Override
13110        protected boolean isPackageForFilter(String packageName,
13111                PackageParser.ActivityIntentInfo info) {
13112            return packageName.equals(info.activity.owner.packageName);
13113        }
13114
13115        @Override
13116        protected ResolveInfo newResult(PackageParser.ActivityIntentInfo info,
13117                int match, int userId) {
13118            if (!sUserManager.exists(userId)) return null;
13119            if (!mSettings.isEnabledAndMatchLPr(info.activity.info, mFlags, userId)) {
13120                return null;
13121            }
13122            final PackageParser.Activity activity = info.activity;
13123            PackageSetting ps = (PackageSetting) activity.owner.mExtras;
13124            if (ps == null) {
13125                return null;
13126            }
13127            final PackageUserState userState = ps.readUserState(userId);
13128            ActivityInfo ai = generateActivityInfo(activity, mFlags, userState, userId);
13129            if (ai == null) {
13130                return null;
13131            }
13132            final boolean matchExplicitlyVisibleOnly =
13133                    (mFlags & PackageManager.MATCH_EXPLICITLY_VISIBLE_ONLY) != 0;
13134            final boolean matchVisibleToInstantApp =
13135                    (mFlags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
13136            final boolean componentVisible =
13137                    matchVisibleToInstantApp
13138                    && info.isVisibleToInstantApp()
13139                    && (!matchExplicitlyVisibleOnly || info.isExplicitlyVisibleToInstantApp());
13140            final boolean matchInstantApp = (mFlags & PackageManager.MATCH_INSTANT) != 0;
13141            // throw out filters that aren't visible to ephemeral apps
13142            if (matchVisibleToInstantApp && !(componentVisible || userState.instantApp)) {
13143                return null;
13144            }
13145            // throw out instant app filters if we're not explicitly requesting them
13146            if (!matchInstantApp && userState.instantApp) {
13147                return null;
13148            }
13149            // throw out instant app filters if updates are available; will trigger
13150            // instant app resolution
13151            if (userState.instantApp && ps.isUpdateAvailable()) {
13152                return null;
13153            }
13154            final ResolveInfo res = new ResolveInfo();
13155            res.activityInfo = ai;
13156            if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
13157                res.filter = info;
13158            }
13159            if (info != null) {
13160                res.handleAllWebDataURI = info.handleAllWebDataURI();
13161            }
13162            res.priority = info.getPriority();
13163            res.preferredOrder = activity.owner.mPreferredOrder;
13164            //System.out.println("Result: " + res.activityInfo.className +
13165            //                   " = " + res.priority);
13166            res.match = match;
13167            res.isDefault = info.hasDefault;
13168            res.labelRes = info.labelRes;
13169            res.nonLocalizedLabel = info.nonLocalizedLabel;
13170            if (userNeedsBadging(userId)) {
13171                res.noResourceId = true;
13172            } else {
13173                res.icon = info.icon;
13174            }
13175            res.iconResourceId = info.icon;
13176            res.system = res.activityInfo.applicationInfo.isSystemApp();
13177            res.isInstantAppAvailable = userState.instantApp;
13178            return res;
13179        }
13180
13181        @Override
13182        protected void sortResults(List<ResolveInfo> results) {
13183            Collections.sort(results, mResolvePrioritySorter);
13184        }
13185
13186        @Override
13187        protected void dumpFilter(PrintWriter out, String prefix,
13188                PackageParser.ActivityIntentInfo filter) {
13189            out.print(prefix); out.print(
13190                    Integer.toHexString(System.identityHashCode(filter.activity)));
13191                    out.print(' ');
13192                    filter.activity.printComponentShortName(out);
13193                    out.print(" filter ");
13194                    out.println(Integer.toHexString(System.identityHashCode(filter)));
13195        }
13196
13197        @Override
13198        protected Object filterToLabel(PackageParser.ActivityIntentInfo filter) {
13199            return filter.activity;
13200        }
13201
13202        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
13203            PackageParser.Activity activity = (PackageParser.Activity)label;
13204            out.print(prefix); out.print(
13205                    Integer.toHexString(System.identityHashCode(activity)));
13206                    out.print(' ');
13207                    activity.printComponentShortName(out);
13208            if (count > 1) {
13209                out.print(" ("); out.print(count); out.print(" filters)");
13210            }
13211            out.println();
13212        }
13213
13214        // Keys are String (activity class name), values are Activity.
13215        private final ArrayMap<ComponentName, PackageParser.Activity> mActivities
13216                = new ArrayMap<ComponentName, PackageParser.Activity>();
13217        private int mFlags;
13218    }
13219
13220    private final class ServiceIntentResolver
13221            extends IntentResolver<PackageParser.ServiceIntentInfo, ResolveInfo> {
13222        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
13223                boolean defaultOnly, int userId) {
13224            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
13225            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
13226        }
13227
13228        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
13229                int userId) {
13230            if (!sUserManager.exists(userId)) return null;
13231            mFlags = flags;
13232            return super.queryIntent(intent, resolvedType,
13233                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0,
13234                    userId);
13235        }
13236
13237        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
13238                int flags, ArrayList<PackageParser.Service> packageServices, int userId) {
13239            if (!sUserManager.exists(userId)) return null;
13240            if (packageServices == null) {
13241                return null;
13242            }
13243            mFlags = flags;
13244            final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0;
13245            final int N = packageServices.size();
13246            ArrayList<PackageParser.ServiceIntentInfo[]> listCut =
13247                new ArrayList<PackageParser.ServiceIntentInfo[]>(N);
13248
13249            ArrayList<PackageParser.ServiceIntentInfo> intentFilters;
13250            for (int i = 0; i < N; ++i) {
13251                intentFilters = packageServices.get(i).intents;
13252                if (intentFilters != null && intentFilters.size() > 0) {
13253                    PackageParser.ServiceIntentInfo[] array =
13254                            new PackageParser.ServiceIntentInfo[intentFilters.size()];
13255                    intentFilters.toArray(array);
13256                    listCut.add(array);
13257                }
13258            }
13259            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
13260        }
13261
13262        public final void addService(PackageParser.Service s) {
13263            mServices.put(s.getComponentName(), s);
13264            if (DEBUG_SHOW_INFO) {
13265                Log.v(TAG, "  "
13266                        + (s.info.nonLocalizedLabel != null
13267                        ? s.info.nonLocalizedLabel : s.info.name) + ":");
13268                Log.v(TAG, "    Class=" + s.info.name);
13269            }
13270            final int NI = s.intents.size();
13271            int j;
13272            for (j=0; j<NI; j++) {
13273                PackageParser.ServiceIntentInfo intent = s.intents.get(j);
13274                if (DEBUG_SHOW_INFO) {
13275                    Log.v(TAG, "    IntentFilter:");
13276                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
13277                }
13278                if (!intent.debugCheck()) {
13279                    Log.w(TAG, "==> For Service " + s.info.name);
13280                }
13281                addFilter(intent);
13282            }
13283        }
13284
13285        public final void removeService(PackageParser.Service s) {
13286            mServices.remove(s.getComponentName());
13287            if (DEBUG_SHOW_INFO) {
13288                Log.v(TAG, "  " + (s.info.nonLocalizedLabel != null
13289                        ? s.info.nonLocalizedLabel : s.info.name) + ":");
13290                Log.v(TAG, "    Class=" + s.info.name);
13291            }
13292            final int NI = s.intents.size();
13293            int j;
13294            for (j=0; j<NI; j++) {
13295                PackageParser.ServiceIntentInfo intent = s.intents.get(j);
13296                if (DEBUG_SHOW_INFO) {
13297                    Log.v(TAG, "    IntentFilter:");
13298                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
13299                }
13300                removeFilter(intent);
13301            }
13302        }
13303
13304        @Override
13305        protected boolean allowFilterResult(
13306                PackageParser.ServiceIntentInfo filter, List<ResolveInfo> dest) {
13307            ServiceInfo filterSi = filter.service.info;
13308            for (int i=dest.size()-1; i>=0; i--) {
13309                ServiceInfo destAi = dest.get(i).serviceInfo;
13310                if (destAi.name == filterSi.name
13311                        && destAi.packageName == filterSi.packageName) {
13312                    return false;
13313                }
13314            }
13315            return true;
13316        }
13317
13318        @Override
13319        protected PackageParser.ServiceIntentInfo[] newArray(int size) {
13320            return new PackageParser.ServiceIntentInfo[size];
13321        }
13322
13323        @Override
13324        protected boolean isFilterStopped(PackageParser.ServiceIntentInfo filter, int userId) {
13325            if (!sUserManager.exists(userId)) return true;
13326            PackageParser.Package p = filter.service.owner;
13327            if (p != null) {
13328                PackageSetting ps = (PackageSetting)p.mExtras;
13329                if (ps != null) {
13330                    // System apps are never considered stopped for purposes of
13331                    // filtering, because there may be no way for the user to
13332                    // actually re-launch them.
13333                    return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0
13334                            && ps.getStopped(userId);
13335                }
13336            }
13337            return false;
13338        }
13339
13340        @Override
13341        protected boolean isPackageForFilter(String packageName,
13342                PackageParser.ServiceIntentInfo info) {
13343            return packageName.equals(info.service.owner.packageName);
13344        }
13345
13346        @Override
13347        protected ResolveInfo newResult(PackageParser.ServiceIntentInfo filter,
13348                int match, int userId) {
13349            if (!sUserManager.exists(userId)) return null;
13350            final PackageParser.ServiceIntentInfo info = (PackageParser.ServiceIntentInfo)filter;
13351            if (!mSettings.isEnabledAndMatchLPr(info.service.info, mFlags, userId)) {
13352                return null;
13353            }
13354            final PackageParser.Service service = info.service;
13355            PackageSetting ps = (PackageSetting) service.owner.mExtras;
13356            if (ps == null) {
13357                return null;
13358            }
13359            final PackageUserState userState = ps.readUserState(userId);
13360            ServiceInfo si = PackageParser.generateServiceInfo(service, mFlags,
13361                    userState, userId);
13362            if (si == null) {
13363                return null;
13364            }
13365            final boolean matchVisibleToInstantApp =
13366                    (mFlags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
13367            final boolean isInstantApp = (mFlags & PackageManager.MATCH_INSTANT) != 0;
13368            // throw out filters that aren't visible to ephemeral apps
13369            if (matchVisibleToInstantApp
13370                    && !(info.isVisibleToInstantApp() || userState.instantApp)) {
13371                return null;
13372            }
13373            // throw out ephemeral filters if we're not explicitly requesting them
13374            if (!isInstantApp && userState.instantApp) {
13375                return null;
13376            }
13377            // throw out instant app filters if updates are available; will trigger
13378            // instant app resolution
13379            if (userState.instantApp && ps.isUpdateAvailable()) {
13380                return null;
13381            }
13382            final ResolveInfo res = new ResolveInfo();
13383            res.serviceInfo = si;
13384            if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
13385                res.filter = filter;
13386            }
13387            res.priority = info.getPriority();
13388            res.preferredOrder = service.owner.mPreferredOrder;
13389            res.match = match;
13390            res.isDefault = info.hasDefault;
13391            res.labelRes = info.labelRes;
13392            res.nonLocalizedLabel = info.nonLocalizedLabel;
13393            res.icon = info.icon;
13394            res.system = res.serviceInfo.applicationInfo.isSystemApp();
13395            return res;
13396        }
13397
13398        @Override
13399        protected void sortResults(List<ResolveInfo> results) {
13400            Collections.sort(results, mResolvePrioritySorter);
13401        }
13402
13403        @Override
13404        protected void dumpFilter(PrintWriter out, String prefix,
13405                PackageParser.ServiceIntentInfo filter) {
13406            out.print(prefix); out.print(
13407                    Integer.toHexString(System.identityHashCode(filter.service)));
13408                    out.print(' ');
13409                    filter.service.printComponentShortName(out);
13410                    out.print(" filter ");
13411                    out.println(Integer.toHexString(System.identityHashCode(filter)));
13412        }
13413
13414        @Override
13415        protected Object filterToLabel(PackageParser.ServiceIntentInfo filter) {
13416            return filter.service;
13417        }
13418
13419        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
13420            PackageParser.Service service = (PackageParser.Service)label;
13421            out.print(prefix); out.print(
13422                    Integer.toHexString(System.identityHashCode(service)));
13423                    out.print(' ');
13424                    service.printComponentShortName(out);
13425            if (count > 1) {
13426                out.print(" ("); out.print(count); out.print(" filters)");
13427            }
13428            out.println();
13429        }
13430
13431//        List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) {
13432//            final Iterator<ResolveInfo> i = resolveInfoList.iterator();
13433//            final List<ResolveInfo> retList = Lists.newArrayList();
13434//            while (i.hasNext()) {
13435//                final ResolveInfo resolveInfo = (ResolveInfo) i;
13436//                if (isEnabledLP(resolveInfo.serviceInfo)) {
13437//                    retList.add(resolveInfo);
13438//                }
13439//            }
13440//            return retList;
13441//        }
13442
13443        // Keys are String (activity class name), values are Activity.
13444        private final ArrayMap<ComponentName, PackageParser.Service> mServices
13445                = new ArrayMap<ComponentName, PackageParser.Service>();
13446        private int mFlags;
13447    }
13448
13449    private final class ProviderIntentResolver
13450            extends IntentResolver<PackageParser.ProviderIntentInfo, ResolveInfo> {
13451        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
13452                boolean defaultOnly, int userId) {
13453            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
13454            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
13455        }
13456
13457        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
13458                int userId) {
13459            if (!sUserManager.exists(userId))
13460                return null;
13461            mFlags = flags;
13462            return super.queryIntent(intent, resolvedType,
13463                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0,
13464                    userId);
13465        }
13466
13467        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
13468                int flags, ArrayList<PackageParser.Provider> packageProviders, int userId) {
13469            if (!sUserManager.exists(userId))
13470                return null;
13471            if (packageProviders == null) {
13472                return null;
13473            }
13474            mFlags = flags;
13475            final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0;
13476            final int N = packageProviders.size();
13477            ArrayList<PackageParser.ProviderIntentInfo[]> listCut =
13478                    new ArrayList<PackageParser.ProviderIntentInfo[]>(N);
13479
13480            ArrayList<PackageParser.ProviderIntentInfo> intentFilters;
13481            for (int i = 0; i < N; ++i) {
13482                intentFilters = packageProviders.get(i).intents;
13483                if (intentFilters != null && intentFilters.size() > 0) {
13484                    PackageParser.ProviderIntentInfo[] array =
13485                            new PackageParser.ProviderIntentInfo[intentFilters.size()];
13486                    intentFilters.toArray(array);
13487                    listCut.add(array);
13488                }
13489            }
13490            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
13491        }
13492
13493        public final void addProvider(PackageParser.Provider p) {
13494            if (mProviders.containsKey(p.getComponentName())) {
13495                Slog.w(TAG, "Provider " + p.getComponentName() + " already defined; ignoring");
13496                return;
13497            }
13498
13499            mProviders.put(p.getComponentName(), p);
13500            if (DEBUG_SHOW_INFO) {
13501                Log.v(TAG, "  "
13502                        + (p.info.nonLocalizedLabel != null
13503                                ? p.info.nonLocalizedLabel : p.info.name) + ":");
13504                Log.v(TAG, "    Class=" + p.info.name);
13505            }
13506            final int NI = p.intents.size();
13507            int j;
13508            for (j = 0; j < NI; j++) {
13509                PackageParser.ProviderIntentInfo intent = p.intents.get(j);
13510                if (DEBUG_SHOW_INFO) {
13511                    Log.v(TAG, "    IntentFilter:");
13512                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
13513                }
13514                if (!intent.debugCheck()) {
13515                    Log.w(TAG, "==> For Provider " + p.info.name);
13516                }
13517                addFilter(intent);
13518            }
13519        }
13520
13521        public final void removeProvider(PackageParser.Provider p) {
13522            mProviders.remove(p.getComponentName());
13523            if (DEBUG_SHOW_INFO) {
13524                Log.v(TAG, "  " + (p.info.nonLocalizedLabel != null
13525                        ? p.info.nonLocalizedLabel : p.info.name) + ":");
13526                Log.v(TAG, "    Class=" + p.info.name);
13527            }
13528            final int NI = p.intents.size();
13529            int j;
13530            for (j = 0; j < NI; j++) {
13531                PackageParser.ProviderIntentInfo intent = p.intents.get(j);
13532                if (DEBUG_SHOW_INFO) {
13533                    Log.v(TAG, "    IntentFilter:");
13534                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
13535                }
13536                removeFilter(intent);
13537            }
13538        }
13539
13540        @Override
13541        protected boolean allowFilterResult(
13542                PackageParser.ProviderIntentInfo filter, List<ResolveInfo> dest) {
13543            ProviderInfo filterPi = filter.provider.info;
13544            for (int i = dest.size() - 1; i >= 0; i--) {
13545                ProviderInfo destPi = dest.get(i).providerInfo;
13546                if (destPi.name == filterPi.name
13547                        && destPi.packageName == filterPi.packageName) {
13548                    return false;
13549                }
13550            }
13551            return true;
13552        }
13553
13554        @Override
13555        protected PackageParser.ProviderIntentInfo[] newArray(int size) {
13556            return new PackageParser.ProviderIntentInfo[size];
13557        }
13558
13559        @Override
13560        protected boolean isFilterStopped(PackageParser.ProviderIntentInfo filter, int userId) {
13561            if (!sUserManager.exists(userId))
13562                return true;
13563            PackageParser.Package p = filter.provider.owner;
13564            if (p != null) {
13565                PackageSetting ps = (PackageSetting) p.mExtras;
13566                if (ps != null) {
13567                    // System apps are never considered stopped for purposes of
13568                    // filtering, because there may be no way for the user to
13569                    // actually re-launch them.
13570                    return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0
13571                            && ps.getStopped(userId);
13572                }
13573            }
13574            return false;
13575        }
13576
13577        @Override
13578        protected boolean isPackageForFilter(String packageName,
13579                PackageParser.ProviderIntentInfo info) {
13580            return packageName.equals(info.provider.owner.packageName);
13581        }
13582
13583        @Override
13584        protected ResolveInfo newResult(PackageParser.ProviderIntentInfo filter,
13585                int match, int userId) {
13586            if (!sUserManager.exists(userId))
13587                return null;
13588            final PackageParser.ProviderIntentInfo info = filter;
13589            if (!mSettings.isEnabledAndMatchLPr(info.provider.info, mFlags, userId)) {
13590                return null;
13591            }
13592            final PackageParser.Provider provider = info.provider;
13593            PackageSetting ps = (PackageSetting) provider.owner.mExtras;
13594            if (ps == null) {
13595                return null;
13596            }
13597            final PackageUserState userState = ps.readUserState(userId);
13598            final boolean matchVisibleToInstantApp =
13599                    (mFlags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
13600            final boolean isInstantApp = (mFlags & PackageManager.MATCH_INSTANT) != 0;
13601            // throw out filters that aren't visible to instant applications
13602            if (matchVisibleToInstantApp
13603                    && !(info.isVisibleToInstantApp() || userState.instantApp)) {
13604                return null;
13605            }
13606            // throw out instant application filters if we're not explicitly requesting them
13607            if (!isInstantApp && userState.instantApp) {
13608                return null;
13609            }
13610            // throw out instant application filters if updates are available; will trigger
13611            // instant application resolution
13612            if (userState.instantApp && ps.isUpdateAvailable()) {
13613                return null;
13614            }
13615            ProviderInfo pi = PackageParser.generateProviderInfo(provider, mFlags,
13616                    userState, userId);
13617            if (pi == null) {
13618                return null;
13619            }
13620            final ResolveInfo res = new ResolveInfo();
13621            res.providerInfo = pi;
13622            if ((mFlags & PackageManager.GET_RESOLVED_FILTER) != 0) {
13623                res.filter = filter;
13624            }
13625            res.priority = info.getPriority();
13626            res.preferredOrder = provider.owner.mPreferredOrder;
13627            res.match = match;
13628            res.isDefault = info.hasDefault;
13629            res.labelRes = info.labelRes;
13630            res.nonLocalizedLabel = info.nonLocalizedLabel;
13631            res.icon = info.icon;
13632            res.system = res.providerInfo.applicationInfo.isSystemApp();
13633            return res;
13634        }
13635
13636        @Override
13637        protected void sortResults(List<ResolveInfo> results) {
13638            Collections.sort(results, mResolvePrioritySorter);
13639        }
13640
13641        @Override
13642        protected void dumpFilter(PrintWriter out, String prefix,
13643                PackageParser.ProviderIntentInfo filter) {
13644            out.print(prefix);
13645            out.print(
13646                    Integer.toHexString(System.identityHashCode(filter.provider)));
13647            out.print(' ');
13648            filter.provider.printComponentShortName(out);
13649            out.print(" filter ");
13650            out.println(Integer.toHexString(System.identityHashCode(filter)));
13651        }
13652
13653        @Override
13654        protected Object filterToLabel(PackageParser.ProviderIntentInfo filter) {
13655            return filter.provider;
13656        }
13657
13658        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
13659            PackageParser.Provider provider = (PackageParser.Provider)label;
13660            out.print(prefix); out.print(
13661                    Integer.toHexString(System.identityHashCode(provider)));
13662                    out.print(' ');
13663                    provider.printComponentShortName(out);
13664            if (count > 1) {
13665                out.print(" ("); out.print(count); out.print(" filters)");
13666            }
13667            out.println();
13668        }
13669
13670        private final ArrayMap<ComponentName, PackageParser.Provider> mProviders
13671                = new ArrayMap<ComponentName, PackageParser.Provider>();
13672        private int mFlags;
13673    }
13674
13675    static final class EphemeralIntentResolver
13676            extends IntentResolver<AuxiliaryResolveInfo, AuxiliaryResolveInfo> {
13677        /**
13678         * The result that has the highest defined order. Ordering applies on a
13679         * per-package basis. Mapping is from package name to Pair of order and
13680         * EphemeralResolveInfo.
13681         * <p>
13682         * NOTE: This is implemented as a field variable for convenience and efficiency.
13683         * By having a field variable, we're able to track filter ordering as soon as
13684         * a non-zero order is defined. Otherwise, multiple loops across the result set
13685         * would be needed to apply ordering. If the intent resolver becomes re-entrant,
13686         * this needs to be contained entirely within {@link #filterResults}.
13687         */
13688        final ArrayMap<String, Pair<Integer, InstantAppResolveInfo>> mOrderResult = new ArrayMap<>();
13689
13690        @Override
13691        protected AuxiliaryResolveInfo[] newArray(int size) {
13692            return new AuxiliaryResolveInfo[size];
13693        }
13694
13695        @Override
13696        protected boolean isPackageForFilter(String packageName, AuxiliaryResolveInfo responseObj) {
13697            return true;
13698        }
13699
13700        @Override
13701        protected AuxiliaryResolveInfo newResult(AuxiliaryResolveInfo responseObj, int match,
13702                int userId) {
13703            if (!sUserManager.exists(userId)) {
13704                return null;
13705            }
13706            final String packageName = responseObj.resolveInfo.getPackageName();
13707            final Integer order = responseObj.getOrder();
13708            final Pair<Integer, InstantAppResolveInfo> lastOrderResult =
13709                    mOrderResult.get(packageName);
13710            // ordering is enabled and this item's order isn't high enough
13711            if (lastOrderResult != null && lastOrderResult.first >= order) {
13712                return null;
13713            }
13714            final InstantAppResolveInfo res = responseObj.resolveInfo;
13715            if (order > 0) {
13716                // non-zero order, enable ordering
13717                mOrderResult.put(packageName, new Pair<>(order, res));
13718            }
13719            return responseObj;
13720        }
13721
13722        @Override
13723        protected void filterResults(List<AuxiliaryResolveInfo> results) {
13724            // only do work if ordering is enabled [most of the time it won't be]
13725            if (mOrderResult.size() == 0) {
13726                return;
13727            }
13728            int resultSize = results.size();
13729            for (int i = 0; i < resultSize; i++) {
13730                final InstantAppResolveInfo info = results.get(i).resolveInfo;
13731                final String packageName = info.getPackageName();
13732                final Pair<Integer, InstantAppResolveInfo> savedInfo = mOrderResult.get(packageName);
13733                if (savedInfo == null) {
13734                    // package doesn't having ordering
13735                    continue;
13736                }
13737                if (savedInfo.second == info) {
13738                    // circled back to the highest ordered item; remove from order list
13739                    mOrderResult.remove(savedInfo);
13740                    if (mOrderResult.size() == 0) {
13741                        // no more ordered items
13742                        break;
13743                    }
13744                    continue;
13745                }
13746                // item has a worse order, remove it from the result list
13747                results.remove(i);
13748                resultSize--;
13749                i--;
13750            }
13751        }
13752    }
13753
13754    private static final Comparator<ResolveInfo> mResolvePrioritySorter =
13755            new Comparator<ResolveInfo>() {
13756        public int compare(ResolveInfo r1, ResolveInfo r2) {
13757            int v1 = r1.priority;
13758            int v2 = r2.priority;
13759            //System.out.println("Comparing: q1=" + q1 + " q2=" + q2);
13760            if (v1 != v2) {
13761                return (v1 > v2) ? -1 : 1;
13762            }
13763            v1 = r1.preferredOrder;
13764            v2 = r2.preferredOrder;
13765            if (v1 != v2) {
13766                return (v1 > v2) ? -1 : 1;
13767            }
13768            if (r1.isDefault != r2.isDefault) {
13769                return r1.isDefault ? -1 : 1;
13770            }
13771            v1 = r1.match;
13772            v2 = r2.match;
13773            //System.out.println("Comparing: m1=" + m1 + " m2=" + m2);
13774            if (v1 != v2) {
13775                return (v1 > v2) ? -1 : 1;
13776            }
13777            if (r1.system != r2.system) {
13778                return r1.system ? -1 : 1;
13779            }
13780            if (r1.activityInfo != null) {
13781                return r1.activityInfo.packageName.compareTo(r2.activityInfo.packageName);
13782            }
13783            if (r1.serviceInfo != null) {
13784                return r1.serviceInfo.packageName.compareTo(r2.serviceInfo.packageName);
13785            }
13786            if (r1.providerInfo != null) {
13787                return r1.providerInfo.packageName.compareTo(r2.providerInfo.packageName);
13788            }
13789            return 0;
13790        }
13791    };
13792
13793    private static final Comparator<ProviderInfo> mProviderInitOrderSorter =
13794            new Comparator<ProviderInfo>() {
13795        public int compare(ProviderInfo p1, ProviderInfo p2) {
13796            final int v1 = p1.initOrder;
13797            final int v2 = p2.initOrder;
13798            return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0);
13799        }
13800    };
13801
13802    public void sendPackageBroadcast(final String action, final String pkg, final Bundle extras,
13803            final int flags, final String targetPkg, final IIntentReceiver finishedReceiver,
13804            final int[] userIds) {
13805        mHandler.post(new Runnable() {
13806            @Override
13807            public void run() {
13808                try {
13809                    final IActivityManager am = ActivityManager.getService();
13810                    if (am == null) return;
13811                    final int[] resolvedUserIds;
13812                    if (userIds == null) {
13813                        resolvedUserIds = am.getRunningUserIds();
13814                    } else {
13815                        resolvedUserIds = userIds;
13816                    }
13817                    for (int id : resolvedUserIds) {
13818                        final Intent intent = new Intent(action,
13819                                pkg != null ? Uri.fromParts(PACKAGE_SCHEME, pkg, null) : null);
13820                        if (extras != null) {
13821                            intent.putExtras(extras);
13822                        }
13823                        if (targetPkg != null) {
13824                            intent.setPackage(targetPkg);
13825                        }
13826                        // Modify the UID when posting to other users
13827                        int uid = intent.getIntExtra(Intent.EXTRA_UID, -1);
13828                        if (uid > 0 && UserHandle.getUserId(uid) != id) {
13829                            uid = UserHandle.getUid(id, UserHandle.getAppId(uid));
13830                            intent.putExtra(Intent.EXTRA_UID, uid);
13831                        }
13832                        intent.putExtra(Intent.EXTRA_USER_HANDLE, id);
13833                        intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT | flags);
13834                        if (DEBUG_BROADCASTS) {
13835                            RuntimeException here = new RuntimeException("here");
13836                            here.fillInStackTrace();
13837                            Slog.d(TAG, "Sending to user " + id + ": "
13838                                    + intent.toShortString(false, true, false, false)
13839                                    + " " + intent.getExtras(), here);
13840                        }
13841                        am.broadcastIntent(null, intent, null, finishedReceiver,
13842                                0, null, null, null, android.app.AppOpsManager.OP_NONE,
13843                                null, finishedReceiver != null, false, id);
13844                    }
13845                } catch (RemoteException ex) {
13846                }
13847            }
13848        });
13849    }
13850
13851    /**
13852     * Check if the external storage media is available. This is true if there
13853     * is a mounted external storage medium or if the external storage is
13854     * emulated.
13855     */
13856    private boolean isExternalMediaAvailable() {
13857        return mMediaMounted || Environment.isExternalStorageEmulated();
13858    }
13859
13860    @Override
13861    public PackageCleanItem nextPackageToClean(PackageCleanItem lastPackage) {
13862        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
13863            return null;
13864        }
13865        // writer
13866        synchronized (mPackages) {
13867            if (!isExternalMediaAvailable()) {
13868                // If the external storage is no longer mounted at this point,
13869                // the caller may not have been able to delete all of this
13870                // packages files and can not delete any more.  Bail.
13871                return null;
13872            }
13873            final ArrayList<PackageCleanItem> pkgs = mSettings.mPackagesToBeCleaned;
13874            if (lastPackage != null) {
13875                pkgs.remove(lastPackage);
13876            }
13877            if (pkgs.size() > 0) {
13878                return pkgs.get(0);
13879            }
13880        }
13881        return null;
13882    }
13883
13884    void schedulePackageCleaning(String packageName, int userId, boolean andCode) {
13885        final Message msg = mHandler.obtainMessage(START_CLEANING_PACKAGE,
13886                userId, andCode ? 1 : 0, packageName);
13887        if (mSystemReady) {
13888            msg.sendToTarget();
13889        } else {
13890            if (mPostSystemReadyMessages == null) {
13891                mPostSystemReadyMessages = new ArrayList<>();
13892            }
13893            mPostSystemReadyMessages.add(msg);
13894        }
13895    }
13896
13897    void startCleaningPackages() {
13898        // reader
13899        if (!isExternalMediaAvailable()) {
13900            return;
13901        }
13902        synchronized (mPackages) {
13903            if (mSettings.mPackagesToBeCleaned.isEmpty()) {
13904                return;
13905            }
13906        }
13907        Intent intent = new Intent(PackageManager.ACTION_CLEAN_EXTERNAL_STORAGE);
13908        intent.setComponent(DEFAULT_CONTAINER_COMPONENT);
13909        IActivityManager am = ActivityManager.getService();
13910        if (am != null) {
13911            int dcsUid = -1;
13912            synchronized (mPackages) {
13913                if (!mDefaultContainerWhitelisted) {
13914                    mDefaultContainerWhitelisted = true;
13915                    PackageSetting ps = mSettings.mPackages.get(DEFAULT_CONTAINER_PACKAGE);
13916                    dcsUid = UserHandle.getUid(UserHandle.USER_SYSTEM, ps.appId);
13917                }
13918            }
13919            try {
13920                if (dcsUid > 0) {
13921                    am.backgroundWhitelistUid(dcsUid);
13922                }
13923                am.startService(null, intent, null, false, mContext.getOpPackageName(),
13924                        UserHandle.USER_SYSTEM);
13925            } catch (RemoteException e) {
13926            }
13927        }
13928    }
13929
13930    @Override
13931    public void installPackageAsUser(String originPath, IPackageInstallObserver2 observer,
13932            int installFlags, String installerPackageName, int userId) {
13933        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, null);
13934
13935        final int callingUid = Binder.getCallingUid();
13936        enforceCrossUserPermission(callingUid, userId,
13937                true /* requireFullPermission */, true /* checkShell */, "installPackageAsUser");
13938
13939        if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) {
13940            try {
13941                if (observer != null) {
13942                    observer.onPackageInstalled("", INSTALL_FAILED_USER_RESTRICTED, null, null);
13943                }
13944            } catch (RemoteException re) {
13945            }
13946            return;
13947        }
13948
13949        if ((callingUid == Process.SHELL_UID) || (callingUid == Process.ROOT_UID)) {
13950            installFlags |= PackageManager.INSTALL_FROM_ADB;
13951
13952        } else {
13953            // Caller holds INSTALL_PACKAGES permission, so we're less strict
13954            // about installerPackageName.
13955
13956            installFlags &= ~PackageManager.INSTALL_FROM_ADB;
13957            installFlags &= ~PackageManager.INSTALL_ALL_USERS;
13958        }
13959
13960        UserHandle user;
13961        if ((installFlags & PackageManager.INSTALL_ALL_USERS) != 0) {
13962            user = UserHandle.ALL;
13963        } else {
13964            user = new UserHandle(userId);
13965        }
13966
13967        // Only system components can circumvent runtime permissions when installing.
13968        if ((installFlags & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0
13969                && mContext.checkCallingOrSelfPermission(Manifest.permission
13970                .INSTALL_GRANT_RUNTIME_PERMISSIONS) == PackageManager.PERMISSION_DENIED) {
13971            throw new SecurityException("You need the "
13972                    + "android.permission.INSTALL_GRANT_RUNTIME_PERMISSIONS permission "
13973                    + "to use the PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS flag");
13974        }
13975
13976        if ((installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0
13977                || (installFlags & PackageManager.INSTALL_EXTERNAL) != 0) {
13978            throw new IllegalArgumentException(
13979                    "New installs into ASEC containers no longer supported");
13980        }
13981
13982        final File originFile = new File(originPath);
13983        final OriginInfo origin = OriginInfo.fromUntrustedFile(originFile);
13984
13985        final Message msg = mHandler.obtainMessage(INIT_COPY);
13986        final VerificationInfo verificationInfo = new VerificationInfo(
13987                null /*originatingUri*/, null /*referrer*/, -1 /*originatingUid*/, callingUid);
13988        final InstallParams params = new InstallParams(origin, null /*moveInfo*/, observer,
13989                installFlags, installerPackageName, null /*volumeUuid*/, verificationInfo, user,
13990                null /*packageAbiOverride*/, null /*grantedPermissions*/,
13991                null /*certificates*/, PackageManager.INSTALL_REASON_UNKNOWN);
13992        params.setTraceMethod("installAsUser").setTraceCookie(System.identityHashCode(params));
13993        msg.obj = params;
13994
13995        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "installAsUser",
13996                System.identityHashCode(msg.obj));
13997        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
13998                System.identityHashCode(msg.obj));
13999
14000        mHandler.sendMessage(msg);
14001    }
14002
14003
14004    /**
14005     * Ensure that the install reason matches what we know about the package installer (e.g. whether
14006     * it is acting on behalf on an enterprise or the user).
14007     *
14008     * Note that the ordering of the conditionals in this method is important. The checks we perform
14009     * are as follows, in this order:
14010     *
14011     * 1) If the install is being performed by a system app, we can trust the app to have set the
14012     *    install reason correctly. Thus, we pass through the install reason unchanged, no matter
14013     *    what it is.
14014     * 2) If the install is being performed by a device or profile owner app, the install reason
14015     *    should be enterprise policy. However, we cannot be sure that the device or profile owner
14016     *    set the install reason correctly. If the app targets an older SDK version where install
14017     *    reasons did not exist yet, or if the app author simply forgot, the install reason may be
14018     *    unset or wrong. Thus, we force the install reason to be enterprise policy.
14019     * 3) In all other cases, the install is being performed by a regular app that is neither part
14020     *    of the system nor a device or profile owner. We have no reason to believe that this app is
14021     *    acting on behalf of the enterprise admin. Thus, we check whether the install reason was
14022     *    set to enterprise policy and if so, change it to unknown instead.
14023     */
14024    private int fixUpInstallReason(String installerPackageName, int installerUid,
14025            int installReason) {
14026        if (checkUidPermission(android.Manifest.permission.INSTALL_PACKAGES, installerUid)
14027                == PERMISSION_GRANTED) {
14028            // If the install is being performed by a system app, we trust that app to have set the
14029            // install reason correctly.
14030            return installReason;
14031        }
14032
14033        final IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface(
14034            ServiceManager.getService(Context.DEVICE_POLICY_SERVICE));
14035        if (dpm != null) {
14036            ComponentName owner = null;
14037            try {
14038                owner = dpm.getDeviceOwnerComponent(true /* callingUserOnly */);
14039                if (owner == null) {
14040                    owner = dpm.getProfileOwner(UserHandle.getUserId(installerUid));
14041                }
14042            } catch (RemoteException e) {
14043            }
14044            if (owner != null && owner.getPackageName().equals(installerPackageName)) {
14045                // If the install is being performed by a device or profile owner, the install
14046                // reason should be enterprise policy.
14047                return PackageManager.INSTALL_REASON_POLICY;
14048            }
14049        }
14050
14051        if (installReason == PackageManager.INSTALL_REASON_POLICY) {
14052            // If the install is being performed by a regular app (i.e. neither system app nor
14053            // device or profile owner), we have no reason to believe that the app is acting on
14054            // behalf of an enterprise. If the app set the install reason to enterprise policy,
14055            // change it to unknown instead.
14056            return PackageManager.INSTALL_REASON_UNKNOWN;
14057        }
14058
14059        // If the install is being performed by a regular app and the install reason was set to any
14060        // value but enterprise policy, leave the install reason unchanged.
14061        return installReason;
14062    }
14063
14064    void installStage(String packageName, File stagedDir, String stagedCid,
14065            IPackageInstallObserver2 observer, PackageInstaller.SessionParams sessionParams,
14066            String installerPackageName, int installerUid, UserHandle user,
14067            Certificate[][] certificates) {
14068        if (DEBUG_EPHEMERAL) {
14069            if ((sessionParams.installFlags & PackageManager.INSTALL_INSTANT_APP) != 0) {
14070                Slog.d(TAG, "Ephemeral install of " + packageName);
14071            }
14072        }
14073        final VerificationInfo verificationInfo = new VerificationInfo(
14074                sessionParams.originatingUri, sessionParams.referrerUri,
14075                sessionParams.originatingUid, installerUid);
14076
14077        final OriginInfo origin;
14078        if (stagedDir != null) {
14079            origin = OriginInfo.fromStagedFile(stagedDir);
14080        } else {
14081            origin = OriginInfo.fromStagedContainer(stagedCid);
14082        }
14083
14084        final Message msg = mHandler.obtainMessage(INIT_COPY);
14085        final int installReason = fixUpInstallReason(installerPackageName, installerUid,
14086                sessionParams.installReason);
14087        final InstallParams params = new InstallParams(origin, null, observer,
14088                sessionParams.installFlags, installerPackageName, sessionParams.volumeUuid,
14089                verificationInfo, user, sessionParams.abiOverride,
14090                sessionParams.grantedRuntimePermissions, certificates, installReason);
14091        params.setTraceMethod("installStage").setTraceCookie(System.identityHashCode(params));
14092        msg.obj = params;
14093
14094        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "installStage",
14095                System.identityHashCode(msg.obj));
14096        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
14097                System.identityHashCode(msg.obj));
14098
14099        mHandler.sendMessage(msg);
14100    }
14101
14102    private void sendPackageAddedForUser(String packageName, PackageSetting pkgSetting,
14103            int userId) {
14104        final boolean isSystem = isSystemApp(pkgSetting) || isUpdatedSystemApp(pkgSetting);
14105        sendPackageAddedForNewUsers(packageName, isSystem, pkgSetting.appId, userId);
14106
14107        // Send a session commit broadcast
14108        final PackageInstaller.SessionInfo info = new PackageInstaller.SessionInfo();
14109        info.installReason = pkgSetting.getInstallReason(userId);
14110        info.appPackageName = packageName;
14111        sendSessionCommitBroadcast(info, userId);
14112    }
14113
14114    public void sendPackageAddedForNewUsers(String packageName, boolean isSystem, int appId, int... userIds) {
14115        if (ArrayUtils.isEmpty(userIds)) {
14116            return;
14117        }
14118        Bundle extras = new Bundle(1);
14119        // Set to UID of the first user, EXTRA_UID is automatically updated in sendPackageBroadcast
14120        extras.putInt(Intent.EXTRA_UID, UserHandle.getUid(userIds[0], appId));
14121
14122        sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
14123                packageName, extras, 0, null, null, userIds);
14124        if (isSystem) {
14125            mHandler.post(() -> {
14126                        for (int userId : userIds) {
14127                            sendBootCompletedBroadcastToSystemApp(packageName, userId);
14128                        }
14129                    }
14130            );
14131        }
14132    }
14133
14134    /**
14135     * The just-installed/enabled app is bundled on the system, so presumed to be able to run
14136     * automatically without needing an explicit launch.
14137     * Send it a LOCKED_BOOT_COMPLETED/BOOT_COMPLETED if it would ordinarily have gotten ones.
14138     */
14139    private void sendBootCompletedBroadcastToSystemApp(String packageName, int userId) {
14140        // If user is not running, the app didn't miss any broadcast
14141        if (!mUserManagerInternal.isUserRunning(userId)) {
14142            return;
14143        }
14144        final IActivityManager am = ActivityManager.getService();
14145        try {
14146            // Deliver LOCKED_BOOT_COMPLETED first
14147            Intent lockedBcIntent = new Intent(Intent.ACTION_LOCKED_BOOT_COMPLETED)
14148                    .setPackage(packageName);
14149            final String[] requiredPermissions = {Manifest.permission.RECEIVE_BOOT_COMPLETED};
14150            am.broadcastIntent(null, lockedBcIntent, null, null, 0, null, null, requiredPermissions,
14151                    android.app.AppOpsManager.OP_NONE, null, false, false, userId);
14152
14153            // Deliver BOOT_COMPLETED only if user is unlocked
14154            if (mUserManagerInternal.isUserUnlockingOrUnlocked(userId)) {
14155                Intent bcIntent = new Intent(Intent.ACTION_BOOT_COMPLETED).setPackage(packageName);
14156                am.broadcastIntent(null, bcIntent, null, null, 0, null, null, requiredPermissions,
14157                        android.app.AppOpsManager.OP_NONE, null, false, false, userId);
14158            }
14159        } catch (RemoteException e) {
14160            throw e.rethrowFromSystemServer();
14161        }
14162    }
14163
14164    @Override
14165    public boolean setApplicationHiddenSettingAsUser(String packageName, boolean hidden,
14166            int userId) {
14167        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
14168        PackageSetting pkgSetting;
14169        final int uid = Binder.getCallingUid();
14170        enforceCrossUserPermission(uid, userId,
14171                true /* requireFullPermission */, true /* checkShell */,
14172                "setApplicationHiddenSetting for user " + userId);
14173
14174        if (hidden && isPackageDeviceAdmin(packageName, userId)) {
14175            Slog.w(TAG, "Not hiding package " + packageName + ": has active device admin");
14176            return false;
14177        }
14178
14179        long callingId = Binder.clearCallingIdentity();
14180        try {
14181            boolean sendAdded = false;
14182            boolean sendRemoved = false;
14183            // writer
14184            synchronized (mPackages) {
14185                pkgSetting = mSettings.mPackages.get(packageName);
14186                if (pkgSetting == null) {
14187                    return false;
14188                }
14189                // Do not allow "android" is being disabled
14190                if ("android".equals(packageName)) {
14191                    Slog.w(TAG, "Cannot hide package: android");
14192                    return false;
14193                }
14194                // Cannot hide static shared libs as they are considered
14195                // a part of the using app (emulating static linking). Also
14196                // static libs are installed always on internal storage.
14197                PackageParser.Package pkg = mPackages.get(packageName);
14198                if (pkg != null && pkg.staticSharedLibName != null) {
14199                    Slog.w(TAG, "Cannot hide package: " + packageName
14200                            + " providing static shared library: "
14201                            + pkg.staticSharedLibName);
14202                    return false;
14203                }
14204                // Only allow protected packages to hide themselves.
14205                if (hidden && !UserHandle.isSameApp(uid, pkgSetting.appId)
14206                        && mProtectedPackages.isPackageStateProtected(userId, packageName)) {
14207                    Slog.w(TAG, "Not hiding protected package: " + packageName);
14208                    return false;
14209                }
14210
14211                if (pkgSetting.getHidden(userId) != hidden) {
14212                    pkgSetting.setHidden(hidden, userId);
14213                    mSettings.writePackageRestrictionsLPr(userId);
14214                    if (hidden) {
14215                        sendRemoved = true;
14216                    } else {
14217                        sendAdded = true;
14218                    }
14219                }
14220            }
14221            if (sendAdded) {
14222                sendPackageAddedForUser(packageName, pkgSetting, userId);
14223                return true;
14224            }
14225            if (sendRemoved) {
14226                killApplication(packageName, UserHandle.getUid(userId, pkgSetting.appId),
14227                        "hiding pkg");
14228                sendApplicationHiddenForUser(packageName, pkgSetting, userId);
14229                return true;
14230            }
14231        } finally {
14232            Binder.restoreCallingIdentity(callingId);
14233        }
14234        return false;
14235    }
14236
14237    private void sendApplicationHiddenForUser(String packageName, PackageSetting pkgSetting,
14238            int userId) {
14239        final PackageRemovedInfo info = new PackageRemovedInfo(this);
14240        info.removedPackage = packageName;
14241        info.installerPackageName = pkgSetting.installerPackageName;
14242        info.removedUsers = new int[] {userId};
14243        info.broadcastUsers = new int[] {userId};
14244        info.uid = UserHandle.getUid(userId, pkgSetting.appId);
14245        info.sendPackageRemovedBroadcasts(true /*killApp*/);
14246    }
14247
14248    private void sendPackagesSuspendedForUser(String[] pkgList, int userId, boolean suspended) {
14249        if (pkgList.length > 0) {
14250            Bundle extras = new Bundle(1);
14251            extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList);
14252
14253            sendPackageBroadcast(
14254                    suspended ? Intent.ACTION_PACKAGES_SUSPENDED
14255                            : Intent.ACTION_PACKAGES_UNSUSPENDED,
14256                    null, extras, Intent.FLAG_RECEIVER_REGISTERED_ONLY, null, null,
14257                    new int[] {userId});
14258        }
14259    }
14260
14261    /**
14262     * Returns true if application is not found or there was an error. Otherwise it returns
14263     * the hidden state of the package for the given user.
14264     */
14265    @Override
14266    public boolean getApplicationHiddenSettingAsUser(String packageName, int userId) {
14267        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
14268        enforceCrossUserPermission(Binder.getCallingUid(), userId,
14269                true /* requireFullPermission */, false /* checkShell */,
14270                "getApplicationHidden for user " + userId);
14271        PackageSetting pkgSetting;
14272        long callingId = Binder.clearCallingIdentity();
14273        try {
14274            // writer
14275            synchronized (mPackages) {
14276                pkgSetting = mSettings.mPackages.get(packageName);
14277                if (pkgSetting == null) {
14278                    return true;
14279                }
14280                return pkgSetting.getHidden(userId);
14281            }
14282        } finally {
14283            Binder.restoreCallingIdentity(callingId);
14284        }
14285    }
14286
14287    /**
14288     * @hide
14289     */
14290    @Override
14291    public int installExistingPackageAsUser(String packageName, int userId, int installFlags,
14292            int installReason) {
14293        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES,
14294                null);
14295        PackageSetting pkgSetting;
14296        final int uid = Binder.getCallingUid();
14297        enforceCrossUserPermission(uid, userId,
14298                true /* requireFullPermission */, true /* checkShell */,
14299                "installExistingPackage for user " + userId);
14300        if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) {
14301            return PackageManager.INSTALL_FAILED_USER_RESTRICTED;
14302        }
14303
14304        long callingId = Binder.clearCallingIdentity();
14305        try {
14306            boolean installed = false;
14307            final boolean instantApp =
14308                    (installFlags & PackageManager.INSTALL_INSTANT_APP) != 0;
14309            final boolean fullApp =
14310                    (installFlags & PackageManager.INSTALL_FULL_APP) != 0;
14311
14312            // writer
14313            synchronized (mPackages) {
14314                pkgSetting = mSettings.mPackages.get(packageName);
14315                if (pkgSetting == null) {
14316                    return PackageManager.INSTALL_FAILED_INVALID_URI;
14317                }
14318                if (!pkgSetting.getInstalled(userId)) {
14319                    pkgSetting.setInstalled(true, userId);
14320                    pkgSetting.setHidden(false, userId);
14321                    pkgSetting.setInstallReason(installReason, userId);
14322                    mSettings.writePackageRestrictionsLPr(userId);
14323                    mSettings.writeKernelMappingLPr(pkgSetting);
14324                    installed = true;
14325                } else if (fullApp && pkgSetting.getInstantApp(userId)) {
14326                    // upgrade app from instant to full; we don't allow app downgrade
14327                    installed = true;
14328                }
14329                setInstantAppForUser(pkgSetting, userId, instantApp, fullApp);
14330            }
14331
14332            if (installed) {
14333                if (pkgSetting.pkg != null) {
14334                    synchronized (mInstallLock) {
14335                        // We don't need to freeze for a brand new install
14336                        prepareAppDataAfterInstallLIF(pkgSetting.pkg);
14337                    }
14338                }
14339                sendPackageAddedForUser(packageName, pkgSetting, userId);
14340                synchronized (mPackages) {
14341                    updateSequenceNumberLP(packageName, new int[]{ userId });
14342                }
14343            }
14344        } finally {
14345            Binder.restoreCallingIdentity(callingId);
14346        }
14347
14348        return PackageManager.INSTALL_SUCCEEDED;
14349    }
14350
14351    void setInstantAppForUser(PackageSetting pkgSetting, int userId,
14352            boolean instantApp, boolean fullApp) {
14353        // no state specified; do nothing
14354        if (!instantApp && !fullApp) {
14355            return;
14356        }
14357        if (userId != UserHandle.USER_ALL) {
14358            if (instantApp && !pkgSetting.getInstantApp(userId)) {
14359                pkgSetting.setInstantApp(true /*instantApp*/, userId);
14360            } else if (fullApp && pkgSetting.getInstantApp(userId)) {
14361                pkgSetting.setInstantApp(false /*instantApp*/, userId);
14362            }
14363        } else {
14364            for (int currentUserId : sUserManager.getUserIds()) {
14365                if (instantApp && !pkgSetting.getInstantApp(currentUserId)) {
14366                    pkgSetting.setInstantApp(true /*instantApp*/, currentUserId);
14367                } else if (fullApp && pkgSetting.getInstantApp(currentUserId)) {
14368                    pkgSetting.setInstantApp(false /*instantApp*/, currentUserId);
14369                }
14370            }
14371        }
14372    }
14373
14374    boolean isUserRestricted(int userId, String restrictionKey) {
14375        Bundle restrictions = sUserManager.getUserRestrictions(userId);
14376        if (restrictions.getBoolean(restrictionKey, false)) {
14377            Log.w(TAG, "User is restricted: " + restrictionKey);
14378            return true;
14379        }
14380        return false;
14381    }
14382
14383    @Override
14384    public String[] setPackagesSuspendedAsUser(String[] packageNames, boolean suspended,
14385            int userId) {
14386        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
14387        enforceCrossUserPermission(Binder.getCallingUid(), userId,
14388                true /* requireFullPermission */, true /* checkShell */,
14389                "setPackagesSuspended for user " + userId);
14390
14391        if (ArrayUtils.isEmpty(packageNames)) {
14392            return packageNames;
14393        }
14394
14395        // List of package names for whom the suspended state has changed.
14396        List<String> changedPackages = new ArrayList<>(packageNames.length);
14397        // List of package names for whom the suspended state is not set as requested in this
14398        // method.
14399        List<String> unactionedPackages = new ArrayList<>(packageNames.length);
14400        long callingId = Binder.clearCallingIdentity();
14401        try {
14402            for (int i = 0; i < packageNames.length; i++) {
14403                String packageName = packageNames[i];
14404                boolean changed = false;
14405                final int appId;
14406                synchronized (mPackages) {
14407                    final PackageSetting pkgSetting = mSettings.mPackages.get(packageName);
14408                    if (pkgSetting == null) {
14409                        Slog.w(TAG, "Could not find package setting for package \"" + packageName
14410                                + "\". Skipping suspending/un-suspending.");
14411                        unactionedPackages.add(packageName);
14412                        continue;
14413                    }
14414                    appId = pkgSetting.appId;
14415                    if (pkgSetting.getSuspended(userId) != suspended) {
14416                        if (!canSuspendPackageForUserLocked(packageName, userId)) {
14417                            unactionedPackages.add(packageName);
14418                            continue;
14419                        }
14420                        pkgSetting.setSuspended(suspended, userId);
14421                        mSettings.writePackageRestrictionsLPr(userId);
14422                        changed = true;
14423                        changedPackages.add(packageName);
14424                    }
14425                }
14426
14427                if (changed && suspended) {
14428                    killApplication(packageName, UserHandle.getUid(userId, appId),
14429                            "suspending package");
14430                }
14431            }
14432        } finally {
14433            Binder.restoreCallingIdentity(callingId);
14434        }
14435
14436        if (!changedPackages.isEmpty()) {
14437            sendPackagesSuspendedForUser(changedPackages.toArray(
14438                    new String[changedPackages.size()]), userId, suspended);
14439        }
14440
14441        return unactionedPackages.toArray(new String[unactionedPackages.size()]);
14442    }
14443
14444    @Override
14445    public boolean isPackageSuspendedForUser(String packageName, int userId) {
14446        final int callingUid = Binder.getCallingUid();
14447        enforceCrossUserPermission(callingUid, userId,
14448                true /* requireFullPermission */, false /* checkShell */,
14449                "isPackageSuspendedForUser for user " + userId);
14450        synchronized (mPackages) {
14451            final PackageSetting ps = mSettings.mPackages.get(packageName);
14452            if (ps == null || filterAppAccessLPr(ps, callingUid, userId)) {
14453                throw new IllegalArgumentException("Unknown target package: " + packageName);
14454            }
14455            return ps.getSuspended(userId);
14456        }
14457    }
14458
14459    private boolean canSuspendPackageForUserLocked(String packageName, int userId) {
14460        if (isPackageDeviceAdmin(packageName, userId)) {
14461            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
14462                    + "\": has an active device admin");
14463            return false;
14464        }
14465
14466        String activeLauncherPackageName = getActiveLauncherPackageName(userId);
14467        if (packageName.equals(activeLauncherPackageName)) {
14468            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
14469                    + "\": contains the active launcher");
14470            return false;
14471        }
14472
14473        if (packageName.equals(mRequiredInstallerPackage)) {
14474            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
14475                    + "\": required for package installation");
14476            return false;
14477        }
14478
14479        if (packageName.equals(mRequiredUninstallerPackage)) {
14480            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
14481                    + "\": required for package uninstallation");
14482            return false;
14483        }
14484
14485        if (packageName.equals(mRequiredVerifierPackage)) {
14486            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
14487                    + "\": required for package verification");
14488            return false;
14489        }
14490
14491        if (packageName.equals(getDefaultDialerPackageName(userId))) {
14492            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
14493                    + "\": is the default dialer");
14494            return false;
14495        }
14496
14497        if (mProtectedPackages.isPackageStateProtected(userId, packageName)) {
14498            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
14499                    + "\": protected package");
14500            return false;
14501        }
14502
14503        // Cannot suspend static shared libs as they are considered
14504        // a part of the using app (emulating static linking). Also
14505        // static libs are installed always on internal storage.
14506        PackageParser.Package pkg = mPackages.get(packageName);
14507        if (pkg != null && pkg.applicationInfo.isStaticSharedLibrary()) {
14508            Slog.w(TAG, "Cannot suspend package: " + packageName
14509                    + " providing static shared library: "
14510                    + pkg.staticSharedLibName);
14511            return false;
14512        }
14513
14514        return true;
14515    }
14516
14517    private String getActiveLauncherPackageName(int userId) {
14518        Intent intent = new Intent(Intent.ACTION_MAIN);
14519        intent.addCategory(Intent.CATEGORY_HOME);
14520        ResolveInfo resolveInfo = resolveIntent(
14521                intent,
14522                intent.resolveTypeIfNeeded(mContext.getContentResolver()),
14523                PackageManager.MATCH_DEFAULT_ONLY,
14524                userId);
14525
14526        return resolveInfo == null ? null : resolveInfo.activityInfo.packageName;
14527    }
14528
14529    private String getDefaultDialerPackageName(int userId) {
14530        synchronized (mPackages) {
14531            return mSettings.getDefaultDialerPackageNameLPw(userId);
14532        }
14533    }
14534
14535    @Override
14536    public void verifyPendingInstall(int id, int verificationCode) throws RemoteException {
14537        mContext.enforceCallingOrSelfPermission(
14538                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
14539                "Only package verification agents can verify applications");
14540
14541        final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED);
14542        final PackageVerificationResponse response = new PackageVerificationResponse(
14543                verificationCode, Binder.getCallingUid());
14544        msg.arg1 = id;
14545        msg.obj = response;
14546        mHandler.sendMessage(msg);
14547    }
14548
14549    @Override
14550    public void extendVerificationTimeout(int id, int verificationCodeAtTimeout,
14551            long millisecondsToDelay) {
14552        mContext.enforceCallingOrSelfPermission(
14553                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
14554                "Only package verification agents can extend verification timeouts");
14555
14556        final PackageVerificationState state = mPendingVerification.get(id);
14557        final PackageVerificationResponse response = new PackageVerificationResponse(
14558                verificationCodeAtTimeout, Binder.getCallingUid());
14559
14560        if (millisecondsToDelay > PackageManager.MAXIMUM_VERIFICATION_TIMEOUT) {
14561            millisecondsToDelay = PackageManager.MAXIMUM_VERIFICATION_TIMEOUT;
14562        }
14563        if (millisecondsToDelay < 0) {
14564            millisecondsToDelay = 0;
14565        }
14566        if ((verificationCodeAtTimeout != PackageManager.VERIFICATION_ALLOW)
14567                && (verificationCodeAtTimeout != PackageManager.VERIFICATION_REJECT)) {
14568            verificationCodeAtTimeout = PackageManager.VERIFICATION_REJECT;
14569        }
14570
14571        if ((state != null) && !state.timeoutExtended()) {
14572            state.extendTimeout();
14573
14574            final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED);
14575            msg.arg1 = id;
14576            msg.obj = response;
14577            mHandler.sendMessageDelayed(msg, millisecondsToDelay);
14578        }
14579    }
14580
14581    private void broadcastPackageVerified(int verificationId, Uri packageUri,
14582            int verificationCode, UserHandle user) {
14583        final Intent intent = new Intent(Intent.ACTION_PACKAGE_VERIFIED);
14584        intent.setDataAndType(packageUri, PACKAGE_MIME_TYPE);
14585        intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
14586        intent.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId);
14587        intent.putExtra(PackageManager.EXTRA_VERIFICATION_RESULT, verificationCode);
14588
14589        mContext.sendBroadcastAsUser(intent, user,
14590                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT);
14591    }
14592
14593    private ComponentName matchComponentForVerifier(String packageName,
14594            List<ResolveInfo> receivers) {
14595        ActivityInfo targetReceiver = null;
14596
14597        final int NR = receivers.size();
14598        for (int i = 0; i < NR; i++) {
14599            final ResolveInfo info = receivers.get(i);
14600            if (info.activityInfo == null) {
14601                continue;
14602            }
14603
14604            if (packageName.equals(info.activityInfo.packageName)) {
14605                targetReceiver = info.activityInfo;
14606                break;
14607            }
14608        }
14609
14610        if (targetReceiver == null) {
14611            return null;
14612        }
14613
14614        return new ComponentName(targetReceiver.packageName, targetReceiver.name);
14615    }
14616
14617    private List<ComponentName> matchVerifiers(PackageInfoLite pkgInfo,
14618            List<ResolveInfo> receivers, final PackageVerificationState verificationState) {
14619        if (pkgInfo.verifiers.length == 0) {
14620            return null;
14621        }
14622
14623        final int N = pkgInfo.verifiers.length;
14624        final List<ComponentName> sufficientVerifiers = new ArrayList<ComponentName>(N + 1);
14625        for (int i = 0; i < N; i++) {
14626            final VerifierInfo verifierInfo = pkgInfo.verifiers[i];
14627
14628            final ComponentName comp = matchComponentForVerifier(verifierInfo.packageName,
14629                    receivers);
14630            if (comp == null) {
14631                continue;
14632            }
14633
14634            final int verifierUid = getUidForVerifier(verifierInfo);
14635            if (verifierUid == -1) {
14636                continue;
14637            }
14638
14639            if (DEBUG_VERIFY) {
14640                Slog.d(TAG, "Added sufficient verifier " + verifierInfo.packageName
14641                        + " with the correct signature");
14642            }
14643            sufficientVerifiers.add(comp);
14644            verificationState.addSufficientVerifier(verifierUid);
14645        }
14646
14647        return sufficientVerifiers;
14648    }
14649
14650    private int getUidForVerifier(VerifierInfo verifierInfo) {
14651        synchronized (mPackages) {
14652            final PackageParser.Package pkg = mPackages.get(verifierInfo.packageName);
14653            if (pkg == null) {
14654                return -1;
14655            } else if (pkg.mSignatures.length != 1) {
14656                Slog.i(TAG, "Verifier package " + verifierInfo.packageName
14657                        + " has more than one signature; ignoring");
14658                return -1;
14659            }
14660
14661            /*
14662             * If the public key of the package's signature does not match
14663             * our expected public key, then this is a different package and
14664             * we should skip.
14665             */
14666
14667            final byte[] expectedPublicKey;
14668            try {
14669                final Signature verifierSig = pkg.mSignatures[0];
14670                final PublicKey publicKey = verifierSig.getPublicKey();
14671                expectedPublicKey = publicKey.getEncoded();
14672            } catch (CertificateException e) {
14673                return -1;
14674            }
14675
14676            final byte[] actualPublicKey = verifierInfo.publicKey.getEncoded();
14677
14678            if (!Arrays.equals(actualPublicKey, expectedPublicKey)) {
14679                Slog.i(TAG, "Verifier package " + verifierInfo.packageName
14680                        + " does not have the expected public key; ignoring");
14681                return -1;
14682            }
14683
14684            return pkg.applicationInfo.uid;
14685        }
14686    }
14687
14688    @Override
14689    public void finishPackageInstall(int token, boolean didLaunch) {
14690        enforceSystemOrRoot("Only the system is allowed to finish installs");
14691
14692        if (DEBUG_INSTALL) {
14693            Slog.v(TAG, "BM finishing package install for " + token);
14694        }
14695        Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "restore", token);
14696
14697        final Message msg = mHandler.obtainMessage(POST_INSTALL, token, didLaunch ? 1 : 0);
14698        mHandler.sendMessage(msg);
14699    }
14700
14701    /**
14702     * Get the verification agent timeout.  Used for both the APK verifier and the
14703     * intent filter verifier.
14704     *
14705     * @return verification timeout in milliseconds
14706     */
14707    private long getVerificationTimeout() {
14708        return android.provider.Settings.Global.getLong(mContext.getContentResolver(),
14709                android.provider.Settings.Global.PACKAGE_VERIFIER_TIMEOUT,
14710                DEFAULT_VERIFICATION_TIMEOUT);
14711    }
14712
14713    /**
14714     * Get the default verification agent response code.
14715     *
14716     * @return default verification response code
14717     */
14718    private int getDefaultVerificationResponse(UserHandle user) {
14719        if (sUserManager.hasUserRestriction(UserManager.ENSURE_VERIFY_APPS, user.getIdentifier())) {
14720            return PackageManager.VERIFICATION_REJECT;
14721        }
14722        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
14723                android.provider.Settings.Global.PACKAGE_VERIFIER_DEFAULT_RESPONSE,
14724                DEFAULT_VERIFICATION_RESPONSE);
14725    }
14726
14727    /**
14728     * Check whether or not package verification has been enabled.
14729     *
14730     * @return true if verification should be performed
14731     */
14732    private boolean isVerificationEnabled(int userId, int installFlags) {
14733        if (!DEFAULT_VERIFY_ENABLE) {
14734            return false;
14735        }
14736
14737        boolean ensureVerifyAppsEnabled = isUserRestricted(userId, UserManager.ENSURE_VERIFY_APPS);
14738
14739        // Check if installing from ADB
14740        if ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0) {
14741            // Do not run verification in a test harness environment
14742            if (ActivityManager.isRunningInTestHarness()) {
14743                return false;
14744            }
14745            if (ensureVerifyAppsEnabled) {
14746                return true;
14747            }
14748            // Check if the developer does not want package verification for ADB installs
14749            if (android.provider.Settings.Global.getInt(mContext.getContentResolver(),
14750                    android.provider.Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB, 1) == 0) {
14751                return false;
14752            }
14753        }
14754
14755        if (ensureVerifyAppsEnabled) {
14756            return true;
14757        }
14758
14759        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
14760                android.provider.Settings.Global.PACKAGE_VERIFIER_ENABLE, 1) == 1;
14761    }
14762
14763    @Override
14764    public void verifyIntentFilter(int id, int verificationCode, List<String> failedDomains)
14765            throws RemoteException {
14766        mContext.enforceCallingOrSelfPermission(
14767                Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT,
14768                "Only intentfilter verification agents can verify applications");
14769
14770        final Message msg = mHandler.obtainMessage(INTENT_FILTER_VERIFIED);
14771        final IntentFilterVerificationResponse response = new IntentFilterVerificationResponse(
14772                Binder.getCallingUid(), verificationCode, failedDomains);
14773        msg.arg1 = id;
14774        msg.obj = response;
14775        mHandler.sendMessage(msg);
14776    }
14777
14778    @Override
14779    public int getIntentVerificationStatus(String packageName, int userId) {
14780        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
14781            return INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED;
14782        }
14783        synchronized (mPackages) {
14784            return mSettings.getIntentFilterVerificationStatusLPr(packageName, userId);
14785        }
14786    }
14787
14788    @Override
14789    public boolean updateIntentVerificationStatus(String packageName, int status, int userId) {
14790        mContext.enforceCallingOrSelfPermission(
14791                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
14792
14793        boolean result = false;
14794        synchronized (mPackages) {
14795            result = mSettings.updateIntentFilterVerificationStatusLPw(packageName, status, userId);
14796        }
14797        if (result) {
14798            scheduleWritePackageRestrictionsLocked(userId);
14799        }
14800        return result;
14801    }
14802
14803    @Override
14804    public @NonNull ParceledListSlice<IntentFilterVerificationInfo> getIntentFilterVerifications(
14805            String packageName) {
14806        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
14807            return ParceledListSlice.emptyList();
14808        }
14809        synchronized (mPackages) {
14810            return new ParceledListSlice<>(mSettings.getIntentFilterVerificationsLPr(packageName));
14811        }
14812    }
14813
14814    @Override
14815    public @NonNull ParceledListSlice<IntentFilter> getAllIntentFilters(String packageName) {
14816        if (TextUtils.isEmpty(packageName)) {
14817            return ParceledListSlice.emptyList();
14818        }
14819        final int callingUid = Binder.getCallingUid();
14820        final int callingUserId = UserHandle.getUserId(callingUid);
14821        synchronized (mPackages) {
14822            PackageParser.Package pkg = mPackages.get(packageName);
14823            if (pkg == null || pkg.activities == null) {
14824                return ParceledListSlice.emptyList();
14825            }
14826            if (pkg.mExtras == null) {
14827                return ParceledListSlice.emptyList();
14828            }
14829            final PackageSetting ps = (PackageSetting) pkg.mExtras;
14830            if (filterAppAccessLPr(ps, callingUid, callingUserId)) {
14831                return ParceledListSlice.emptyList();
14832            }
14833            final int count = pkg.activities.size();
14834            ArrayList<IntentFilter> result = new ArrayList<>();
14835            for (int n=0; n<count; n++) {
14836                PackageParser.Activity activity = pkg.activities.get(n);
14837                if (activity.intents != null && activity.intents.size() > 0) {
14838                    result.addAll(activity.intents);
14839                }
14840            }
14841            return new ParceledListSlice<>(result);
14842        }
14843    }
14844
14845    @Override
14846    public boolean setDefaultBrowserPackageName(String packageName, int userId) {
14847        mContext.enforceCallingOrSelfPermission(
14848                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
14849
14850        synchronized (mPackages) {
14851            boolean result = mSettings.setDefaultBrowserPackageNameLPw(packageName, userId);
14852            if (packageName != null) {
14853                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultBrowserLPr(
14854                        packageName, userId);
14855            }
14856            return result;
14857        }
14858    }
14859
14860    @Override
14861    public String getDefaultBrowserPackageName(int userId) {
14862        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
14863            return null;
14864        }
14865        synchronized (mPackages) {
14866            return mSettings.getDefaultBrowserPackageNameLPw(userId);
14867        }
14868    }
14869
14870    /**
14871     * Get the "allow unknown sources" setting.
14872     *
14873     * @return the current "allow unknown sources" setting
14874     */
14875    private int getUnknownSourcesSettings() {
14876        return android.provider.Settings.Secure.getInt(mContext.getContentResolver(),
14877                android.provider.Settings.Secure.INSTALL_NON_MARKET_APPS,
14878                -1);
14879    }
14880
14881    @Override
14882    public void setInstallerPackageName(String targetPackage, String installerPackageName) {
14883        final int callingUid = Binder.getCallingUid();
14884        if (getInstantAppPackageName(callingUid) != null) {
14885            return;
14886        }
14887        // writer
14888        synchronized (mPackages) {
14889            PackageSetting targetPackageSetting = mSettings.mPackages.get(targetPackage);
14890            if (targetPackageSetting == null) {
14891                throw new IllegalArgumentException("Unknown target package: " + targetPackage);
14892            }
14893
14894            PackageSetting installerPackageSetting;
14895            if (installerPackageName != null) {
14896                installerPackageSetting = mSettings.mPackages.get(installerPackageName);
14897                if (installerPackageSetting == null) {
14898                    throw new IllegalArgumentException("Unknown installer package: "
14899                            + installerPackageName);
14900                }
14901            } else {
14902                installerPackageSetting = null;
14903            }
14904
14905            Signature[] callerSignature;
14906            Object obj = mSettings.getUserIdLPr(callingUid);
14907            if (obj != null) {
14908                if (obj instanceof SharedUserSetting) {
14909                    callerSignature = ((SharedUserSetting)obj).signatures.mSignatures;
14910                } else if (obj instanceof PackageSetting) {
14911                    callerSignature = ((PackageSetting)obj).signatures.mSignatures;
14912                } else {
14913                    throw new SecurityException("Bad object " + obj + " for uid " + callingUid);
14914                }
14915            } else {
14916                throw new SecurityException("Unknown calling UID: " + callingUid);
14917            }
14918
14919            // Verify: can't set installerPackageName to a package that is
14920            // not signed with the same cert as the caller.
14921            if (installerPackageSetting != null) {
14922                if (compareSignatures(callerSignature,
14923                        installerPackageSetting.signatures.mSignatures)
14924                        != PackageManager.SIGNATURE_MATCH) {
14925                    throw new SecurityException(
14926                            "Caller does not have same cert as new installer package "
14927                            + installerPackageName);
14928                }
14929            }
14930
14931            // Verify: if target already has an installer package, it must
14932            // be signed with the same cert as the caller.
14933            if (targetPackageSetting.installerPackageName != null) {
14934                PackageSetting setting = mSettings.mPackages.get(
14935                        targetPackageSetting.installerPackageName);
14936                // If the currently set package isn't valid, then it's always
14937                // okay to change it.
14938                if (setting != null) {
14939                    if (compareSignatures(callerSignature,
14940                            setting.signatures.mSignatures)
14941                            != PackageManager.SIGNATURE_MATCH) {
14942                        throw new SecurityException(
14943                                "Caller does not have same cert as old installer package "
14944                                + targetPackageSetting.installerPackageName);
14945                    }
14946                }
14947            }
14948
14949            // Okay!
14950            targetPackageSetting.installerPackageName = installerPackageName;
14951            if (installerPackageName != null) {
14952                mSettings.mInstallerPackages.add(installerPackageName);
14953            }
14954            scheduleWriteSettingsLocked();
14955        }
14956    }
14957
14958    @Override
14959    public void setApplicationCategoryHint(String packageName, int categoryHint,
14960            String callerPackageName) {
14961        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
14962            throw new SecurityException("Instant applications don't have access to this method");
14963        }
14964        mContext.getSystemService(AppOpsManager.class).checkPackage(Binder.getCallingUid(),
14965                callerPackageName);
14966        synchronized (mPackages) {
14967            PackageSetting ps = mSettings.mPackages.get(packageName);
14968            if (ps == null) {
14969                throw new IllegalArgumentException("Unknown target package " + packageName);
14970            }
14971
14972            if (!Objects.equals(callerPackageName, ps.installerPackageName)) {
14973                throw new IllegalArgumentException("Calling package " + callerPackageName
14974                        + " is not installer for " + packageName);
14975            }
14976
14977            if (ps.categoryHint != categoryHint) {
14978                ps.categoryHint = categoryHint;
14979                scheduleWriteSettingsLocked();
14980            }
14981        }
14982    }
14983
14984    private void processPendingInstall(final InstallArgs args, final int currentStatus) {
14985        // Queue up an async operation since the package installation may take a little while.
14986        mHandler.post(new Runnable() {
14987            public void run() {
14988                mHandler.removeCallbacks(this);
14989                 // Result object to be returned
14990                PackageInstalledInfo res = new PackageInstalledInfo();
14991                res.setReturnCode(currentStatus);
14992                res.uid = -1;
14993                res.pkg = null;
14994                res.removedInfo = null;
14995                if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
14996                    args.doPreInstall(res.returnCode);
14997                    synchronized (mInstallLock) {
14998                        installPackageTracedLI(args, res);
14999                    }
15000                    args.doPostInstall(res.returnCode, res.uid);
15001                }
15002
15003                // A restore should be performed at this point if (a) the install
15004                // succeeded, (b) the operation is not an update, and (c) the new
15005                // package has not opted out of backup participation.
15006                final boolean update = res.removedInfo != null
15007                        && res.removedInfo.removedPackage != null;
15008                final int flags = (res.pkg == null) ? 0 : res.pkg.applicationInfo.flags;
15009                boolean doRestore = !update
15010                        && ((flags & ApplicationInfo.FLAG_ALLOW_BACKUP) != 0);
15011
15012                // Set up the post-install work request bookkeeping.  This will be used
15013                // and cleaned up by the post-install event handling regardless of whether
15014                // there's a restore pass performed.  Token values are >= 1.
15015                int token;
15016                if (mNextInstallToken < 0) mNextInstallToken = 1;
15017                token = mNextInstallToken++;
15018
15019                PostInstallData data = new PostInstallData(args, res);
15020                mRunningInstalls.put(token, data);
15021                if (DEBUG_INSTALL) Log.v(TAG, "+ starting restore round-trip " + token);
15022
15023                if (res.returnCode == PackageManager.INSTALL_SUCCEEDED && doRestore) {
15024                    // Pass responsibility to the Backup Manager.  It will perform a
15025                    // restore if appropriate, then pass responsibility back to the
15026                    // Package Manager to run the post-install observer callbacks
15027                    // and broadcasts.
15028                    IBackupManager bm = IBackupManager.Stub.asInterface(
15029                            ServiceManager.getService(Context.BACKUP_SERVICE));
15030                    if (bm != null) {
15031                        if (DEBUG_INSTALL) Log.v(TAG, "token " + token
15032                                + " to BM for possible restore");
15033                        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "restore", token);
15034                        try {
15035                            // TODO: http://b/22388012
15036                            if (bm.isBackupServiceActive(UserHandle.USER_SYSTEM)) {
15037                                bm.restoreAtInstall(res.pkg.applicationInfo.packageName, token);
15038                            } else {
15039                                doRestore = false;
15040                            }
15041                        } catch (RemoteException e) {
15042                            // can't happen; the backup manager is local
15043                        } catch (Exception e) {
15044                            Slog.e(TAG, "Exception trying to enqueue restore", e);
15045                            doRestore = false;
15046                        }
15047                    } else {
15048                        Slog.e(TAG, "Backup Manager not found!");
15049                        doRestore = false;
15050                    }
15051                }
15052
15053                if (!doRestore) {
15054                    // No restore possible, or the Backup Manager was mysteriously not
15055                    // available -- just fire the post-install work request directly.
15056                    if (DEBUG_INSTALL) Log.v(TAG, "No restore - queue post-install for " + token);
15057
15058                    Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "postInstall", token);
15059
15060                    Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0);
15061                    mHandler.sendMessage(msg);
15062                }
15063            }
15064        });
15065    }
15066
15067    /**
15068     * Callback from PackageSettings whenever an app is first transitioned out of the
15069     * 'stopped' state.  Normally we just issue the broadcast, but we can't do that if
15070     * the app was "launched" for a restoreAtInstall operation.  Therefore we check
15071     * here whether the app is the target of an ongoing install, and only send the
15072     * broadcast immediately if it is not in that state.  If it *is* undergoing a restore,
15073     * the first-launch broadcast will be sent implicitly on that basis in POST_INSTALL
15074     * handling.
15075     */
15076    void notifyFirstLaunch(final String pkgName, final String installerPackage, final int userId) {
15077        // Serialize this with the rest of the install-process message chain.  In the
15078        // restore-at-install case, this Runnable will necessarily run before the
15079        // POST_INSTALL message is processed, so the contents of mRunningInstalls
15080        // are coherent.  In the non-restore case, the app has already completed install
15081        // and been launched through some other means, so it is not in a problematic
15082        // state for observers to see the FIRST_LAUNCH signal.
15083        mHandler.post(new Runnable() {
15084            @Override
15085            public void run() {
15086                for (int i = 0; i < mRunningInstalls.size(); i++) {
15087                    final PostInstallData data = mRunningInstalls.valueAt(i);
15088                    if (data.res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
15089                        continue;
15090                    }
15091                    if (pkgName.equals(data.res.pkg.applicationInfo.packageName)) {
15092                        // right package; but is it for the right user?
15093                        for (int uIndex = 0; uIndex < data.res.newUsers.length; uIndex++) {
15094                            if (userId == data.res.newUsers[uIndex]) {
15095                                if (DEBUG_BACKUP) {
15096                                    Slog.i(TAG, "Package " + pkgName
15097                                            + " being restored so deferring FIRST_LAUNCH");
15098                                }
15099                                return;
15100                            }
15101                        }
15102                    }
15103                }
15104                // didn't find it, so not being restored
15105                if (DEBUG_BACKUP) {
15106                    Slog.i(TAG, "Package " + pkgName + " sending normal FIRST_LAUNCH");
15107                }
15108                sendFirstLaunchBroadcast(pkgName, installerPackage, new int[] {userId});
15109            }
15110        });
15111    }
15112
15113    private void sendFirstLaunchBroadcast(String pkgName, String installerPkg, int[] userIds) {
15114        sendPackageBroadcast(Intent.ACTION_PACKAGE_FIRST_LAUNCH, pkgName, null, 0,
15115                installerPkg, null, userIds);
15116    }
15117
15118    private abstract class HandlerParams {
15119        private static final int MAX_RETRIES = 4;
15120
15121        /**
15122         * Number of times startCopy() has been attempted and had a non-fatal
15123         * error.
15124         */
15125        private int mRetries = 0;
15126
15127        /** User handle for the user requesting the information or installation. */
15128        private final UserHandle mUser;
15129        String traceMethod;
15130        int traceCookie;
15131
15132        HandlerParams(UserHandle user) {
15133            mUser = user;
15134        }
15135
15136        UserHandle getUser() {
15137            return mUser;
15138        }
15139
15140        HandlerParams setTraceMethod(String traceMethod) {
15141            this.traceMethod = traceMethod;
15142            return this;
15143        }
15144
15145        HandlerParams setTraceCookie(int traceCookie) {
15146            this.traceCookie = traceCookie;
15147            return this;
15148        }
15149
15150        final boolean startCopy() {
15151            boolean res;
15152            try {
15153                if (DEBUG_INSTALL) Slog.i(TAG, "startCopy " + mUser + ": " + this);
15154
15155                if (++mRetries > MAX_RETRIES) {
15156                    Slog.w(TAG, "Failed to invoke remote methods on default container service. Giving up");
15157                    mHandler.sendEmptyMessage(MCS_GIVE_UP);
15158                    handleServiceError();
15159                    return false;
15160                } else {
15161                    handleStartCopy();
15162                    res = true;
15163                }
15164            } catch (RemoteException e) {
15165                if (DEBUG_INSTALL) Slog.i(TAG, "Posting install MCS_RECONNECT");
15166                mHandler.sendEmptyMessage(MCS_RECONNECT);
15167                res = false;
15168            }
15169            handleReturnCode();
15170            return res;
15171        }
15172
15173        final void serviceError() {
15174            if (DEBUG_INSTALL) Slog.i(TAG, "serviceError");
15175            handleServiceError();
15176            handleReturnCode();
15177        }
15178
15179        abstract void handleStartCopy() throws RemoteException;
15180        abstract void handleServiceError();
15181        abstract void handleReturnCode();
15182    }
15183
15184    private static void clearDirectory(IMediaContainerService mcs, File[] paths) {
15185        for (File path : paths) {
15186            try {
15187                mcs.clearDirectory(path.getAbsolutePath());
15188            } catch (RemoteException e) {
15189            }
15190        }
15191    }
15192
15193    static class OriginInfo {
15194        /**
15195         * Location where install is coming from, before it has been
15196         * copied/renamed into place. This could be a single monolithic APK
15197         * file, or a cluster directory. This location may be untrusted.
15198         */
15199        final File file;
15200        final String cid;
15201
15202        /**
15203         * Flag indicating that {@link #file} or {@link #cid} has already been
15204         * staged, meaning downstream users don't need to defensively copy the
15205         * contents.
15206         */
15207        final boolean staged;
15208
15209        /**
15210         * Flag indicating that {@link #file} or {@link #cid} is an already
15211         * installed app that is being moved.
15212         */
15213        final boolean existing;
15214
15215        final String resolvedPath;
15216        final File resolvedFile;
15217
15218        static OriginInfo fromNothing() {
15219            return new OriginInfo(null, null, false, false);
15220        }
15221
15222        static OriginInfo fromUntrustedFile(File file) {
15223            return new OriginInfo(file, null, false, false);
15224        }
15225
15226        static OriginInfo fromExistingFile(File file) {
15227            return new OriginInfo(file, null, false, true);
15228        }
15229
15230        static OriginInfo fromStagedFile(File file) {
15231            return new OriginInfo(file, null, true, false);
15232        }
15233
15234        static OriginInfo fromStagedContainer(String cid) {
15235            return new OriginInfo(null, cid, true, false);
15236        }
15237
15238        private OriginInfo(File file, String cid, boolean staged, boolean existing) {
15239            this.file = file;
15240            this.cid = cid;
15241            this.staged = staged;
15242            this.existing = existing;
15243
15244            if (cid != null) {
15245                resolvedPath = PackageHelper.getSdDir(cid);
15246                resolvedFile = new File(resolvedPath);
15247            } else if (file != null) {
15248                resolvedPath = file.getAbsolutePath();
15249                resolvedFile = file;
15250            } else {
15251                resolvedPath = null;
15252                resolvedFile = null;
15253            }
15254        }
15255    }
15256
15257    static class MoveInfo {
15258        final int moveId;
15259        final String fromUuid;
15260        final String toUuid;
15261        final String packageName;
15262        final String dataAppName;
15263        final int appId;
15264        final String seinfo;
15265        final int targetSdkVersion;
15266
15267        public MoveInfo(int moveId, String fromUuid, String toUuid, String packageName,
15268                String dataAppName, int appId, String seinfo, int targetSdkVersion) {
15269            this.moveId = moveId;
15270            this.fromUuid = fromUuid;
15271            this.toUuid = toUuid;
15272            this.packageName = packageName;
15273            this.dataAppName = dataAppName;
15274            this.appId = appId;
15275            this.seinfo = seinfo;
15276            this.targetSdkVersion = targetSdkVersion;
15277        }
15278    }
15279
15280    static class VerificationInfo {
15281        /** A constant used to indicate that a uid value is not present. */
15282        public static final int NO_UID = -1;
15283
15284        /** URI referencing where the package was downloaded from. */
15285        final Uri originatingUri;
15286
15287        /** HTTP referrer URI associated with the originatingURI. */
15288        final Uri referrer;
15289
15290        /** UID of the application that the install request originated from. */
15291        final int originatingUid;
15292
15293        /** UID of application requesting the install */
15294        final int installerUid;
15295
15296        VerificationInfo(Uri originatingUri, Uri referrer, int originatingUid, int installerUid) {
15297            this.originatingUri = originatingUri;
15298            this.referrer = referrer;
15299            this.originatingUid = originatingUid;
15300            this.installerUid = installerUid;
15301        }
15302    }
15303
15304    class InstallParams extends HandlerParams {
15305        final OriginInfo origin;
15306        final MoveInfo move;
15307        final IPackageInstallObserver2 observer;
15308        int installFlags;
15309        final String installerPackageName;
15310        final String volumeUuid;
15311        private InstallArgs mArgs;
15312        private int mRet;
15313        final String packageAbiOverride;
15314        final String[] grantedRuntimePermissions;
15315        final VerificationInfo verificationInfo;
15316        final Certificate[][] certificates;
15317        final int installReason;
15318
15319        InstallParams(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer,
15320                int installFlags, String installerPackageName, String volumeUuid,
15321                VerificationInfo verificationInfo, UserHandle user, String packageAbiOverride,
15322                String[] grantedPermissions, Certificate[][] certificates, int installReason) {
15323            super(user);
15324            this.origin = origin;
15325            this.move = move;
15326            this.observer = observer;
15327            this.installFlags = installFlags;
15328            this.installerPackageName = installerPackageName;
15329            this.volumeUuid = volumeUuid;
15330            this.verificationInfo = verificationInfo;
15331            this.packageAbiOverride = packageAbiOverride;
15332            this.grantedRuntimePermissions = grantedPermissions;
15333            this.certificates = certificates;
15334            this.installReason = installReason;
15335        }
15336
15337        @Override
15338        public String toString() {
15339            return "InstallParams{" + Integer.toHexString(System.identityHashCode(this))
15340                    + " file=" + origin.file + " cid=" + origin.cid + "}";
15341        }
15342
15343        private int installLocationPolicy(PackageInfoLite pkgLite) {
15344            String packageName = pkgLite.packageName;
15345            int installLocation = pkgLite.installLocation;
15346            boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
15347            // reader
15348            synchronized (mPackages) {
15349                // Currently installed package which the new package is attempting to replace or
15350                // null if no such package is installed.
15351                PackageParser.Package installedPkg = mPackages.get(packageName);
15352                // Package which currently owns the data which the new package will own if installed.
15353                // If an app is unstalled while keeping data (e.g., adb uninstall -k), installedPkg
15354                // will be null whereas dataOwnerPkg will contain information about the package
15355                // which was uninstalled while keeping its data.
15356                PackageParser.Package dataOwnerPkg = installedPkg;
15357                if (dataOwnerPkg  == null) {
15358                    PackageSetting ps = mSettings.mPackages.get(packageName);
15359                    if (ps != null) {
15360                        dataOwnerPkg = ps.pkg;
15361                    }
15362                }
15363
15364                if (dataOwnerPkg != null) {
15365                    // If installed, the package will get access to data left on the device by its
15366                    // predecessor. As a security measure, this is permited only if this is not a
15367                    // version downgrade or if the predecessor package is marked as debuggable and
15368                    // a downgrade is explicitly requested.
15369                    //
15370                    // On debuggable platform builds, downgrades are permitted even for
15371                    // non-debuggable packages to make testing easier. Debuggable platform builds do
15372                    // not offer security guarantees and thus it's OK to disable some security
15373                    // mechanisms to make debugging/testing easier on those builds. However, even on
15374                    // debuggable builds downgrades of packages are permitted only if requested via
15375                    // installFlags. This is because we aim to keep the behavior of debuggable
15376                    // platform builds as close as possible to the behavior of non-debuggable
15377                    // platform builds.
15378                    final boolean downgradeRequested =
15379                            (installFlags & PackageManager.INSTALL_ALLOW_DOWNGRADE) != 0;
15380                    final boolean packageDebuggable =
15381                                (dataOwnerPkg.applicationInfo.flags
15382                                        & ApplicationInfo.FLAG_DEBUGGABLE) != 0;
15383                    final boolean downgradePermitted =
15384                            (downgradeRequested) && ((Build.IS_DEBUGGABLE) || (packageDebuggable));
15385                    if (!downgradePermitted) {
15386                        try {
15387                            checkDowngrade(dataOwnerPkg, pkgLite);
15388                        } catch (PackageManagerException e) {
15389                            Slog.w(TAG, "Downgrade detected: " + e.getMessage());
15390                            return PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE;
15391                        }
15392                    }
15393                }
15394
15395                if (installedPkg != null) {
15396                    if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
15397                        // Check for updated system application.
15398                        if ((installedPkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
15399                            if (onSd) {
15400                                Slog.w(TAG, "Cannot install update to system app on sdcard");
15401                                return PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION;
15402                            }
15403                            return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
15404                        } else {
15405                            if (onSd) {
15406                                // Install flag overrides everything.
15407                                return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
15408                            }
15409                            // If current upgrade specifies particular preference
15410                            if (installLocation == PackageInfo.INSTALL_LOCATION_INTERNAL_ONLY) {
15411                                // Application explicitly specified internal.
15412                                return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
15413                            } else if (installLocation == PackageInfo.INSTALL_LOCATION_PREFER_EXTERNAL) {
15414                                // App explictly prefers external. Let policy decide
15415                            } else {
15416                                // Prefer previous location
15417                                if (isExternal(installedPkg)) {
15418                                    return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
15419                                }
15420                                return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
15421                            }
15422                        }
15423                    } else {
15424                        // Invalid install. Return error code
15425                        return PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS;
15426                    }
15427                }
15428            }
15429            // All the special cases have been taken care of.
15430            // Return result based on recommended install location.
15431            if (onSd) {
15432                return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
15433            }
15434            return pkgLite.recommendedInstallLocation;
15435        }
15436
15437        /*
15438         * Invoke remote method to get package information and install
15439         * location values. Override install location based on default
15440         * policy if needed and then create install arguments based
15441         * on the install location.
15442         */
15443        public void handleStartCopy() throws RemoteException {
15444            int ret = PackageManager.INSTALL_SUCCEEDED;
15445
15446            // If we're already staged, we've firmly committed to an install location
15447            if (origin.staged) {
15448                if (origin.file != null) {
15449                    installFlags |= PackageManager.INSTALL_INTERNAL;
15450                    installFlags &= ~PackageManager.INSTALL_EXTERNAL;
15451                } else if (origin.cid != null) {
15452                    installFlags |= PackageManager.INSTALL_EXTERNAL;
15453                    installFlags &= ~PackageManager.INSTALL_INTERNAL;
15454                } else {
15455                    throw new IllegalStateException("Invalid stage location");
15456                }
15457            }
15458
15459            final boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
15460            final boolean onInt = (installFlags & PackageManager.INSTALL_INTERNAL) != 0;
15461            final boolean ephemeral = (installFlags & PackageManager.INSTALL_INSTANT_APP) != 0;
15462            PackageInfoLite pkgLite = null;
15463
15464            if (onInt && onSd) {
15465                // Check if both bits are set.
15466                Slog.w(TAG, "Conflicting flags specified for installing on both internal and external");
15467                ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
15468            } else if (onSd && ephemeral) {
15469                Slog.w(TAG,  "Conflicting flags specified for installing ephemeral on external");
15470                ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
15471            } else {
15472                pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, installFlags,
15473                        packageAbiOverride);
15474
15475                if (DEBUG_EPHEMERAL && ephemeral) {
15476                    Slog.v(TAG, "pkgLite for install: " + pkgLite);
15477                }
15478
15479                /*
15480                 * If we have too little free space, try to free cache
15481                 * before giving up.
15482                 */
15483                if (!origin.staged && pkgLite.recommendedInstallLocation
15484                        == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) {
15485                    // TODO: focus freeing disk space on the target device
15486                    final StorageManager storage = StorageManager.from(mContext);
15487                    final long lowThreshold = storage.getStorageLowBytes(
15488                            Environment.getDataDirectory());
15489
15490                    final long sizeBytes = mContainerService.calculateInstalledSize(
15491                            origin.resolvedPath, isForwardLocked(), packageAbiOverride);
15492
15493                    try {
15494                        mInstaller.freeCache(null, sizeBytes + lowThreshold, 0);
15495                        pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath,
15496                                installFlags, packageAbiOverride);
15497                    } catch (InstallerException e) {
15498                        Slog.w(TAG, "Failed to free cache", e);
15499                    }
15500
15501                    /*
15502                     * The cache free must have deleted the file we
15503                     * downloaded to install.
15504                     *
15505                     * TODO: fix the "freeCache" call to not delete
15506                     *       the file we care about.
15507                     */
15508                    if (pkgLite.recommendedInstallLocation
15509                            == PackageHelper.RECOMMEND_FAILED_INVALID_URI) {
15510                        pkgLite.recommendedInstallLocation
15511                            = PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE;
15512                    }
15513                }
15514            }
15515
15516            if (ret == PackageManager.INSTALL_SUCCEEDED) {
15517                int loc = pkgLite.recommendedInstallLocation;
15518                if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION) {
15519                    ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
15520                } else if (loc == PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS) {
15521                    ret = PackageManager.INSTALL_FAILED_ALREADY_EXISTS;
15522                } else if (loc == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) {
15523                    ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
15524                } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_APK) {
15525                    ret = PackageManager.INSTALL_FAILED_INVALID_APK;
15526                } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_URI) {
15527                    ret = PackageManager.INSTALL_FAILED_INVALID_URI;
15528                } else if (loc == PackageHelper.RECOMMEND_MEDIA_UNAVAILABLE) {
15529                    ret = PackageManager.INSTALL_FAILED_MEDIA_UNAVAILABLE;
15530                } else {
15531                    // Override with defaults if needed.
15532                    loc = installLocationPolicy(pkgLite);
15533                    if (loc == PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE) {
15534                        ret = PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE;
15535                    } else if (!onSd && !onInt) {
15536                        // Override install location with flags
15537                        if (loc == PackageHelper.RECOMMEND_INSTALL_EXTERNAL) {
15538                            // Set the flag to install on external media.
15539                            installFlags |= PackageManager.INSTALL_EXTERNAL;
15540                            installFlags &= ~PackageManager.INSTALL_INTERNAL;
15541                        } else if (loc == PackageHelper.RECOMMEND_INSTALL_EPHEMERAL) {
15542                            if (DEBUG_EPHEMERAL) {
15543                                Slog.v(TAG, "...setting INSTALL_EPHEMERAL install flag");
15544                            }
15545                            installFlags |= PackageManager.INSTALL_INSTANT_APP;
15546                            installFlags &= ~(PackageManager.INSTALL_EXTERNAL
15547                                    |PackageManager.INSTALL_INTERNAL);
15548                        } else {
15549                            // Make sure the flag for installing on external
15550                            // media is unset
15551                            installFlags |= PackageManager.INSTALL_INTERNAL;
15552                            installFlags &= ~PackageManager.INSTALL_EXTERNAL;
15553                        }
15554                    }
15555                }
15556            }
15557
15558            final InstallArgs args = createInstallArgs(this);
15559            mArgs = args;
15560
15561            if (ret == PackageManager.INSTALL_SUCCEEDED) {
15562                // TODO: http://b/22976637
15563                // Apps installed for "all" users use the device owner to verify the app
15564                UserHandle verifierUser = getUser();
15565                if (verifierUser == UserHandle.ALL) {
15566                    verifierUser = UserHandle.SYSTEM;
15567                }
15568
15569                /*
15570                 * Determine if we have any installed package verifiers. If we
15571                 * do, then we'll defer to them to verify the packages.
15572                 */
15573                final int requiredUid = mRequiredVerifierPackage == null ? -1
15574                        : getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING,
15575                                verifierUser.getIdentifier());
15576                if (!origin.existing && requiredUid != -1
15577                        && isVerificationEnabled(verifierUser.getIdentifier(), installFlags)) {
15578                    final Intent verification = new Intent(
15579                            Intent.ACTION_PACKAGE_NEEDS_VERIFICATION);
15580                    verification.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
15581                    verification.setDataAndType(Uri.fromFile(new File(origin.resolvedPath)),
15582                            PACKAGE_MIME_TYPE);
15583                    verification.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
15584
15585                    // Query all live verifiers based on current user state
15586                    final List<ResolveInfo> receivers = queryIntentReceiversInternal(verification,
15587                            PACKAGE_MIME_TYPE, 0, verifierUser.getIdentifier());
15588
15589                    if (DEBUG_VERIFY) {
15590                        Slog.d(TAG, "Found " + receivers.size() + " verifiers for intent "
15591                                + verification.toString() + " with " + pkgLite.verifiers.length
15592                                + " optional verifiers");
15593                    }
15594
15595                    final int verificationId = mPendingVerificationToken++;
15596
15597                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId);
15598
15599                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_PACKAGE,
15600                            installerPackageName);
15601
15602                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALL_FLAGS,
15603                            installFlags);
15604
15605                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_PACKAGE_NAME,
15606                            pkgLite.packageName);
15607
15608                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_VERSION_CODE,
15609                            pkgLite.versionCode);
15610
15611                    if (verificationInfo != null) {
15612                        if (verificationInfo.originatingUri != null) {
15613                            verification.putExtra(Intent.EXTRA_ORIGINATING_URI,
15614                                    verificationInfo.originatingUri);
15615                        }
15616                        if (verificationInfo.referrer != null) {
15617                            verification.putExtra(Intent.EXTRA_REFERRER,
15618                                    verificationInfo.referrer);
15619                        }
15620                        if (verificationInfo.originatingUid >= 0) {
15621                            verification.putExtra(Intent.EXTRA_ORIGINATING_UID,
15622                                    verificationInfo.originatingUid);
15623                        }
15624                        if (verificationInfo.installerUid >= 0) {
15625                            verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_UID,
15626                                    verificationInfo.installerUid);
15627                        }
15628                    }
15629
15630                    final PackageVerificationState verificationState = new PackageVerificationState(
15631                            requiredUid, args);
15632
15633                    mPendingVerification.append(verificationId, verificationState);
15634
15635                    final List<ComponentName> sufficientVerifiers = matchVerifiers(pkgLite,
15636                            receivers, verificationState);
15637
15638                    DeviceIdleController.LocalService idleController = getDeviceIdleController();
15639                    final long idleDuration = getVerificationTimeout();
15640
15641                    /*
15642                     * If any sufficient verifiers were listed in the package
15643                     * manifest, attempt to ask them.
15644                     */
15645                    if (sufficientVerifiers != null) {
15646                        final int N = sufficientVerifiers.size();
15647                        if (N == 0) {
15648                            Slog.i(TAG, "Additional verifiers required, but none installed.");
15649                            ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
15650                        } else {
15651                            for (int i = 0; i < N; i++) {
15652                                final ComponentName verifierComponent = sufficientVerifiers.get(i);
15653                                idleController.addPowerSaveTempWhitelistApp(Process.myUid(),
15654                                        verifierComponent.getPackageName(), idleDuration,
15655                                        verifierUser.getIdentifier(), false, "package verifier");
15656
15657                                final Intent sufficientIntent = new Intent(verification);
15658                                sufficientIntent.setComponent(verifierComponent);
15659                                mContext.sendBroadcastAsUser(sufficientIntent, verifierUser);
15660                            }
15661                        }
15662                    }
15663
15664                    final ComponentName requiredVerifierComponent = matchComponentForVerifier(
15665                            mRequiredVerifierPackage, receivers);
15666                    if (ret == PackageManager.INSTALL_SUCCEEDED
15667                            && mRequiredVerifierPackage != null) {
15668                        Trace.asyncTraceBegin(
15669                                TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId);
15670                        /*
15671                         * Send the intent to the required verification agent,
15672                         * but only start the verification timeout after the
15673                         * target BroadcastReceivers have run.
15674                         */
15675                        verification.setComponent(requiredVerifierComponent);
15676                        idleController.addPowerSaveTempWhitelistApp(Process.myUid(),
15677                                mRequiredVerifierPackage, idleDuration,
15678                                verifierUser.getIdentifier(), false, "package verifier");
15679                        mContext.sendOrderedBroadcastAsUser(verification, verifierUser,
15680                                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
15681                                new BroadcastReceiver() {
15682                                    @Override
15683                                    public void onReceive(Context context, Intent intent) {
15684                                        final Message msg = mHandler
15685                                                .obtainMessage(CHECK_PENDING_VERIFICATION);
15686                                        msg.arg1 = verificationId;
15687                                        mHandler.sendMessageDelayed(msg, getVerificationTimeout());
15688                                    }
15689                                }, null, 0, null, null);
15690
15691                        /*
15692                         * We don't want the copy to proceed until verification
15693                         * succeeds, so null out this field.
15694                         */
15695                        mArgs = null;
15696                    }
15697                } else {
15698                    /*
15699                     * No package verification is enabled, so immediately start
15700                     * the remote call to initiate copy using temporary file.
15701                     */
15702                    ret = args.copyApk(mContainerService, true);
15703                }
15704            }
15705
15706            mRet = ret;
15707        }
15708
15709        @Override
15710        void handleReturnCode() {
15711            // If mArgs is null, then MCS couldn't be reached. When it
15712            // reconnects, it will try again to install. At that point, this
15713            // will succeed.
15714            if (mArgs != null) {
15715                processPendingInstall(mArgs, mRet);
15716            }
15717        }
15718
15719        @Override
15720        void handleServiceError() {
15721            mArgs = createInstallArgs(this);
15722            mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
15723        }
15724
15725        public boolean isForwardLocked() {
15726            return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
15727        }
15728    }
15729
15730    /**
15731     * Used during creation of InstallArgs
15732     *
15733     * @param installFlags package installation flags
15734     * @return true if should be installed on external storage
15735     */
15736    private static boolean installOnExternalAsec(int installFlags) {
15737        if ((installFlags & PackageManager.INSTALL_INTERNAL) != 0) {
15738            return false;
15739        }
15740        if ((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) {
15741            return true;
15742        }
15743        return false;
15744    }
15745
15746    /**
15747     * Used during creation of InstallArgs
15748     *
15749     * @param installFlags package installation flags
15750     * @return true if should be installed as forward locked
15751     */
15752    private static boolean installForwardLocked(int installFlags) {
15753        return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
15754    }
15755
15756    private InstallArgs createInstallArgs(InstallParams params) {
15757        if (params.move != null) {
15758            return new MoveInstallArgs(params);
15759        } else if (installOnExternalAsec(params.installFlags) || params.isForwardLocked()) {
15760            return new AsecInstallArgs(params);
15761        } else {
15762            return new FileInstallArgs(params);
15763        }
15764    }
15765
15766    /**
15767     * Create args that describe an existing installed package. Typically used
15768     * when cleaning up old installs, or used as a move source.
15769     */
15770    private InstallArgs createInstallArgsForExisting(int installFlags, String codePath,
15771            String resourcePath, String[] instructionSets) {
15772        final boolean isInAsec;
15773        if (installOnExternalAsec(installFlags)) {
15774            /* Apps on SD card are always in ASEC containers. */
15775            isInAsec = true;
15776        } else if (installForwardLocked(installFlags)
15777                && !codePath.startsWith(mDrmAppPrivateInstallDir.getAbsolutePath())) {
15778            /*
15779             * Forward-locked apps are only in ASEC containers if they're the
15780             * new style
15781             */
15782            isInAsec = true;
15783        } else {
15784            isInAsec = false;
15785        }
15786
15787        if (isInAsec) {
15788            return new AsecInstallArgs(codePath, instructionSets,
15789                    installOnExternalAsec(installFlags), installForwardLocked(installFlags));
15790        } else {
15791            return new FileInstallArgs(codePath, resourcePath, instructionSets);
15792        }
15793    }
15794
15795    static abstract class InstallArgs {
15796        /** @see InstallParams#origin */
15797        final OriginInfo origin;
15798        /** @see InstallParams#move */
15799        final MoveInfo move;
15800
15801        final IPackageInstallObserver2 observer;
15802        // Always refers to PackageManager flags only
15803        final int installFlags;
15804        final String installerPackageName;
15805        final String volumeUuid;
15806        final UserHandle user;
15807        final String abiOverride;
15808        final String[] installGrantPermissions;
15809        /** If non-null, drop an async trace when the install completes */
15810        final String traceMethod;
15811        final int traceCookie;
15812        final Certificate[][] certificates;
15813        final int installReason;
15814
15815        // The list of instruction sets supported by this app. This is currently
15816        // only used during the rmdex() phase to clean up resources. We can get rid of this
15817        // if we move dex files under the common app path.
15818        /* nullable */ String[] instructionSets;
15819
15820        InstallArgs(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer,
15821                int installFlags, String installerPackageName, String volumeUuid,
15822                UserHandle user, String[] instructionSets,
15823                String abiOverride, String[] installGrantPermissions,
15824                String traceMethod, int traceCookie, Certificate[][] certificates,
15825                int installReason) {
15826            this.origin = origin;
15827            this.move = move;
15828            this.installFlags = installFlags;
15829            this.observer = observer;
15830            this.installerPackageName = installerPackageName;
15831            this.volumeUuid = volumeUuid;
15832            this.user = user;
15833            this.instructionSets = instructionSets;
15834            this.abiOverride = abiOverride;
15835            this.installGrantPermissions = installGrantPermissions;
15836            this.traceMethod = traceMethod;
15837            this.traceCookie = traceCookie;
15838            this.certificates = certificates;
15839            this.installReason = installReason;
15840        }
15841
15842        abstract int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException;
15843        abstract int doPreInstall(int status);
15844
15845        /**
15846         * Rename package into final resting place. All paths on the given
15847         * scanned package should be updated to reflect the rename.
15848         */
15849        abstract boolean doRename(int status, PackageParser.Package pkg, String oldCodePath);
15850        abstract int doPostInstall(int status, int uid);
15851
15852        /** @see PackageSettingBase#codePathString */
15853        abstract String getCodePath();
15854        /** @see PackageSettingBase#resourcePathString */
15855        abstract String getResourcePath();
15856
15857        // Need installer lock especially for dex file removal.
15858        abstract void cleanUpResourcesLI();
15859        abstract boolean doPostDeleteLI(boolean delete);
15860
15861        /**
15862         * Called before the source arguments are copied. This is used mostly
15863         * for MoveParams when it needs to read the source file to put it in the
15864         * destination.
15865         */
15866        int doPreCopy() {
15867            return PackageManager.INSTALL_SUCCEEDED;
15868        }
15869
15870        /**
15871         * Called after the source arguments are copied. This is used mostly for
15872         * MoveParams when it needs to read the source file to put it in the
15873         * destination.
15874         */
15875        int doPostCopy(int uid) {
15876            return PackageManager.INSTALL_SUCCEEDED;
15877        }
15878
15879        protected boolean isFwdLocked() {
15880            return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
15881        }
15882
15883        protected boolean isExternalAsec() {
15884            return (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
15885        }
15886
15887        protected boolean isEphemeral() {
15888            return (installFlags & PackageManager.INSTALL_INSTANT_APP) != 0;
15889        }
15890
15891        UserHandle getUser() {
15892            return user;
15893        }
15894    }
15895
15896    private void removeDexFiles(List<String> allCodePaths, String[] instructionSets) {
15897        if (!allCodePaths.isEmpty()) {
15898            if (instructionSets == null) {
15899                throw new IllegalStateException("instructionSet == null");
15900            }
15901            String[] dexCodeInstructionSets = getDexCodeInstructionSets(instructionSets);
15902            for (String codePath : allCodePaths) {
15903                for (String dexCodeInstructionSet : dexCodeInstructionSets) {
15904                    try {
15905                        mInstaller.rmdex(codePath, dexCodeInstructionSet);
15906                    } catch (InstallerException ignored) {
15907                    }
15908                }
15909            }
15910        }
15911    }
15912
15913    /**
15914     * Logic to handle installation of non-ASEC applications, including copying
15915     * and renaming logic.
15916     */
15917    class FileInstallArgs extends InstallArgs {
15918        private File codeFile;
15919        private File resourceFile;
15920
15921        // Example topology:
15922        // /data/app/com.example/base.apk
15923        // /data/app/com.example/split_foo.apk
15924        // /data/app/com.example/lib/arm/libfoo.so
15925        // /data/app/com.example/lib/arm64/libfoo.so
15926        // /data/app/com.example/dalvik/arm/base.apk@classes.dex
15927
15928        /** New install */
15929        FileInstallArgs(InstallParams params) {
15930            super(params.origin, params.move, params.observer, params.installFlags,
15931                    params.installerPackageName, params.volumeUuid,
15932                    params.getUser(), null /*instructionSets*/, params.packageAbiOverride,
15933                    params.grantedRuntimePermissions,
15934                    params.traceMethod, params.traceCookie, params.certificates,
15935                    params.installReason);
15936            if (isFwdLocked()) {
15937                throw new IllegalArgumentException("Forward locking only supported in ASEC");
15938            }
15939        }
15940
15941        /** Existing install */
15942        FileInstallArgs(String codePath, String resourcePath, String[] instructionSets) {
15943            super(OriginInfo.fromNothing(), null, null, 0, null, null, null, instructionSets,
15944                    null, null, null, 0, null /*certificates*/,
15945                    PackageManager.INSTALL_REASON_UNKNOWN);
15946            this.codeFile = (codePath != null) ? new File(codePath) : null;
15947            this.resourceFile = (resourcePath != null) ? new File(resourcePath) : null;
15948        }
15949
15950        int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
15951            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyApk");
15952            try {
15953                return doCopyApk(imcs, temp);
15954            } finally {
15955                Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
15956            }
15957        }
15958
15959        private int doCopyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
15960            if (origin.staged) {
15961                if (DEBUG_INSTALL) Slog.d(TAG, origin.file + " already staged; skipping copy");
15962                codeFile = origin.file;
15963                resourceFile = origin.file;
15964                return PackageManager.INSTALL_SUCCEEDED;
15965            }
15966
15967            try {
15968                final boolean isEphemeral = (installFlags & PackageManager.INSTALL_INSTANT_APP) != 0;
15969                final File tempDir =
15970                        mInstallerService.allocateStageDirLegacy(volumeUuid, isEphemeral);
15971                codeFile = tempDir;
15972                resourceFile = tempDir;
15973            } catch (IOException e) {
15974                Slog.w(TAG, "Failed to create copy file: " + e);
15975                return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
15976            }
15977
15978            final IParcelFileDescriptorFactory target = new IParcelFileDescriptorFactory.Stub() {
15979                @Override
15980                public ParcelFileDescriptor open(String name, int mode) throws RemoteException {
15981                    if (!FileUtils.isValidExtFilename(name)) {
15982                        throw new IllegalArgumentException("Invalid filename: " + name);
15983                    }
15984                    try {
15985                        final File file = new File(codeFile, name);
15986                        final FileDescriptor fd = Os.open(file.getAbsolutePath(),
15987                                O_RDWR | O_CREAT, 0644);
15988                        Os.chmod(file.getAbsolutePath(), 0644);
15989                        return new ParcelFileDescriptor(fd);
15990                    } catch (ErrnoException e) {
15991                        throw new RemoteException("Failed to open: " + e.getMessage());
15992                    }
15993                }
15994            };
15995
15996            int ret = PackageManager.INSTALL_SUCCEEDED;
15997            ret = imcs.copyPackage(origin.file.getAbsolutePath(), target);
15998            if (ret != PackageManager.INSTALL_SUCCEEDED) {
15999                Slog.e(TAG, "Failed to copy package");
16000                return ret;
16001            }
16002
16003            final File libraryRoot = new File(codeFile, LIB_DIR_NAME);
16004            NativeLibraryHelper.Handle handle = null;
16005            try {
16006                handle = NativeLibraryHelper.Handle.create(codeFile);
16007                ret = NativeLibraryHelper.copyNativeBinariesWithOverride(handle, libraryRoot,
16008                        abiOverride);
16009            } catch (IOException e) {
16010                Slog.e(TAG, "Copying native libraries failed", e);
16011                ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
16012            } finally {
16013                IoUtils.closeQuietly(handle);
16014            }
16015
16016            return ret;
16017        }
16018
16019        int doPreInstall(int status) {
16020            if (status != PackageManager.INSTALL_SUCCEEDED) {
16021                cleanUp();
16022            }
16023            return status;
16024        }
16025
16026        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
16027            if (status != PackageManager.INSTALL_SUCCEEDED) {
16028                cleanUp();
16029                return false;
16030            }
16031
16032            final File targetDir = codeFile.getParentFile();
16033            final File beforeCodeFile = codeFile;
16034            final File afterCodeFile = getNextCodePath(targetDir, pkg.packageName);
16035
16036            if (DEBUG_INSTALL) Slog.d(TAG, "Renaming " + beforeCodeFile + " to " + afterCodeFile);
16037            try {
16038                Os.rename(beforeCodeFile.getAbsolutePath(), afterCodeFile.getAbsolutePath());
16039            } catch (ErrnoException e) {
16040                Slog.w(TAG, "Failed to rename", e);
16041                return false;
16042            }
16043
16044            if (!SELinux.restoreconRecursive(afterCodeFile)) {
16045                Slog.w(TAG, "Failed to restorecon");
16046                return false;
16047            }
16048
16049            // Reflect the rename internally
16050            codeFile = afterCodeFile;
16051            resourceFile = afterCodeFile;
16052
16053            // Reflect the rename in scanned details
16054            pkg.setCodePath(afterCodeFile.getAbsolutePath());
16055            pkg.setBaseCodePath(FileUtils.rewriteAfterRename(beforeCodeFile,
16056                    afterCodeFile, pkg.baseCodePath));
16057            pkg.setSplitCodePaths(FileUtils.rewriteAfterRename(beforeCodeFile,
16058                    afterCodeFile, pkg.splitCodePaths));
16059
16060            // Reflect the rename in app info
16061            pkg.setApplicationVolumeUuid(pkg.volumeUuid);
16062            pkg.setApplicationInfoCodePath(pkg.codePath);
16063            pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
16064            pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
16065            pkg.setApplicationInfoResourcePath(pkg.codePath);
16066            pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath);
16067            pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
16068
16069            return true;
16070        }
16071
16072        int doPostInstall(int status, int uid) {
16073            if (status != PackageManager.INSTALL_SUCCEEDED) {
16074                cleanUp();
16075            }
16076            return status;
16077        }
16078
16079        @Override
16080        String getCodePath() {
16081            return (codeFile != null) ? codeFile.getAbsolutePath() : null;
16082        }
16083
16084        @Override
16085        String getResourcePath() {
16086            return (resourceFile != null) ? resourceFile.getAbsolutePath() : null;
16087        }
16088
16089        private boolean cleanUp() {
16090            if (codeFile == null || !codeFile.exists()) {
16091                return false;
16092            }
16093
16094            removeCodePathLI(codeFile);
16095
16096            if (resourceFile != null && !FileUtils.contains(codeFile, resourceFile)) {
16097                resourceFile.delete();
16098            }
16099
16100            return true;
16101        }
16102
16103        void cleanUpResourcesLI() {
16104            // Try enumerating all code paths before deleting
16105            List<String> allCodePaths = Collections.EMPTY_LIST;
16106            if (codeFile != null && codeFile.exists()) {
16107                try {
16108                    final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0);
16109                    allCodePaths = pkg.getAllCodePaths();
16110                } catch (PackageParserException e) {
16111                    // Ignored; we tried our best
16112                }
16113            }
16114
16115            cleanUp();
16116            removeDexFiles(allCodePaths, instructionSets);
16117        }
16118
16119        boolean doPostDeleteLI(boolean delete) {
16120            // XXX err, shouldn't we respect the delete flag?
16121            cleanUpResourcesLI();
16122            return true;
16123        }
16124    }
16125
16126    private boolean isAsecExternal(String cid) {
16127        final String asecPath = PackageHelper.getSdFilesystem(cid);
16128        return !asecPath.startsWith(mAsecInternalPath);
16129    }
16130
16131    private static void maybeThrowExceptionForMultiArchCopy(String message, int copyRet) throws
16132            PackageManagerException {
16133        if (copyRet < 0) {
16134            if (copyRet != PackageManager.NO_NATIVE_LIBRARIES &&
16135                    copyRet != PackageManager.INSTALL_FAILED_NO_MATCHING_ABIS) {
16136                throw new PackageManagerException(copyRet, message);
16137            }
16138        }
16139    }
16140
16141    /**
16142     * Extract the StorageManagerService "container ID" from the full code path of an
16143     * .apk.
16144     */
16145    static String cidFromCodePath(String fullCodePath) {
16146        int eidx = fullCodePath.lastIndexOf("/");
16147        String subStr1 = fullCodePath.substring(0, eidx);
16148        int sidx = subStr1.lastIndexOf("/");
16149        return subStr1.substring(sidx+1, eidx);
16150    }
16151
16152    /**
16153     * Logic to handle installation of ASEC applications, including copying and
16154     * renaming logic.
16155     */
16156    class AsecInstallArgs extends InstallArgs {
16157        static final String RES_FILE_NAME = "pkg.apk";
16158        static final String PUBLIC_RES_FILE_NAME = "res.zip";
16159
16160        String cid;
16161        String packagePath;
16162        String resourcePath;
16163
16164        /** New install */
16165        AsecInstallArgs(InstallParams params) {
16166            super(params.origin, params.move, params.observer, params.installFlags,
16167                    params.installerPackageName, params.volumeUuid,
16168                    params.getUser(), null /* instruction sets */, params.packageAbiOverride,
16169                    params.grantedRuntimePermissions,
16170                    params.traceMethod, params.traceCookie, params.certificates,
16171                    params.installReason);
16172        }
16173
16174        /** Existing install */
16175        AsecInstallArgs(String fullCodePath, String[] instructionSets,
16176                        boolean isExternal, boolean isForwardLocked) {
16177            super(OriginInfo.fromNothing(), null, null, (isExternal ? INSTALL_EXTERNAL : 0)
16178                    | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null,
16179                    instructionSets, null, null, null, 0, null /*certificates*/,
16180                    PackageManager.INSTALL_REASON_UNKNOWN);
16181            // Hackily pretend we're still looking at a full code path
16182            if (!fullCodePath.endsWith(RES_FILE_NAME)) {
16183                fullCodePath = new File(fullCodePath, RES_FILE_NAME).getAbsolutePath();
16184            }
16185
16186            // Extract cid from fullCodePath
16187            int eidx = fullCodePath.lastIndexOf("/");
16188            String subStr1 = fullCodePath.substring(0, eidx);
16189            int sidx = subStr1.lastIndexOf("/");
16190            cid = subStr1.substring(sidx+1, eidx);
16191            setMountPath(subStr1);
16192        }
16193
16194        AsecInstallArgs(String cid, String[] instructionSets, boolean isForwardLocked) {
16195            super(OriginInfo.fromNothing(), null, null, (isAsecExternal(cid) ? INSTALL_EXTERNAL : 0)
16196                    | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null,
16197                    instructionSets, null, null, null, 0, null /*certificates*/,
16198                    PackageManager.INSTALL_REASON_UNKNOWN);
16199            this.cid = cid;
16200            setMountPath(PackageHelper.getSdDir(cid));
16201        }
16202
16203        void createCopyFile() {
16204            cid = mInstallerService.allocateExternalStageCidLegacy();
16205        }
16206
16207        int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
16208            if (origin.staged && origin.cid != null) {
16209                if (DEBUG_INSTALL) Slog.d(TAG, origin.cid + " already staged; skipping copy");
16210                cid = origin.cid;
16211                setMountPath(PackageHelper.getSdDir(cid));
16212                return PackageManager.INSTALL_SUCCEEDED;
16213            }
16214
16215            if (temp) {
16216                createCopyFile();
16217            } else {
16218                /*
16219                 * Pre-emptively destroy the container since it's destroyed if
16220                 * copying fails due to it existing anyway.
16221                 */
16222                PackageHelper.destroySdDir(cid);
16223            }
16224
16225            final String newMountPath = imcs.copyPackageToContainer(
16226                    origin.file.getAbsolutePath(), cid, getEncryptKey(), isExternalAsec(),
16227                    isFwdLocked(), deriveAbiOverride(abiOverride, null /* settings */));
16228
16229            if (newMountPath != null) {
16230                setMountPath(newMountPath);
16231                return PackageManager.INSTALL_SUCCEEDED;
16232            } else {
16233                return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
16234            }
16235        }
16236
16237        @Override
16238        String getCodePath() {
16239            return packagePath;
16240        }
16241
16242        @Override
16243        String getResourcePath() {
16244            return resourcePath;
16245        }
16246
16247        int doPreInstall(int status) {
16248            if (status != PackageManager.INSTALL_SUCCEEDED) {
16249                // Destroy container
16250                PackageHelper.destroySdDir(cid);
16251            } else {
16252                boolean mounted = PackageHelper.isContainerMounted(cid);
16253                if (!mounted) {
16254                    String newMountPath = PackageHelper.mountSdDir(cid, getEncryptKey(),
16255                            Process.SYSTEM_UID);
16256                    if (newMountPath != null) {
16257                        setMountPath(newMountPath);
16258                    } else {
16259                        return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
16260                    }
16261                }
16262            }
16263            return status;
16264        }
16265
16266        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
16267            String newCacheId = getNextCodePath(oldCodePath, pkg.packageName, "/" + RES_FILE_NAME);
16268            String newMountPath = null;
16269            if (PackageHelper.isContainerMounted(cid)) {
16270                // Unmount the container
16271                if (!PackageHelper.unMountSdDir(cid)) {
16272                    Slog.i(TAG, "Failed to unmount " + cid + " before renaming");
16273                    return false;
16274                }
16275            }
16276            if (!PackageHelper.renameSdDir(cid, newCacheId)) {
16277                Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId +
16278                        " which might be stale. Will try to clean up.");
16279                // Clean up the stale container and proceed to recreate.
16280                if (!PackageHelper.destroySdDir(newCacheId)) {
16281                    Slog.e(TAG, "Very strange. Cannot clean up stale container " + newCacheId);
16282                    return false;
16283                }
16284                // Successfully cleaned up stale container. Try to rename again.
16285                if (!PackageHelper.renameSdDir(cid, newCacheId)) {
16286                    Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId
16287                            + " inspite of cleaning it up.");
16288                    return false;
16289                }
16290            }
16291            if (!PackageHelper.isContainerMounted(newCacheId)) {
16292                Slog.w(TAG, "Mounting container " + newCacheId);
16293                newMountPath = PackageHelper.mountSdDir(newCacheId,
16294                        getEncryptKey(), Process.SYSTEM_UID);
16295            } else {
16296                newMountPath = PackageHelper.getSdDir(newCacheId);
16297            }
16298            if (newMountPath == null) {
16299                Slog.w(TAG, "Failed to get cache path for  " + newCacheId);
16300                return false;
16301            }
16302            Log.i(TAG, "Succesfully renamed " + cid +
16303                    " to " + newCacheId +
16304                    " at new path: " + newMountPath);
16305            cid = newCacheId;
16306
16307            final File beforeCodeFile = new File(packagePath);
16308            setMountPath(newMountPath);
16309            final File afterCodeFile = new File(packagePath);
16310
16311            // Reflect the rename in scanned details
16312            pkg.setCodePath(afterCodeFile.getAbsolutePath());
16313            pkg.setBaseCodePath(FileUtils.rewriteAfterRename(beforeCodeFile,
16314                    afterCodeFile, pkg.baseCodePath));
16315            pkg.setSplitCodePaths(FileUtils.rewriteAfterRename(beforeCodeFile,
16316                    afterCodeFile, pkg.splitCodePaths));
16317
16318            // Reflect the rename in app info
16319            pkg.setApplicationVolumeUuid(pkg.volumeUuid);
16320            pkg.setApplicationInfoCodePath(pkg.codePath);
16321            pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
16322            pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
16323            pkg.setApplicationInfoResourcePath(pkg.codePath);
16324            pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath);
16325            pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
16326
16327            return true;
16328        }
16329
16330        private void setMountPath(String mountPath) {
16331            final File mountFile = new File(mountPath);
16332
16333            final File monolithicFile = new File(mountFile, RES_FILE_NAME);
16334            if (monolithicFile.exists()) {
16335                packagePath = monolithicFile.getAbsolutePath();
16336                if (isFwdLocked()) {
16337                    resourcePath = new File(mountFile, PUBLIC_RES_FILE_NAME).getAbsolutePath();
16338                } else {
16339                    resourcePath = packagePath;
16340                }
16341            } else {
16342                packagePath = mountFile.getAbsolutePath();
16343                resourcePath = packagePath;
16344            }
16345        }
16346
16347        int doPostInstall(int status, int uid) {
16348            if (status != PackageManager.INSTALL_SUCCEEDED) {
16349                cleanUp();
16350            } else {
16351                final int groupOwner;
16352                final String protectedFile;
16353                if (isFwdLocked()) {
16354                    groupOwner = UserHandle.getSharedAppGid(uid);
16355                    protectedFile = RES_FILE_NAME;
16356                } else {
16357                    groupOwner = -1;
16358                    protectedFile = null;
16359                }
16360
16361                if (uid < Process.FIRST_APPLICATION_UID
16362                        || !PackageHelper.fixSdPermissions(cid, groupOwner, protectedFile)) {
16363                    Slog.e(TAG, "Failed to finalize " + cid);
16364                    PackageHelper.destroySdDir(cid);
16365                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
16366                }
16367
16368                boolean mounted = PackageHelper.isContainerMounted(cid);
16369                if (!mounted) {
16370                    PackageHelper.mountSdDir(cid, getEncryptKey(), Process.myUid());
16371                }
16372            }
16373            return status;
16374        }
16375
16376        private void cleanUp() {
16377            if (DEBUG_SD_INSTALL) Slog.i(TAG, "cleanUp");
16378
16379            // Destroy secure container
16380            PackageHelper.destroySdDir(cid);
16381        }
16382
16383        private List<String> getAllCodePaths() {
16384            final File codeFile = new File(getCodePath());
16385            if (codeFile != null && codeFile.exists()) {
16386                try {
16387                    final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0);
16388                    return pkg.getAllCodePaths();
16389                } catch (PackageParserException e) {
16390                    // Ignored; we tried our best
16391                }
16392            }
16393            return Collections.EMPTY_LIST;
16394        }
16395
16396        void cleanUpResourcesLI() {
16397            // Enumerate all code paths before deleting
16398            cleanUpResourcesLI(getAllCodePaths());
16399        }
16400
16401        private void cleanUpResourcesLI(List<String> allCodePaths) {
16402            cleanUp();
16403            removeDexFiles(allCodePaths, instructionSets);
16404        }
16405
16406        String getPackageName() {
16407            return getAsecPackageName(cid);
16408        }
16409
16410        boolean doPostDeleteLI(boolean delete) {
16411            if (DEBUG_SD_INSTALL) Slog.i(TAG, "doPostDeleteLI() del=" + delete);
16412            final List<String> allCodePaths = getAllCodePaths();
16413            boolean mounted = PackageHelper.isContainerMounted(cid);
16414            if (mounted) {
16415                // Unmount first
16416                if (PackageHelper.unMountSdDir(cid)) {
16417                    mounted = false;
16418                }
16419            }
16420            if (!mounted && delete) {
16421                cleanUpResourcesLI(allCodePaths);
16422            }
16423            return !mounted;
16424        }
16425
16426        @Override
16427        int doPreCopy() {
16428            if (isFwdLocked()) {
16429                if (!PackageHelper.fixSdPermissions(cid, getPackageUid(DEFAULT_CONTAINER_PACKAGE,
16430                        MATCH_SYSTEM_ONLY, UserHandle.USER_SYSTEM), RES_FILE_NAME)) {
16431                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
16432                }
16433            }
16434
16435            return PackageManager.INSTALL_SUCCEEDED;
16436        }
16437
16438        @Override
16439        int doPostCopy(int uid) {
16440            if (isFwdLocked()) {
16441                if (uid < Process.FIRST_APPLICATION_UID
16442                        || !PackageHelper.fixSdPermissions(cid, UserHandle.getSharedAppGid(uid),
16443                                RES_FILE_NAME)) {
16444                    Slog.e(TAG, "Failed to finalize " + cid);
16445                    PackageHelper.destroySdDir(cid);
16446                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
16447                }
16448            }
16449
16450            return PackageManager.INSTALL_SUCCEEDED;
16451        }
16452    }
16453
16454    /**
16455     * Logic to handle movement of existing installed applications.
16456     */
16457    class MoveInstallArgs extends InstallArgs {
16458        private File codeFile;
16459        private File resourceFile;
16460
16461        /** New install */
16462        MoveInstallArgs(InstallParams params) {
16463            super(params.origin, params.move, params.observer, params.installFlags,
16464                    params.installerPackageName, params.volumeUuid,
16465                    params.getUser(), null /* instruction sets */, params.packageAbiOverride,
16466                    params.grantedRuntimePermissions,
16467                    params.traceMethod, params.traceCookie, params.certificates,
16468                    params.installReason);
16469        }
16470
16471        int copyApk(IMediaContainerService imcs, boolean temp) {
16472            if (DEBUG_INSTALL) Slog.d(TAG, "Moving " + move.packageName + " from "
16473                    + move.fromUuid + " to " + move.toUuid);
16474            synchronized (mInstaller) {
16475                try {
16476                    mInstaller.moveCompleteApp(move.fromUuid, move.toUuid, move.packageName,
16477                            move.dataAppName, move.appId, move.seinfo, move.targetSdkVersion);
16478                } catch (InstallerException e) {
16479                    Slog.w(TAG, "Failed to move app", e);
16480                    return PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
16481                }
16482            }
16483
16484            codeFile = new File(Environment.getDataAppDirectory(move.toUuid), move.dataAppName);
16485            resourceFile = codeFile;
16486            if (DEBUG_INSTALL) Slog.d(TAG, "codeFile after move is " + codeFile);
16487
16488            return PackageManager.INSTALL_SUCCEEDED;
16489        }
16490
16491        int doPreInstall(int status) {
16492            if (status != PackageManager.INSTALL_SUCCEEDED) {
16493                cleanUp(move.toUuid);
16494            }
16495            return status;
16496        }
16497
16498        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
16499            if (status != PackageManager.INSTALL_SUCCEEDED) {
16500                cleanUp(move.toUuid);
16501                return false;
16502            }
16503
16504            // Reflect the move in app info
16505            pkg.setApplicationVolumeUuid(pkg.volumeUuid);
16506            pkg.setApplicationInfoCodePath(pkg.codePath);
16507            pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
16508            pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
16509            pkg.setApplicationInfoResourcePath(pkg.codePath);
16510            pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath);
16511            pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
16512
16513            return true;
16514        }
16515
16516        int doPostInstall(int status, int uid) {
16517            if (status == PackageManager.INSTALL_SUCCEEDED) {
16518                cleanUp(move.fromUuid);
16519            } else {
16520                cleanUp(move.toUuid);
16521            }
16522            return status;
16523        }
16524
16525        @Override
16526        String getCodePath() {
16527            return (codeFile != null) ? codeFile.getAbsolutePath() : null;
16528        }
16529
16530        @Override
16531        String getResourcePath() {
16532            return (resourceFile != null) ? resourceFile.getAbsolutePath() : null;
16533        }
16534
16535        private boolean cleanUp(String volumeUuid) {
16536            final File codeFile = new File(Environment.getDataAppDirectory(volumeUuid),
16537                    move.dataAppName);
16538            Slog.d(TAG, "Cleaning up " + move.packageName + " on " + volumeUuid);
16539            final int[] userIds = sUserManager.getUserIds();
16540            synchronized (mInstallLock) {
16541                // Clean up both app data and code
16542                // All package moves are frozen until finished
16543                for (int userId : userIds) {
16544                    try {
16545                        mInstaller.destroyAppData(volumeUuid, move.packageName, userId,
16546                                StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE, 0);
16547                    } catch (InstallerException e) {
16548                        Slog.w(TAG, String.valueOf(e));
16549                    }
16550                }
16551                removeCodePathLI(codeFile);
16552            }
16553            return true;
16554        }
16555
16556        void cleanUpResourcesLI() {
16557            throw new UnsupportedOperationException();
16558        }
16559
16560        boolean doPostDeleteLI(boolean delete) {
16561            throw new UnsupportedOperationException();
16562        }
16563    }
16564
16565    static String getAsecPackageName(String packageCid) {
16566        int idx = packageCid.lastIndexOf("-");
16567        if (idx == -1) {
16568            return packageCid;
16569        }
16570        return packageCid.substring(0, idx);
16571    }
16572
16573    // Utility method used to create code paths based on package name and available index.
16574    private static String getNextCodePath(String oldCodePath, String prefix, String suffix) {
16575        String idxStr = "";
16576        int idx = 1;
16577        // Fall back to default value of idx=1 if prefix is not
16578        // part of oldCodePath
16579        if (oldCodePath != null) {
16580            String subStr = oldCodePath;
16581            // Drop the suffix right away
16582            if (suffix != null && subStr.endsWith(suffix)) {
16583                subStr = subStr.substring(0, subStr.length() - suffix.length());
16584            }
16585            // If oldCodePath already contains prefix find out the
16586            // ending index to either increment or decrement.
16587            int sidx = subStr.lastIndexOf(prefix);
16588            if (sidx != -1) {
16589                subStr = subStr.substring(sidx + prefix.length());
16590                if (subStr != null) {
16591                    if (subStr.startsWith(INSTALL_PACKAGE_SUFFIX)) {
16592                        subStr = subStr.substring(INSTALL_PACKAGE_SUFFIX.length());
16593                    }
16594                    try {
16595                        idx = Integer.parseInt(subStr);
16596                        if (idx <= 1) {
16597                            idx++;
16598                        } else {
16599                            idx--;
16600                        }
16601                    } catch(NumberFormatException e) {
16602                    }
16603                }
16604            }
16605        }
16606        idxStr = INSTALL_PACKAGE_SUFFIX + Integer.toString(idx);
16607        return prefix + idxStr;
16608    }
16609
16610    private File getNextCodePath(File targetDir, String packageName) {
16611        File result;
16612        SecureRandom random = new SecureRandom();
16613        byte[] bytes = new byte[16];
16614        do {
16615            random.nextBytes(bytes);
16616            String suffix = Base64.encodeToString(bytes, Base64.URL_SAFE | Base64.NO_WRAP);
16617            result = new File(targetDir, packageName + "-" + suffix);
16618        } while (result.exists());
16619        return result;
16620    }
16621
16622    // Utility method that returns the relative package path with respect
16623    // to the installation directory. Like say for /data/data/com.test-1.apk
16624    // string com.test-1 is returned.
16625    static String deriveCodePathName(String codePath) {
16626        if (codePath == null) {
16627            return null;
16628        }
16629        final File codeFile = new File(codePath);
16630        final String name = codeFile.getName();
16631        if (codeFile.isDirectory()) {
16632            return name;
16633        } else if (name.endsWith(".apk") || name.endsWith(".tmp")) {
16634            final int lastDot = name.lastIndexOf('.');
16635            return name.substring(0, lastDot);
16636        } else {
16637            Slog.w(TAG, "Odd, " + codePath + " doesn't look like an APK");
16638            return null;
16639        }
16640    }
16641
16642    static class PackageInstalledInfo {
16643        String name;
16644        int uid;
16645        // The set of users that originally had this package installed.
16646        int[] origUsers;
16647        // The set of users that now have this package installed.
16648        int[] newUsers;
16649        PackageParser.Package pkg;
16650        int returnCode;
16651        String returnMsg;
16652        PackageRemovedInfo removedInfo;
16653        ArrayMap<String, PackageInstalledInfo> addedChildPackages;
16654
16655        public void setError(int code, String msg) {
16656            setReturnCode(code);
16657            setReturnMessage(msg);
16658            Slog.w(TAG, msg);
16659        }
16660
16661        public void setError(String msg, PackageParserException e) {
16662            setReturnCode(e.error);
16663            setReturnMessage(ExceptionUtils.getCompleteMessage(msg, e));
16664            Slog.w(TAG, msg, e);
16665        }
16666
16667        public void setError(String msg, PackageManagerException e) {
16668            returnCode = e.error;
16669            setReturnMessage(ExceptionUtils.getCompleteMessage(msg, e));
16670            Slog.w(TAG, msg, e);
16671        }
16672
16673        public void setReturnCode(int returnCode) {
16674            this.returnCode = returnCode;
16675            final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0;
16676            for (int i = 0; i < childCount; i++) {
16677                addedChildPackages.valueAt(i).returnCode = returnCode;
16678            }
16679        }
16680
16681        private void setReturnMessage(String returnMsg) {
16682            this.returnMsg = returnMsg;
16683            final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0;
16684            for (int i = 0; i < childCount; i++) {
16685                addedChildPackages.valueAt(i).returnMsg = returnMsg;
16686            }
16687        }
16688
16689        // In some error cases we want to convey more info back to the observer
16690        String origPackage;
16691        String origPermission;
16692    }
16693
16694    /*
16695     * Install a non-existing package.
16696     */
16697    private void installNewPackageLIF(PackageParser.Package pkg, final int policyFlags,
16698            int scanFlags, UserHandle user, String installerPackageName, String volumeUuid,
16699            PackageInstalledInfo res, int installReason) {
16700        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installNewPackage");
16701
16702        // Remember this for later, in case we need to rollback this install
16703        String pkgName = pkg.packageName;
16704
16705        if (DEBUG_INSTALL) Slog.d(TAG, "installNewPackageLI: " + pkg);
16706
16707        synchronized(mPackages) {
16708            final String renamedPackage = mSettings.getRenamedPackageLPr(pkgName);
16709            if (renamedPackage != null) {
16710                // A package with the same name is already installed, though
16711                // it has been renamed to an older name.  The package we
16712                // are trying to install should be installed as an update to
16713                // the existing one, but that has not been requested, so bail.
16714                res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName
16715                        + " without first uninstalling package running as "
16716                        + renamedPackage);
16717                return;
16718            }
16719            if (mPackages.containsKey(pkgName)) {
16720                // Don't allow installation over an existing package with the same name.
16721                res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName
16722                        + " without first uninstalling.");
16723                return;
16724            }
16725        }
16726
16727        try {
16728            PackageParser.Package newPackage = scanPackageTracedLI(pkg, policyFlags, scanFlags,
16729                    System.currentTimeMillis(), user);
16730
16731            updateSettingsLI(newPackage, installerPackageName, null, res, user, installReason);
16732
16733            if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
16734                prepareAppDataAfterInstallLIF(newPackage);
16735
16736            } else {
16737                // Remove package from internal structures, but keep around any
16738                // data that might have already existed
16739                deletePackageLIF(pkgName, UserHandle.ALL, false, null,
16740                        PackageManager.DELETE_KEEP_DATA, res.removedInfo, true, null);
16741            }
16742        } catch (PackageManagerException e) {
16743            res.setError("Package couldn't be installed in " + pkg.codePath, e);
16744        }
16745
16746        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
16747    }
16748
16749    private boolean shouldCheckUpgradeKeySetLP(PackageSetting oldPs, int scanFlags) {
16750        // Can't rotate keys during boot or if sharedUser.
16751        if (oldPs == null || (scanFlags&SCAN_INITIAL) != 0 || oldPs.sharedUser != null
16752                || !oldPs.keySetData.isUsingUpgradeKeySets()) {
16753            return false;
16754        }
16755        // app is using upgradeKeySets; make sure all are valid
16756        KeySetManagerService ksms = mSettings.mKeySetManagerService;
16757        long[] upgradeKeySets = oldPs.keySetData.getUpgradeKeySets();
16758        for (int i = 0; i < upgradeKeySets.length; i++) {
16759            if (!ksms.isIdValidKeySetId(upgradeKeySets[i])) {
16760                Slog.wtf(TAG, "Package "
16761                         + (oldPs.name != null ? oldPs.name : "<null>")
16762                         + " contains upgrade-key-set reference to unknown key-set: "
16763                         + upgradeKeySets[i]
16764                         + " reverting to signatures check.");
16765                return false;
16766            }
16767        }
16768        return true;
16769    }
16770
16771    private boolean checkUpgradeKeySetLP(PackageSetting oldPS, PackageParser.Package newPkg) {
16772        // Upgrade keysets are being used.  Determine if new package has a superset of the
16773        // required keys.
16774        long[] upgradeKeySets = oldPS.keySetData.getUpgradeKeySets();
16775        KeySetManagerService ksms = mSettings.mKeySetManagerService;
16776        for (int i = 0; i < upgradeKeySets.length; i++) {
16777            Set<PublicKey> upgradeSet = ksms.getPublicKeysFromKeySetLPr(upgradeKeySets[i]);
16778            if (upgradeSet != null && newPkg.mSigningKeys.containsAll(upgradeSet)) {
16779                return true;
16780            }
16781        }
16782        return false;
16783    }
16784
16785    private static void updateDigest(MessageDigest digest, File file) throws IOException {
16786        try (DigestInputStream digestStream =
16787                new DigestInputStream(new FileInputStream(file), digest)) {
16788            while (digestStream.read() != -1) {} // nothing to do; just plow through the file
16789        }
16790    }
16791
16792    private void replacePackageLIF(PackageParser.Package pkg, final int policyFlags, int scanFlags,
16793            UserHandle user, String installerPackageName, PackageInstalledInfo res,
16794            int installReason) {
16795        final boolean isInstantApp = (scanFlags & SCAN_AS_INSTANT_APP) != 0;
16796
16797        final PackageParser.Package oldPackage;
16798        final PackageSetting ps;
16799        final String pkgName = pkg.packageName;
16800        final int[] allUsers;
16801        final int[] installedUsers;
16802
16803        synchronized(mPackages) {
16804            oldPackage = mPackages.get(pkgName);
16805            if (DEBUG_INSTALL) Slog.d(TAG, "replacePackageLI: new=" + pkg + ", old=" + oldPackage);
16806
16807            // don't allow upgrade to target a release SDK from a pre-release SDK
16808            final boolean oldTargetsPreRelease = oldPackage.applicationInfo.targetSdkVersion
16809                    == android.os.Build.VERSION_CODES.CUR_DEVELOPMENT;
16810            final boolean newTargetsPreRelease = pkg.applicationInfo.targetSdkVersion
16811                    == android.os.Build.VERSION_CODES.CUR_DEVELOPMENT;
16812            if (oldTargetsPreRelease
16813                    && !newTargetsPreRelease
16814                    && ((policyFlags & PackageParser.PARSE_FORCE_SDK) == 0)) {
16815                Slog.w(TAG, "Can't install package targeting released sdk");
16816                res.setReturnCode(PackageManager.INSTALL_FAILED_UPDATE_INCOMPATIBLE);
16817                return;
16818            }
16819
16820            ps = mSettings.mPackages.get(pkgName);
16821
16822            // verify signatures are valid
16823            if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) {
16824                if (!checkUpgradeKeySetLP(ps, pkg)) {
16825                    res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
16826                            "New package not signed by keys specified by upgrade-keysets: "
16827                                    + pkgName);
16828                    return;
16829                }
16830            } else {
16831                // default to original signature matching
16832                if (compareSignatures(oldPackage.mSignatures, pkg.mSignatures)
16833                        != PackageManager.SIGNATURE_MATCH) {
16834                    res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
16835                            "New package has a different signature: " + pkgName);
16836                    return;
16837                }
16838            }
16839
16840            // don't allow a system upgrade unless the upgrade hash matches
16841            if (oldPackage.restrictUpdateHash != null && oldPackage.isSystemApp()) {
16842                byte[] digestBytes = null;
16843                try {
16844                    final MessageDigest digest = MessageDigest.getInstance("SHA-512");
16845                    updateDigest(digest, new File(pkg.baseCodePath));
16846                    if (!ArrayUtils.isEmpty(pkg.splitCodePaths)) {
16847                        for (String path : pkg.splitCodePaths) {
16848                            updateDigest(digest, new File(path));
16849                        }
16850                    }
16851                    digestBytes = digest.digest();
16852                } catch (NoSuchAlgorithmException | IOException e) {
16853                    res.setError(INSTALL_FAILED_INVALID_APK,
16854                            "Could not compute hash: " + pkgName);
16855                    return;
16856                }
16857                if (!Arrays.equals(oldPackage.restrictUpdateHash, digestBytes)) {
16858                    res.setError(INSTALL_FAILED_INVALID_APK,
16859                            "New package fails restrict-update check: " + pkgName);
16860                    return;
16861                }
16862                // retain upgrade restriction
16863                pkg.restrictUpdateHash = oldPackage.restrictUpdateHash;
16864            }
16865
16866            // Check for shared user id changes
16867            String invalidPackageName =
16868                    getParentOrChildPackageChangedSharedUser(oldPackage, pkg);
16869            if (invalidPackageName != null) {
16870                res.setError(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE,
16871                        "Package " + invalidPackageName + " tried to change user "
16872                                + oldPackage.mSharedUserId);
16873                return;
16874            }
16875
16876            // In case of rollback, remember per-user/profile install state
16877            allUsers = sUserManager.getUserIds();
16878            installedUsers = ps.queryInstalledUsers(allUsers, true);
16879
16880            // don't allow an upgrade from full to ephemeral
16881            if (isInstantApp) {
16882                if (user == null || user.getIdentifier() == UserHandle.USER_ALL) {
16883                    for (int currentUser : allUsers) {
16884                        if (!ps.getInstantApp(currentUser)) {
16885                            // can't downgrade from full to instant
16886                            Slog.w(TAG, "Can't replace full app with instant app: " + pkgName
16887                                    + " for user: " + currentUser);
16888                            res.setReturnCode(PackageManager.INSTALL_FAILED_INSTANT_APP_INVALID);
16889                            return;
16890                        }
16891                    }
16892                } else if (!ps.getInstantApp(user.getIdentifier())) {
16893                    // can't downgrade from full to instant
16894                    Slog.w(TAG, "Can't replace full app with instant app: " + pkgName
16895                            + " for user: " + user.getIdentifier());
16896                    res.setReturnCode(PackageManager.INSTALL_FAILED_INSTANT_APP_INVALID);
16897                    return;
16898                }
16899            }
16900        }
16901
16902        // Update what is removed
16903        res.removedInfo = new PackageRemovedInfo(this);
16904        res.removedInfo.uid = oldPackage.applicationInfo.uid;
16905        res.removedInfo.removedPackage = oldPackage.packageName;
16906        res.removedInfo.installerPackageName = ps.installerPackageName;
16907        res.removedInfo.isStaticSharedLib = pkg.staticSharedLibName != null;
16908        res.removedInfo.isUpdate = true;
16909        res.removedInfo.origUsers = installedUsers;
16910        res.removedInfo.installReasons = new SparseArray<>(installedUsers.length);
16911        for (int i = 0; i < installedUsers.length; i++) {
16912            final int userId = installedUsers[i];
16913            res.removedInfo.installReasons.put(userId, ps.getInstallReason(userId));
16914        }
16915
16916        final int childCount = (oldPackage.childPackages != null)
16917                ? oldPackage.childPackages.size() : 0;
16918        for (int i = 0; i < childCount; i++) {
16919            boolean childPackageUpdated = false;
16920            PackageParser.Package childPkg = oldPackage.childPackages.get(i);
16921            final PackageSetting childPs = mSettings.getPackageLPr(childPkg.packageName);
16922            if (res.addedChildPackages != null) {
16923                PackageInstalledInfo childRes = res.addedChildPackages.get(childPkg.packageName);
16924                if (childRes != null) {
16925                    childRes.removedInfo.uid = childPkg.applicationInfo.uid;
16926                    childRes.removedInfo.removedPackage = childPkg.packageName;
16927                    if (childPs != null) {
16928                        childRes.removedInfo.installerPackageName = childPs.installerPackageName;
16929                    }
16930                    childRes.removedInfo.isUpdate = true;
16931                    childRes.removedInfo.installReasons = res.removedInfo.installReasons;
16932                    childPackageUpdated = true;
16933                }
16934            }
16935            if (!childPackageUpdated) {
16936                PackageRemovedInfo childRemovedRes = new PackageRemovedInfo(this);
16937                childRemovedRes.removedPackage = childPkg.packageName;
16938                if (childPs != null) {
16939                    childRemovedRes.installerPackageName = childPs.installerPackageName;
16940                }
16941                childRemovedRes.isUpdate = false;
16942                childRemovedRes.dataRemoved = true;
16943                synchronized (mPackages) {
16944                    if (childPs != null) {
16945                        childRemovedRes.origUsers = childPs.queryInstalledUsers(allUsers, true);
16946                    }
16947                }
16948                if (res.removedInfo.removedChildPackages == null) {
16949                    res.removedInfo.removedChildPackages = new ArrayMap<>();
16950                }
16951                res.removedInfo.removedChildPackages.put(childPkg.packageName, childRemovedRes);
16952            }
16953        }
16954
16955        boolean sysPkg = (isSystemApp(oldPackage));
16956        if (sysPkg) {
16957            // Set the system/privileged flags as needed
16958            final boolean privileged =
16959                    (oldPackage.applicationInfo.privateFlags
16960                            & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0;
16961            final int systemPolicyFlags = policyFlags
16962                    | PackageParser.PARSE_IS_SYSTEM
16963                    | (privileged ? PackageParser.PARSE_IS_PRIVILEGED : 0);
16964
16965            replaceSystemPackageLIF(oldPackage, pkg, systemPolicyFlags, scanFlags,
16966                    user, allUsers, installerPackageName, res, installReason);
16967        } else {
16968            replaceNonSystemPackageLIF(oldPackage, pkg, policyFlags, scanFlags,
16969                    user, allUsers, installerPackageName, res, installReason);
16970        }
16971    }
16972
16973    @Override
16974    public List<String> getPreviousCodePaths(String packageName) {
16975        final List<String> result = new ArrayList<>();
16976        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
16977            return result;
16978        }
16979        final PackageSetting ps = mSettings.mPackages.get(packageName);
16980        if (ps != null && ps.oldCodePaths != null) {
16981            result.addAll(ps.oldCodePaths);
16982        }
16983        return result;
16984    }
16985
16986    private void replaceNonSystemPackageLIF(PackageParser.Package deletedPackage,
16987            PackageParser.Package pkg, final int policyFlags, int scanFlags, UserHandle user,
16988            int[] allUsers, String installerPackageName, PackageInstalledInfo res,
16989            int installReason) {
16990        if (DEBUG_INSTALL) Slog.d(TAG, "replaceNonSystemPackageLI: new=" + pkg + ", old="
16991                + deletedPackage);
16992
16993        String pkgName = deletedPackage.packageName;
16994        boolean deletedPkg = true;
16995        boolean addedPkg = false;
16996        boolean updatedSettings = false;
16997        final boolean killApp = (scanFlags & SCAN_DONT_KILL_APP) == 0;
16998        final int deleteFlags = PackageManager.DELETE_KEEP_DATA
16999                | (killApp ? 0 : PackageManager.DELETE_DONT_KILL_APP);
17000
17001        final long origUpdateTime = (pkg.mExtras != null)
17002                ? ((PackageSetting)pkg.mExtras).lastUpdateTime : 0;
17003
17004        // First delete the existing package while retaining the data directory
17005        if (!deletePackageLIF(pkgName, null, true, allUsers, deleteFlags,
17006                res.removedInfo, true, pkg)) {
17007            // If the existing package wasn't successfully deleted
17008            res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, "replaceNonSystemPackageLI");
17009            deletedPkg = false;
17010        } else {
17011            // Successfully deleted the old package; proceed with replace.
17012
17013            // If deleted package lived in a container, give users a chance to
17014            // relinquish resources before killing.
17015            if (deletedPackage.isForwardLocked() || isExternal(deletedPackage)) {
17016                if (DEBUG_INSTALL) {
17017                    Slog.i(TAG, "upgrading pkg " + deletedPackage + " is ASEC-hosted -> UNAVAILABLE");
17018                }
17019                final int[] uidArray = new int[] { deletedPackage.applicationInfo.uid };
17020                final ArrayList<String> pkgList = new ArrayList<String>(1);
17021                pkgList.add(deletedPackage.applicationInfo.packageName);
17022                sendResourcesChangedBroadcast(false, true, pkgList, uidArray, null);
17023            }
17024
17025            clearAppDataLIF(pkg, UserHandle.USER_ALL, StorageManager.FLAG_STORAGE_DE
17026                    | StorageManager.FLAG_STORAGE_CE | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
17027            clearAppProfilesLIF(deletedPackage, UserHandle.USER_ALL);
17028
17029            try {
17030                final PackageParser.Package newPackage = scanPackageTracedLI(pkg, policyFlags,
17031                        scanFlags | SCAN_UPDATE_TIME, System.currentTimeMillis(), user);
17032                updateSettingsLI(newPackage, installerPackageName, allUsers, res, user,
17033                        installReason);
17034
17035                // Update the in-memory copy of the previous code paths.
17036                PackageSetting ps = mSettings.mPackages.get(pkgName);
17037                if (!killApp) {
17038                    if (ps.oldCodePaths == null) {
17039                        ps.oldCodePaths = new ArraySet<>();
17040                    }
17041                    Collections.addAll(ps.oldCodePaths, deletedPackage.baseCodePath);
17042                    if (deletedPackage.splitCodePaths != null) {
17043                        Collections.addAll(ps.oldCodePaths, deletedPackage.splitCodePaths);
17044                    }
17045                } else {
17046                    ps.oldCodePaths = null;
17047                }
17048                if (ps.childPackageNames != null) {
17049                    for (int i = ps.childPackageNames.size() - 1; i >= 0; --i) {
17050                        final String childPkgName = ps.childPackageNames.get(i);
17051                        final PackageSetting childPs = mSettings.mPackages.get(childPkgName);
17052                        childPs.oldCodePaths = ps.oldCodePaths;
17053                    }
17054                }
17055                // set instant app status, but, only if it's explicitly specified
17056                final boolean instantApp = (scanFlags & SCAN_AS_INSTANT_APP) != 0;
17057                final boolean fullApp = (scanFlags & SCAN_AS_FULL_APP) != 0;
17058                setInstantAppForUser(ps, user.getIdentifier(), instantApp, fullApp);
17059                prepareAppDataAfterInstallLIF(newPackage);
17060                addedPkg = true;
17061                mDexManager.notifyPackageUpdated(newPackage.packageName,
17062                        newPackage.baseCodePath, newPackage.splitCodePaths);
17063            } catch (PackageManagerException e) {
17064                res.setError("Package couldn't be installed in " + pkg.codePath, e);
17065            }
17066        }
17067
17068        if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
17069            if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, rolling pack: " + pkgName);
17070
17071            // Revert all internal state mutations and added folders for the failed install
17072            if (addedPkg) {
17073                deletePackageLIF(pkgName, null, true, allUsers, deleteFlags,
17074                        res.removedInfo, true, null);
17075            }
17076
17077            // Restore the old package
17078            if (deletedPkg) {
17079                if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, reinstalling: " + deletedPackage);
17080                File restoreFile = new File(deletedPackage.codePath);
17081                // Parse old package
17082                boolean oldExternal = isExternal(deletedPackage);
17083                int oldParseFlags  = mDefParseFlags | PackageParser.PARSE_CHATTY |
17084                        (deletedPackage.isForwardLocked() ? PackageParser.PARSE_FORWARD_LOCK : 0) |
17085                        (oldExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0);
17086                int oldScanFlags = SCAN_UPDATE_SIGNATURE | SCAN_UPDATE_TIME;
17087                try {
17088                    scanPackageTracedLI(restoreFile, oldParseFlags, oldScanFlags, origUpdateTime,
17089                            null);
17090                } catch (PackageManagerException e) {
17091                    Slog.e(TAG, "Failed to restore package : " + pkgName + " after failed upgrade: "
17092                            + e.getMessage());
17093                    return;
17094                }
17095
17096                synchronized (mPackages) {
17097                    // Ensure the installer package name up to date
17098                    setInstallerPackageNameLPw(deletedPackage, installerPackageName);
17099
17100                    // Update permissions for restored package
17101                    updatePermissionsLPw(deletedPackage, UPDATE_PERMISSIONS_ALL);
17102
17103                    mSettings.writeLPr();
17104                }
17105
17106                Slog.i(TAG, "Successfully restored package : " + pkgName + " after failed upgrade");
17107            }
17108        } else {
17109            synchronized (mPackages) {
17110                PackageSetting ps = mSettings.getPackageLPr(pkg.packageName);
17111                if (ps != null) {
17112                    res.removedInfo.removedForAllUsers = mPackages.get(ps.name) == null;
17113                    if (res.removedInfo.removedChildPackages != null) {
17114                        final int childCount = res.removedInfo.removedChildPackages.size();
17115                        // Iterate in reverse as we may modify the collection
17116                        for (int i = childCount - 1; i >= 0; i--) {
17117                            String childPackageName = res.removedInfo.removedChildPackages.keyAt(i);
17118                            if (res.addedChildPackages.containsKey(childPackageName)) {
17119                                res.removedInfo.removedChildPackages.removeAt(i);
17120                            } else {
17121                                PackageRemovedInfo childInfo = res.removedInfo
17122                                        .removedChildPackages.valueAt(i);
17123                                childInfo.removedForAllUsers = mPackages.get(
17124                                        childInfo.removedPackage) == null;
17125                            }
17126                        }
17127                    }
17128                }
17129            }
17130        }
17131    }
17132
17133    private void replaceSystemPackageLIF(PackageParser.Package deletedPackage,
17134            PackageParser.Package pkg, final int policyFlags, int scanFlags, UserHandle user,
17135            int[] allUsers, String installerPackageName, PackageInstalledInfo res,
17136            int installReason) {
17137        if (DEBUG_INSTALL) Slog.d(TAG, "replaceSystemPackageLI: new=" + pkg
17138                + ", old=" + deletedPackage);
17139
17140        final boolean disabledSystem;
17141
17142        // Remove existing system package
17143        removePackageLI(deletedPackage, true);
17144
17145        synchronized (mPackages) {
17146            disabledSystem = disableSystemPackageLPw(deletedPackage, pkg);
17147        }
17148        if (!disabledSystem) {
17149            // We didn't need to disable the .apk as a current system package,
17150            // which means we are replacing another update that is already
17151            // installed.  We need to make sure to delete the older one's .apk.
17152            res.removedInfo.args = createInstallArgsForExisting(0,
17153                    deletedPackage.applicationInfo.getCodePath(),
17154                    deletedPackage.applicationInfo.getResourcePath(),
17155                    getAppDexInstructionSets(deletedPackage.applicationInfo));
17156        } else {
17157            res.removedInfo.args = null;
17158        }
17159
17160        // Successfully disabled the old package. Now proceed with re-installation
17161        clearAppDataLIF(pkg, UserHandle.USER_ALL, StorageManager.FLAG_STORAGE_DE
17162                | StorageManager.FLAG_STORAGE_CE | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
17163        clearAppProfilesLIF(deletedPackage, UserHandle.USER_ALL);
17164
17165        res.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
17166        pkg.setApplicationInfoFlags(ApplicationInfo.FLAG_UPDATED_SYSTEM_APP,
17167                ApplicationInfo.FLAG_UPDATED_SYSTEM_APP);
17168
17169        PackageParser.Package newPackage = null;
17170        try {
17171            // Add the package to the internal data structures
17172            newPackage = scanPackageTracedLI(pkg, policyFlags, scanFlags, 0, user);
17173
17174            // Set the update and install times
17175            PackageSetting deletedPkgSetting = (PackageSetting) deletedPackage.mExtras;
17176            setInstallAndUpdateTime(newPackage, deletedPkgSetting.firstInstallTime,
17177                    System.currentTimeMillis());
17178
17179            // Update the package dynamic state if succeeded
17180            if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
17181                // Now that the install succeeded make sure we remove data
17182                // directories for any child package the update removed.
17183                final int deletedChildCount = (deletedPackage.childPackages != null)
17184                        ? deletedPackage.childPackages.size() : 0;
17185                final int newChildCount = (newPackage.childPackages != null)
17186                        ? newPackage.childPackages.size() : 0;
17187                for (int i = 0; i < deletedChildCount; i++) {
17188                    PackageParser.Package deletedChildPkg = deletedPackage.childPackages.get(i);
17189                    boolean childPackageDeleted = true;
17190                    for (int j = 0; j < newChildCount; j++) {
17191                        PackageParser.Package newChildPkg = newPackage.childPackages.get(j);
17192                        if (deletedChildPkg.packageName.equals(newChildPkg.packageName)) {
17193                            childPackageDeleted = false;
17194                            break;
17195                        }
17196                    }
17197                    if (childPackageDeleted) {
17198                        PackageSetting ps = mSettings.getDisabledSystemPkgLPr(
17199                                deletedChildPkg.packageName);
17200                        if (ps != null && res.removedInfo.removedChildPackages != null) {
17201                            PackageRemovedInfo removedChildRes = res.removedInfo
17202                                    .removedChildPackages.get(deletedChildPkg.packageName);
17203                            removePackageDataLIF(ps, allUsers, removedChildRes, 0, false);
17204                            removedChildRes.removedForAllUsers = mPackages.get(ps.name) == null;
17205                        }
17206                    }
17207                }
17208
17209                updateSettingsLI(newPackage, installerPackageName, allUsers, res, user,
17210                        installReason);
17211                prepareAppDataAfterInstallLIF(newPackage);
17212
17213                mDexManager.notifyPackageUpdated(newPackage.packageName,
17214                            newPackage.baseCodePath, newPackage.splitCodePaths);
17215            }
17216        } catch (PackageManagerException e) {
17217            res.setReturnCode(INSTALL_FAILED_INTERNAL_ERROR);
17218            res.setError("Package couldn't be installed in " + pkg.codePath, e);
17219        }
17220
17221        if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
17222            // Re installation failed. Restore old information
17223            // Remove new pkg information
17224            if (newPackage != null) {
17225                removeInstalledPackageLI(newPackage, true);
17226            }
17227            // Add back the old system package
17228            try {
17229                scanPackageTracedLI(deletedPackage, policyFlags, SCAN_UPDATE_SIGNATURE, 0, user);
17230            } catch (PackageManagerException e) {
17231                Slog.e(TAG, "Failed to restore original package: " + e.getMessage());
17232            }
17233
17234            synchronized (mPackages) {
17235                if (disabledSystem) {
17236                    enableSystemPackageLPw(deletedPackage);
17237                }
17238
17239                // Ensure the installer package name up to date
17240                setInstallerPackageNameLPw(deletedPackage, installerPackageName);
17241
17242                // Update permissions for restored package
17243                updatePermissionsLPw(deletedPackage, UPDATE_PERMISSIONS_ALL);
17244
17245                mSettings.writeLPr();
17246            }
17247
17248            Slog.i(TAG, "Successfully restored package : " + deletedPackage.packageName
17249                    + " after failed upgrade");
17250        }
17251    }
17252
17253    /**
17254     * Checks whether the parent or any of the child packages have a change shared
17255     * user. For a package to be a valid update the shred users of the parent and
17256     * the children should match. We may later support changing child shared users.
17257     * @param oldPkg The updated package.
17258     * @param newPkg The update package.
17259     * @return The shared user that change between the versions.
17260     */
17261    private String getParentOrChildPackageChangedSharedUser(PackageParser.Package oldPkg,
17262            PackageParser.Package newPkg) {
17263        // Check parent shared user
17264        if (!Objects.equals(oldPkg.mSharedUserId, newPkg.mSharedUserId)) {
17265            return newPkg.packageName;
17266        }
17267        // Check child shared users
17268        final int oldChildCount = (oldPkg.childPackages != null) ? oldPkg.childPackages.size() : 0;
17269        final int newChildCount = (newPkg.childPackages != null) ? newPkg.childPackages.size() : 0;
17270        for (int i = 0; i < newChildCount; i++) {
17271            PackageParser.Package newChildPkg = newPkg.childPackages.get(i);
17272            // If this child was present, did it have the same shared user?
17273            for (int j = 0; j < oldChildCount; j++) {
17274                PackageParser.Package oldChildPkg = oldPkg.childPackages.get(j);
17275                if (newChildPkg.packageName.equals(oldChildPkg.packageName)
17276                        && !Objects.equals(newChildPkg.mSharedUserId, oldChildPkg.mSharedUserId)) {
17277                    return newChildPkg.packageName;
17278                }
17279            }
17280        }
17281        return null;
17282    }
17283
17284    private void removeNativeBinariesLI(PackageSetting ps) {
17285        // Remove the lib path for the parent package
17286        if (ps != null) {
17287            NativeLibraryHelper.removeNativeBinariesLI(ps.legacyNativeLibraryPathString);
17288            // Remove the lib path for the child packages
17289            final int childCount = (ps.childPackageNames != null) ? ps.childPackageNames.size() : 0;
17290            for (int i = 0; i < childCount; i++) {
17291                PackageSetting childPs = null;
17292                synchronized (mPackages) {
17293                    childPs = mSettings.getPackageLPr(ps.childPackageNames.get(i));
17294                }
17295                if (childPs != null) {
17296                    NativeLibraryHelper.removeNativeBinariesLI(childPs
17297                            .legacyNativeLibraryPathString);
17298                }
17299            }
17300        }
17301    }
17302
17303    private void enableSystemPackageLPw(PackageParser.Package pkg) {
17304        // Enable the parent package
17305        mSettings.enableSystemPackageLPw(pkg.packageName);
17306        // Enable the child packages
17307        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
17308        for (int i = 0; i < childCount; i++) {
17309            PackageParser.Package childPkg = pkg.childPackages.get(i);
17310            mSettings.enableSystemPackageLPw(childPkg.packageName);
17311        }
17312    }
17313
17314    private boolean disableSystemPackageLPw(PackageParser.Package oldPkg,
17315            PackageParser.Package newPkg) {
17316        // Disable the parent package (parent always replaced)
17317        boolean disabled = mSettings.disableSystemPackageLPw(oldPkg.packageName, true);
17318        // Disable the child packages
17319        final int childCount = (oldPkg.childPackages != null) ? oldPkg.childPackages.size() : 0;
17320        for (int i = 0; i < childCount; i++) {
17321            PackageParser.Package childPkg = oldPkg.childPackages.get(i);
17322            final boolean replace = newPkg.hasChildPackage(childPkg.packageName);
17323            disabled |= mSettings.disableSystemPackageLPw(childPkg.packageName, replace);
17324        }
17325        return disabled;
17326    }
17327
17328    private void setInstallerPackageNameLPw(PackageParser.Package pkg,
17329            String installerPackageName) {
17330        // Enable the parent package
17331        mSettings.setInstallerPackageName(pkg.packageName, installerPackageName);
17332        // Enable the child packages
17333        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
17334        for (int i = 0; i < childCount; i++) {
17335            PackageParser.Package childPkg = pkg.childPackages.get(i);
17336            mSettings.setInstallerPackageName(childPkg.packageName, installerPackageName);
17337        }
17338    }
17339
17340    private int[] revokeUnusedSharedUserPermissionsLPw(SharedUserSetting su, int[] allUserIds) {
17341        // Collect all used permissions in the UID
17342        ArraySet<String> usedPermissions = new ArraySet<>();
17343        final int packageCount = su.packages.size();
17344        for (int i = 0; i < packageCount; i++) {
17345            PackageSetting ps = su.packages.valueAt(i);
17346            if (ps.pkg == null) {
17347                continue;
17348            }
17349            final int requestedPermCount = ps.pkg.requestedPermissions.size();
17350            for (int j = 0; j < requestedPermCount; j++) {
17351                String permission = ps.pkg.requestedPermissions.get(j);
17352                BasePermission bp = mSettings.mPermissions.get(permission);
17353                if (bp != null) {
17354                    usedPermissions.add(permission);
17355                }
17356            }
17357        }
17358
17359        PermissionsState permissionsState = su.getPermissionsState();
17360        // Prune install permissions
17361        List<PermissionState> installPermStates = permissionsState.getInstallPermissionStates();
17362        final int installPermCount = installPermStates.size();
17363        for (int i = installPermCount - 1; i >= 0;  i--) {
17364            PermissionState permissionState = installPermStates.get(i);
17365            if (!usedPermissions.contains(permissionState.getName())) {
17366                BasePermission bp = mSettings.mPermissions.get(permissionState.getName());
17367                if (bp != null) {
17368                    permissionsState.revokeInstallPermission(bp);
17369                    permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL,
17370                            PackageManager.MASK_PERMISSION_FLAGS, 0);
17371                }
17372            }
17373        }
17374
17375        int[] runtimePermissionChangedUserIds = EmptyArray.INT;
17376
17377        // Prune runtime permissions
17378        for (int userId : allUserIds) {
17379            List<PermissionState> runtimePermStates = permissionsState
17380                    .getRuntimePermissionStates(userId);
17381            final int runtimePermCount = runtimePermStates.size();
17382            for (int i = runtimePermCount - 1; i >= 0; i--) {
17383                PermissionState permissionState = runtimePermStates.get(i);
17384                if (!usedPermissions.contains(permissionState.getName())) {
17385                    BasePermission bp = mSettings.mPermissions.get(permissionState.getName());
17386                    if (bp != null) {
17387                        permissionsState.revokeRuntimePermission(bp, userId);
17388                        permissionsState.updatePermissionFlags(bp, userId,
17389                                PackageManager.MASK_PERMISSION_FLAGS, 0);
17390                        runtimePermissionChangedUserIds = ArrayUtils.appendInt(
17391                                runtimePermissionChangedUserIds, userId);
17392                    }
17393                }
17394            }
17395        }
17396
17397        return runtimePermissionChangedUserIds;
17398    }
17399
17400    private void updateSettingsLI(PackageParser.Package newPackage, String installerPackageName,
17401            int[] allUsers, PackageInstalledInfo res, UserHandle user, int installReason) {
17402        // Update the parent package setting
17403        updateSettingsInternalLI(newPackage, installerPackageName, allUsers, res.origUsers,
17404                res, user, installReason);
17405        // Update the child packages setting
17406        final int childCount = (newPackage.childPackages != null)
17407                ? newPackage.childPackages.size() : 0;
17408        for (int i = 0; i < childCount; i++) {
17409            PackageParser.Package childPackage = newPackage.childPackages.get(i);
17410            PackageInstalledInfo childRes = res.addedChildPackages.get(childPackage.packageName);
17411            updateSettingsInternalLI(childPackage, installerPackageName, allUsers,
17412                    childRes.origUsers, childRes, user, installReason);
17413        }
17414    }
17415
17416    private void updateSettingsInternalLI(PackageParser.Package newPackage,
17417            String installerPackageName, int[] allUsers, int[] installedForUsers,
17418            PackageInstalledInfo res, UserHandle user, int installReason) {
17419        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings");
17420
17421        String pkgName = newPackage.packageName;
17422        synchronized (mPackages) {
17423            //write settings. the installStatus will be incomplete at this stage.
17424            //note that the new package setting would have already been
17425            //added to mPackages. It hasn't been persisted yet.
17426            mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_INCOMPLETE);
17427            // TODO: Remove this write? It's also written at the end of this method
17428            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings");
17429            mSettings.writeLPr();
17430            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
17431        }
17432
17433        if (DEBUG_INSTALL) Slog.d(TAG, "New package installed in " + newPackage.codePath);
17434        synchronized (mPackages) {
17435            updatePermissionsLPw(newPackage.packageName, newPackage,
17436                    UPDATE_PERMISSIONS_REPLACE_PKG | (newPackage.permissions.size() > 0
17437                            ? UPDATE_PERMISSIONS_ALL : 0));
17438            // For system-bundled packages, we assume that installing an upgraded version
17439            // of the package implies that the user actually wants to run that new code,
17440            // so we enable the package.
17441            PackageSetting ps = mSettings.mPackages.get(pkgName);
17442            final int userId = user.getIdentifier();
17443            if (ps != null) {
17444                if (isSystemApp(newPackage)) {
17445                    if (DEBUG_INSTALL) {
17446                        Slog.d(TAG, "Implicitly enabling system package on upgrade: " + pkgName);
17447                    }
17448                    // Enable system package for requested users
17449                    if (res.origUsers != null) {
17450                        for (int origUserId : res.origUsers) {
17451                            if (userId == UserHandle.USER_ALL || userId == origUserId) {
17452                                ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT,
17453                                        origUserId, installerPackageName);
17454                            }
17455                        }
17456                    }
17457                    // Also convey the prior install/uninstall state
17458                    if (allUsers != null && installedForUsers != null) {
17459                        for (int currentUserId : allUsers) {
17460                            final boolean installed = ArrayUtils.contains(
17461                                    installedForUsers, currentUserId);
17462                            if (DEBUG_INSTALL) {
17463                                Slog.d(TAG, "    user " + currentUserId + " => " + installed);
17464                            }
17465                            ps.setInstalled(installed, currentUserId);
17466                        }
17467                        // these install state changes will be persisted in the
17468                        // upcoming call to mSettings.writeLPr().
17469                    }
17470                }
17471                // It's implied that when a user requests installation, they want the app to be
17472                // installed and enabled.
17473                if (userId != UserHandle.USER_ALL) {
17474                    ps.setInstalled(true, userId);
17475                    ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, userId, installerPackageName);
17476                }
17477
17478                // When replacing an existing package, preserve the original install reason for all
17479                // users that had the package installed before.
17480                final Set<Integer> previousUserIds = new ArraySet<>();
17481                if (res.removedInfo != null && res.removedInfo.installReasons != null) {
17482                    final int installReasonCount = res.removedInfo.installReasons.size();
17483                    for (int i = 0; i < installReasonCount; i++) {
17484                        final int previousUserId = res.removedInfo.installReasons.keyAt(i);
17485                        final int previousInstallReason = res.removedInfo.installReasons.valueAt(i);
17486                        ps.setInstallReason(previousInstallReason, previousUserId);
17487                        previousUserIds.add(previousUserId);
17488                    }
17489                }
17490
17491                // Set install reason for users that are having the package newly installed.
17492                if (userId == UserHandle.USER_ALL) {
17493                    for (int currentUserId : sUserManager.getUserIds()) {
17494                        if (!previousUserIds.contains(currentUserId)) {
17495                            ps.setInstallReason(installReason, currentUserId);
17496                        }
17497                    }
17498                } else if (!previousUserIds.contains(userId)) {
17499                    ps.setInstallReason(installReason, userId);
17500                }
17501                mSettings.writeKernelMappingLPr(ps);
17502            }
17503            res.name = pkgName;
17504            res.uid = newPackage.applicationInfo.uid;
17505            res.pkg = newPackage;
17506            mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_COMPLETE);
17507            mSettings.setInstallerPackageName(pkgName, installerPackageName);
17508            res.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
17509            //to update install status
17510            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings");
17511            mSettings.writeLPr();
17512            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
17513        }
17514
17515        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
17516    }
17517
17518    private void installPackageTracedLI(InstallArgs args, PackageInstalledInfo res) {
17519        try {
17520            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installPackage");
17521            installPackageLI(args, res);
17522        } finally {
17523            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
17524        }
17525    }
17526
17527    private void installPackageLI(InstallArgs args, PackageInstalledInfo res) {
17528        final int installFlags = args.installFlags;
17529        final String installerPackageName = args.installerPackageName;
17530        final String volumeUuid = args.volumeUuid;
17531        final File tmpPackageFile = new File(args.getCodePath());
17532        final boolean forwardLocked = ((installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0);
17533        final boolean onExternal = (((installFlags & PackageManager.INSTALL_EXTERNAL) != 0)
17534                || (args.volumeUuid != null));
17535        final boolean instantApp = ((installFlags & PackageManager.INSTALL_INSTANT_APP) != 0);
17536        final boolean fullApp = ((installFlags & PackageManager.INSTALL_FULL_APP) != 0);
17537        final boolean forceSdk = ((installFlags & PackageManager.INSTALL_FORCE_SDK) != 0);
17538        boolean replace = false;
17539        int scanFlags = SCAN_NEW_INSTALL | SCAN_UPDATE_SIGNATURE;
17540        if (args.move != null) {
17541            // moving a complete application; perform an initial scan on the new install location
17542            scanFlags |= SCAN_INITIAL;
17543        }
17544        if ((installFlags & PackageManager.INSTALL_DONT_KILL_APP) != 0) {
17545            scanFlags |= SCAN_DONT_KILL_APP;
17546        }
17547        if (instantApp) {
17548            scanFlags |= SCAN_AS_INSTANT_APP;
17549        }
17550        if (fullApp) {
17551            scanFlags |= SCAN_AS_FULL_APP;
17552        }
17553
17554        // Result object to be returned
17555        res.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
17556
17557        if (DEBUG_INSTALL) Slog.d(TAG, "installPackageLI: path=" + tmpPackageFile);
17558
17559        // Sanity check
17560        if (instantApp && (forwardLocked || onExternal)) {
17561            Slog.i(TAG, "Incompatible ephemeral install; fwdLocked=" + forwardLocked
17562                    + " external=" + onExternal);
17563            res.setReturnCode(PackageManager.INSTALL_FAILED_INSTANT_APP_INVALID);
17564            return;
17565        }
17566
17567        // Retrieve PackageSettings and parse package
17568        final int parseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY
17569                | PackageParser.PARSE_ENFORCE_CODE
17570                | (forwardLocked ? PackageParser.PARSE_FORWARD_LOCK : 0)
17571                | (onExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0)
17572                | (instantApp ? PackageParser.PARSE_IS_EPHEMERAL : 0)
17573                | (forceSdk ? PackageParser.PARSE_FORCE_SDK : 0);
17574        PackageParser pp = new PackageParser();
17575        pp.setSeparateProcesses(mSeparateProcesses);
17576        pp.setDisplayMetrics(mMetrics);
17577        pp.setCallback(mPackageParserCallback);
17578
17579        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "parsePackage");
17580        final PackageParser.Package pkg;
17581        try {
17582            pkg = pp.parsePackage(tmpPackageFile, parseFlags);
17583        } catch (PackageParserException e) {
17584            res.setError("Failed parse during installPackageLI", e);
17585            return;
17586        } finally {
17587            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
17588        }
17589
17590        // Instant apps must have target SDK >= O and have targetSanboxVersion >= 2
17591        if (instantApp && pkg.applicationInfo.targetSdkVersion <= Build.VERSION_CODES.N_MR1) {
17592            Slog.w(TAG, "Instant app package " + pkg.packageName
17593                    + " does not target O, this will be a fatal error.");
17594            // STOPSHIP: Make this a fatal error
17595            pkg.applicationInfo.targetSdkVersion = Build.VERSION_CODES.O;
17596        }
17597        if (instantApp && pkg.applicationInfo.targetSandboxVersion != 2) {
17598            Slog.w(TAG, "Instant app package " + pkg.packageName
17599                    + " does not target targetSandboxVersion 2, this will be a fatal error.");
17600            // STOPSHIP: Make this a fatal error
17601            pkg.applicationInfo.targetSandboxVersion = 2;
17602        }
17603
17604        if (pkg.applicationInfo.isStaticSharedLibrary()) {
17605            // Static shared libraries have synthetic package names
17606            renameStaticSharedLibraryPackage(pkg);
17607
17608            // No static shared libs on external storage
17609            if (onExternal) {
17610                Slog.i(TAG, "Static shared libs can only be installed on internal storage.");
17611                res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION,
17612                        "Packages declaring static-shared libs cannot be updated");
17613                return;
17614            }
17615        }
17616
17617        // If we are installing a clustered package add results for the children
17618        if (pkg.childPackages != null) {
17619            synchronized (mPackages) {
17620                final int childCount = pkg.childPackages.size();
17621                for (int i = 0; i < childCount; i++) {
17622                    PackageParser.Package childPkg = pkg.childPackages.get(i);
17623                    PackageInstalledInfo childRes = new PackageInstalledInfo();
17624                    childRes.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
17625                    childRes.pkg = childPkg;
17626                    childRes.name = childPkg.packageName;
17627                    PackageSetting childPs = mSettings.getPackageLPr(childPkg.packageName);
17628                    if (childPs != null) {
17629                        childRes.origUsers = childPs.queryInstalledUsers(
17630                                sUserManager.getUserIds(), true);
17631                    }
17632                    if ((mPackages.containsKey(childPkg.packageName))) {
17633                        childRes.removedInfo = new PackageRemovedInfo(this);
17634                        childRes.removedInfo.removedPackage = childPkg.packageName;
17635                        childRes.removedInfo.installerPackageName = childPs.installerPackageName;
17636                    }
17637                    if (res.addedChildPackages == null) {
17638                        res.addedChildPackages = new ArrayMap<>();
17639                    }
17640                    res.addedChildPackages.put(childPkg.packageName, childRes);
17641                }
17642            }
17643        }
17644
17645        // If package doesn't declare API override, mark that we have an install
17646        // time CPU ABI override.
17647        if (TextUtils.isEmpty(pkg.cpuAbiOverride)) {
17648            pkg.cpuAbiOverride = args.abiOverride;
17649        }
17650
17651        String pkgName = res.name = pkg.packageName;
17652        if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_TEST_ONLY) != 0) {
17653            if ((installFlags & PackageManager.INSTALL_ALLOW_TEST) == 0) {
17654                res.setError(INSTALL_FAILED_TEST_ONLY, "installPackageLI");
17655                return;
17656            }
17657        }
17658
17659        try {
17660            // either use what we've been given or parse directly from the APK
17661            if (args.certificates != null) {
17662                try {
17663                    PackageParser.populateCertificates(pkg, args.certificates);
17664                } catch (PackageParserException e) {
17665                    // there was something wrong with the certificates we were given;
17666                    // try to pull them from the APK
17667                    PackageParser.collectCertificates(pkg, parseFlags);
17668                }
17669            } else {
17670                PackageParser.collectCertificates(pkg, parseFlags);
17671            }
17672        } catch (PackageParserException e) {
17673            res.setError("Failed collect during installPackageLI", e);
17674            return;
17675        }
17676
17677        // Get rid of all references to package scan path via parser.
17678        pp = null;
17679        String oldCodePath = null;
17680        boolean systemApp = false;
17681        synchronized (mPackages) {
17682            // Check if installing already existing package
17683            if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
17684                String oldName = mSettings.getRenamedPackageLPr(pkgName);
17685                if (pkg.mOriginalPackages != null
17686                        && pkg.mOriginalPackages.contains(oldName)
17687                        && mPackages.containsKey(oldName)) {
17688                    // This package is derived from an original package,
17689                    // and this device has been updating from that original
17690                    // name.  We must continue using the original name, so
17691                    // rename the new package here.
17692                    pkg.setPackageName(oldName);
17693                    pkgName = pkg.packageName;
17694                    replace = true;
17695                    if (DEBUG_INSTALL) Slog.d(TAG, "Replacing existing renamed package: oldName="
17696                            + oldName + " pkgName=" + pkgName);
17697                } else if (mPackages.containsKey(pkgName)) {
17698                    // This package, under its official name, already exists
17699                    // on the device; we should replace it.
17700                    replace = true;
17701                    if (DEBUG_INSTALL) Slog.d(TAG, "Replace existing pacakge: " + pkgName);
17702                }
17703
17704                // Child packages are installed through the parent package
17705                if (pkg.parentPackage != null) {
17706                    res.setError(PackageManager.INSTALL_PARSE_FAILED_BAD_PACKAGE_NAME,
17707                            "Package " + pkg.packageName + " is child of package "
17708                                    + pkg.parentPackage.parentPackage + ". Child packages "
17709                                    + "can be updated only through the parent package.");
17710                    return;
17711                }
17712
17713                if (replace) {
17714                    // Prevent apps opting out from runtime permissions
17715                    PackageParser.Package oldPackage = mPackages.get(pkgName);
17716                    final int oldTargetSdk = oldPackage.applicationInfo.targetSdkVersion;
17717                    final int newTargetSdk = pkg.applicationInfo.targetSdkVersion;
17718                    if (oldTargetSdk > Build.VERSION_CODES.LOLLIPOP_MR1
17719                            && newTargetSdk <= Build.VERSION_CODES.LOLLIPOP_MR1) {
17720                        res.setError(PackageManager.INSTALL_FAILED_PERMISSION_MODEL_DOWNGRADE,
17721                                "Package " + pkg.packageName + " new target SDK " + newTargetSdk
17722                                        + " doesn't support runtime permissions but the old"
17723                                        + " target SDK " + oldTargetSdk + " does.");
17724                        return;
17725                    }
17726                    // Prevent apps from downgrading their targetSandbox.
17727                    final int oldTargetSandbox = oldPackage.applicationInfo.targetSandboxVersion;
17728                    final int newTargetSandbox = pkg.applicationInfo.targetSandboxVersion;
17729                    if (oldTargetSandbox == 2 && newTargetSandbox != 2) {
17730                        res.setError(PackageManager.INSTALL_FAILED_SANDBOX_VERSION_DOWNGRADE,
17731                                "Package " + pkg.packageName + " new target sandbox "
17732                                + newTargetSandbox + " is incompatible with the previous value of"
17733                                + oldTargetSandbox + ".");
17734                        return;
17735                    }
17736
17737                    // Prevent installing of child packages
17738                    if (oldPackage.parentPackage != null) {
17739                        res.setError(PackageManager.INSTALL_PARSE_FAILED_BAD_PACKAGE_NAME,
17740                                "Package " + pkg.packageName + " is child of package "
17741                                        + oldPackage.parentPackage + ". Child packages "
17742                                        + "can be updated only through the parent package.");
17743                        return;
17744                    }
17745                }
17746            }
17747
17748            PackageSetting ps = mSettings.mPackages.get(pkgName);
17749            if (ps != null) {
17750                if (DEBUG_INSTALL) Slog.d(TAG, "Existing package: " + ps);
17751
17752                // Static shared libs have same package with different versions where
17753                // we internally use a synthetic package name to allow multiple versions
17754                // of the same package, therefore we need to compare signatures against
17755                // the package setting for the latest library version.
17756                PackageSetting signatureCheckPs = ps;
17757                if (pkg.applicationInfo.isStaticSharedLibrary()) {
17758                    SharedLibraryEntry libraryEntry = getLatestSharedLibraVersionLPr(pkg);
17759                    if (libraryEntry != null) {
17760                        signatureCheckPs = mSettings.getPackageLPr(libraryEntry.apk);
17761                    }
17762                }
17763
17764                // Quick sanity check that we're signed correctly if updating;
17765                // we'll check this again later when scanning, but we want to
17766                // bail early here before tripping over redefined permissions.
17767                if (shouldCheckUpgradeKeySetLP(signatureCheckPs, scanFlags)) {
17768                    if (!checkUpgradeKeySetLP(signatureCheckPs, pkg)) {
17769                        res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package "
17770                                + pkg.packageName + " upgrade keys do not match the "
17771                                + "previously installed version");
17772                        return;
17773                    }
17774                } else {
17775                    try {
17776                        verifySignaturesLP(signatureCheckPs, pkg);
17777                    } catch (PackageManagerException e) {
17778                        res.setError(e.error, e.getMessage());
17779                        return;
17780                    }
17781                }
17782
17783                oldCodePath = mSettings.mPackages.get(pkgName).codePathString;
17784                if (ps.pkg != null && ps.pkg.applicationInfo != null) {
17785                    systemApp = (ps.pkg.applicationInfo.flags &
17786                            ApplicationInfo.FLAG_SYSTEM) != 0;
17787                }
17788                res.origUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
17789            }
17790
17791            int N = pkg.permissions.size();
17792            for (int i = N-1; i >= 0; i--) {
17793                PackageParser.Permission perm = pkg.permissions.get(i);
17794                BasePermission bp = mSettings.mPermissions.get(perm.info.name);
17795
17796                // Don't allow anyone but the system to define ephemeral permissions.
17797                if ((perm.info.protectionLevel & PermissionInfo.PROTECTION_FLAG_EPHEMERAL) != 0
17798                        && !systemApp) {
17799                    Slog.w(TAG, "Non-System package " + pkg.packageName
17800                            + " attempting to delcare ephemeral permission "
17801                            + perm.info.name + "; Removing ephemeral.");
17802                    perm.info.protectionLevel &= ~PermissionInfo.PROTECTION_FLAG_EPHEMERAL;
17803                }
17804                // Check whether the newly-scanned package wants to define an already-defined perm
17805                if (bp != null) {
17806                    // If the defining package is signed with our cert, it's okay.  This
17807                    // also includes the "updating the same package" case, of course.
17808                    // "updating same package" could also involve key-rotation.
17809                    final boolean sigsOk;
17810                    if (bp.sourcePackage.equals(pkg.packageName)
17811                            && (bp.packageSetting instanceof PackageSetting)
17812                            && (shouldCheckUpgradeKeySetLP((PackageSetting) bp.packageSetting,
17813                                    scanFlags))) {
17814                        sigsOk = checkUpgradeKeySetLP((PackageSetting) bp.packageSetting, pkg);
17815                    } else {
17816                        sigsOk = compareSignatures(bp.packageSetting.signatures.mSignatures,
17817                                pkg.mSignatures) == PackageManager.SIGNATURE_MATCH;
17818                    }
17819                    if (!sigsOk) {
17820                        // If the owning package is the system itself, we log but allow
17821                        // install to proceed; we fail the install on all other permission
17822                        // redefinitions.
17823                        if (!bp.sourcePackage.equals("android")) {
17824                            res.setError(INSTALL_FAILED_DUPLICATE_PERMISSION, "Package "
17825                                    + pkg.packageName + " attempting to redeclare permission "
17826                                    + perm.info.name + " already owned by " + bp.sourcePackage);
17827                            res.origPermission = perm.info.name;
17828                            res.origPackage = bp.sourcePackage;
17829                            return;
17830                        } else {
17831                            Slog.w(TAG, "Package " + pkg.packageName
17832                                    + " attempting to redeclare system permission "
17833                                    + perm.info.name + "; ignoring new declaration");
17834                            pkg.permissions.remove(i);
17835                        }
17836                    } else if (!PLATFORM_PACKAGE_NAME.equals(pkg.packageName)) {
17837                        // Prevent apps to change protection level to dangerous from any other
17838                        // type as this would allow a privilege escalation where an app adds a
17839                        // normal/signature permission in other app's group and later redefines
17840                        // it as dangerous leading to the group auto-grant.
17841                        if ((perm.info.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE)
17842                                == PermissionInfo.PROTECTION_DANGEROUS) {
17843                            if (bp != null && !bp.isRuntime()) {
17844                                Slog.w(TAG, "Package " + pkg.packageName + " trying to change a "
17845                                        + "non-runtime permission " + perm.info.name
17846                                        + " to runtime; keeping old protection level");
17847                                perm.info.protectionLevel = bp.protectionLevel;
17848                            }
17849                        }
17850                    }
17851                }
17852            }
17853        }
17854
17855        if (systemApp) {
17856            if (onExternal) {
17857                // Abort update; system app can't be replaced with app on sdcard
17858                res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION,
17859                        "Cannot install updates to system apps on sdcard");
17860                return;
17861            } else if (instantApp) {
17862                // Abort update; system app can't be replaced with an instant app
17863                res.setError(INSTALL_FAILED_INSTANT_APP_INVALID,
17864                        "Cannot update a system app with an instant app");
17865                return;
17866            }
17867        }
17868
17869        if (args.move != null) {
17870            // We did an in-place move, so dex is ready to roll
17871            scanFlags |= SCAN_NO_DEX;
17872            scanFlags |= SCAN_MOVE;
17873
17874            synchronized (mPackages) {
17875                final PackageSetting ps = mSettings.mPackages.get(pkgName);
17876                if (ps == null) {
17877                    res.setError(INSTALL_FAILED_INTERNAL_ERROR,
17878                            "Missing settings for moved package " + pkgName);
17879                }
17880
17881                // We moved the entire application as-is, so bring over the
17882                // previously derived ABI information.
17883                pkg.applicationInfo.primaryCpuAbi = ps.primaryCpuAbiString;
17884                pkg.applicationInfo.secondaryCpuAbi = ps.secondaryCpuAbiString;
17885            }
17886
17887        } else if (!forwardLocked && !pkg.applicationInfo.isExternalAsec()) {
17888            // Enable SCAN_NO_DEX flag to skip dexopt at a later stage
17889            scanFlags |= SCAN_NO_DEX;
17890
17891            try {
17892                String abiOverride = (TextUtils.isEmpty(pkg.cpuAbiOverride) ?
17893                    args.abiOverride : pkg.cpuAbiOverride);
17894                derivePackageAbi(pkg, new File(pkg.codePath), abiOverride,
17895                        true /*extractLibs*/, mAppLib32InstallDir);
17896            } catch (PackageManagerException pme) {
17897                Slog.e(TAG, "Error deriving application ABI", pme);
17898                res.setError(INSTALL_FAILED_INTERNAL_ERROR, "Error deriving application ABI");
17899                return;
17900            }
17901
17902            // Shared libraries for the package need to be updated.
17903            synchronized (mPackages) {
17904                try {
17905                    updateSharedLibrariesLPr(pkg, null);
17906                } catch (PackageManagerException e) {
17907                    Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
17908                }
17909            }
17910
17911            // dexopt can take some time to complete, so, for instant apps, we skip this
17912            // step during installation. Instead, we'll take extra time the first time the
17913            // instant app starts. It's preferred to do it this way to provide continuous
17914            // progress to the user instead of mysteriously blocking somewhere in the
17915            // middle of running an instant app.
17916            if (!instantApp) {
17917                Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt");
17918                // Do not run PackageDexOptimizer through the local performDexOpt
17919                // method because `pkg` may not be in `mPackages` yet.
17920                //
17921                // Also, don't fail application installs if the dexopt step fails.
17922                mPackageDexOptimizer.performDexOpt(pkg, pkg.usesLibraryFiles,
17923                        null /* instructionSets */, false /* checkProfiles */,
17924                        getCompilerFilterForReason(REASON_INSTALL),
17925                        getOrCreateCompilerPackageStats(pkg),
17926                        mDexManager.isUsedByOtherApps(pkg.packageName));
17927                Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
17928            }
17929
17930            // Notify BackgroundDexOptService that the package has been changed.
17931            // If this is an update of a package which used to fail to compile,
17932            // BDOS will remove it from its blacklist.
17933            // TODO: Layering violation
17934            BackgroundDexOptService.notifyPackageChanged(pkg.packageName);
17935        }
17936
17937        if (!args.doRename(res.returnCode, pkg, oldCodePath)) {
17938            res.setError(INSTALL_FAILED_INSUFFICIENT_STORAGE, "Failed rename");
17939            return;
17940        }
17941
17942        startIntentFilterVerifications(args.user.getIdentifier(), replace, pkg);
17943
17944        try (PackageFreezer freezer = freezePackageForInstall(pkgName, installFlags,
17945                "installPackageLI")) {
17946            if (replace) {
17947                if (pkg.applicationInfo.isStaticSharedLibrary()) {
17948                    // Static libs have a synthetic package name containing the version
17949                    // and cannot be updated as an update would get a new package name,
17950                    // unless this is the exact same version code which is useful for
17951                    // development.
17952                    PackageParser.Package existingPkg = mPackages.get(pkg.packageName);
17953                    if (existingPkg != null && existingPkg.mVersionCode != pkg.mVersionCode) {
17954                        res.setError(INSTALL_FAILED_DUPLICATE_PACKAGE, "Packages declaring "
17955                                + "static-shared libs cannot be updated");
17956                        return;
17957                    }
17958                }
17959                replacePackageLIF(pkg, parseFlags, scanFlags | SCAN_REPLACING, args.user,
17960                        installerPackageName, res, args.installReason);
17961            } else {
17962                installNewPackageLIF(pkg, parseFlags, scanFlags | SCAN_DELETE_DATA_ON_FAILURES,
17963                        args.user, installerPackageName, volumeUuid, res, args.installReason);
17964            }
17965        }
17966
17967        synchronized (mPackages) {
17968            final PackageSetting ps = mSettings.mPackages.get(pkgName);
17969            if (ps != null) {
17970                res.newUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
17971                ps.setUpdateAvailable(false /*updateAvailable*/);
17972            }
17973
17974            final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
17975            for (int i = 0; i < childCount; i++) {
17976                PackageParser.Package childPkg = pkg.childPackages.get(i);
17977                PackageInstalledInfo childRes = res.addedChildPackages.get(childPkg.packageName);
17978                PackageSetting childPs = mSettings.getPackageLPr(childPkg.packageName);
17979                if (childPs != null) {
17980                    childRes.newUsers = childPs.queryInstalledUsers(
17981                            sUserManager.getUserIds(), true);
17982                }
17983            }
17984
17985            if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
17986                updateSequenceNumberLP(pkgName, res.newUsers);
17987                updateInstantAppInstallerLocked(pkgName);
17988            }
17989        }
17990    }
17991
17992    private void startIntentFilterVerifications(int userId, boolean replacing,
17993            PackageParser.Package pkg) {
17994        if (mIntentFilterVerifierComponent == null) {
17995            Slog.w(TAG, "No IntentFilter verification will not be done as "
17996                    + "there is no IntentFilterVerifier available!");
17997            return;
17998        }
17999
18000        final int verifierUid = getPackageUid(
18001                mIntentFilterVerifierComponent.getPackageName(),
18002                MATCH_DEBUG_TRIAGED_MISSING,
18003                (userId == UserHandle.USER_ALL) ? UserHandle.USER_SYSTEM : userId);
18004
18005        Message msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS);
18006        msg.obj = new IFVerificationParams(pkg, replacing, userId, verifierUid);
18007        mHandler.sendMessage(msg);
18008
18009        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
18010        for (int i = 0; i < childCount; i++) {
18011            PackageParser.Package childPkg = pkg.childPackages.get(i);
18012            msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS);
18013            msg.obj = new IFVerificationParams(childPkg, replacing, userId, verifierUid);
18014            mHandler.sendMessage(msg);
18015        }
18016    }
18017
18018    private void verifyIntentFiltersIfNeeded(int userId, int verifierUid, boolean replacing,
18019            PackageParser.Package pkg) {
18020        int size = pkg.activities.size();
18021        if (size == 0) {
18022            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
18023                    "No activity, so no need to verify any IntentFilter!");
18024            return;
18025        }
18026
18027        final boolean hasDomainURLs = hasDomainURLs(pkg);
18028        if (!hasDomainURLs) {
18029            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
18030                    "No domain URLs, so no need to verify any IntentFilter!");
18031            return;
18032        }
18033
18034        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Checking for userId:" + userId
18035                + " if any IntentFilter from the " + size
18036                + " Activities needs verification ...");
18037
18038        int count = 0;
18039        final String packageName = pkg.packageName;
18040
18041        synchronized (mPackages) {
18042            // If this is a new install and we see that we've already run verification for this
18043            // package, we have nothing to do: it means the state was restored from backup.
18044            if (!replacing) {
18045                IntentFilterVerificationInfo ivi =
18046                        mSettings.getIntentFilterVerificationLPr(packageName);
18047                if (ivi != null) {
18048                    if (DEBUG_DOMAIN_VERIFICATION) {
18049                        Slog.i(TAG, "Package " + packageName+ " already verified: status="
18050                                + ivi.getStatusString());
18051                    }
18052                    return;
18053                }
18054            }
18055
18056            // If any filters need to be verified, then all need to be.
18057            boolean needToVerify = false;
18058            for (PackageParser.Activity a : pkg.activities) {
18059                for (ActivityIntentInfo filter : a.intents) {
18060                    if (filter.needsVerification() && needsNetworkVerificationLPr(filter)) {
18061                        if (DEBUG_DOMAIN_VERIFICATION) {
18062                            Slog.d(TAG, "Intent filter needs verification, so processing all filters");
18063                        }
18064                        needToVerify = true;
18065                        break;
18066                    }
18067                }
18068            }
18069
18070            if (needToVerify) {
18071                final int verificationId = mIntentFilterVerificationToken++;
18072                for (PackageParser.Activity a : pkg.activities) {
18073                    for (ActivityIntentInfo filter : a.intents) {
18074                        if (filter.handlesWebUris(true) && needsNetworkVerificationLPr(filter)) {
18075                            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
18076                                    "Verification needed for IntentFilter:" + filter.toString());
18077                            mIntentFilterVerifier.addOneIntentFilterVerification(
18078                                    verifierUid, userId, verificationId, filter, packageName);
18079                            count++;
18080                        }
18081                    }
18082                }
18083            }
18084        }
18085
18086        if (count > 0) {
18087            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Starting " + count
18088                    + " IntentFilter verification" + (count > 1 ? "s" : "")
18089                    +  " for userId:" + userId);
18090            mIntentFilterVerifier.startVerifications(userId);
18091        } else {
18092            if (DEBUG_DOMAIN_VERIFICATION) {
18093                Slog.d(TAG, "No filters or not all autoVerify for " + packageName);
18094            }
18095        }
18096    }
18097
18098    private boolean needsNetworkVerificationLPr(ActivityIntentInfo filter) {
18099        final ComponentName cn  = filter.activity.getComponentName();
18100        final String packageName = cn.getPackageName();
18101
18102        IntentFilterVerificationInfo ivi = mSettings.getIntentFilterVerificationLPr(
18103                packageName);
18104        if (ivi == null) {
18105            return true;
18106        }
18107        int status = ivi.getStatus();
18108        switch (status) {
18109            case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED:
18110            case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK:
18111                return true;
18112
18113            default:
18114                // Nothing to do
18115                return false;
18116        }
18117    }
18118
18119    private static boolean isMultiArch(ApplicationInfo info) {
18120        return (info.flags & ApplicationInfo.FLAG_MULTIARCH) != 0;
18121    }
18122
18123    private static boolean isExternal(PackageParser.Package pkg) {
18124        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
18125    }
18126
18127    private static boolean isExternal(PackageSetting ps) {
18128        return (ps.pkgFlags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
18129    }
18130
18131    private static boolean isSystemApp(PackageParser.Package pkg) {
18132        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0;
18133    }
18134
18135    private static boolean isPrivilegedApp(PackageParser.Package pkg) {
18136        return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0;
18137    }
18138
18139    private static boolean hasDomainURLs(PackageParser.Package pkg) {
18140        return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_HAS_DOMAIN_URLS) != 0;
18141    }
18142
18143    private static boolean isSystemApp(PackageSetting ps) {
18144        return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0;
18145    }
18146
18147    private static boolean isUpdatedSystemApp(PackageSetting ps) {
18148        return (ps.pkgFlags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0;
18149    }
18150
18151    private int packageFlagsToInstallFlags(PackageSetting ps) {
18152        int installFlags = 0;
18153        if (isExternal(ps) && TextUtils.isEmpty(ps.volumeUuid)) {
18154            // This existing package was an external ASEC install when we have
18155            // the external flag without a UUID
18156            installFlags |= PackageManager.INSTALL_EXTERNAL;
18157        }
18158        if (ps.isForwardLocked()) {
18159            installFlags |= PackageManager.INSTALL_FORWARD_LOCK;
18160        }
18161        return installFlags;
18162    }
18163
18164    private String getVolumeUuidForPackage(PackageParser.Package pkg) {
18165        if (isExternal(pkg)) {
18166            if (TextUtils.isEmpty(pkg.volumeUuid)) {
18167                return StorageManager.UUID_PRIMARY_PHYSICAL;
18168            } else {
18169                return pkg.volumeUuid;
18170            }
18171        } else {
18172            return StorageManager.UUID_PRIVATE_INTERNAL;
18173        }
18174    }
18175
18176    private VersionInfo getSettingsVersionForPackage(PackageParser.Package pkg) {
18177        if (isExternal(pkg)) {
18178            if (TextUtils.isEmpty(pkg.volumeUuid)) {
18179                return mSettings.getExternalVersion();
18180            } else {
18181                return mSettings.findOrCreateVersion(pkg.volumeUuid);
18182            }
18183        } else {
18184            return mSettings.getInternalVersion();
18185        }
18186    }
18187
18188    private void deleteTempPackageFiles() {
18189        final FilenameFilter filter = new FilenameFilter() {
18190            public boolean accept(File dir, String name) {
18191                return name.startsWith("vmdl") && name.endsWith(".tmp");
18192            }
18193        };
18194        for (File file : mDrmAppPrivateInstallDir.listFiles(filter)) {
18195            file.delete();
18196        }
18197    }
18198
18199    @Override
18200    public void deletePackageAsUser(String packageName, int versionCode,
18201            IPackageDeleteObserver observer, int userId, int flags) {
18202        deletePackageVersioned(new VersionedPackage(packageName, versionCode),
18203                new LegacyPackageDeleteObserver(observer).getBinder(), userId, flags);
18204    }
18205
18206    @Override
18207    public void deletePackageVersioned(VersionedPackage versionedPackage,
18208            final IPackageDeleteObserver2 observer, final int userId, final int deleteFlags) {
18209        mContext.enforceCallingOrSelfPermission(
18210                android.Manifest.permission.DELETE_PACKAGES, null);
18211        Preconditions.checkNotNull(versionedPackage);
18212        Preconditions.checkNotNull(observer);
18213        Preconditions.checkArgumentInRange(versionedPackage.getVersionCode(),
18214                PackageManager.VERSION_CODE_HIGHEST,
18215                Integer.MAX_VALUE, "versionCode must be >= -1");
18216
18217        final String packageName = versionedPackage.getPackageName();
18218        final int versionCode = versionedPackage.getVersionCode();
18219        final String internalPackageName;
18220        synchronized (mPackages) {
18221            // Normalize package name to handle renamed packages and static libs
18222            internalPackageName = resolveInternalPackageNameLPr(versionedPackage.getPackageName(),
18223                    versionedPackage.getVersionCode());
18224        }
18225
18226        final int uid = Binder.getCallingUid();
18227        if (!isOrphaned(internalPackageName)
18228                && !isCallerAllowedToSilentlyUninstall(uid, internalPackageName)) {
18229            try {
18230                final Intent intent = new Intent(Intent.ACTION_UNINSTALL_PACKAGE);
18231                intent.setData(Uri.fromParts(PACKAGE_SCHEME, packageName, null));
18232                intent.putExtra(PackageInstaller.EXTRA_CALLBACK, observer.asBinder());
18233                observer.onUserActionRequired(intent);
18234            } catch (RemoteException re) {
18235            }
18236            return;
18237        }
18238        final boolean deleteAllUsers = (deleteFlags & PackageManager.DELETE_ALL_USERS) != 0;
18239        final int[] users = deleteAllUsers ? sUserManager.getUserIds() : new int[]{ userId };
18240        if (UserHandle.getUserId(uid) != userId || (deleteAllUsers && users.length > 1)) {
18241            mContext.enforceCallingOrSelfPermission(
18242                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
18243                    "deletePackage for user " + userId);
18244        }
18245
18246        if (isUserRestricted(userId, UserManager.DISALLOW_UNINSTALL_APPS)) {
18247            try {
18248                observer.onPackageDeleted(packageName,
18249                        PackageManager.DELETE_FAILED_USER_RESTRICTED, null);
18250            } catch (RemoteException re) {
18251            }
18252            return;
18253        }
18254
18255        if (!deleteAllUsers && getBlockUninstallForUser(internalPackageName, userId)) {
18256            try {
18257                observer.onPackageDeleted(packageName,
18258                        PackageManager.DELETE_FAILED_OWNER_BLOCKED, null);
18259            } catch (RemoteException re) {
18260            }
18261            return;
18262        }
18263
18264        if (DEBUG_REMOVE) {
18265            Slog.d(TAG, "deletePackageAsUser: pkg=" + internalPackageName + " user=" + userId
18266                    + " deleteAllUsers: " + deleteAllUsers + " version="
18267                    + (versionCode == PackageManager.VERSION_CODE_HIGHEST
18268                    ? "VERSION_CODE_HIGHEST" : versionCode));
18269        }
18270        // Queue up an async operation since the package deletion may take a little while.
18271        mHandler.post(new Runnable() {
18272            public void run() {
18273                mHandler.removeCallbacks(this);
18274                int returnCode;
18275                if (!deleteAllUsers) {
18276                    returnCode = deletePackageX(internalPackageName, versionCode,
18277                            userId, deleteFlags);
18278                } else {
18279                    int[] blockUninstallUserIds = getBlockUninstallForUsers(
18280                            internalPackageName, users);
18281                    // If nobody is blocking uninstall, proceed with delete for all users
18282                    if (ArrayUtils.isEmpty(blockUninstallUserIds)) {
18283                        returnCode = deletePackageX(internalPackageName, versionCode,
18284                                userId, deleteFlags);
18285                    } else {
18286                        // Otherwise uninstall individually for users with blockUninstalls=false
18287                        final int userFlags = deleteFlags & ~PackageManager.DELETE_ALL_USERS;
18288                        for (int userId : users) {
18289                            if (!ArrayUtils.contains(blockUninstallUserIds, userId)) {
18290                                returnCode = deletePackageX(internalPackageName, versionCode,
18291                                        userId, userFlags);
18292                                if (returnCode != PackageManager.DELETE_SUCCEEDED) {
18293                                    Slog.w(TAG, "Package delete failed for user " + userId
18294                                            + ", returnCode " + returnCode);
18295                                }
18296                            }
18297                        }
18298                        // The app has only been marked uninstalled for certain users.
18299                        // We still need to report that delete was blocked
18300                        returnCode = PackageManager.DELETE_FAILED_OWNER_BLOCKED;
18301                    }
18302                }
18303                try {
18304                    observer.onPackageDeleted(packageName, returnCode, null);
18305                } catch (RemoteException e) {
18306                    Log.i(TAG, "Observer no longer exists.");
18307                } //end catch
18308            } //end run
18309        });
18310    }
18311
18312    private String resolveExternalPackageNameLPr(PackageParser.Package pkg) {
18313        if (pkg.staticSharedLibName != null) {
18314            return pkg.manifestPackageName;
18315        }
18316        return pkg.packageName;
18317    }
18318
18319    private String resolveInternalPackageNameLPr(String packageName, int versionCode) {
18320        // Handle renamed packages
18321        String normalizedPackageName = mSettings.getRenamedPackageLPr(packageName);
18322        packageName = normalizedPackageName != null ? normalizedPackageName : packageName;
18323
18324        // Is this a static library?
18325        SparseArray<SharedLibraryEntry> versionedLib =
18326                mStaticLibsByDeclaringPackage.get(packageName);
18327        if (versionedLib == null || versionedLib.size() <= 0) {
18328            return packageName;
18329        }
18330
18331        // Figure out which lib versions the caller can see
18332        SparseIntArray versionsCallerCanSee = null;
18333        final int callingAppId = UserHandle.getAppId(Binder.getCallingUid());
18334        if (callingAppId != Process.SYSTEM_UID && callingAppId != Process.SHELL_UID
18335                && callingAppId != Process.ROOT_UID) {
18336            versionsCallerCanSee = new SparseIntArray();
18337            String libName = versionedLib.valueAt(0).info.getName();
18338            String[] uidPackages = getPackagesForUid(Binder.getCallingUid());
18339            if (uidPackages != null) {
18340                for (String uidPackage : uidPackages) {
18341                    PackageSetting ps = mSettings.getPackageLPr(uidPackage);
18342                    final int libIdx = ArrayUtils.indexOf(ps.usesStaticLibraries, libName);
18343                    if (libIdx >= 0) {
18344                        final int libVersion = ps.usesStaticLibrariesVersions[libIdx];
18345                        versionsCallerCanSee.append(libVersion, libVersion);
18346                    }
18347                }
18348            }
18349        }
18350
18351        // Caller can see nothing - done
18352        if (versionsCallerCanSee != null && versionsCallerCanSee.size() <= 0) {
18353            return packageName;
18354        }
18355
18356        // Find the version the caller can see and the app version code
18357        SharedLibraryEntry highestVersion = null;
18358        final int versionCount = versionedLib.size();
18359        for (int i = 0; i < versionCount; i++) {
18360            SharedLibraryEntry libEntry = versionedLib.valueAt(i);
18361            if (versionsCallerCanSee != null && versionsCallerCanSee.indexOfKey(
18362                    libEntry.info.getVersion()) < 0) {
18363                continue;
18364            }
18365            final int libVersionCode = libEntry.info.getDeclaringPackage().getVersionCode();
18366            if (versionCode != PackageManager.VERSION_CODE_HIGHEST) {
18367                if (libVersionCode == versionCode) {
18368                    return libEntry.apk;
18369                }
18370            } else if (highestVersion == null) {
18371                highestVersion = libEntry;
18372            } else if (libVersionCode  > highestVersion.info
18373                    .getDeclaringPackage().getVersionCode()) {
18374                highestVersion = libEntry;
18375            }
18376        }
18377
18378        if (highestVersion != null) {
18379            return highestVersion.apk;
18380        }
18381
18382        return packageName;
18383    }
18384
18385    private boolean isCallerAllowedToSilentlyUninstall(int callingUid, String pkgName) {
18386        if (callingUid == Process.SHELL_UID || callingUid == Process.ROOT_UID
18387              || UserHandle.getAppId(callingUid) == Process.SYSTEM_UID) {
18388            return true;
18389        }
18390        final int callingUserId = UserHandle.getUserId(callingUid);
18391        // If the caller installed the pkgName, then allow it to silently uninstall.
18392        if (callingUid == getPackageUid(getInstallerPackageName(pkgName), 0, callingUserId)) {
18393            return true;
18394        }
18395
18396        // Allow package verifier to silently uninstall.
18397        if (mRequiredVerifierPackage != null &&
18398                callingUid == getPackageUid(mRequiredVerifierPackage, 0, callingUserId)) {
18399            return true;
18400        }
18401
18402        // Allow package uninstaller to silently uninstall.
18403        if (mRequiredUninstallerPackage != null &&
18404                callingUid == getPackageUid(mRequiredUninstallerPackage, 0, callingUserId)) {
18405            return true;
18406        }
18407
18408        // Allow storage manager to silently uninstall.
18409        if (mStorageManagerPackage != null &&
18410                callingUid == getPackageUid(mStorageManagerPackage, 0, callingUserId)) {
18411            return true;
18412        }
18413        return false;
18414    }
18415
18416    private int[] getBlockUninstallForUsers(String packageName, int[] userIds) {
18417        int[] result = EMPTY_INT_ARRAY;
18418        for (int userId : userIds) {
18419            if (getBlockUninstallForUser(packageName, userId)) {
18420                result = ArrayUtils.appendInt(result, userId);
18421            }
18422        }
18423        return result;
18424    }
18425
18426    @Override
18427    public boolean isPackageDeviceAdminOnAnyUser(String packageName) {
18428        final int callingUid = Binder.getCallingUid();
18429        if (getInstantAppPackageName(callingUid) != null
18430                && !isCallerSameApp(packageName, callingUid)) {
18431            return false;
18432        }
18433        return isPackageDeviceAdmin(packageName, UserHandle.USER_ALL);
18434    }
18435
18436    private boolean isPackageDeviceAdmin(String packageName, int userId) {
18437        IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface(
18438                ServiceManager.getService(Context.DEVICE_POLICY_SERVICE));
18439        try {
18440            if (dpm != null) {
18441                final ComponentName deviceOwnerComponentName = dpm.getDeviceOwnerComponent(
18442                        /* callingUserOnly =*/ false);
18443                final String deviceOwnerPackageName = deviceOwnerComponentName == null ? null
18444                        : deviceOwnerComponentName.getPackageName();
18445                // Does the package contains the device owner?
18446                // TODO Do we have to do it even if userId != UserHandle.USER_ALL?  Otherwise,
18447                // this check is probably not needed, since DO should be registered as a device
18448                // admin on some user too. (Original bug for this: b/17657954)
18449                if (packageName.equals(deviceOwnerPackageName)) {
18450                    return true;
18451                }
18452                // Does it contain a device admin for any user?
18453                int[] users;
18454                if (userId == UserHandle.USER_ALL) {
18455                    users = sUserManager.getUserIds();
18456                } else {
18457                    users = new int[]{userId};
18458                }
18459                for (int i = 0; i < users.length; ++i) {
18460                    if (dpm.packageHasActiveAdmins(packageName, users[i])) {
18461                        return true;
18462                    }
18463                }
18464            }
18465        } catch (RemoteException e) {
18466        }
18467        return false;
18468    }
18469
18470    private boolean shouldKeepUninstalledPackageLPr(String packageName) {
18471        return mKeepUninstalledPackages != null && mKeepUninstalledPackages.contains(packageName);
18472    }
18473
18474    /**
18475     *  This method is an internal method that could be get invoked either
18476     *  to delete an installed package or to clean up a failed installation.
18477     *  After deleting an installed package, a broadcast is sent to notify any
18478     *  listeners that the package has been removed. For cleaning up a failed
18479     *  installation, the broadcast is not necessary since the package's
18480     *  installation wouldn't have sent the initial broadcast either
18481     *  The key steps in deleting a package are
18482     *  deleting the package information in internal structures like mPackages,
18483     *  deleting the packages base directories through installd
18484     *  updating mSettings to reflect current status
18485     *  persisting settings for later use
18486     *  sending a broadcast if necessary
18487     */
18488    private int deletePackageX(String packageName, int versionCode, int userId, int deleteFlags) {
18489        final PackageRemovedInfo info = new PackageRemovedInfo(this);
18490        final boolean res;
18491
18492        final int removeUser = (deleteFlags & PackageManager.DELETE_ALL_USERS) != 0
18493                ? UserHandle.USER_ALL : userId;
18494
18495        if (isPackageDeviceAdmin(packageName, removeUser)) {
18496            Slog.w(TAG, "Not removing package " + packageName + ": has active device admin");
18497            return PackageManager.DELETE_FAILED_DEVICE_POLICY_MANAGER;
18498        }
18499
18500        PackageSetting uninstalledPs = null;
18501        PackageParser.Package pkg = null;
18502
18503        // for the uninstall-updates case and restricted profiles, remember the per-
18504        // user handle installed state
18505        int[] allUsers;
18506        synchronized (mPackages) {
18507            uninstalledPs = mSettings.mPackages.get(packageName);
18508            if (uninstalledPs == null) {
18509                Slog.w(TAG, "Not removing non-existent package " + packageName);
18510                return PackageManager.DELETE_FAILED_INTERNAL_ERROR;
18511            }
18512
18513            if (versionCode != PackageManager.VERSION_CODE_HIGHEST
18514                    && uninstalledPs.versionCode != versionCode) {
18515                Slog.w(TAG, "Not removing package " + packageName + " with versionCode "
18516                        + uninstalledPs.versionCode + " != " + versionCode);
18517                return PackageManager.DELETE_FAILED_INTERNAL_ERROR;
18518            }
18519
18520            // Static shared libs can be declared by any package, so let us not
18521            // allow removing a package if it provides a lib others depend on.
18522            pkg = mPackages.get(packageName);
18523
18524            allUsers = sUserManager.getUserIds();
18525
18526            if (pkg != null && pkg.staticSharedLibName != null) {
18527                SharedLibraryEntry libEntry = getSharedLibraryEntryLPr(pkg.staticSharedLibName,
18528                        pkg.staticSharedLibVersion);
18529                if (libEntry != null) {
18530                    for (int currUserId : allUsers) {
18531                        if (userId != UserHandle.USER_ALL && userId != currUserId) {
18532                            continue;
18533                        }
18534                        List<VersionedPackage> libClientPackages = getPackagesUsingSharedLibraryLPr(
18535                                libEntry.info, 0, currUserId);
18536                        if (!ArrayUtils.isEmpty(libClientPackages)) {
18537                            Slog.w(TAG, "Not removing package " + pkg.manifestPackageName
18538                                    + " hosting lib " + libEntry.info.getName() + " version "
18539                                    + libEntry.info.getVersion() + " used by " + libClientPackages
18540                                    + " for user " + currUserId);
18541                            return PackageManager.DELETE_FAILED_USED_SHARED_LIBRARY;
18542                        }
18543                    }
18544                }
18545            }
18546
18547            info.origUsers = uninstalledPs.queryInstalledUsers(allUsers, true);
18548        }
18549
18550        final int freezeUser;
18551        if (isUpdatedSystemApp(uninstalledPs)
18552                && ((deleteFlags & PackageManager.DELETE_SYSTEM_APP) == 0)) {
18553            // We're downgrading a system app, which will apply to all users, so
18554            // freeze them all during the downgrade
18555            freezeUser = UserHandle.USER_ALL;
18556        } else {
18557            freezeUser = removeUser;
18558        }
18559
18560        synchronized (mInstallLock) {
18561            if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageX: pkg=" + packageName + " user=" + userId);
18562            try (PackageFreezer freezer = freezePackageForDelete(packageName, freezeUser,
18563                    deleteFlags, "deletePackageX")) {
18564                res = deletePackageLIF(packageName, UserHandle.of(removeUser), true, allUsers,
18565                        deleteFlags | FLAGS_REMOVE_CHATTY, info, true, null);
18566            }
18567            synchronized (mPackages) {
18568                if (res) {
18569                    if (pkg != null) {
18570                        mInstantAppRegistry.onPackageUninstalledLPw(pkg, info.removedUsers);
18571                    }
18572                    updateSequenceNumberLP(packageName, info.removedUsers);
18573                    updateInstantAppInstallerLocked(packageName);
18574                }
18575            }
18576        }
18577
18578        if (res) {
18579            final boolean killApp = (deleteFlags & PackageManager.DELETE_DONT_KILL_APP) == 0;
18580            info.sendPackageRemovedBroadcasts(killApp);
18581            info.sendSystemPackageUpdatedBroadcasts();
18582            info.sendSystemPackageAppearedBroadcasts();
18583        }
18584        // Force a gc here.
18585        Runtime.getRuntime().gc();
18586        // Delete the resources here after sending the broadcast to let
18587        // other processes clean up before deleting resources.
18588        if (info.args != null) {
18589            synchronized (mInstallLock) {
18590                info.args.doPostDeleteLI(true);
18591            }
18592        }
18593
18594        return res ? PackageManager.DELETE_SUCCEEDED : PackageManager.DELETE_FAILED_INTERNAL_ERROR;
18595    }
18596
18597    static class PackageRemovedInfo {
18598        final PackageSender packageSender;
18599        String removedPackage;
18600        String installerPackageName;
18601        int uid = -1;
18602        int removedAppId = -1;
18603        int[] origUsers;
18604        int[] removedUsers = null;
18605        int[] broadcastUsers = null;
18606        SparseArray<Integer> installReasons;
18607        boolean isRemovedPackageSystemUpdate = false;
18608        boolean isUpdate;
18609        boolean dataRemoved;
18610        boolean removedForAllUsers;
18611        boolean isStaticSharedLib;
18612        // Clean up resources deleted packages.
18613        InstallArgs args = null;
18614        ArrayMap<String, PackageRemovedInfo> removedChildPackages;
18615        ArrayMap<String, PackageInstalledInfo> appearedChildPackages;
18616
18617        PackageRemovedInfo(PackageSender packageSender) {
18618            this.packageSender = packageSender;
18619        }
18620
18621        void sendPackageRemovedBroadcasts(boolean killApp) {
18622            sendPackageRemovedBroadcastInternal(killApp);
18623            final int childCount = removedChildPackages != null ? removedChildPackages.size() : 0;
18624            for (int i = 0; i < childCount; i++) {
18625                PackageRemovedInfo childInfo = removedChildPackages.valueAt(i);
18626                childInfo.sendPackageRemovedBroadcastInternal(killApp);
18627            }
18628        }
18629
18630        void sendSystemPackageUpdatedBroadcasts() {
18631            if (isRemovedPackageSystemUpdate) {
18632                sendSystemPackageUpdatedBroadcastsInternal();
18633                final int childCount = (removedChildPackages != null)
18634                        ? removedChildPackages.size() : 0;
18635                for (int i = 0; i < childCount; i++) {
18636                    PackageRemovedInfo childInfo = removedChildPackages.valueAt(i);
18637                    if (childInfo.isRemovedPackageSystemUpdate) {
18638                        childInfo.sendSystemPackageUpdatedBroadcastsInternal();
18639                    }
18640                }
18641            }
18642        }
18643
18644        void sendSystemPackageAppearedBroadcasts() {
18645            final int packageCount = (appearedChildPackages != null)
18646                    ? appearedChildPackages.size() : 0;
18647            for (int i = 0; i < packageCount; i++) {
18648                PackageInstalledInfo installedInfo = appearedChildPackages.valueAt(i);
18649                packageSender.sendPackageAddedForNewUsers(installedInfo.name,
18650                    true, UserHandle.getAppId(installedInfo.uid),
18651                    installedInfo.newUsers);
18652            }
18653        }
18654
18655        private void sendSystemPackageUpdatedBroadcastsInternal() {
18656            Bundle extras = new Bundle(2);
18657            extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid);
18658            extras.putBoolean(Intent.EXTRA_REPLACING, true);
18659            packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
18660                removedPackage, extras, 0, null /*targetPackage*/, null, null);
18661            packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED,
18662                removedPackage, extras, 0, null /*targetPackage*/, null, null);
18663            packageSender.sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED,
18664                null, null, 0, removedPackage, null, null);
18665            if (installerPackageName != null) {
18666                packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
18667                        removedPackage, extras, 0 /*flags*/,
18668                        installerPackageName, null, null);
18669                packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED,
18670                        removedPackage, extras, 0 /*flags*/,
18671                        installerPackageName, null, null);
18672            }
18673        }
18674
18675        private void sendPackageRemovedBroadcastInternal(boolean killApp) {
18676            // Don't send static shared library removal broadcasts as these
18677            // libs are visible only the the apps that depend on them an one
18678            // cannot remove the library if it has a dependency.
18679            if (isStaticSharedLib) {
18680                return;
18681            }
18682            Bundle extras = new Bundle(2);
18683            extras.putInt(Intent.EXTRA_UID, removedAppId >= 0  ? removedAppId : uid);
18684            extras.putBoolean(Intent.EXTRA_DATA_REMOVED, dataRemoved);
18685            extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, !killApp);
18686            if (isUpdate || isRemovedPackageSystemUpdate) {
18687                extras.putBoolean(Intent.EXTRA_REPLACING, true);
18688            }
18689            extras.putBoolean(Intent.EXTRA_REMOVED_FOR_ALL_USERS, removedForAllUsers);
18690            if (removedPackage != null) {
18691                packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED,
18692                    removedPackage, extras, 0, null /*targetPackage*/, null, broadcastUsers);
18693                if (installerPackageName != null) {
18694                    packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED,
18695                            removedPackage, extras, 0 /*flags*/,
18696                            installerPackageName, null, broadcastUsers);
18697                }
18698                if (dataRemoved && !isRemovedPackageSystemUpdate) {
18699                    packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_FULLY_REMOVED,
18700                        removedPackage, extras,
18701                        Intent.FLAG_RECEIVER_INCLUDE_BACKGROUND,
18702                        null, null, broadcastUsers);
18703                }
18704            }
18705            if (removedAppId >= 0) {
18706                packageSender.sendPackageBroadcast(Intent.ACTION_UID_REMOVED, null, extras,
18707                        Intent.FLAG_RECEIVER_INCLUDE_BACKGROUND, null, null, broadcastUsers);
18708            }
18709        }
18710
18711        void populateUsers(int[] userIds, PackageSetting deletedPackageSetting) {
18712            removedUsers = userIds;
18713            if (removedUsers == null) {
18714                broadcastUsers = null;
18715                return;
18716            }
18717
18718            broadcastUsers = EMPTY_INT_ARRAY;
18719            for (int i = userIds.length - 1; i >= 0; --i) {
18720                final int userId = userIds[i];
18721                if (deletedPackageSetting.getInstantApp(userId)) {
18722                    continue;
18723                }
18724                broadcastUsers = ArrayUtils.appendInt(broadcastUsers, userId);
18725            }
18726        }
18727    }
18728
18729    /*
18730     * This method deletes the package from internal data structures. If the DONT_DELETE_DATA
18731     * flag is not set, the data directory is removed as well.
18732     * make sure this flag is set for partially installed apps. If not its meaningless to
18733     * delete a partially installed application.
18734     */
18735    private void removePackageDataLIF(PackageSetting ps, int[] allUserHandles,
18736            PackageRemovedInfo outInfo, int flags, boolean writeSettings) {
18737        String packageName = ps.name;
18738        if (DEBUG_REMOVE) Slog.d(TAG, "removePackageDataLI: " + ps);
18739        // Retrieve object to delete permissions for shared user later on
18740        final PackageParser.Package deletedPkg;
18741        final PackageSetting deletedPs;
18742        // reader
18743        synchronized (mPackages) {
18744            deletedPkg = mPackages.get(packageName);
18745            deletedPs = mSettings.mPackages.get(packageName);
18746            if (outInfo != null) {
18747                outInfo.removedPackage = packageName;
18748                outInfo.installerPackageName = ps.installerPackageName;
18749                outInfo.isStaticSharedLib = deletedPkg != null
18750                        && deletedPkg.staticSharedLibName != null;
18751                outInfo.populateUsers(deletedPs == null ? null
18752                        : deletedPs.queryInstalledUsers(sUserManager.getUserIds(), true), deletedPs);
18753            }
18754        }
18755
18756        removePackageLI(ps, (flags & FLAGS_REMOVE_CHATTY) != 0);
18757
18758        if ((flags & PackageManager.DELETE_KEEP_DATA) == 0) {
18759            final PackageParser.Package resolvedPkg;
18760            if (deletedPkg != null) {
18761                resolvedPkg = deletedPkg;
18762            } else {
18763                // We don't have a parsed package when it lives on an ejected
18764                // adopted storage device, so fake something together
18765                resolvedPkg = new PackageParser.Package(ps.name);
18766                resolvedPkg.setVolumeUuid(ps.volumeUuid);
18767            }
18768            destroyAppDataLIF(resolvedPkg, UserHandle.USER_ALL,
18769                    StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
18770            destroyAppProfilesLIF(resolvedPkg, UserHandle.USER_ALL);
18771            if (outInfo != null) {
18772                outInfo.dataRemoved = true;
18773            }
18774            schedulePackageCleaning(packageName, UserHandle.USER_ALL, true);
18775        }
18776
18777        int removedAppId = -1;
18778
18779        // writer
18780        synchronized (mPackages) {
18781            boolean installedStateChanged = false;
18782            if (deletedPs != null) {
18783                if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) {
18784                    clearIntentFilterVerificationsLPw(deletedPs.name, UserHandle.USER_ALL);
18785                    clearDefaultBrowserIfNeeded(packageName);
18786                    mSettings.mKeySetManagerService.removeAppKeySetDataLPw(packageName);
18787                    removedAppId = mSettings.removePackageLPw(packageName);
18788                    if (outInfo != null) {
18789                        outInfo.removedAppId = removedAppId;
18790                    }
18791                    updatePermissionsLPw(deletedPs.name, null, 0);
18792                    if (deletedPs.sharedUser != null) {
18793                        // Remove permissions associated with package. Since runtime
18794                        // permissions are per user we have to kill the removed package
18795                        // or packages running under the shared user of the removed
18796                        // package if revoking the permissions requested only by the removed
18797                        // package is successful and this causes a change in gids.
18798                        for (int userId : UserManagerService.getInstance().getUserIds()) {
18799                            final int userIdToKill = mSettings.updateSharedUserPermsLPw(deletedPs,
18800                                    userId);
18801                            if (userIdToKill == UserHandle.USER_ALL
18802                                    || userIdToKill >= UserHandle.USER_SYSTEM) {
18803                                // If gids changed for this user, kill all affected packages.
18804                                mHandler.post(new Runnable() {
18805                                    @Override
18806                                    public void run() {
18807                                        // This has to happen with no lock held.
18808                                        killApplication(deletedPs.name, deletedPs.appId,
18809                                                KILL_APP_REASON_GIDS_CHANGED);
18810                                    }
18811                                });
18812                                break;
18813                            }
18814                        }
18815                    }
18816                    clearPackagePreferredActivitiesLPw(deletedPs.name, UserHandle.USER_ALL);
18817                }
18818                // make sure to preserve per-user disabled state if this removal was just
18819                // a downgrade of a system app to the factory package
18820                if (allUserHandles != null && outInfo != null && outInfo.origUsers != null) {
18821                    if (DEBUG_REMOVE) {
18822                        Slog.d(TAG, "Propagating install state across downgrade");
18823                    }
18824                    for (int userId : allUserHandles) {
18825                        final boolean installed = ArrayUtils.contains(outInfo.origUsers, userId);
18826                        if (DEBUG_REMOVE) {
18827                            Slog.d(TAG, "    user " + userId + " => " + installed);
18828                        }
18829                        if (installed != ps.getInstalled(userId)) {
18830                            installedStateChanged = true;
18831                        }
18832                        ps.setInstalled(installed, userId);
18833                    }
18834                }
18835            }
18836            // can downgrade to reader
18837            if (writeSettings) {
18838                // Save settings now
18839                mSettings.writeLPr();
18840            }
18841            if (installedStateChanged) {
18842                mSettings.writeKernelMappingLPr(ps);
18843            }
18844        }
18845        if (removedAppId != -1) {
18846            // A user ID was deleted here. Go through all users and remove it
18847            // from KeyStore.
18848            removeKeystoreDataIfNeeded(UserHandle.USER_ALL, removedAppId);
18849        }
18850    }
18851
18852    static boolean locationIsPrivileged(File path) {
18853        try {
18854            final String privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app")
18855                    .getCanonicalPath();
18856            return path.getCanonicalPath().startsWith(privilegedAppDir);
18857        } catch (IOException e) {
18858            Slog.e(TAG, "Unable to access code path " + path);
18859        }
18860        return false;
18861    }
18862
18863    /*
18864     * Tries to delete system package.
18865     */
18866    private boolean deleteSystemPackageLIF(PackageParser.Package deletedPkg,
18867            PackageSetting deletedPs, int[] allUserHandles, int flags, PackageRemovedInfo outInfo,
18868            boolean writeSettings) {
18869        if (deletedPs.parentPackageName != null) {
18870            Slog.w(TAG, "Attempt to delete child system package " + deletedPkg.packageName);
18871            return false;
18872        }
18873
18874        final boolean applyUserRestrictions
18875                = (allUserHandles != null) && (outInfo.origUsers != null);
18876        final PackageSetting disabledPs;
18877        // Confirm if the system package has been updated
18878        // An updated system app can be deleted. This will also have to restore
18879        // the system pkg from system partition
18880        // reader
18881        synchronized (mPackages) {
18882            disabledPs = mSettings.getDisabledSystemPkgLPr(deletedPs.name);
18883        }
18884
18885        if (DEBUG_REMOVE) Slog.d(TAG, "deleteSystemPackageLI: newPs=" + deletedPkg.packageName
18886                + " disabledPs=" + disabledPs);
18887
18888        if (disabledPs == null) {
18889            Slog.w(TAG, "Attempt to delete unknown system package "+ deletedPkg.packageName);
18890            return false;
18891        } else if (DEBUG_REMOVE) {
18892            Slog.d(TAG, "Deleting system pkg from data partition");
18893        }
18894
18895        if (DEBUG_REMOVE) {
18896            if (applyUserRestrictions) {
18897                Slog.d(TAG, "Remembering install states:");
18898                for (int userId : allUserHandles) {
18899                    final boolean finstalled = ArrayUtils.contains(outInfo.origUsers, userId);
18900                    Slog.d(TAG, "   u=" + userId + " inst=" + finstalled);
18901                }
18902            }
18903        }
18904
18905        // Delete the updated package
18906        outInfo.isRemovedPackageSystemUpdate = true;
18907        if (outInfo.removedChildPackages != null) {
18908            final int childCount = (deletedPs.childPackageNames != null)
18909                    ? deletedPs.childPackageNames.size() : 0;
18910            for (int i = 0; i < childCount; i++) {
18911                String childPackageName = deletedPs.childPackageNames.get(i);
18912                if (disabledPs.childPackageNames != null && disabledPs.childPackageNames
18913                        .contains(childPackageName)) {
18914                    PackageRemovedInfo childInfo = outInfo.removedChildPackages.get(
18915                            childPackageName);
18916                    if (childInfo != null) {
18917                        childInfo.isRemovedPackageSystemUpdate = true;
18918                    }
18919                }
18920            }
18921        }
18922
18923        if (disabledPs.versionCode < deletedPs.versionCode) {
18924            // Delete data for downgrades
18925            flags &= ~PackageManager.DELETE_KEEP_DATA;
18926        } else {
18927            // Preserve data by setting flag
18928            flags |= PackageManager.DELETE_KEEP_DATA;
18929        }
18930
18931        boolean ret = deleteInstalledPackageLIF(deletedPs, true, flags, allUserHandles,
18932                outInfo, writeSettings, disabledPs.pkg);
18933        if (!ret) {
18934            return false;
18935        }
18936
18937        // writer
18938        synchronized (mPackages) {
18939            // Reinstate the old system package
18940            enableSystemPackageLPw(disabledPs.pkg);
18941            // Remove any native libraries from the upgraded package.
18942            removeNativeBinariesLI(deletedPs);
18943        }
18944
18945        // Install the system package
18946        if (DEBUG_REMOVE) Slog.d(TAG, "Re-installing system package: " + disabledPs);
18947        int parseFlags = mDefParseFlags
18948                | PackageParser.PARSE_MUST_BE_APK
18949                | PackageParser.PARSE_IS_SYSTEM
18950                | PackageParser.PARSE_IS_SYSTEM_DIR;
18951        if (locationIsPrivileged(disabledPs.codePath)) {
18952            parseFlags |= PackageParser.PARSE_IS_PRIVILEGED;
18953        }
18954
18955        final PackageParser.Package newPkg;
18956        try {
18957            newPkg = scanPackageTracedLI(disabledPs.codePath, parseFlags, 0 /* scanFlags */,
18958                0 /* currentTime */, null);
18959        } catch (PackageManagerException e) {
18960            Slog.w(TAG, "Failed to restore system package:" + deletedPkg.packageName + ": "
18961                    + e.getMessage());
18962            return false;
18963        }
18964
18965        try {
18966            // update shared libraries for the newly re-installed system package
18967            updateSharedLibrariesLPr(newPkg, null);
18968        } catch (PackageManagerException e) {
18969            Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
18970        }
18971
18972        prepareAppDataAfterInstallLIF(newPkg);
18973
18974        // writer
18975        synchronized (mPackages) {
18976            PackageSetting ps = mSettings.mPackages.get(newPkg.packageName);
18977
18978            // Propagate the permissions state as we do not want to drop on the floor
18979            // runtime permissions. The update permissions method below will take
18980            // care of removing obsolete permissions and grant install permissions.
18981            ps.getPermissionsState().copyFrom(deletedPs.getPermissionsState());
18982            updatePermissionsLPw(newPkg.packageName, newPkg,
18983                    UPDATE_PERMISSIONS_ALL | UPDATE_PERMISSIONS_REPLACE_PKG);
18984
18985            if (applyUserRestrictions) {
18986                boolean installedStateChanged = false;
18987                if (DEBUG_REMOVE) {
18988                    Slog.d(TAG, "Propagating install state across reinstall");
18989                }
18990                for (int userId : allUserHandles) {
18991                    final boolean installed = ArrayUtils.contains(outInfo.origUsers, userId);
18992                    if (DEBUG_REMOVE) {
18993                        Slog.d(TAG, "    user " + userId + " => " + installed);
18994                    }
18995                    if (installed != ps.getInstalled(userId)) {
18996                        installedStateChanged = true;
18997                    }
18998                    ps.setInstalled(installed, userId);
18999
19000                    mSettings.writeRuntimePermissionsForUserLPr(userId, false);
19001                }
19002                // Regardless of writeSettings we need to ensure that this restriction
19003                // state propagation is persisted
19004                mSettings.writeAllUsersPackageRestrictionsLPr();
19005                if (installedStateChanged) {
19006                    mSettings.writeKernelMappingLPr(ps);
19007                }
19008            }
19009            // can downgrade to reader here
19010            if (writeSettings) {
19011                mSettings.writeLPr();
19012            }
19013        }
19014        return true;
19015    }
19016
19017    private boolean deleteInstalledPackageLIF(PackageSetting ps,
19018            boolean deleteCodeAndResources, int flags, int[] allUserHandles,
19019            PackageRemovedInfo outInfo, boolean writeSettings,
19020            PackageParser.Package replacingPackage) {
19021        synchronized (mPackages) {
19022            if (outInfo != null) {
19023                outInfo.uid = ps.appId;
19024            }
19025
19026            if (outInfo != null && outInfo.removedChildPackages != null) {
19027                final int childCount = (ps.childPackageNames != null)
19028                        ? ps.childPackageNames.size() : 0;
19029                for (int i = 0; i < childCount; i++) {
19030                    String childPackageName = ps.childPackageNames.get(i);
19031                    PackageSetting childPs = mSettings.mPackages.get(childPackageName);
19032                    if (childPs == null) {
19033                        return false;
19034                    }
19035                    PackageRemovedInfo childInfo = outInfo.removedChildPackages.get(
19036                            childPackageName);
19037                    if (childInfo != null) {
19038                        childInfo.uid = childPs.appId;
19039                    }
19040                }
19041            }
19042        }
19043
19044        // Delete package data from internal structures and also remove data if flag is set
19045        removePackageDataLIF(ps, allUserHandles, outInfo, flags, writeSettings);
19046
19047        // Delete the child packages data
19048        final int childCount = (ps.childPackageNames != null) ? ps.childPackageNames.size() : 0;
19049        for (int i = 0; i < childCount; i++) {
19050            PackageSetting childPs;
19051            synchronized (mPackages) {
19052                childPs = mSettings.getPackageLPr(ps.childPackageNames.get(i));
19053            }
19054            if (childPs != null) {
19055                PackageRemovedInfo childOutInfo = (outInfo != null
19056                        && outInfo.removedChildPackages != null)
19057                        ? outInfo.removedChildPackages.get(childPs.name) : null;
19058                final int deleteFlags = (flags & DELETE_KEEP_DATA) != 0
19059                        && (replacingPackage != null
19060                        && !replacingPackage.hasChildPackage(childPs.name))
19061                        ? flags & ~DELETE_KEEP_DATA : flags;
19062                removePackageDataLIF(childPs, allUserHandles, childOutInfo,
19063                        deleteFlags, writeSettings);
19064            }
19065        }
19066
19067        // Delete application code and resources only for parent packages
19068        if (ps.parentPackageName == null) {
19069            if (deleteCodeAndResources && (outInfo != null)) {
19070                outInfo.args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
19071                        ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
19072                if (DEBUG_SD_INSTALL) Slog.i(TAG, "args=" + outInfo.args);
19073            }
19074        }
19075
19076        return true;
19077    }
19078
19079    @Override
19080    public boolean setBlockUninstallForUser(String packageName, boolean blockUninstall,
19081            int userId) {
19082        mContext.enforceCallingOrSelfPermission(
19083                android.Manifest.permission.DELETE_PACKAGES, null);
19084        synchronized (mPackages) {
19085            // Cannot block uninstall of static shared libs as they are
19086            // considered a part of the using app (emulating static linking).
19087            // Also static libs are installed always on internal storage.
19088            PackageParser.Package pkg = mPackages.get(packageName);
19089            if (pkg != null && pkg.staticSharedLibName != null) {
19090                Slog.w(TAG, "Cannot block uninstall of package: " + packageName
19091                        + " providing static shared library: " + pkg.staticSharedLibName);
19092                return false;
19093            }
19094            mSettings.setBlockUninstallLPw(userId, packageName, blockUninstall);
19095            mSettings.writePackageRestrictionsLPr(userId);
19096        }
19097        return true;
19098    }
19099
19100    @Override
19101    public boolean getBlockUninstallForUser(String packageName, int userId) {
19102        synchronized (mPackages) {
19103            return mSettings.getBlockUninstallLPr(userId, packageName);
19104        }
19105    }
19106
19107    @Override
19108    public boolean setRequiredForSystemUser(String packageName, boolean systemUserApp) {
19109        enforceSystemOrRoot("setRequiredForSystemUser can only be run by the system or root");
19110        synchronized (mPackages) {
19111            PackageSetting ps = mSettings.mPackages.get(packageName);
19112            if (ps == null) {
19113                Log.w(TAG, "Package doesn't exist: " + packageName);
19114                return false;
19115            }
19116            if (systemUserApp) {
19117                ps.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_REQUIRED_FOR_SYSTEM_USER;
19118            } else {
19119                ps.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_REQUIRED_FOR_SYSTEM_USER;
19120            }
19121            mSettings.writeLPr();
19122        }
19123        return true;
19124    }
19125
19126    /*
19127     * This method handles package deletion in general
19128     */
19129    private boolean deletePackageLIF(String packageName, UserHandle user,
19130            boolean deleteCodeAndResources, int[] allUserHandles, int flags,
19131            PackageRemovedInfo outInfo, boolean writeSettings,
19132            PackageParser.Package replacingPackage) {
19133        if (packageName == null) {
19134            Slog.w(TAG, "Attempt to delete null packageName.");
19135            return false;
19136        }
19137
19138        if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageLI: " + packageName + " user " + user);
19139
19140        PackageSetting ps;
19141        synchronized (mPackages) {
19142            ps = mSettings.mPackages.get(packageName);
19143            if (ps == null) {
19144                Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
19145                return false;
19146            }
19147
19148            if (ps.parentPackageName != null && (!isSystemApp(ps)
19149                    || (flags & PackageManager.DELETE_SYSTEM_APP) != 0)) {
19150                if (DEBUG_REMOVE) {
19151                    Slog.d(TAG, "Uninstalled child package:" + packageName + " for user:"
19152                            + ((user == null) ? UserHandle.USER_ALL : user));
19153                }
19154                final int removedUserId = (user != null) ? user.getIdentifier()
19155                        : UserHandle.USER_ALL;
19156                if (!clearPackageStateForUserLIF(ps, removedUserId, outInfo)) {
19157                    return false;
19158                }
19159                markPackageUninstalledForUserLPw(ps, user);
19160                scheduleWritePackageRestrictionsLocked(user);
19161                return true;
19162            }
19163        }
19164
19165        if (((!isSystemApp(ps) || (flags&PackageManager.DELETE_SYSTEM_APP) != 0) && user != null
19166                && user.getIdentifier() != UserHandle.USER_ALL)) {
19167            // The caller is asking that the package only be deleted for a single
19168            // user.  To do this, we just mark its uninstalled state and delete
19169            // its data. If this is a system app, we only allow this to happen if
19170            // they have set the special DELETE_SYSTEM_APP which requests different
19171            // semantics than normal for uninstalling system apps.
19172            markPackageUninstalledForUserLPw(ps, user);
19173
19174            if (!isSystemApp(ps)) {
19175                // Do not uninstall the APK if an app should be cached
19176                boolean keepUninstalledPackage = shouldKeepUninstalledPackageLPr(packageName);
19177                if (ps.isAnyInstalled(sUserManager.getUserIds()) || keepUninstalledPackage) {
19178                    // Other user still have this package installed, so all
19179                    // we need to do is clear this user's data and save that
19180                    // it is uninstalled.
19181                    if (DEBUG_REMOVE) Slog.d(TAG, "Still installed by other users");
19182                    if (!clearPackageStateForUserLIF(ps, user.getIdentifier(), outInfo)) {
19183                        return false;
19184                    }
19185                    scheduleWritePackageRestrictionsLocked(user);
19186                    return true;
19187                } else {
19188                    // We need to set it back to 'installed' so the uninstall
19189                    // broadcasts will be sent correctly.
19190                    if (DEBUG_REMOVE) Slog.d(TAG, "Not installed by other users, full delete");
19191                    ps.setInstalled(true, user.getIdentifier());
19192                    mSettings.writeKernelMappingLPr(ps);
19193                }
19194            } else {
19195                // This is a system app, so we assume that the
19196                // other users still have this package installed, so all
19197                // we need to do is clear this user's data and save that
19198                // it is uninstalled.
19199                if (DEBUG_REMOVE) Slog.d(TAG, "Deleting system app");
19200                if (!clearPackageStateForUserLIF(ps, user.getIdentifier(), outInfo)) {
19201                    return false;
19202                }
19203                scheduleWritePackageRestrictionsLocked(user);
19204                return true;
19205            }
19206        }
19207
19208        // If we are deleting a composite package for all users, keep track
19209        // of result for each child.
19210        if (ps.childPackageNames != null && outInfo != null) {
19211            synchronized (mPackages) {
19212                final int childCount = ps.childPackageNames.size();
19213                outInfo.removedChildPackages = new ArrayMap<>(childCount);
19214                for (int i = 0; i < childCount; i++) {
19215                    String childPackageName = ps.childPackageNames.get(i);
19216                    PackageRemovedInfo childInfo = new PackageRemovedInfo(this);
19217                    childInfo.removedPackage = childPackageName;
19218                    childInfo.installerPackageName = ps.installerPackageName;
19219                    outInfo.removedChildPackages.put(childPackageName, childInfo);
19220                    PackageSetting childPs = mSettings.getPackageLPr(childPackageName);
19221                    if (childPs != null) {
19222                        childInfo.origUsers = childPs.queryInstalledUsers(allUserHandles, true);
19223                    }
19224                }
19225            }
19226        }
19227
19228        boolean ret = false;
19229        if (isSystemApp(ps)) {
19230            if (DEBUG_REMOVE) Slog.d(TAG, "Removing system package: " + ps.name);
19231            // When an updated system application is deleted we delete the existing resources
19232            // as well and fall back to existing code in system partition
19233            ret = deleteSystemPackageLIF(ps.pkg, ps, allUserHandles, flags, outInfo, writeSettings);
19234        } else {
19235            if (DEBUG_REMOVE) Slog.d(TAG, "Removing non-system package: " + ps.name);
19236            ret = deleteInstalledPackageLIF(ps, deleteCodeAndResources, flags, allUserHandles,
19237                    outInfo, writeSettings, replacingPackage);
19238        }
19239
19240        // Take a note whether we deleted the package for all users
19241        if (outInfo != null) {
19242            outInfo.removedForAllUsers = mPackages.get(ps.name) == null;
19243            if (outInfo.removedChildPackages != null) {
19244                synchronized (mPackages) {
19245                    final int childCount = outInfo.removedChildPackages.size();
19246                    for (int i = 0; i < childCount; i++) {
19247                        PackageRemovedInfo childInfo = outInfo.removedChildPackages.valueAt(i);
19248                        if (childInfo != null) {
19249                            childInfo.removedForAllUsers = mPackages.get(
19250                                    childInfo.removedPackage) == null;
19251                        }
19252                    }
19253                }
19254            }
19255            // If we uninstalled an update to a system app there may be some
19256            // child packages that appeared as they are declared in the system
19257            // app but were not declared in the update.
19258            if (isSystemApp(ps)) {
19259                synchronized (mPackages) {
19260                    PackageSetting updatedPs = mSettings.getPackageLPr(ps.name);
19261                    final int childCount = (updatedPs.childPackageNames != null)
19262                            ? updatedPs.childPackageNames.size() : 0;
19263                    for (int i = 0; i < childCount; i++) {
19264                        String childPackageName = updatedPs.childPackageNames.get(i);
19265                        if (outInfo.removedChildPackages == null
19266                                || outInfo.removedChildPackages.indexOfKey(childPackageName) < 0) {
19267                            PackageSetting childPs = mSettings.getPackageLPr(childPackageName);
19268                            if (childPs == null) {
19269                                continue;
19270                            }
19271                            PackageInstalledInfo installRes = new PackageInstalledInfo();
19272                            installRes.name = childPackageName;
19273                            installRes.newUsers = childPs.queryInstalledUsers(allUserHandles, true);
19274                            installRes.pkg = mPackages.get(childPackageName);
19275                            installRes.uid = childPs.pkg.applicationInfo.uid;
19276                            if (outInfo.appearedChildPackages == null) {
19277                                outInfo.appearedChildPackages = new ArrayMap<>();
19278                            }
19279                            outInfo.appearedChildPackages.put(childPackageName, installRes);
19280                        }
19281                    }
19282                }
19283            }
19284        }
19285
19286        return ret;
19287    }
19288
19289    private void markPackageUninstalledForUserLPw(PackageSetting ps, UserHandle user) {
19290        final int[] userIds = (user == null || user.getIdentifier() == UserHandle.USER_ALL)
19291                ? sUserManager.getUserIds() : new int[] {user.getIdentifier()};
19292        for (int nextUserId : userIds) {
19293            if (DEBUG_REMOVE) {
19294                Slog.d(TAG, "Marking package:" + ps.name + " uninstalled for user:" + nextUserId);
19295            }
19296            ps.setUserState(nextUserId, 0, COMPONENT_ENABLED_STATE_DEFAULT,
19297                    false /*installed*/,
19298                    true /*stopped*/,
19299                    true /*notLaunched*/,
19300                    false /*hidden*/,
19301                    false /*suspended*/,
19302                    false /*instantApp*/,
19303                    null /*lastDisableAppCaller*/,
19304                    null /*enabledComponents*/,
19305                    null /*disabledComponents*/,
19306                    ps.readUserState(nextUserId).domainVerificationStatus,
19307                    0, PackageManager.INSTALL_REASON_UNKNOWN);
19308        }
19309        mSettings.writeKernelMappingLPr(ps);
19310    }
19311
19312    private boolean clearPackageStateForUserLIF(PackageSetting ps, int userId,
19313            PackageRemovedInfo outInfo) {
19314        final PackageParser.Package pkg;
19315        synchronized (mPackages) {
19316            pkg = mPackages.get(ps.name);
19317        }
19318
19319        final int[] userIds = (userId == UserHandle.USER_ALL) ? sUserManager.getUserIds()
19320                : new int[] {userId};
19321        for (int nextUserId : userIds) {
19322            if (DEBUG_REMOVE) {
19323                Slog.d(TAG, "Updating package:" + ps.name + " install state for user:"
19324                        + nextUserId);
19325            }
19326
19327            destroyAppDataLIF(pkg, userId,
19328                    StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
19329            destroyAppProfilesLIF(pkg, userId);
19330            clearDefaultBrowserIfNeededForUser(ps.name, userId);
19331            removeKeystoreDataIfNeeded(nextUserId, ps.appId);
19332            schedulePackageCleaning(ps.name, nextUserId, false);
19333            synchronized (mPackages) {
19334                if (clearPackagePreferredActivitiesLPw(ps.name, nextUserId)) {
19335                    scheduleWritePackageRestrictionsLocked(nextUserId);
19336                }
19337                resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, nextUserId);
19338            }
19339        }
19340
19341        if (outInfo != null) {
19342            outInfo.removedPackage = ps.name;
19343            outInfo.installerPackageName = ps.installerPackageName;
19344            outInfo.isStaticSharedLib = pkg != null && pkg.staticSharedLibName != null;
19345            outInfo.removedAppId = ps.appId;
19346            outInfo.removedUsers = userIds;
19347            outInfo.broadcastUsers = userIds;
19348        }
19349
19350        return true;
19351    }
19352
19353    private final class ClearStorageConnection implements ServiceConnection {
19354        IMediaContainerService mContainerService;
19355
19356        @Override
19357        public void onServiceConnected(ComponentName name, IBinder service) {
19358            synchronized (this) {
19359                mContainerService = IMediaContainerService.Stub
19360                        .asInterface(Binder.allowBlocking(service));
19361                notifyAll();
19362            }
19363        }
19364
19365        @Override
19366        public void onServiceDisconnected(ComponentName name) {
19367        }
19368    }
19369
19370    private void clearExternalStorageDataSync(String packageName, int userId, boolean allData) {
19371        if (DEFAULT_CONTAINER_PACKAGE.equals(packageName)) return;
19372
19373        final boolean mounted;
19374        if (Environment.isExternalStorageEmulated()) {
19375            mounted = true;
19376        } else {
19377            final String status = Environment.getExternalStorageState();
19378
19379            mounted = status.equals(Environment.MEDIA_MOUNTED)
19380                    || status.equals(Environment.MEDIA_MOUNTED_READ_ONLY);
19381        }
19382
19383        if (!mounted) {
19384            return;
19385        }
19386
19387        final Intent containerIntent = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
19388        int[] users;
19389        if (userId == UserHandle.USER_ALL) {
19390            users = sUserManager.getUserIds();
19391        } else {
19392            users = new int[] { userId };
19393        }
19394        final ClearStorageConnection conn = new ClearStorageConnection();
19395        if (mContext.bindServiceAsUser(
19396                containerIntent, conn, Context.BIND_AUTO_CREATE, UserHandle.SYSTEM)) {
19397            try {
19398                for (int curUser : users) {
19399                    long timeout = SystemClock.uptimeMillis() + 5000;
19400                    synchronized (conn) {
19401                        long now;
19402                        while (conn.mContainerService == null &&
19403                                (now = SystemClock.uptimeMillis()) < timeout) {
19404                            try {
19405                                conn.wait(timeout - now);
19406                            } catch (InterruptedException e) {
19407                            }
19408                        }
19409                    }
19410                    if (conn.mContainerService == null) {
19411                        return;
19412                    }
19413
19414                    final UserEnvironment userEnv = new UserEnvironment(curUser);
19415                    clearDirectory(conn.mContainerService,
19416                            userEnv.buildExternalStorageAppCacheDirs(packageName));
19417                    if (allData) {
19418                        clearDirectory(conn.mContainerService,
19419                                userEnv.buildExternalStorageAppDataDirs(packageName));
19420                        clearDirectory(conn.mContainerService,
19421                                userEnv.buildExternalStorageAppMediaDirs(packageName));
19422                    }
19423                }
19424            } finally {
19425                mContext.unbindService(conn);
19426            }
19427        }
19428    }
19429
19430    @Override
19431    public void clearApplicationProfileData(String packageName) {
19432        enforceSystemOrRoot("Only the system can clear all profile data");
19433
19434        final PackageParser.Package pkg;
19435        synchronized (mPackages) {
19436            pkg = mPackages.get(packageName);
19437        }
19438
19439        try (PackageFreezer freezer = freezePackage(packageName, "clearApplicationProfileData")) {
19440            synchronized (mInstallLock) {
19441                clearAppProfilesLIF(pkg, UserHandle.USER_ALL);
19442            }
19443        }
19444    }
19445
19446    @Override
19447    public void clearApplicationUserData(final String packageName,
19448            final IPackageDataObserver observer, final int userId) {
19449        mContext.enforceCallingOrSelfPermission(
19450                android.Manifest.permission.CLEAR_APP_USER_DATA, null);
19451
19452        enforceCrossUserPermission(Binder.getCallingUid(), userId,
19453                true /* requireFullPermission */, false /* checkShell */, "clear application data");
19454
19455        if (mProtectedPackages.isPackageDataProtected(userId, packageName)) {
19456            throw new SecurityException("Cannot clear data for a protected package: "
19457                    + packageName);
19458        }
19459        // Queue up an async operation since the package deletion may take a little while.
19460        mHandler.post(new Runnable() {
19461            public void run() {
19462                mHandler.removeCallbacks(this);
19463                final boolean succeeded;
19464                try (PackageFreezer freezer = freezePackage(packageName,
19465                        "clearApplicationUserData")) {
19466                    synchronized (mInstallLock) {
19467                        succeeded = clearApplicationUserDataLIF(packageName, userId);
19468                    }
19469                    clearExternalStorageDataSync(packageName, userId, true);
19470                    synchronized (mPackages) {
19471                        mInstantAppRegistry.deleteInstantApplicationMetadataLPw(
19472                                packageName, userId);
19473                    }
19474                }
19475                if (succeeded) {
19476                    // invoke DeviceStorageMonitor's update method to clear any notifications
19477                    DeviceStorageMonitorInternal dsm = LocalServices
19478                            .getService(DeviceStorageMonitorInternal.class);
19479                    if (dsm != null) {
19480                        dsm.checkMemory();
19481                    }
19482                }
19483                if(observer != null) {
19484                    try {
19485                        observer.onRemoveCompleted(packageName, succeeded);
19486                    } catch (RemoteException e) {
19487                        Log.i(TAG, "Observer no longer exists.");
19488                    }
19489                } //end if observer
19490            } //end run
19491        });
19492    }
19493
19494    private boolean clearApplicationUserDataLIF(String packageName, int userId) {
19495        if (packageName == null) {
19496            Slog.w(TAG, "Attempt to delete null packageName.");
19497            return false;
19498        }
19499
19500        // Try finding details about the requested package
19501        PackageParser.Package pkg;
19502        synchronized (mPackages) {
19503            pkg = mPackages.get(packageName);
19504            if (pkg == null) {
19505                final PackageSetting ps = mSettings.mPackages.get(packageName);
19506                if (ps != null) {
19507                    pkg = ps.pkg;
19508                }
19509            }
19510
19511            if (pkg == null) {
19512                Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
19513                return false;
19514            }
19515
19516            PackageSetting ps = (PackageSetting) pkg.mExtras;
19517            resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
19518        }
19519
19520        clearAppDataLIF(pkg, userId,
19521                StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
19522
19523        final int appId = UserHandle.getAppId(pkg.applicationInfo.uid);
19524        removeKeystoreDataIfNeeded(userId, appId);
19525
19526        UserManagerInternal umInternal = getUserManagerInternal();
19527        final int flags;
19528        if (umInternal.isUserUnlockingOrUnlocked(userId)) {
19529            flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
19530        } else if (umInternal.isUserRunning(userId)) {
19531            flags = StorageManager.FLAG_STORAGE_DE;
19532        } else {
19533            flags = 0;
19534        }
19535        prepareAppDataContentsLIF(pkg, userId, flags);
19536
19537        return true;
19538    }
19539
19540    /**
19541     * Reverts user permission state changes (permissions and flags) in
19542     * all packages for a given user.
19543     *
19544     * @param userId The device user for which to do a reset.
19545     */
19546    private void resetUserChangesToRuntimePermissionsAndFlagsLPw(int userId) {
19547        final int packageCount = mPackages.size();
19548        for (int i = 0; i < packageCount; i++) {
19549            PackageParser.Package pkg = mPackages.valueAt(i);
19550            PackageSetting ps = (PackageSetting) pkg.mExtras;
19551            resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
19552        }
19553    }
19554
19555    private void resetNetworkPolicies(int userId) {
19556        LocalServices.getService(NetworkPolicyManagerInternal.class).resetUserState(userId);
19557    }
19558
19559    /**
19560     * Reverts user permission state changes (permissions and flags).
19561     *
19562     * @param ps The package for which to reset.
19563     * @param userId The device user for which to do a reset.
19564     */
19565    private void resetUserChangesToRuntimePermissionsAndFlagsLPw(
19566            final PackageSetting ps, final int userId) {
19567        if (ps.pkg == null) {
19568            return;
19569        }
19570
19571        // These are flags that can change base on user actions.
19572        final int userSettableMask = FLAG_PERMISSION_USER_SET
19573                | FLAG_PERMISSION_USER_FIXED
19574                | FLAG_PERMISSION_REVOKE_ON_UPGRADE
19575                | FLAG_PERMISSION_REVIEW_REQUIRED;
19576
19577        final int policyOrSystemFlags = FLAG_PERMISSION_SYSTEM_FIXED
19578                | FLAG_PERMISSION_POLICY_FIXED;
19579
19580        boolean writeInstallPermissions = false;
19581        boolean writeRuntimePermissions = false;
19582
19583        final int permissionCount = ps.pkg.requestedPermissions.size();
19584        for (int i = 0; i < permissionCount; i++) {
19585            String permission = ps.pkg.requestedPermissions.get(i);
19586
19587            BasePermission bp = mSettings.mPermissions.get(permission);
19588            if (bp == null) {
19589                continue;
19590            }
19591
19592            // If shared user we just reset the state to which only this app contributed.
19593            if (ps.sharedUser != null) {
19594                boolean used = false;
19595                final int packageCount = ps.sharedUser.packages.size();
19596                for (int j = 0; j < packageCount; j++) {
19597                    PackageSetting pkg = ps.sharedUser.packages.valueAt(j);
19598                    if (pkg.pkg != null && !pkg.pkg.packageName.equals(ps.pkg.packageName)
19599                            && pkg.pkg.requestedPermissions.contains(permission)) {
19600                        used = true;
19601                        break;
19602                    }
19603                }
19604                if (used) {
19605                    continue;
19606                }
19607            }
19608
19609            PermissionsState permissionsState = ps.getPermissionsState();
19610
19611            final int oldFlags = permissionsState.getPermissionFlags(bp.name, userId);
19612
19613            // Always clear the user settable flags.
19614            final boolean hasInstallState = permissionsState.getInstallPermissionState(
19615                    bp.name) != null;
19616            // If permission review is enabled and this is a legacy app, mark the
19617            // permission as requiring a review as this is the initial state.
19618            int flags = 0;
19619            if (mPermissionReviewRequired
19620                    && ps.pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) {
19621                flags |= FLAG_PERMISSION_REVIEW_REQUIRED;
19622            }
19623            if (permissionsState.updatePermissionFlags(bp, userId, userSettableMask, flags)) {
19624                if (hasInstallState) {
19625                    writeInstallPermissions = true;
19626                } else {
19627                    writeRuntimePermissions = true;
19628                }
19629            }
19630
19631            // Below is only runtime permission handling.
19632            if (!bp.isRuntime()) {
19633                continue;
19634            }
19635
19636            // Never clobber system or policy.
19637            if ((oldFlags & policyOrSystemFlags) != 0) {
19638                continue;
19639            }
19640
19641            // If this permission was granted by default, make sure it is.
19642            if ((oldFlags & FLAG_PERMISSION_GRANTED_BY_DEFAULT) != 0) {
19643                if (permissionsState.grantRuntimePermission(bp, userId)
19644                        != PERMISSION_OPERATION_FAILURE) {
19645                    writeRuntimePermissions = true;
19646                }
19647            // If permission review is enabled the permissions for a legacy apps
19648            // are represented as constantly granted runtime ones, so don't revoke.
19649            } else if ((flags & FLAG_PERMISSION_REVIEW_REQUIRED) == 0) {
19650                // Otherwise, reset the permission.
19651                final int revokeResult = permissionsState.revokeRuntimePermission(bp, userId);
19652                switch (revokeResult) {
19653                    case PERMISSION_OPERATION_SUCCESS:
19654                    case PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: {
19655                        writeRuntimePermissions = true;
19656                        final int appId = ps.appId;
19657                        mHandler.post(new Runnable() {
19658                            @Override
19659                            public void run() {
19660                                killUid(appId, userId, KILL_APP_REASON_PERMISSIONS_REVOKED);
19661                            }
19662                        });
19663                    } break;
19664                }
19665            }
19666        }
19667
19668        // Synchronously write as we are taking permissions away.
19669        if (writeRuntimePermissions) {
19670            mSettings.writeRuntimePermissionsForUserLPr(userId, true);
19671        }
19672
19673        // Synchronously write as we are taking permissions away.
19674        if (writeInstallPermissions) {
19675            mSettings.writeLPr();
19676        }
19677    }
19678
19679    /**
19680     * Remove entries from the keystore daemon. Will only remove it if the
19681     * {@code appId} is valid.
19682     */
19683    private static void removeKeystoreDataIfNeeded(int userId, int appId) {
19684        if (appId < 0) {
19685            return;
19686        }
19687
19688        final KeyStore keyStore = KeyStore.getInstance();
19689        if (keyStore != null) {
19690            if (userId == UserHandle.USER_ALL) {
19691                for (final int individual : sUserManager.getUserIds()) {
19692                    keyStore.clearUid(UserHandle.getUid(individual, appId));
19693                }
19694            } else {
19695                keyStore.clearUid(UserHandle.getUid(userId, appId));
19696            }
19697        } else {
19698            Slog.w(TAG, "Could not contact keystore to clear entries for app id " + appId);
19699        }
19700    }
19701
19702    @Override
19703    public void deleteApplicationCacheFiles(final String packageName,
19704            final IPackageDataObserver observer) {
19705        final int userId = UserHandle.getCallingUserId();
19706        deleteApplicationCacheFilesAsUser(packageName, userId, observer);
19707    }
19708
19709    @Override
19710    public void deleteApplicationCacheFilesAsUser(final String packageName, final int userId,
19711            final IPackageDataObserver observer) {
19712        mContext.enforceCallingOrSelfPermission(
19713                android.Manifest.permission.DELETE_CACHE_FILES, null);
19714        enforceCrossUserPermission(Binder.getCallingUid(), userId,
19715                /* requireFullPermission= */ true, /* checkShell= */ false,
19716                "delete application cache files");
19717
19718        final PackageParser.Package pkg;
19719        synchronized (mPackages) {
19720            pkg = mPackages.get(packageName);
19721        }
19722
19723        // Queue up an async operation since the package deletion may take a little while.
19724        mHandler.post(new Runnable() {
19725            public void run() {
19726                synchronized (mInstallLock) {
19727                    final int flags = StorageManager.FLAG_STORAGE_DE
19728                            | StorageManager.FLAG_STORAGE_CE;
19729                    // We're only clearing cache files, so we don't care if the
19730                    // app is unfrozen and still able to run
19731                    clearAppDataLIF(pkg, userId, flags | Installer.FLAG_CLEAR_CACHE_ONLY);
19732                    clearAppDataLIF(pkg, userId, flags | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
19733                }
19734                clearExternalStorageDataSync(packageName, userId, false);
19735                if (observer != null) {
19736                    try {
19737                        observer.onRemoveCompleted(packageName, true);
19738                    } catch (RemoteException e) {
19739                        Log.i(TAG, "Observer no longer exists.");
19740                    }
19741                }
19742            }
19743        });
19744    }
19745
19746    @Override
19747    public void getPackageSizeInfo(final String packageName, int userHandle,
19748            final IPackageStatsObserver observer) {
19749        throw new UnsupportedOperationException(
19750                "Shame on you for calling the hidden API getPackageSizeInfo(). Shame!");
19751    }
19752
19753    private boolean getPackageSizeInfoLI(String packageName, int userId, PackageStats stats) {
19754        final PackageSetting ps;
19755        synchronized (mPackages) {
19756            ps = mSettings.mPackages.get(packageName);
19757            if (ps == null) {
19758                Slog.w(TAG, "Failed to find settings for " + packageName);
19759                return false;
19760            }
19761        }
19762
19763        final String[] packageNames = { packageName };
19764        final long[] ceDataInodes = { ps.getCeDataInode(userId) };
19765        final String[] codePaths = { ps.codePathString };
19766
19767        try {
19768            mInstaller.getAppSize(ps.volumeUuid, packageNames, userId, 0,
19769                    ps.appId, ceDataInodes, codePaths, stats);
19770
19771            // For now, ignore code size of packages on system partition
19772            if (isSystemApp(ps) && !isUpdatedSystemApp(ps)) {
19773                stats.codeSize = 0;
19774            }
19775
19776            // External clients expect these to be tracked separately
19777            stats.dataSize -= stats.cacheSize;
19778
19779        } catch (InstallerException e) {
19780            Slog.w(TAG, String.valueOf(e));
19781            return false;
19782        }
19783
19784        return true;
19785    }
19786
19787    private int getUidTargetSdkVersionLockedLPr(int uid) {
19788        Object obj = mSettings.getUserIdLPr(uid);
19789        if (obj instanceof SharedUserSetting) {
19790            final SharedUserSetting sus = (SharedUserSetting) obj;
19791            int vers = Build.VERSION_CODES.CUR_DEVELOPMENT;
19792            final Iterator<PackageSetting> it = sus.packages.iterator();
19793            while (it.hasNext()) {
19794                final PackageSetting ps = it.next();
19795                if (ps.pkg != null) {
19796                    int v = ps.pkg.applicationInfo.targetSdkVersion;
19797                    if (v < vers) vers = v;
19798                }
19799            }
19800            return vers;
19801        } else if (obj instanceof PackageSetting) {
19802            final PackageSetting ps = (PackageSetting) obj;
19803            if (ps.pkg != null) {
19804                return ps.pkg.applicationInfo.targetSdkVersion;
19805            }
19806        }
19807        return Build.VERSION_CODES.CUR_DEVELOPMENT;
19808    }
19809
19810    @Override
19811    public void addPreferredActivity(IntentFilter filter, int match,
19812            ComponentName[] set, ComponentName activity, int userId) {
19813        addPreferredActivityInternal(filter, match, set, activity, true, userId,
19814                "Adding preferred");
19815    }
19816
19817    private void addPreferredActivityInternal(IntentFilter filter, int match,
19818            ComponentName[] set, ComponentName activity, boolean always, int userId,
19819            String opname) {
19820        // writer
19821        int callingUid = Binder.getCallingUid();
19822        enforceCrossUserPermission(callingUid, userId,
19823                true /* requireFullPermission */, false /* checkShell */, "add preferred activity");
19824        if (filter.countActions() == 0) {
19825            Slog.w(TAG, "Cannot set a preferred activity with no filter actions");
19826            return;
19827        }
19828        synchronized (mPackages) {
19829            if (mContext.checkCallingOrSelfPermission(
19830                    android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
19831                    != PackageManager.PERMISSION_GRANTED) {
19832                if (getUidTargetSdkVersionLockedLPr(callingUid)
19833                        < Build.VERSION_CODES.FROYO) {
19834                    Slog.w(TAG, "Ignoring addPreferredActivity() from uid "
19835                            + callingUid);
19836                    return;
19837                }
19838                mContext.enforceCallingOrSelfPermission(
19839                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
19840            }
19841
19842            PreferredIntentResolver pir = mSettings.editPreferredActivitiesLPw(userId);
19843            Slog.i(TAG, opname + " activity " + activity.flattenToShortString() + " for user "
19844                    + userId + ":");
19845            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
19846            pir.addFilter(new PreferredActivity(filter, match, set, activity, always));
19847            scheduleWritePackageRestrictionsLocked(userId);
19848            postPreferredActivityChangedBroadcast(userId);
19849        }
19850    }
19851
19852    private void postPreferredActivityChangedBroadcast(int userId) {
19853        mHandler.post(() -> {
19854            final IActivityManager am = ActivityManager.getService();
19855            if (am == null) {
19856                return;
19857            }
19858
19859            final Intent intent = new Intent(Intent.ACTION_PREFERRED_ACTIVITY_CHANGED);
19860            intent.putExtra(Intent.EXTRA_USER_HANDLE, userId);
19861            try {
19862                am.broadcastIntent(null, intent, null, null,
19863                        0, null, null, null, android.app.AppOpsManager.OP_NONE,
19864                        null, false, false, userId);
19865            } catch (RemoteException e) {
19866            }
19867        });
19868    }
19869
19870    @Override
19871    public void replacePreferredActivity(IntentFilter filter, int match,
19872            ComponentName[] set, ComponentName activity, int userId) {
19873        if (filter.countActions() != 1) {
19874            throw new IllegalArgumentException(
19875                    "replacePreferredActivity expects filter to have only 1 action.");
19876        }
19877        if (filter.countDataAuthorities() != 0
19878                || filter.countDataPaths() != 0
19879                || filter.countDataSchemes() > 1
19880                || filter.countDataTypes() != 0) {
19881            throw new IllegalArgumentException(
19882                    "replacePreferredActivity expects filter to have no data authorities, " +
19883                    "paths, or types; and at most one scheme.");
19884        }
19885
19886        final int callingUid = Binder.getCallingUid();
19887        enforceCrossUserPermission(callingUid, userId,
19888                true /* requireFullPermission */, false /* checkShell */,
19889                "replace preferred activity");
19890        synchronized (mPackages) {
19891            if (mContext.checkCallingOrSelfPermission(
19892                    android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
19893                    != PackageManager.PERMISSION_GRANTED) {
19894                if (getUidTargetSdkVersionLockedLPr(callingUid)
19895                        < Build.VERSION_CODES.FROYO) {
19896                    Slog.w(TAG, "Ignoring replacePreferredActivity() from uid "
19897                            + Binder.getCallingUid());
19898                    return;
19899                }
19900                mContext.enforceCallingOrSelfPermission(
19901                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
19902            }
19903
19904            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
19905            if (pir != null) {
19906                // Get all of the existing entries that exactly match this filter.
19907                ArrayList<PreferredActivity> existing = pir.findFilters(filter);
19908                if (existing != null && existing.size() == 1) {
19909                    PreferredActivity cur = existing.get(0);
19910                    if (DEBUG_PREFERRED) {
19911                        Slog.i(TAG, "Checking replace of preferred:");
19912                        filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
19913                        if (!cur.mPref.mAlways) {
19914                            Slog.i(TAG, "  -- CUR; not mAlways!");
19915                        } else {
19916                            Slog.i(TAG, "  -- CUR: mMatch=" + cur.mPref.mMatch);
19917                            Slog.i(TAG, "  -- CUR: mSet="
19918                                    + Arrays.toString(cur.mPref.mSetComponents));
19919                            Slog.i(TAG, "  -- CUR: mComponent=" + cur.mPref.mShortComponent);
19920                            Slog.i(TAG, "  -- NEW: mMatch="
19921                                    + (match&IntentFilter.MATCH_CATEGORY_MASK));
19922                            Slog.i(TAG, "  -- CUR: mSet=" + Arrays.toString(set));
19923                            Slog.i(TAG, "  -- CUR: mComponent=" + activity.flattenToShortString());
19924                        }
19925                    }
19926                    if (cur.mPref.mAlways && cur.mPref.mComponent.equals(activity)
19927                            && cur.mPref.mMatch == (match&IntentFilter.MATCH_CATEGORY_MASK)
19928                            && cur.mPref.sameSet(set)) {
19929                        // Setting the preferred activity to what it happens to be already
19930                        if (DEBUG_PREFERRED) {
19931                            Slog.i(TAG, "Replacing with same preferred activity "
19932                                    + cur.mPref.mShortComponent + " for user "
19933                                    + userId + ":");
19934                            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
19935                        }
19936                        return;
19937                    }
19938                }
19939
19940                if (existing != null) {
19941                    if (DEBUG_PREFERRED) {
19942                        Slog.i(TAG, existing.size() + " existing preferred matches for:");
19943                        filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
19944                    }
19945                    for (int i = 0; i < existing.size(); i++) {
19946                        PreferredActivity pa = existing.get(i);
19947                        if (DEBUG_PREFERRED) {
19948                            Slog.i(TAG, "Removing existing preferred activity "
19949                                    + pa.mPref.mComponent + ":");
19950                            pa.dump(new LogPrinter(Log.INFO, TAG), "  ");
19951                        }
19952                        pir.removeFilter(pa);
19953                    }
19954                }
19955            }
19956            addPreferredActivityInternal(filter, match, set, activity, true, userId,
19957                    "Replacing preferred");
19958        }
19959    }
19960
19961    @Override
19962    public void clearPackagePreferredActivities(String packageName) {
19963        final int callingUid = Binder.getCallingUid();
19964        if (getInstantAppPackageName(callingUid) != null) {
19965            return;
19966        }
19967        // writer
19968        synchronized (mPackages) {
19969            PackageParser.Package pkg = mPackages.get(packageName);
19970            if (pkg == null || pkg.applicationInfo.uid != callingUid) {
19971                if (mContext.checkCallingOrSelfPermission(
19972                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
19973                        != PackageManager.PERMISSION_GRANTED) {
19974                    if (getUidTargetSdkVersionLockedLPr(callingUid)
19975                            < Build.VERSION_CODES.FROYO) {
19976                        Slog.w(TAG, "Ignoring clearPackagePreferredActivities() from uid "
19977                                + callingUid);
19978                        return;
19979                    }
19980                    mContext.enforceCallingOrSelfPermission(
19981                            android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
19982                }
19983            }
19984
19985            int user = UserHandle.getCallingUserId();
19986            if (clearPackagePreferredActivitiesLPw(packageName, user)) {
19987                scheduleWritePackageRestrictionsLocked(user);
19988            }
19989        }
19990    }
19991
19992    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
19993    boolean clearPackagePreferredActivitiesLPw(String packageName, int userId) {
19994        ArrayList<PreferredActivity> removed = null;
19995        boolean changed = false;
19996        for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
19997            final int thisUserId = mSettings.mPreferredActivities.keyAt(i);
19998            PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
19999            if (userId != UserHandle.USER_ALL && userId != thisUserId) {
20000                continue;
20001            }
20002            Iterator<PreferredActivity> it = pir.filterIterator();
20003            while (it.hasNext()) {
20004                PreferredActivity pa = it.next();
20005                // Mark entry for removal only if it matches the package name
20006                // and the entry is of type "always".
20007                if (packageName == null ||
20008                        (pa.mPref.mComponent.getPackageName().equals(packageName)
20009                                && pa.mPref.mAlways)) {
20010                    if (removed == null) {
20011                        removed = new ArrayList<PreferredActivity>();
20012                    }
20013                    removed.add(pa);
20014                }
20015            }
20016            if (removed != null) {
20017                for (int j=0; j<removed.size(); j++) {
20018                    PreferredActivity pa = removed.get(j);
20019                    pir.removeFilter(pa);
20020                }
20021                changed = true;
20022            }
20023        }
20024        if (changed) {
20025            postPreferredActivityChangedBroadcast(userId);
20026        }
20027        return changed;
20028    }
20029
20030    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
20031    private void clearIntentFilterVerificationsLPw(int userId) {
20032        final int packageCount = mPackages.size();
20033        for (int i = 0; i < packageCount; i++) {
20034            PackageParser.Package pkg = mPackages.valueAt(i);
20035            clearIntentFilterVerificationsLPw(pkg.packageName, userId);
20036        }
20037    }
20038
20039    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
20040    void clearIntentFilterVerificationsLPw(String packageName, int userId) {
20041        if (userId == UserHandle.USER_ALL) {
20042            if (mSettings.removeIntentFilterVerificationLPw(packageName,
20043                    sUserManager.getUserIds())) {
20044                for (int oneUserId : sUserManager.getUserIds()) {
20045                    scheduleWritePackageRestrictionsLocked(oneUserId);
20046                }
20047            }
20048        } else {
20049            if (mSettings.removeIntentFilterVerificationLPw(packageName, userId)) {
20050                scheduleWritePackageRestrictionsLocked(userId);
20051            }
20052        }
20053    }
20054
20055    /** Clears state for all users, and touches intent filter verification policy */
20056    void clearDefaultBrowserIfNeeded(String packageName) {
20057        for (int oneUserId : sUserManager.getUserIds()) {
20058            clearDefaultBrowserIfNeededForUser(packageName, oneUserId);
20059        }
20060    }
20061
20062    private void clearDefaultBrowserIfNeededForUser(String packageName, int userId) {
20063        final String defaultBrowserPackageName = getDefaultBrowserPackageName(userId);
20064        if (!TextUtils.isEmpty(defaultBrowserPackageName)) {
20065            if (packageName.equals(defaultBrowserPackageName)) {
20066                setDefaultBrowserPackageName(null, userId);
20067            }
20068        }
20069    }
20070
20071    @Override
20072    public void resetApplicationPreferences(int userId) {
20073        mContext.enforceCallingOrSelfPermission(
20074                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
20075        final long identity = Binder.clearCallingIdentity();
20076        // writer
20077        try {
20078            synchronized (mPackages) {
20079                clearPackagePreferredActivitiesLPw(null, userId);
20080                mSettings.applyDefaultPreferredAppsLPw(this, userId);
20081                // TODO: We have to reset the default SMS and Phone. This requires
20082                // significant refactoring to keep all default apps in the package
20083                // manager (cleaner but more work) or have the services provide
20084                // callbacks to the package manager to request a default app reset.
20085                applyFactoryDefaultBrowserLPw(userId);
20086                clearIntentFilterVerificationsLPw(userId);
20087                primeDomainVerificationsLPw(userId);
20088                resetUserChangesToRuntimePermissionsAndFlagsLPw(userId);
20089                scheduleWritePackageRestrictionsLocked(userId);
20090            }
20091            resetNetworkPolicies(userId);
20092        } finally {
20093            Binder.restoreCallingIdentity(identity);
20094        }
20095    }
20096
20097    @Override
20098    public int getPreferredActivities(List<IntentFilter> outFilters,
20099            List<ComponentName> outActivities, String packageName) {
20100        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
20101            return 0;
20102        }
20103        int num = 0;
20104        final int userId = UserHandle.getCallingUserId();
20105        // reader
20106        synchronized (mPackages) {
20107            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
20108            if (pir != null) {
20109                final Iterator<PreferredActivity> it = pir.filterIterator();
20110                while (it.hasNext()) {
20111                    final PreferredActivity pa = it.next();
20112                    if (packageName == null
20113                            || (pa.mPref.mComponent.getPackageName().equals(packageName)
20114                                    && pa.mPref.mAlways)) {
20115                        if (outFilters != null) {
20116                            outFilters.add(new IntentFilter(pa));
20117                        }
20118                        if (outActivities != null) {
20119                            outActivities.add(pa.mPref.mComponent);
20120                        }
20121                    }
20122                }
20123            }
20124        }
20125
20126        return num;
20127    }
20128
20129    @Override
20130    public void addPersistentPreferredActivity(IntentFilter filter, ComponentName activity,
20131            int userId) {
20132        int callingUid = Binder.getCallingUid();
20133        if (callingUid != Process.SYSTEM_UID) {
20134            throw new SecurityException(
20135                    "addPersistentPreferredActivity can only be run by the system");
20136        }
20137        if (filter.countActions() == 0) {
20138            Slog.w(TAG, "Cannot set a preferred activity with no filter actions");
20139            return;
20140        }
20141        synchronized (mPackages) {
20142            Slog.i(TAG, "Adding persistent preferred activity " + activity + " for user " + userId +
20143                    ":");
20144            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
20145            mSettings.editPersistentPreferredActivitiesLPw(userId).addFilter(
20146                    new PersistentPreferredActivity(filter, activity));
20147            scheduleWritePackageRestrictionsLocked(userId);
20148            postPreferredActivityChangedBroadcast(userId);
20149        }
20150    }
20151
20152    @Override
20153    public void clearPackagePersistentPreferredActivities(String packageName, int userId) {
20154        int callingUid = Binder.getCallingUid();
20155        if (callingUid != Process.SYSTEM_UID) {
20156            throw new SecurityException(
20157                    "clearPackagePersistentPreferredActivities can only be run by the system");
20158        }
20159        ArrayList<PersistentPreferredActivity> removed = null;
20160        boolean changed = false;
20161        synchronized (mPackages) {
20162            for (int i=0; i<mSettings.mPersistentPreferredActivities.size(); i++) {
20163                final int thisUserId = mSettings.mPersistentPreferredActivities.keyAt(i);
20164                PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities
20165                        .valueAt(i);
20166                if (userId != thisUserId) {
20167                    continue;
20168                }
20169                Iterator<PersistentPreferredActivity> it = ppir.filterIterator();
20170                while (it.hasNext()) {
20171                    PersistentPreferredActivity ppa = it.next();
20172                    // Mark entry for removal only if it matches the package name.
20173                    if (ppa.mComponent.getPackageName().equals(packageName)) {
20174                        if (removed == null) {
20175                            removed = new ArrayList<PersistentPreferredActivity>();
20176                        }
20177                        removed.add(ppa);
20178                    }
20179                }
20180                if (removed != null) {
20181                    for (int j=0; j<removed.size(); j++) {
20182                        PersistentPreferredActivity ppa = removed.get(j);
20183                        ppir.removeFilter(ppa);
20184                    }
20185                    changed = true;
20186                }
20187            }
20188
20189            if (changed) {
20190                scheduleWritePackageRestrictionsLocked(userId);
20191                postPreferredActivityChangedBroadcast(userId);
20192            }
20193        }
20194    }
20195
20196    /**
20197     * Common machinery for picking apart a restored XML blob and passing
20198     * it to a caller-supplied functor to be applied to the running system.
20199     */
20200    private void restoreFromXml(XmlPullParser parser, int userId,
20201            String expectedStartTag, BlobXmlRestorer functor)
20202            throws IOException, XmlPullParserException {
20203        int type;
20204        while ((type = parser.next()) != XmlPullParser.START_TAG
20205                && type != XmlPullParser.END_DOCUMENT) {
20206        }
20207        if (type != XmlPullParser.START_TAG) {
20208            // oops didn't find a start tag?!
20209            if (DEBUG_BACKUP) {
20210                Slog.e(TAG, "Didn't find start tag during restore");
20211            }
20212            return;
20213        }
20214Slog.v(TAG, ":: restoreFromXml() : got to tag " + parser.getName());
20215        // this is supposed to be TAG_PREFERRED_BACKUP
20216        if (!expectedStartTag.equals(parser.getName())) {
20217            if (DEBUG_BACKUP) {
20218                Slog.e(TAG, "Found unexpected tag " + parser.getName());
20219            }
20220            return;
20221        }
20222
20223        // skip interfering stuff, then we're aligned with the backing implementation
20224        while ((type = parser.next()) == XmlPullParser.TEXT) { }
20225Slog.v(TAG, ":: stepped forward, applying functor at tag " + parser.getName());
20226        functor.apply(parser, userId);
20227    }
20228
20229    private interface BlobXmlRestorer {
20230        public void apply(XmlPullParser parser, int userId) throws IOException, XmlPullParserException;
20231    }
20232
20233    /**
20234     * Non-Binder method, support for the backup/restore mechanism: write the
20235     * full set of preferred activities in its canonical XML format.  Returns the
20236     * XML output as a byte array, or null if there is none.
20237     */
20238    @Override
20239    public byte[] getPreferredActivityBackup(int userId) {
20240        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
20241            throw new SecurityException("Only the system may call getPreferredActivityBackup()");
20242        }
20243
20244        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
20245        try {
20246            final XmlSerializer serializer = new FastXmlSerializer();
20247            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
20248            serializer.startDocument(null, true);
20249            serializer.startTag(null, TAG_PREFERRED_BACKUP);
20250
20251            synchronized (mPackages) {
20252                mSettings.writePreferredActivitiesLPr(serializer, userId, true);
20253            }
20254
20255            serializer.endTag(null, TAG_PREFERRED_BACKUP);
20256            serializer.endDocument();
20257            serializer.flush();
20258        } catch (Exception e) {
20259            if (DEBUG_BACKUP) {
20260                Slog.e(TAG, "Unable to write preferred activities for backup", e);
20261            }
20262            return null;
20263        }
20264
20265        return dataStream.toByteArray();
20266    }
20267
20268    @Override
20269    public void restorePreferredActivities(byte[] backup, int userId) {
20270        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
20271            throw new SecurityException("Only the system may call restorePreferredActivities()");
20272        }
20273
20274        try {
20275            final XmlPullParser parser = Xml.newPullParser();
20276            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
20277            restoreFromXml(parser, userId, TAG_PREFERRED_BACKUP,
20278                    new BlobXmlRestorer() {
20279                        @Override
20280                        public void apply(XmlPullParser parser, int userId)
20281                                throws XmlPullParserException, IOException {
20282                            synchronized (mPackages) {
20283                                mSettings.readPreferredActivitiesLPw(parser, userId);
20284                            }
20285                        }
20286                    } );
20287        } catch (Exception e) {
20288            if (DEBUG_BACKUP) {
20289                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
20290            }
20291        }
20292    }
20293
20294    /**
20295     * Non-Binder method, support for the backup/restore mechanism: write the
20296     * default browser (etc) settings in its canonical XML format.  Returns the default
20297     * browser XML representation as a byte array, or null if there is none.
20298     */
20299    @Override
20300    public byte[] getDefaultAppsBackup(int userId) {
20301        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
20302            throw new SecurityException("Only the system may call getDefaultAppsBackup()");
20303        }
20304
20305        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
20306        try {
20307            final XmlSerializer serializer = new FastXmlSerializer();
20308            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
20309            serializer.startDocument(null, true);
20310            serializer.startTag(null, TAG_DEFAULT_APPS);
20311
20312            synchronized (mPackages) {
20313                mSettings.writeDefaultAppsLPr(serializer, userId);
20314            }
20315
20316            serializer.endTag(null, TAG_DEFAULT_APPS);
20317            serializer.endDocument();
20318            serializer.flush();
20319        } catch (Exception e) {
20320            if (DEBUG_BACKUP) {
20321                Slog.e(TAG, "Unable to write default apps for backup", e);
20322            }
20323            return null;
20324        }
20325
20326        return dataStream.toByteArray();
20327    }
20328
20329    @Override
20330    public void restoreDefaultApps(byte[] backup, int userId) {
20331        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
20332            throw new SecurityException("Only the system may call restoreDefaultApps()");
20333        }
20334
20335        try {
20336            final XmlPullParser parser = Xml.newPullParser();
20337            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
20338            restoreFromXml(parser, userId, TAG_DEFAULT_APPS,
20339                    new BlobXmlRestorer() {
20340                        @Override
20341                        public void apply(XmlPullParser parser, int userId)
20342                                throws XmlPullParserException, IOException {
20343                            synchronized (mPackages) {
20344                                mSettings.readDefaultAppsLPw(parser, userId);
20345                            }
20346                        }
20347                    } );
20348        } catch (Exception e) {
20349            if (DEBUG_BACKUP) {
20350                Slog.e(TAG, "Exception restoring default apps: " + e.getMessage());
20351            }
20352        }
20353    }
20354
20355    @Override
20356    public byte[] getIntentFilterVerificationBackup(int userId) {
20357        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
20358            throw new SecurityException("Only the system may call getIntentFilterVerificationBackup()");
20359        }
20360
20361        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
20362        try {
20363            final XmlSerializer serializer = new FastXmlSerializer();
20364            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
20365            serializer.startDocument(null, true);
20366            serializer.startTag(null, TAG_INTENT_FILTER_VERIFICATION);
20367
20368            synchronized (mPackages) {
20369                mSettings.writeAllDomainVerificationsLPr(serializer, userId);
20370            }
20371
20372            serializer.endTag(null, TAG_INTENT_FILTER_VERIFICATION);
20373            serializer.endDocument();
20374            serializer.flush();
20375        } catch (Exception e) {
20376            if (DEBUG_BACKUP) {
20377                Slog.e(TAG, "Unable to write default apps for backup", e);
20378            }
20379            return null;
20380        }
20381
20382        return dataStream.toByteArray();
20383    }
20384
20385    @Override
20386    public void restoreIntentFilterVerification(byte[] backup, int userId) {
20387        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
20388            throw new SecurityException("Only the system may call restorePreferredActivities()");
20389        }
20390
20391        try {
20392            final XmlPullParser parser = Xml.newPullParser();
20393            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
20394            restoreFromXml(parser, userId, TAG_INTENT_FILTER_VERIFICATION,
20395                    new BlobXmlRestorer() {
20396                        @Override
20397                        public void apply(XmlPullParser parser, int userId)
20398                                throws XmlPullParserException, IOException {
20399                            synchronized (mPackages) {
20400                                mSettings.readAllDomainVerificationsLPr(parser, userId);
20401                                mSettings.writeLPr();
20402                            }
20403                        }
20404                    } );
20405        } catch (Exception e) {
20406            if (DEBUG_BACKUP) {
20407                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
20408            }
20409        }
20410    }
20411
20412    @Override
20413    public byte[] getPermissionGrantBackup(int userId) {
20414        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
20415            throw new SecurityException("Only the system may call getPermissionGrantBackup()");
20416        }
20417
20418        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
20419        try {
20420            final XmlSerializer serializer = new FastXmlSerializer();
20421            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
20422            serializer.startDocument(null, true);
20423            serializer.startTag(null, TAG_PERMISSION_BACKUP);
20424
20425            synchronized (mPackages) {
20426                serializeRuntimePermissionGrantsLPr(serializer, userId);
20427            }
20428
20429            serializer.endTag(null, TAG_PERMISSION_BACKUP);
20430            serializer.endDocument();
20431            serializer.flush();
20432        } catch (Exception e) {
20433            if (DEBUG_BACKUP) {
20434                Slog.e(TAG, "Unable to write default apps for backup", e);
20435            }
20436            return null;
20437        }
20438
20439        return dataStream.toByteArray();
20440    }
20441
20442    @Override
20443    public void restorePermissionGrants(byte[] backup, int userId) {
20444        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
20445            throw new SecurityException("Only the system may call restorePermissionGrants()");
20446        }
20447
20448        try {
20449            final XmlPullParser parser = Xml.newPullParser();
20450            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
20451            restoreFromXml(parser, userId, TAG_PERMISSION_BACKUP,
20452                    new BlobXmlRestorer() {
20453                        @Override
20454                        public void apply(XmlPullParser parser, int userId)
20455                                throws XmlPullParserException, IOException {
20456                            synchronized (mPackages) {
20457                                processRestoredPermissionGrantsLPr(parser, userId);
20458                            }
20459                        }
20460                    } );
20461        } catch (Exception e) {
20462            if (DEBUG_BACKUP) {
20463                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
20464            }
20465        }
20466    }
20467
20468    private void serializeRuntimePermissionGrantsLPr(XmlSerializer serializer, final int userId)
20469            throws IOException {
20470        serializer.startTag(null, TAG_ALL_GRANTS);
20471
20472        final int N = mSettings.mPackages.size();
20473        for (int i = 0; i < N; i++) {
20474            final PackageSetting ps = mSettings.mPackages.valueAt(i);
20475            boolean pkgGrantsKnown = false;
20476
20477            PermissionsState packagePerms = ps.getPermissionsState();
20478
20479            for (PermissionState state : packagePerms.getRuntimePermissionStates(userId)) {
20480                final int grantFlags = state.getFlags();
20481                // only look at grants that are not system/policy fixed
20482                if ((grantFlags & SYSTEM_RUNTIME_GRANT_MASK) == 0) {
20483                    final boolean isGranted = state.isGranted();
20484                    // And only back up the user-twiddled state bits
20485                    if (isGranted || (grantFlags & USER_RUNTIME_GRANT_MASK) != 0) {
20486                        final String packageName = mSettings.mPackages.keyAt(i);
20487                        if (!pkgGrantsKnown) {
20488                            serializer.startTag(null, TAG_GRANT);
20489                            serializer.attribute(null, ATTR_PACKAGE_NAME, packageName);
20490                            pkgGrantsKnown = true;
20491                        }
20492
20493                        final boolean userSet =
20494                                (grantFlags & FLAG_PERMISSION_USER_SET) != 0;
20495                        final boolean userFixed =
20496                                (grantFlags & FLAG_PERMISSION_USER_FIXED) != 0;
20497                        final boolean revoke =
20498                                (grantFlags & FLAG_PERMISSION_REVOKE_ON_UPGRADE) != 0;
20499
20500                        serializer.startTag(null, TAG_PERMISSION);
20501                        serializer.attribute(null, ATTR_PERMISSION_NAME, state.getName());
20502                        if (isGranted) {
20503                            serializer.attribute(null, ATTR_IS_GRANTED, "true");
20504                        }
20505                        if (userSet) {
20506                            serializer.attribute(null, ATTR_USER_SET, "true");
20507                        }
20508                        if (userFixed) {
20509                            serializer.attribute(null, ATTR_USER_FIXED, "true");
20510                        }
20511                        if (revoke) {
20512                            serializer.attribute(null, ATTR_REVOKE_ON_UPGRADE, "true");
20513                        }
20514                        serializer.endTag(null, TAG_PERMISSION);
20515                    }
20516                }
20517            }
20518
20519            if (pkgGrantsKnown) {
20520                serializer.endTag(null, TAG_GRANT);
20521            }
20522        }
20523
20524        serializer.endTag(null, TAG_ALL_GRANTS);
20525    }
20526
20527    private void processRestoredPermissionGrantsLPr(XmlPullParser parser, int userId)
20528            throws XmlPullParserException, IOException {
20529        String pkgName = null;
20530        int outerDepth = parser.getDepth();
20531        int type;
20532        while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
20533                && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) {
20534            if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) {
20535                continue;
20536            }
20537
20538            final String tagName = parser.getName();
20539            if (tagName.equals(TAG_GRANT)) {
20540                pkgName = parser.getAttributeValue(null, ATTR_PACKAGE_NAME);
20541                if (DEBUG_BACKUP) {
20542                    Slog.v(TAG, "+++ Restoring grants for package " + pkgName);
20543                }
20544            } else if (tagName.equals(TAG_PERMISSION)) {
20545
20546                final boolean isGranted = "true".equals(parser.getAttributeValue(null, ATTR_IS_GRANTED));
20547                final String permName = parser.getAttributeValue(null, ATTR_PERMISSION_NAME);
20548
20549                int newFlagSet = 0;
20550                if ("true".equals(parser.getAttributeValue(null, ATTR_USER_SET))) {
20551                    newFlagSet |= FLAG_PERMISSION_USER_SET;
20552                }
20553                if ("true".equals(parser.getAttributeValue(null, ATTR_USER_FIXED))) {
20554                    newFlagSet |= FLAG_PERMISSION_USER_FIXED;
20555                }
20556                if ("true".equals(parser.getAttributeValue(null, ATTR_REVOKE_ON_UPGRADE))) {
20557                    newFlagSet |= FLAG_PERMISSION_REVOKE_ON_UPGRADE;
20558                }
20559                if (DEBUG_BACKUP) {
20560                    Slog.v(TAG, "  + Restoring grant: pkg=" + pkgName + " perm=" + permName
20561                            + " granted=" + isGranted + " bits=0x" + Integer.toHexString(newFlagSet));
20562                }
20563                final PackageSetting ps = mSettings.mPackages.get(pkgName);
20564                if (ps != null) {
20565                    // Already installed so we apply the grant immediately
20566                    if (DEBUG_BACKUP) {
20567                        Slog.v(TAG, "        + already installed; applying");
20568                    }
20569                    PermissionsState perms = ps.getPermissionsState();
20570                    BasePermission bp = mSettings.mPermissions.get(permName);
20571                    if (bp != null) {
20572                        if (isGranted) {
20573                            perms.grantRuntimePermission(bp, userId);
20574                        }
20575                        if (newFlagSet != 0) {
20576                            perms.updatePermissionFlags(bp, userId, USER_RUNTIME_GRANT_MASK, newFlagSet);
20577                        }
20578                    }
20579                } else {
20580                    // Need to wait for post-restore install to apply the grant
20581                    if (DEBUG_BACKUP) {
20582                        Slog.v(TAG, "        - not yet installed; saving for later");
20583                    }
20584                    mSettings.processRestoredPermissionGrantLPr(pkgName, permName,
20585                            isGranted, newFlagSet, userId);
20586                }
20587            } else {
20588                PackageManagerService.reportSettingsProblem(Log.WARN,
20589                        "Unknown element under <" + TAG_PERMISSION_BACKUP + ">: " + tagName);
20590                XmlUtils.skipCurrentTag(parser);
20591            }
20592        }
20593
20594        scheduleWriteSettingsLocked();
20595        mSettings.writeRuntimePermissionsForUserLPr(userId, false);
20596    }
20597
20598    @Override
20599    public void addCrossProfileIntentFilter(IntentFilter intentFilter, String ownerPackage,
20600            int sourceUserId, int targetUserId, int flags) {
20601        mContext.enforceCallingOrSelfPermission(
20602                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
20603        int callingUid = Binder.getCallingUid();
20604        enforceOwnerRights(ownerPackage, callingUid);
20605        enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId);
20606        if (intentFilter.countActions() == 0) {
20607            Slog.w(TAG, "Cannot set a crossProfile intent filter with no filter actions");
20608            return;
20609        }
20610        synchronized (mPackages) {
20611            CrossProfileIntentFilter newFilter = new CrossProfileIntentFilter(intentFilter,
20612                    ownerPackage, targetUserId, flags);
20613            CrossProfileIntentResolver resolver =
20614                    mSettings.editCrossProfileIntentResolverLPw(sourceUserId);
20615            ArrayList<CrossProfileIntentFilter> existing = resolver.findFilters(intentFilter);
20616            // We have all those whose filter is equal. Now checking if the rest is equal as well.
20617            if (existing != null) {
20618                int size = existing.size();
20619                for (int i = 0; i < size; i++) {
20620                    if (newFilter.equalsIgnoreFilter(existing.get(i))) {
20621                        return;
20622                    }
20623                }
20624            }
20625            resolver.addFilter(newFilter);
20626            scheduleWritePackageRestrictionsLocked(sourceUserId);
20627        }
20628    }
20629
20630    @Override
20631    public void clearCrossProfileIntentFilters(int sourceUserId, String ownerPackage) {
20632        mContext.enforceCallingOrSelfPermission(
20633                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
20634        int callingUid = Binder.getCallingUid();
20635        enforceOwnerRights(ownerPackage, callingUid);
20636        enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId);
20637        synchronized (mPackages) {
20638            CrossProfileIntentResolver resolver =
20639                    mSettings.editCrossProfileIntentResolverLPw(sourceUserId);
20640            ArraySet<CrossProfileIntentFilter> set =
20641                    new ArraySet<CrossProfileIntentFilter>(resolver.filterSet());
20642            for (CrossProfileIntentFilter filter : set) {
20643                if (filter.getOwnerPackage().equals(ownerPackage)) {
20644                    resolver.removeFilter(filter);
20645                }
20646            }
20647            scheduleWritePackageRestrictionsLocked(sourceUserId);
20648        }
20649    }
20650
20651    // Enforcing that callingUid is owning pkg on userId
20652    private void enforceOwnerRights(String pkg, int callingUid) {
20653        // The system owns everything.
20654        if (UserHandle.getAppId(callingUid) == Process.SYSTEM_UID) {
20655            return;
20656        }
20657        int callingUserId = UserHandle.getUserId(callingUid);
20658        PackageInfo pi = getPackageInfo(pkg, 0, callingUserId);
20659        if (pi == null) {
20660            throw new IllegalArgumentException("Unknown package " + pkg + " on user "
20661                    + callingUserId);
20662        }
20663        if (!UserHandle.isSameApp(pi.applicationInfo.uid, callingUid)) {
20664            throw new SecurityException("Calling uid " + callingUid
20665                    + " does not own package " + pkg);
20666        }
20667    }
20668
20669    @Override
20670    public ComponentName getHomeActivities(List<ResolveInfo> allHomeCandidates) {
20671        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
20672            return null;
20673        }
20674        return getHomeActivitiesAsUser(allHomeCandidates, UserHandle.getCallingUserId());
20675    }
20676
20677    public void sendSessionCommitBroadcast(PackageInstaller.SessionInfo sessionInfo, int userId) {
20678        UserManagerService ums = UserManagerService.getInstance();
20679        if (ums != null) {
20680            final UserInfo parent = ums.getProfileParent(userId);
20681            final int launcherUid = (parent != null) ? parent.id : userId;
20682            final ComponentName launcherComponent = getDefaultHomeActivity(launcherUid);
20683            if (launcherComponent != null) {
20684                Intent launcherIntent = new Intent(PackageInstaller.ACTION_SESSION_COMMITTED)
20685                        .putExtra(PackageInstaller.EXTRA_SESSION, sessionInfo)
20686                        .putExtra(Intent.EXTRA_USER, UserHandle.of(userId))
20687                        .setPackage(launcherComponent.getPackageName());
20688                mContext.sendBroadcastAsUser(launcherIntent, UserHandle.of(launcherUid));
20689            }
20690        }
20691    }
20692
20693    /**
20694     * Report the 'Home' activity which is currently set as "always use this one". If non is set
20695     * then reports the most likely home activity or null if there are more than one.
20696     */
20697    private ComponentName getDefaultHomeActivity(int userId) {
20698        List<ResolveInfo> allHomeCandidates = new ArrayList<>();
20699        ComponentName cn = getHomeActivitiesAsUser(allHomeCandidates, userId);
20700        if (cn != null) {
20701            return cn;
20702        }
20703
20704        // Find the launcher with the highest priority and return that component if there are no
20705        // other home activity with the same priority.
20706        int lastPriority = Integer.MIN_VALUE;
20707        ComponentName lastComponent = null;
20708        final int size = allHomeCandidates.size();
20709        for (int i = 0; i < size; i++) {
20710            final ResolveInfo ri = allHomeCandidates.get(i);
20711            if (ri.priority > lastPriority) {
20712                lastComponent = ri.activityInfo.getComponentName();
20713                lastPriority = ri.priority;
20714            } else if (ri.priority == lastPriority) {
20715                // Two components found with same priority.
20716                lastComponent = null;
20717            }
20718        }
20719        return lastComponent;
20720    }
20721
20722    private Intent getHomeIntent() {
20723        Intent intent = new Intent(Intent.ACTION_MAIN);
20724        intent.addCategory(Intent.CATEGORY_HOME);
20725        intent.addCategory(Intent.CATEGORY_DEFAULT);
20726        return intent;
20727    }
20728
20729    private IntentFilter getHomeFilter() {
20730        IntentFilter filter = new IntentFilter(Intent.ACTION_MAIN);
20731        filter.addCategory(Intent.CATEGORY_HOME);
20732        filter.addCategory(Intent.CATEGORY_DEFAULT);
20733        return filter;
20734    }
20735
20736    ComponentName getHomeActivitiesAsUser(List<ResolveInfo> allHomeCandidates,
20737            int userId) {
20738        Intent intent  = getHomeIntent();
20739        List<ResolveInfo> list = queryIntentActivitiesInternal(intent, null,
20740                PackageManager.GET_META_DATA, userId);
20741        ResolveInfo preferred = findPreferredActivity(intent, null, 0, list, 0,
20742                true, false, false, userId);
20743
20744        allHomeCandidates.clear();
20745        if (list != null) {
20746            for (ResolveInfo ri : list) {
20747                allHomeCandidates.add(ri);
20748            }
20749        }
20750        return (preferred == null || preferred.activityInfo == null)
20751                ? null
20752                : new ComponentName(preferred.activityInfo.packageName,
20753                        preferred.activityInfo.name);
20754    }
20755
20756    @Override
20757    public void setHomeActivity(ComponentName comp, int userId) {
20758        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
20759            return;
20760        }
20761        ArrayList<ResolveInfo> homeActivities = new ArrayList<>();
20762        getHomeActivitiesAsUser(homeActivities, userId);
20763
20764        boolean found = false;
20765
20766        final int size = homeActivities.size();
20767        final ComponentName[] set = new ComponentName[size];
20768        for (int i = 0; i < size; i++) {
20769            final ResolveInfo candidate = homeActivities.get(i);
20770            final ActivityInfo info = candidate.activityInfo;
20771            final ComponentName activityName = new ComponentName(info.packageName, info.name);
20772            set[i] = activityName;
20773            if (!found && activityName.equals(comp)) {
20774                found = true;
20775            }
20776        }
20777        if (!found) {
20778            throw new IllegalArgumentException("Component " + comp + " cannot be home on user "
20779                    + userId);
20780        }
20781        replacePreferredActivity(getHomeFilter(), IntentFilter.MATCH_CATEGORY_EMPTY,
20782                set, comp, userId);
20783    }
20784
20785    private @Nullable String getSetupWizardPackageName() {
20786        final Intent intent = new Intent(Intent.ACTION_MAIN);
20787        intent.addCategory(Intent.CATEGORY_SETUP_WIZARD);
20788
20789        final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, null,
20790                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE
20791                        | MATCH_DISABLED_COMPONENTS,
20792                UserHandle.myUserId());
20793        if (matches.size() == 1) {
20794            return matches.get(0).getComponentInfo().packageName;
20795        } else {
20796            Slog.e(TAG, "There should probably be exactly one setup wizard; found " + matches.size()
20797                    + ": matches=" + matches);
20798            return null;
20799        }
20800    }
20801
20802    private @Nullable String getStorageManagerPackageName() {
20803        final Intent intent = new Intent(StorageManager.ACTION_MANAGE_STORAGE);
20804
20805        final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, null,
20806                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE
20807                        | MATCH_DISABLED_COMPONENTS,
20808                UserHandle.myUserId());
20809        if (matches.size() == 1) {
20810            return matches.get(0).getComponentInfo().packageName;
20811        } else {
20812            Slog.e(TAG, "There should probably be exactly one storage manager; found "
20813                    + matches.size() + ": matches=" + matches);
20814            return null;
20815        }
20816    }
20817
20818    @Override
20819    public void setApplicationEnabledSetting(String appPackageName,
20820            int newState, int flags, int userId, String callingPackage) {
20821        if (!sUserManager.exists(userId)) return;
20822        if (callingPackage == null) {
20823            callingPackage = Integer.toString(Binder.getCallingUid());
20824        }
20825        setEnabledSetting(appPackageName, null, newState, flags, userId, callingPackage);
20826    }
20827
20828    @Override
20829    public void setUpdateAvailable(String packageName, boolean updateAvailable) {
20830        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, null);
20831        synchronized (mPackages) {
20832            final PackageSetting pkgSetting = mSettings.mPackages.get(packageName);
20833            if (pkgSetting != null) {
20834                pkgSetting.setUpdateAvailable(updateAvailable);
20835            }
20836        }
20837    }
20838
20839    @Override
20840    public void setComponentEnabledSetting(ComponentName componentName,
20841            int newState, int flags, int userId) {
20842        if (!sUserManager.exists(userId)) return;
20843        setEnabledSetting(componentName.getPackageName(),
20844                componentName.getClassName(), newState, flags, userId, null);
20845    }
20846
20847    private void setEnabledSetting(final String packageName, String className, int newState,
20848            final int flags, int userId, String callingPackage) {
20849        if (!(newState == COMPONENT_ENABLED_STATE_DEFAULT
20850              || newState == COMPONENT_ENABLED_STATE_ENABLED
20851              || newState == COMPONENT_ENABLED_STATE_DISABLED
20852              || newState == COMPONENT_ENABLED_STATE_DISABLED_USER
20853              || newState == COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED)) {
20854            throw new IllegalArgumentException("Invalid new component state: "
20855                    + newState);
20856        }
20857        PackageSetting pkgSetting;
20858        final int callingUid = Binder.getCallingUid();
20859        final int permission;
20860        if (callingUid == Process.SYSTEM_UID) {
20861            permission = PackageManager.PERMISSION_GRANTED;
20862        } else {
20863            permission = mContext.checkCallingOrSelfPermission(
20864                    android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
20865        }
20866        enforceCrossUserPermission(callingUid, userId,
20867                false /* requireFullPermission */, true /* checkShell */, "set enabled");
20868        final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
20869        boolean sendNow = false;
20870        boolean isApp = (className == null);
20871        final boolean isCallerInstantApp = (getInstantAppPackageName(callingUid) != null);
20872        String componentName = isApp ? packageName : className;
20873        int packageUid = -1;
20874        ArrayList<String> components;
20875
20876        // reader
20877        synchronized (mPackages) {
20878            pkgSetting = mSettings.mPackages.get(packageName);
20879            if (pkgSetting == null) {
20880                if (!isCallerInstantApp) {
20881                    if (className == null) {
20882                        throw new IllegalArgumentException("Unknown package: " + packageName);
20883                    }
20884                    throw new IllegalArgumentException(
20885                            "Unknown component: " + packageName + "/" + className);
20886                } else {
20887                    // throw SecurityException to prevent leaking package information
20888                    throw new SecurityException(
20889                            "Attempt to change component state; "
20890                            + "pid=" + Binder.getCallingPid()
20891                            + ", uid=" + callingUid
20892                            + (className == null
20893                                    ? ", package=" + packageName
20894                                    : ", component=" + packageName + "/" + className));
20895                }
20896            }
20897        }
20898
20899        // Limit who can change which apps
20900        if (!UserHandle.isSameApp(callingUid, pkgSetting.appId)) {
20901            // Don't allow apps that don't have permission to modify other apps
20902            if (!allowedByPermission) {
20903                throw new SecurityException(
20904                        "Attempt to change component state; "
20905                        + "pid=" + Binder.getCallingPid()
20906                        + ", uid=" + callingUid
20907                        + (className == null
20908                                ? ", package=" + packageName
20909                                : ", component=" + packageName + "/" + className));
20910            }
20911            // Don't allow changing protected packages.
20912            if (mProtectedPackages.isPackageStateProtected(userId, packageName)) {
20913                throw new SecurityException("Cannot disable a protected package: " + packageName);
20914            }
20915        }
20916
20917        synchronized (mPackages) {
20918            if (callingUid == Process.SHELL_UID
20919                    && (pkgSetting.pkgFlags & ApplicationInfo.FLAG_TEST_ONLY) == 0) {
20920                // Shell can only change whole packages between ENABLED and DISABLED_USER states
20921                // unless it is a test package.
20922                int oldState = pkgSetting.getEnabled(userId);
20923                if (className == null
20924                    &&
20925                    (oldState == COMPONENT_ENABLED_STATE_DISABLED_USER
20926                     || oldState == COMPONENT_ENABLED_STATE_DEFAULT
20927                     || oldState == COMPONENT_ENABLED_STATE_ENABLED)
20928                    &&
20929                    (newState == COMPONENT_ENABLED_STATE_DISABLED_USER
20930                     || newState == COMPONENT_ENABLED_STATE_DEFAULT
20931                     || newState == COMPONENT_ENABLED_STATE_ENABLED)) {
20932                    // ok
20933                } else {
20934                    throw new SecurityException(
20935                            "Shell cannot change component state for " + packageName + "/"
20936                            + className + " to " + newState);
20937                }
20938            }
20939            if (className == null) {
20940                // We're dealing with an application/package level state change
20941                if (pkgSetting.getEnabled(userId) == newState) {
20942                    // Nothing to do
20943                    return;
20944                }
20945                if (newState == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT
20946                    || newState == PackageManager.COMPONENT_ENABLED_STATE_ENABLED) {
20947                    // Don't care about who enables an app.
20948                    callingPackage = null;
20949                }
20950                pkgSetting.setEnabled(newState, userId, callingPackage);
20951                // pkgSetting.pkg.mSetEnabled = newState;
20952            } else {
20953                // We're dealing with a component level state change
20954                // First, verify that this is a valid class name.
20955                PackageParser.Package pkg = pkgSetting.pkg;
20956                if (pkg == null || !pkg.hasComponentClassName(className)) {
20957                    if (pkg != null &&
20958                            pkg.applicationInfo.targetSdkVersion >=
20959                                    Build.VERSION_CODES.JELLY_BEAN) {
20960                        throw new IllegalArgumentException("Component class " + className
20961                                + " does not exist in " + packageName);
20962                    } else {
20963                        Slog.w(TAG, "Failed setComponentEnabledSetting: component class "
20964                                + className + " does not exist in " + packageName);
20965                    }
20966                }
20967                switch (newState) {
20968                case COMPONENT_ENABLED_STATE_ENABLED:
20969                    if (!pkgSetting.enableComponentLPw(className, userId)) {
20970                        return;
20971                    }
20972                    break;
20973                case COMPONENT_ENABLED_STATE_DISABLED:
20974                    if (!pkgSetting.disableComponentLPw(className, userId)) {
20975                        return;
20976                    }
20977                    break;
20978                case COMPONENT_ENABLED_STATE_DEFAULT:
20979                    if (!pkgSetting.restoreComponentLPw(className, userId)) {
20980                        return;
20981                    }
20982                    break;
20983                default:
20984                    Slog.e(TAG, "Invalid new component state: " + newState);
20985                    return;
20986                }
20987            }
20988            scheduleWritePackageRestrictionsLocked(userId);
20989            updateSequenceNumberLP(packageName, new int[] { userId });
20990            final long callingId = Binder.clearCallingIdentity();
20991            try {
20992                updateInstantAppInstallerLocked(packageName);
20993            } finally {
20994                Binder.restoreCallingIdentity(callingId);
20995            }
20996            components = mPendingBroadcasts.get(userId, packageName);
20997            final boolean newPackage = components == null;
20998            if (newPackage) {
20999                components = new ArrayList<String>();
21000            }
21001            if (!components.contains(componentName)) {
21002                components.add(componentName);
21003            }
21004            if ((flags&PackageManager.DONT_KILL_APP) == 0) {
21005                sendNow = true;
21006                // Purge entry from pending broadcast list if another one exists already
21007                // since we are sending one right away.
21008                mPendingBroadcasts.remove(userId, packageName);
21009            } else {
21010                if (newPackage) {
21011                    mPendingBroadcasts.put(userId, packageName, components);
21012                }
21013                if (!mHandler.hasMessages(SEND_PENDING_BROADCAST)) {
21014                    // Schedule a message
21015                    mHandler.sendEmptyMessageDelayed(SEND_PENDING_BROADCAST, BROADCAST_DELAY);
21016                }
21017            }
21018        }
21019
21020        long callingId = Binder.clearCallingIdentity();
21021        try {
21022            if (sendNow) {
21023                packageUid = UserHandle.getUid(userId, pkgSetting.appId);
21024                sendPackageChangedBroadcast(packageName,
21025                        (flags&PackageManager.DONT_KILL_APP) != 0, components, packageUid);
21026            }
21027        } finally {
21028            Binder.restoreCallingIdentity(callingId);
21029        }
21030    }
21031
21032    @Override
21033    public void flushPackageRestrictionsAsUser(int userId) {
21034        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
21035            return;
21036        }
21037        if (!sUserManager.exists(userId)) {
21038            return;
21039        }
21040        enforceCrossUserPermission(Binder.getCallingUid(), userId, false /* requireFullPermission*/,
21041                false /* checkShell */, "flushPackageRestrictions");
21042        synchronized (mPackages) {
21043            mSettings.writePackageRestrictionsLPr(userId);
21044            mDirtyUsers.remove(userId);
21045            if (mDirtyUsers.isEmpty()) {
21046                mHandler.removeMessages(WRITE_PACKAGE_RESTRICTIONS);
21047            }
21048        }
21049    }
21050
21051    private void sendPackageChangedBroadcast(String packageName,
21052            boolean killFlag, ArrayList<String> componentNames, int packageUid) {
21053        if (DEBUG_INSTALL)
21054            Log.v(TAG, "Sending package changed: package=" + packageName + " components="
21055                    + componentNames);
21056        Bundle extras = new Bundle(4);
21057        extras.putString(Intent.EXTRA_CHANGED_COMPONENT_NAME, componentNames.get(0));
21058        String nameList[] = new String[componentNames.size()];
21059        componentNames.toArray(nameList);
21060        extras.putStringArray(Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST, nameList);
21061        extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, killFlag);
21062        extras.putInt(Intent.EXTRA_UID, packageUid);
21063        // If this is not reporting a change of the overall package, then only send it
21064        // to registered receivers.  We don't want to launch a swath of apps for every
21065        // little component state change.
21066        final int flags = !componentNames.contains(packageName)
21067                ? Intent.FLAG_RECEIVER_REGISTERED_ONLY : 0;
21068        sendPackageBroadcast(Intent.ACTION_PACKAGE_CHANGED,  packageName, extras, flags, null, null,
21069                new int[] {UserHandle.getUserId(packageUid)});
21070    }
21071
21072    @Override
21073    public void setPackageStoppedState(String packageName, boolean stopped, int userId) {
21074        if (!sUserManager.exists(userId)) return;
21075        final int callingUid = Binder.getCallingUid();
21076        if (getInstantAppPackageName(callingUid) != null) {
21077            return;
21078        }
21079        final int permission = mContext.checkCallingOrSelfPermission(
21080                android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
21081        final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
21082        enforceCrossUserPermission(callingUid, userId,
21083                true /* requireFullPermission */, true /* checkShell */, "stop package");
21084        // writer
21085        synchronized (mPackages) {
21086            if (mSettings.setPackageStoppedStateLPw(this, packageName, stopped,
21087                    allowedByPermission, callingUid, userId)) {
21088                scheduleWritePackageRestrictionsLocked(userId);
21089            }
21090        }
21091    }
21092
21093    @Override
21094    public String getInstallerPackageName(String packageName) {
21095        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
21096            return null;
21097        }
21098        // reader
21099        synchronized (mPackages) {
21100            return mSettings.getInstallerPackageNameLPr(packageName);
21101        }
21102    }
21103
21104    public boolean isOrphaned(String packageName) {
21105        // reader
21106        synchronized (mPackages) {
21107            return mSettings.isOrphaned(packageName);
21108        }
21109    }
21110
21111    @Override
21112    public int getApplicationEnabledSetting(String packageName, int userId) {
21113        if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
21114        int callingUid = Binder.getCallingUid();
21115        enforceCrossUserPermission(callingUid, userId,
21116                false /* requireFullPermission */, false /* checkShell */, "get enabled");
21117        // reader
21118        synchronized (mPackages) {
21119            if (filterAppAccessLPr(mSettings.getPackageLPr(packageName), callingUid, userId)) {
21120                return COMPONENT_ENABLED_STATE_DISABLED;
21121            }
21122            return mSettings.getApplicationEnabledSettingLPr(packageName, userId);
21123        }
21124    }
21125
21126    @Override
21127    public int getComponentEnabledSetting(ComponentName component, int userId) {
21128        if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
21129        int callingUid = Binder.getCallingUid();
21130        enforceCrossUserPermission(callingUid, userId,
21131                false /*requireFullPermission*/, false /*checkShell*/, "getComponentEnabled");
21132        synchronized (mPackages) {
21133            if (filterAppAccessLPr(mSettings.getPackageLPr(component.getPackageName()), callingUid,
21134                    component, TYPE_UNKNOWN, userId)) {
21135                return COMPONENT_ENABLED_STATE_DISABLED;
21136            }
21137            return mSettings.getComponentEnabledSettingLPr(component, userId);
21138        }
21139    }
21140
21141    @Override
21142    public void enterSafeMode() {
21143        enforceSystemOrRoot("Only the system can request entering safe mode");
21144
21145        if (!mSystemReady) {
21146            mSafeMode = true;
21147        }
21148    }
21149
21150    @Override
21151    public void systemReady() {
21152        enforceSystemOrRoot("Only the system can claim the system is ready");
21153
21154        mSystemReady = true;
21155        final ContentResolver resolver = mContext.getContentResolver();
21156        ContentObserver co = new ContentObserver(mHandler) {
21157            @Override
21158            public void onChange(boolean selfChange) {
21159                mEphemeralAppsDisabled =
21160                        (Global.getInt(resolver, Global.ENABLE_EPHEMERAL_FEATURE, 1) == 0) ||
21161                                (Secure.getInt(resolver, Secure.INSTANT_APPS_ENABLED, 1) == 0);
21162            }
21163        };
21164        mContext.getContentResolver().registerContentObserver(android.provider.Settings.Global
21165                        .getUriFor(Global.ENABLE_EPHEMERAL_FEATURE),
21166                false, co, UserHandle.USER_SYSTEM);
21167        mContext.getContentResolver().registerContentObserver(android.provider.Settings.Global
21168                        .getUriFor(Secure.INSTANT_APPS_ENABLED), false, co, UserHandle.USER_SYSTEM);
21169        co.onChange(true);
21170
21171        // Disable any carrier apps. We do this very early in boot to prevent the apps from being
21172        // disabled after already being started.
21173        CarrierAppUtils.disableCarrierAppsUntilPrivileged(mContext.getOpPackageName(), this,
21174                mContext.getContentResolver(), UserHandle.USER_SYSTEM);
21175
21176        // Read the compatibilty setting when the system is ready.
21177        boolean compatibilityModeEnabled = android.provider.Settings.Global.getInt(
21178                mContext.getContentResolver(),
21179                android.provider.Settings.Global.COMPATIBILITY_MODE, 1) == 1;
21180        PackageParser.setCompatibilityModeEnabled(compatibilityModeEnabled);
21181        if (DEBUG_SETTINGS) {
21182            Log.d(TAG, "compatibility mode:" + compatibilityModeEnabled);
21183        }
21184
21185        int[] grantPermissionsUserIds = EMPTY_INT_ARRAY;
21186
21187        synchronized (mPackages) {
21188            // Verify that all of the preferred activity components actually
21189            // exist.  It is possible for applications to be updated and at
21190            // that point remove a previously declared activity component that
21191            // had been set as a preferred activity.  We try to clean this up
21192            // the next time we encounter that preferred activity, but it is
21193            // possible for the user flow to never be able to return to that
21194            // situation so here we do a sanity check to make sure we haven't
21195            // left any junk around.
21196            ArrayList<PreferredActivity> removed = new ArrayList<PreferredActivity>();
21197            for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
21198                PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
21199                removed.clear();
21200                for (PreferredActivity pa : pir.filterSet()) {
21201                    if (mActivities.mActivities.get(pa.mPref.mComponent) == null) {
21202                        removed.add(pa);
21203                    }
21204                }
21205                if (removed.size() > 0) {
21206                    for (int r=0; r<removed.size(); r++) {
21207                        PreferredActivity pa = removed.get(r);
21208                        Slog.w(TAG, "Removing dangling preferred activity: "
21209                                + pa.mPref.mComponent);
21210                        pir.removeFilter(pa);
21211                    }
21212                    mSettings.writePackageRestrictionsLPr(
21213                            mSettings.mPreferredActivities.keyAt(i));
21214                }
21215            }
21216
21217            for (int userId : UserManagerService.getInstance().getUserIds()) {
21218                if (!mSettings.areDefaultRuntimePermissionsGrantedLPr(userId)) {
21219                    grantPermissionsUserIds = ArrayUtils.appendInt(
21220                            grantPermissionsUserIds, userId);
21221                }
21222            }
21223        }
21224        sUserManager.systemReady();
21225
21226        // If we upgraded grant all default permissions before kicking off.
21227        for (int userId : grantPermissionsUserIds) {
21228            mDefaultPermissionPolicy.grantDefaultPermissions(userId);
21229        }
21230
21231        // If we did not grant default permissions, we preload from this the
21232        // default permission exceptions lazily to ensure we don't hit the
21233        // disk on a new user creation.
21234        if (grantPermissionsUserIds == EMPTY_INT_ARRAY) {
21235            mDefaultPermissionPolicy.scheduleReadDefaultPermissionExceptions();
21236        }
21237
21238        // Kick off any messages waiting for system ready
21239        if (mPostSystemReadyMessages != null) {
21240            for (Message msg : mPostSystemReadyMessages) {
21241                msg.sendToTarget();
21242            }
21243            mPostSystemReadyMessages = null;
21244        }
21245
21246        // Watch for external volumes that come and go over time
21247        final StorageManager storage = mContext.getSystemService(StorageManager.class);
21248        storage.registerListener(mStorageListener);
21249
21250        mInstallerService.systemReady();
21251        mPackageDexOptimizer.systemReady();
21252
21253        StorageManagerInternal StorageManagerInternal = LocalServices.getService(
21254                StorageManagerInternal.class);
21255        StorageManagerInternal.addExternalStoragePolicy(
21256                new StorageManagerInternal.ExternalStorageMountPolicy() {
21257            @Override
21258            public int getMountMode(int uid, String packageName) {
21259                if (Process.isIsolated(uid)) {
21260                    return Zygote.MOUNT_EXTERNAL_NONE;
21261                }
21262                if (checkUidPermission(WRITE_MEDIA_STORAGE, uid) == PERMISSION_GRANTED) {
21263                    return Zygote.MOUNT_EXTERNAL_DEFAULT;
21264                }
21265                if (checkUidPermission(READ_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) {
21266                    return Zygote.MOUNT_EXTERNAL_DEFAULT;
21267                }
21268                if (checkUidPermission(WRITE_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) {
21269                    return Zygote.MOUNT_EXTERNAL_READ;
21270                }
21271                return Zygote.MOUNT_EXTERNAL_WRITE;
21272            }
21273
21274            @Override
21275            public boolean hasExternalStorage(int uid, String packageName) {
21276                return true;
21277            }
21278        });
21279
21280        // Now that we're mostly running, clean up stale users and apps
21281        sUserManager.reconcileUsers(StorageManager.UUID_PRIVATE_INTERNAL);
21282        reconcileApps(StorageManager.UUID_PRIVATE_INTERNAL);
21283
21284        if (mPrivappPermissionsViolations != null) {
21285            Slog.wtf(TAG,"Signature|privileged permissions not in "
21286                    + "privapp-permissions whitelist: " + mPrivappPermissionsViolations);
21287            mPrivappPermissionsViolations = null;
21288        }
21289    }
21290
21291    public void waitForAppDataPrepared() {
21292        if (mPrepareAppDataFuture == null) {
21293            return;
21294        }
21295        ConcurrentUtils.waitForFutureNoInterrupt(mPrepareAppDataFuture, "wait for prepareAppData");
21296        mPrepareAppDataFuture = null;
21297    }
21298
21299    @Override
21300    public boolean isSafeMode() {
21301        // allow instant applications
21302        return mSafeMode;
21303    }
21304
21305    @Override
21306    public boolean hasSystemUidErrors() {
21307        // allow instant applications
21308        return mHasSystemUidErrors;
21309    }
21310
21311    static String arrayToString(int[] array) {
21312        StringBuffer buf = new StringBuffer(128);
21313        buf.append('[');
21314        if (array != null) {
21315            for (int i=0; i<array.length; i++) {
21316                if (i > 0) buf.append(", ");
21317                buf.append(array[i]);
21318            }
21319        }
21320        buf.append(']');
21321        return buf.toString();
21322    }
21323
21324    static class DumpState {
21325        public static final int DUMP_LIBS = 1 << 0;
21326        public static final int DUMP_FEATURES = 1 << 1;
21327        public static final int DUMP_ACTIVITY_RESOLVERS = 1 << 2;
21328        public static final int DUMP_SERVICE_RESOLVERS = 1 << 3;
21329        public static final int DUMP_RECEIVER_RESOLVERS = 1 << 4;
21330        public static final int DUMP_CONTENT_RESOLVERS = 1 << 5;
21331        public static final int DUMP_PERMISSIONS = 1 << 6;
21332        public static final int DUMP_PACKAGES = 1 << 7;
21333        public static final int DUMP_SHARED_USERS = 1 << 8;
21334        public static final int DUMP_MESSAGES = 1 << 9;
21335        public static final int DUMP_PROVIDERS = 1 << 10;
21336        public static final int DUMP_VERIFIERS = 1 << 11;
21337        public static final int DUMP_PREFERRED = 1 << 12;
21338        public static final int DUMP_PREFERRED_XML = 1 << 13;
21339        public static final int DUMP_KEYSETS = 1 << 14;
21340        public static final int DUMP_VERSION = 1 << 15;
21341        public static final int DUMP_INSTALLS = 1 << 16;
21342        public static final int DUMP_INTENT_FILTER_VERIFIERS = 1 << 17;
21343        public static final int DUMP_DOMAIN_PREFERRED = 1 << 18;
21344        public static final int DUMP_FROZEN = 1 << 19;
21345        public static final int DUMP_DEXOPT = 1 << 20;
21346        public static final int DUMP_COMPILER_STATS = 1 << 21;
21347        public static final int DUMP_ENABLED_OVERLAYS = 1 << 22;
21348        public static final int DUMP_CHANGES = 1 << 23;
21349
21350        public static final int OPTION_SHOW_FILTERS = 1 << 0;
21351
21352        private int mTypes;
21353
21354        private int mOptions;
21355
21356        private boolean mTitlePrinted;
21357
21358        private SharedUserSetting mSharedUser;
21359
21360        public boolean isDumping(int type) {
21361            if (mTypes == 0 && type != DUMP_PREFERRED_XML) {
21362                return true;
21363            }
21364
21365            return (mTypes & type) != 0;
21366        }
21367
21368        public void setDump(int type) {
21369            mTypes |= type;
21370        }
21371
21372        public boolean isOptionEnabled(int option) {
21373            return (mOptions & option) != 0;
21374        }
21375
21376        public void setOptionEnabled(int option) {
21377            mOptions |= option;
21378        }
21379
21380        public boolean onTitlePrinted() {
21381            final boolean printed = mTitlePrinted;
21382            mTitlePrinted = true;
21383            return printed;
21384        }
21385
21386        public boolean getTitlePrinted() {
21387            return mTitlePrinted;
21388        }
21389
21390        public void setTitlePrinted(boolean enabled) {
21391            mTitlePrinted = enabled;
21392        }
21393
21394        public SharedUserSetting getSharedUser() {
21395            return mSharedUser;
21396        }
21397
21398        public void setSharedUser(SharedUserSetting user) {
21399            mSharedUser = user;
21400        }
21401    }
21402
21403    @Override
21404    public void onShellCommand(FileDescriptor in, FileDescriptor out,
21405            FileDescriptor err, String[] args, ShellCallback callback,
21406            ResultReceiver resultReceiver) {
21407        (new PackageManagerShellCommand(this)).exec(
21408                this, in, out, err, args, callback, resultReceiver);
21409    }
21410
21411    @Override
21412    protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
21413        if (!DumpUtils.checkDumpAndUsageStatsPermission(mContext, TAG, pw)) return;
21414
21415        DumpState dumpState = new DumpState();
21416        boolean fullPreferred = false;
21417        boolean checkin = false;
21418
21419        String packageName = null;
21420        ArraySet<String> permissionNames = null;
21421
21422        int opti = 0;
21423        while (opti < args.length) {
21424            String opt = args[opti];
21425            if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') {
21426                break;
21427            }
21428            opti++;
21429
21430            if ("-a".equals(opt)) {
21431                // Right now we only know how to print all.
21432            } else if ("-h".equals(opt)) {
21433                pw.println("Package manager dump options:");
21434                pw.println("  [-h] [-f] [--checkin] [cmd] ...");
21435                pw.println("    --checkin: dump for a checkin");
21436                pw.println("    -f: print details of intent filters");
21437                pw.println("    -h: print this help");
21438                pw.println("  cmd may be one of:");
21439                pw.println("    l[ibraries]: list known shared libraries");
21440                pw.println("    f[eatures]: list device features");
21441                pw.println("    k[eysets]: print known keysets");
21442                pw.println("    r[esolvers] [activity|service|receiver|content]: dump intent resolvers");
21443                pw.println("    perm[issions]: dump permissions");
21444                pw.println("    permission [name ...]: dump declaration and use of given permission");
21445                pw.println("    pref[erred]: print preferred package settings");
21446                pw.println("    preferred-xml [--full]: print preferred package settings as xml");
21447                pw.println("    prov[iders]: dump content providers");
21448                pw.println("    p[ackages]: dump installed packages");
21449                pw.println("    s[hared-users]: dump shared user IDs");
21450                pw.println("    m[essages]: print collected runtime messages");
21451                pw.println("    v[erifiers]: print package verifier info");
21452                pw.println("    d[omain-preferred-apps]: print domains preferred apps");
21453                pw.println("    i[ntent-filter-verifiers]|ifv: print intent filter verifier info");
21454                pw.println("    version: print database version info");
21455                pw.println("    write: write current settings now");
21456                pw.println("    installs: details about install sessions");
21457                pw.println("    check-permission <permission> <package> [<user>]: does pkg hold perm?");
21458                pw.println("    dexopt: dump dexopt state");
21459                pw.println("    compiler-stats: dump compiler statistics");
21460                pw.println("    enabled-overlays: dump list of enabled overlay packages");
21461                pw.println("    <package.name>: info about given package");
21462                return;
21463            } else if ("--checkin".equals(opt)) {
21464                checkin = true;
21465            } else if ("-f".equals(opt)) {
21466                dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS);
21467            } else if ("--proto".equals(opt)) {
21468                dumpProto(fd);
21469                return;
21470            } else {
21471                pw.println("Unknown argument: " + opt + "; use -h for help");
21472            }
21473        }
21474
21475        // Is the caller requesting to dump a particular piece of data?
21476        if (opti < args.length) {
21477            String cmd = args[opti];
21478            opti++;
21479            // Is this a package name?
21480            if ("android".equals(cmd) || cmd.contains(".")) {
21481                packageName = cmd;
21482                // When dumping a single package, we always dump all of its
21483                // filter information since the amount of data will be reasonable.
21484                dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS);
21485            } else if ("check-permission".equals(cmd)) {
21486                if (opti >= args.length) {
21487                    pw.println("Error: check-permission missing permission argument");
21488                    return;
21489                }
21490                String perm = args[opti];
21491                opti++;
21492                if (opti >= args.length) {
21493                    pw.println("Error: check-permission missing package argument");
21494                    return;
21495                }
21496
21497                String pkg = args[opti];
21498                opti++;
21499                int user = UserHandle.getUserId(Binder.getCallingUid());
21500                if (opti < args.length) {
21501                    try {
21502                        user = Integer.parseInt(args[opti]);
21503                    } catch (NumberFormatException e) {
21504                        pw.println("Error: check-permission user argument is not a number: "
21505                                + args[opti]);
21506                        return;
21507                    }
21508                }
21509
21510                // Normalize package name to handle renamed packages and static libs
21511                pkg = resolveInternalPackageNameLPr(pkg, PackageManager.VERSION_CODE_HIGHEST);
21512
21513                pw.println(checkPermission(perm, pkg, user));
21514                return;
21515            } else if ("l".equals(cmd) || "libraries".equals(cmd)) {
21516                dumpState.setDump(DumpState.DUMP_LIBS);
21517            } else if ("f".equals(cmd) || "features".equals(cmd)) {
21518                dumpState.setDump(DumpState.DUMP_FEATURES);
21519            } else if ("r".equals(cmd) || "resolvers".equals(cmd)) {
21520                if (opti >= args.length) {
21521                    dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS
21522                            | DumpState.DUMP_SERVICE_RESOLVERS
21523                            | DumpState.DUMP_RECEIVER_RESOLVERS
21524                            | DumpState.DUMP_CONTENT_RESOLVERS);
21525                } else {
21526                    while (opti < args.length) {
21527                        String name = args[opti];
21528                        if ("a".equals(name) || "activity".equals(name)) {
21529                            dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS);
21530                        } else if ("s".equals(name) || "service".equals(name)) {
21531                            dumpState.setDump(DumpState.DUMP_SERVICE_RESOLVERS);
21532                        } else if ("r".equals(name) || "receiver".equals(name)) {
21533                            dumpState.setDump(DumpState.DUMP_RECEIVER_RESOLVERS);
21534                        } else if ("c".equals(name) || "content".equals(name)) {
21535                            dumpState.setDump(DumpState.DUMP_CONTENT_RESOLVERS);
21536                        } else {
21537                            pw.println("Error: unknown resolver table type: " + name);
21538                            return;
21539                        }
21540                        opti++;
21541                    }
21542                }
21543            } else if ("perm".equals(cmd) || "permissions".equals(cmd)) {
21544                dumpState.setDump(DumpState.DUMP_PERMISSIONS);
21545            } else if ("permission".equals(cmd)) {
21546                if (opti >= args.length) {
21547                    pw.println("Error: permission requires permission name");
21548                    return;
21549                }
21550                permissionNames = new ArraySet<>();
21551                while (opti < args.length) {
21552                    permissionNames.add(args[opti]);
21553                    opti++;
21554                }
21555                dumpState.setDump(DumpState.DUMP_PERMISSIONS
21556                        | DumpState.DUMP_PACKAGES | DumpState.DUMP_SHARED_USERS);
21557            } else if ("pref".equals(cmd) || "preferred".equals(cmd)) {
21558                dumpState.setDump(DumpState.DUMP_PREFERRED);
21559            } else if ("preferred-xml".equals(cmd)) {
21560                dumpState.setDump(DumpState.DUMP_PREFERRED_XML);
21561                if (opti < args.length && "--full".equals(args[opti])) {
21562                    fullPreferred = true;
21563                    opti++;
21564                }
21565            } else if ("d".equals(cmd) || "domain-preferred-apps".equals(cmd)) {
21566                dumpState.setDump(DumpState.DUMP_DOMAIN_PREFERRED);
21567            } else if ("p".equals(cmd) || "packages".equals(cmd)) {
21568                dumpState.setDump(DumpState.DUMP_PACKAGES);
21569            } else if ("s".equals(cmd) || "shared-users".equals(cmd)) {
21570                dumpState.setDump(DumpState.DUMP_SHARED_USERS);
21571            } else if ("prov".equals(cmd) || "providers".equals(cmd)) {
21572                dumpState.setDump(DumpState.DUMP_PROVIDERS);
21573            } else if ("m".equals(cmd) || "messages".equals(cmd)) {
21574                dumpState.setDump(DumpState.DUMP_MESSAGES);
21575            } else if ("v".equals(cmd) || "verifiers".equals(cmd)) {
21576                dumpState.setDump(DumpState.DUMP_VERIFIERS);
21577            } else if ("i".equals(cmd) || "ifv".equals(cmd)
21578                    || "intent-filter-verifiers".equals(cmd)) {
21579                dumpState.setDump(DumpState.DUMP_INTENT_FILTER_VERIFIERS);
21580            } else if ("version".equals(cmd)) {
21581                dumpState.setDump(DumpState.DUMP_VERSION);
21582            } else if ("k".equals(cmd) || "keysets".equals(cmd)) {
21583                dumpState.setDump(DumpState.DUMP_KEYSETS);
21584            } else if ("installs".equals(cmd)) {
21585                dumpState.setDump(DumpState.DUMP_INSTALLS);
21586            } else if ("frozen".equals(cmd)) {
21587                dumpState.setDump(DumpState.DUMP_FROZEN);
21588            } else if ("dexopt".equals(cmd)) {
21589                dumpState.setDump(DumpState.DUMP_DEXOPT);
21590            } else if ("compiler-stats".equals(cmd)) {
21591                dumpState.setDump(DumpState.DUMP_COMPILER_STATS);
21592            } else if ("enabled-overlays".equals(cmd)) {
21593                dumpState.setDump(DumpState.DUMP_ENABLED_OVERLAYS);
21594            } else if ("changes".equals(cmd)) {
21595                dumpState.setDump(DumpState.DUMP_CHANGES);
21596            } else if ("write".equals(cmd)) {
21597                synchronized (mPackages) {
21598                    mSettings.writeLPr();
21599                    pw.println("Settings written.");
21600                    return;
21601                }
21602            }
21603        }
21604
21605        if (checkin) {
21606            pw.println("vers,1");
21607        }
21608
21609        // reader
21610        synchronized (mPackages) {
21611            if (dumpState.isDumping(DumpState.DUMP_VERSION) && packageName == null) {
21612                if (!checkin) {
21613                    if (dumpState.onTitlePrinted())
21614                        pw.println();
21615                    pw.println("Database versions:");
21616                    mSettings.dumpVersionLPr(new IndentingPrintWriter(pw, "  "));
21617                }
21618            }
21619
21620            if (dumpState.isDumping(DumpState.DUMP_VERIFIERS) && packageName == null) {
21621                if (!checkin) {
21622                    if (dumpState.onTitlePrinted())
21623                        pw.println();
21624                    pw.println("Verifiers:");
21625                    pw.print("  Required: ");
21626                    pw.print(mRequiredVerifierPackage);
21627                    pw.print(" (uid=");
21628                    pw.print(getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING,
21629                            UserHandle.USER_SYSTEM));
21630                    pw.println(")");
21631                } else if (mRequiredVerifierPackage != null) {
21632                    pw.print("vrfy,"); pw.print(mRequiredVerifierPackage);
21633                    pw.print(",");
21634                    pw.println(getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING,
21635                            UserHandle.USER_SYSTEM));
21636                }
21637            }
21638
21639            if (dumpState.isDumping(DumpState.DUMP_INTENT_FILTER_VERIFIERS) &&
21640                    packageName == null) {
21641                if (mIntentFilterVerifierComponent != null) {
21642                    String verifierPackageName = mIntentFilterVerifierComponent.getPackageName();
21643                    if (!checkin) {
21644                        if (dumpState.onTitlePrinted())
21645                            pw.println();
21646                        pw.println("Intent Filter Verifier:");
21647                        pw.print("  Using: ");
21648                        pw.print(verifierPackageName);
21649                        pw.print(" (uid=");
21650                        pw.print(getPackageUid(verifierPackageName, MATCH_DEBUG_TRIAGED_MISSING,
21651                                UserHandle.USER_SYSTEM));
21652                        pw.println(")");
21653                    } else if (verifierPackageName != null) {
21654                        pw.print("ifv,"); pw.print(verifierPackageName);
21655                        pw.print(",");
21656                        pw.println(getPackageUid(verifierPackageName, MATCH_DEBUG_TRIAGED_MISSING,
21657                                UserHandle.USER_SYSTEM));
21658                    }
21659                } else {
21660                    pw.println();
21661                    pw.println("No Intent Filter Verifier available!");
21662                }
21663            }
21664
21665            if (dumpState.isDumping(DumpState.DUMP_LIBS) && packageName == null) {
21666                boolean printedHeader = false;
21667                final Iterator<String> it = mSharedLibraries.keySet().iterator();
21668                while (it.hasNext()) {
21669                    String libName = it.next();
21670                    SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(libName);
21671                    if (versionedLib == null) {
21672                        continue;
21673                    }
21674                    final int versionCount = versionedLib.size();
21675                    for (int i = 0; i < versionCount; i++) {
21676                        SharedLibraryEntry libEntry = versionedLib.valueAt(i);
21677                        if (!checkin) {
21678                            if (!printedHeader) {
21679                                if (dumpState.onTitlePrinted())
21680                                    pw.println();
21681                                pw.println("Libraries:");
21682                                printedHeader = true;
21683                            }
21684                            pw.print("  ");
21685                        } else {
21686                            pw.print("lib,");
21687                        }
21688                        pw.print(libEntry.info.getName());
21689                        if (libEntry.info.isStatic()) {
21690                            pw.print(" version=" + libEntry.info.getVersion());
21691                        }
21692                        if (!checkin) {
21693                            pw.print(" -> ");
21694                        }
21695                        if (libEntry.path != null) {
21696                            pw.print(" (jar) ");
21697                            pw.print(libEntry.path);
21698                        } else {
21699                            pw.print(" (apk) ");
21700                            pw.print(libEntry.apk);
21701                        }
21702                        pw.println();
21703                    }
21704                }
21705            }
21706
21707            if (dumpState.isDumping(DumpState.DUMP_FEATURES) && packageName == null) {
21708                if (dumpState.onTitlePrinted())
21709                    pw.println();
21710                if (!checkin) {
21711                    pw.println("Features:");
21712                }
21713
21714                synchronized (mAvailableFeatures) {
21715                    for (FeatureInfo feat : mAvailableFeatures.values()) {
21716                        if (checkin) {
21717                            pw.print("feat,");
21718                            pw.print(feat.name);
21719                            pw.print(",");
21720                            pw.println(feat.version);
21721                        } else {
21722                            pw.print("  ");
21723                            pw.print(feat.name);
21724                            if (feat.version > 0) {
21725                                pw.print(" version=");
21726                                pw.print(feat.version);
21727                            }
21728                            pw.println();
21729                        }
21730                    }
21731                }
21732            }
21733
21734            if (!checkin && dumpState.isDumping(DumpState.DUMP_ACTIVITY_RESOLVERS)) {
21735                if (mActivities.dump(pw, dumpState.getTitlePrinted() ? "\nActivity Resolver Table:"
21736                        : "Activity Resolver Table:", "  ", packageName,
21737                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
21738                    dumpState.setTitlePrinted(true);
21739                }
21740            }
21741            if (!checkin && dumpState.isDumping(DumpState.DUMP_RECEIVER_RESOLVERS)) {
21742                if (mReceivers.dump(pw, dumpState.getTitlePrinted() ? "\nReceiver Resolver Table:"
21743                        : "Receiver Resolver Table:", "  ", packageName,
21744                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
21745                    dumpState.setTitlePrinted(true);
21746                }
21747            }
21748            if (!checkin && dumpState.isDumping(DumpState.DUMP_SERVICE_RESOLVERS)) {
21749                if (mServices.dump(pw, dumpState.getTitlePrinted() ? "\nService Resolver Table:"
21750                        : "Service Resolver Table:", "  ", packageName,
21751                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
21752                    dumpState.setTitlePrinted(true);
21753                }
21754            }
21755            if (!checkin && dumpState.isDumping(DumpState.DUMP_CONTENT_RESOLVERS)) {
21756                if (mProviders.dump(pw, dumpState.getTitlePrinted() ? "\nProvider Resolver Table:"
21757                        : "Provider Resolver Table:", "  ", packageName,
21758                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
21759                    dumpState.setTitlePrinted(true);
21760                }
21761            }
21762
21763            if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED)) {
21764                for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
21765                    PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
21766                    int user = mSettings.mPreferredActivities.keyAt(i);
21767                    if (pir.dump(pw,
21768                            dumpState.getTitlePrinted()
21769                                ? "\nPreferred Activities User " + user + ":"
21770                                : "Preferred Activities User " + user + ":", "  ",
21771                            packageName, true, false)) {
21772                        dumpState.setTitlePrinted(true);
21773                    }
21774                }
21775            }
21776
21777            if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED_XML)) {
21778                pw.flush();
21779                FileOutputStream fout = new FileOutputStream(fd);
21780                BufferedOutputStream str = new BufferedOutputStream(fout);
21781                XmlSerializer serializer = new FastXmlSerializer();
21782                try {
21783                    serializer.setOutput(str, StandardCharsets.UTF_8.name());
21784                    serializer.startDocument(null, true);
21785                    serializer.setFeature(
21786                            "http://xmlpull.org/v1/doc/features.html#indent-output", true);
21787                    mSettings.writePreferredActivitiesLPr(serializer, 0, fullPreferred);
21788                    serializer.endDocument();
21789                    serializer.flush();
21790                } catch (IllegalArgumentException e) {
21791                    pw.println("Failed writing: " + e);
21792                } catch (IllegalStateException e) {
21793                    pw.println("Failed writing: " + e);
21794                } catch (IOException e) {
21795                    pw.println("Failed writing: " + e);
21796                }
21797            }
21798
21799            if (!checkin
21800                    && dumpState.isDumping(DumpState.DUMP_DOMAIN_PREFERRED)
21801                    && packageName == null) {
21802                pw.println();
21803                int count = mSettings.mPackages.size();
21804                if (count == 0) {
21805                    pw.println("No applications!");
21806                    pw.println();
21807                } else {
21808                    final String prefix = "  ";
21809                    Collection<PackageSetting> allPackageSettings = mSettings.mPackages.values();
21810                    if (allPackageSettings.size() == 0) {
21811                        pw.println("No domain preferred apps!");
21812                        pw.println();
21813                    } else {
21814                        pw.println("App verification status:");
21815                        pw.println();
21816                        count = 0;
21817                        for (PackageSetting ps : allPackageSettings) {
21818                            IntentFilterVerificationInfo ivi = ps.getIntentFilterVerificationInfo();
21819                            if (ivi == null || ivi.getPackageName() == null) continue;
21820                            pw.println(prefix + "Package: " + ivi.getPackageName());
21821                            pw.println(prefix + "Domains: " + ivi.getDomainsString());
21822                            pw.println(prefix + "Status:  " + ivi.getStatusString());
21823                            pw.println();
21824                            count++;
21825                        }
21826                        if (count == 0) {
21827                            pw.println(prefix + "No app verification established.");
21828                            pw.println();
21829                        }
21830                        for (int userId : sUserManager.getUserIds()) {
21831                            pw.println("App linkages for user " + userId + ":");
21832                            pw.println();
21833                            count = 0;
21834                            for (PackageSetting ps : allPackageSettings) {
21835                                final long status = ps.getDomainVerificationStatusForUser(userId);
21836                                if (status >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED
21837                                        && !DEBUG_DOMAIN_VERIFICATION) {
21838                                    continue;
21839                                }
21840                                pw.println(prefix + "Package: " + ps.name);
21841                                pw.println(prefix + "Domains: " + dumpDomainString(ps.name));
21842                                String statusStr = IntentFilterVerificationInfo.
21843                                        getStatusStringFromValue(status);
21844                                pw.println(prefix + "Status:  " + statusStr);
21845                                pw.println();
21846                                count++;
21847                            }
21848                            if (count == 0) {
21849                                pw.println(prefix + "No configured app linkages.");
21850                                pw.println();
21851                            }
21852                        }
21853                    }
21854                }
21855            }
21856
21857            if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS)) {
21858                mSettings.dumpPermissionsLPr(pw, packageName, permissionNames, dumpState);
21859                if (packageName == null && permissionNames == null) {
21860                    for (int iperm=0; iperm<mAppOpPermissionPackages.size(); iperm++) {
21861                        if (iperm == 0) {
21862                            if (dumpState.onTitlePrinted())
21863                                pw.println();
21864                            pw.println("AppOp Permissions:");
21865                        }
21866                        pw.print("  AppOp Permission ");
21867                        pw.print(mAppOpPermissionPackages.keyAt(iperm));
21868                        pw.println(":");
21869                        ArraySet<String> pkgs = mAppOpPermissionPackages.valueAt(iperm);
21870                        for (int ipkg=0; ipkg<pkgs.size(); ipkg++) {
21871                            pw.print("    "); pw.println(pkgs.valueAt(ipkg));
21872                        }
21873                    }
21874                }
21875            }
21876
21877            if (!checkin && dumpState.isDumping(DumpState.DUMP_PROVIDERS)) {
21878                boolean printedSomething = false;
21879                for (PackageParser.Provider p : mProviders.mProviders.values()) {
21880                    if (packageName != null && !packageName.equals(p.info.packageName)) {
21881                        continue;
21882                    }
21883                    if (!printedSomething) {
21884                        if (dumpState.onTitlePrinted())
21885                            pw.println();
21886                        pw.println("Registered ContentProviders:");
21887                        printedSomething = true;
21888                    }
21889                    pw.print("  "); p.printComponentShortName(pw); pw.println(":");
21890                    pw.print("    "); pw.println(p.toString());
21891                }
21892                printedSomething = false;
21893                for (Map.Entry<String, PackageParser.Provider> entry :
21894                        mProvidersByAuthority.entrySet()) {
21895                    PackageParser.Provider p = entry.getValue();
21896                    if (packageName != null && !packageName.equals(p.info.packageName)) {
21897                        continue;
21898                    }
21899                    if (!printedSomething) {
21900                        if (dumpState.onTitlePrinted())
21901                            pw.println();
21902                        pw.println("ContentProvider Authorities:");
21903                        printedSomething = true;
21904                    }
21905                    pw.print("  ["); pw.print(entry.getKey()); pw.println("]:");
21906                    pw.print("    "); pw.println(p.toString());
21907                    if (p.info != null && p.info.applicationInfo != null) {
21908                        final String appInfo = p.info.applicationInfo.toString();
21909                        pw.print("      applicationInfo="); pw.println(appInfo);
21910                    }
21911                }
21912            }
21913
21914            if (!checkin && dumpState.isDumping(DumpState.DUMP_KEYSETS)) {
21915                mSettings.mKeySetManagerService.dumpLPr(pw, packageName, dumpState);
21916            }
21917
21918            if (dumpState.isDumping(DumpState.DUMP_PACKAGES)) {
21919                mSettings.dumpPackagesLPr(pw, packageName, permissionNames, dumpState, checkin);
21920            }
21921
21922            if (dumpState.isDumping(DumpState.DUMP_SHARED_USERS)) {
21923                mSettings.dumpSharedUsersLPr(pw, packageName, permissionNames, dumpState, checkin);
21924            }
21925
21926            if (dumpState.isDumping(DumpState.DUMP_CHANGES)) {
21927                if (dumpState.onTitlePrinted()) pw.println();
21928                pw.println("Package Changes:");
21929                pw.print("  Sequence number="); pw.println(mChangedPackagesSequenceNumber);
21930                final int K = mChangedPackages.size();
21931                for (int i = 0; i < K; i++) {
21932                    final SparseArray<String> changes = mChangedPackages.valueAt(i);
21933                    pw.print("  User "); pw.print(mChangedPackages.keyAt(i)); pw.println(":");
21934                    final int N = changes.size();
21935                    if (N == 0) {
21936                        pw.print("    "); pw.println("No packages changed");
21937                    } else {
21938                        for (int j = 0; j < N; j++) {
21939                            final String pkgName = changes.valueAt(j);
21940                            final int sequenceNumber = changes.keyAt(j);
21941                            pw.print("    ");
21942                            pw.print("seq=");
21943                            pw.print(sequenceNumber);
21944                            pw.print(", package=");
21945                            pw.println(pkgName);
21946                        }
21947                    }
21948                }
21949            }
21950
21951            if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS) && packageName == null) {
21952                mSettings.dumpRestoredPermissionGrantsLPr(pw, dumpState);
21953            }
21954
21955            if (!checkin && dumpState.isDumping(DumpState.DUMP_FROZEN) && packageName == null) {
21956                // XXX should handle packageName != null by dumping only install data that
21957                // the given package is involved with.
21958                if (dumpState.onTitlePrinted()) pw.println();
21959
21960                final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, "  ", 120);
21961                ipw.println();
21962                ipw.println("Frozen packages:");
21963                ipw.increaseIndent();
21964                if (mFrozenPackages.size() == 0) {
21965                    ipw.println("(none)");
21966                } else {
21967                    for (int i = 0; i < mFrozenPackages.size(); i++) {
21968                        ipw.println(mFrozenPackages.valueAt(i));
21969                    }
21970                }
21971                ipw.decreaseIndent();
21972            }
21973
21974            if (!checkin && dumpState.isDumping(DumpState.DUMP_DEXOPT)) {
21975                if (dumpState.onTitlePrinted()) pw.println();
21976                dumpDexoptStateLPr(pw, packageName);
21977            }
21978
21979            if (!checkin && dumpState.isDumping(DumpState.DUMP_COMPILER_STATS)) {
21980                if (dumpState.onTitlePrinted()) pw.println();
21981                dumpCompilerStatsLPr(pw, packageName);
21982            }
21983
21984            if (!checkin && dumpState.isDumping(DumpState.DUMP_ENABLED_OVERLAYS)) {
21985                if (dumpState.onTitlePrinted()) pw.println();
21986                dumpEnabledOverlaysLPr(pw);
21987            }
21988
21989            if (!checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES) && packageName == null) {
21990                if (dumpState.onTitlePrinted()) pw.println();
21991                mSettings.dumpReadMessagesLPr(pw, dumpState);
21992
21993                pw.println();
21994                pw.println("Package warning messages:");
21995                BufferedReader in = null;
21996                String line = null;
21997                try {
21998                    in = new BufferedReader(new FileReader(getSettingsProblemFile()));
21999                    while ((line = in.readLine()) != null) {
22000                        if (line.contains("ignored: updated version")) continue;
22001                        pw.println(line);
22002                    }
22003                } catch (IOException ignored) {
22004                } finally {
22005                    IoUtils.closeQuietly(in);
22006                }
22007            }
22008
22009            if (checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES)) {
22010                BufferedReader in = null;
22011                String line = null;
22012                try {
22013                    in = new BufferedReader(new FileReader(getSettingsProblemFile()));
22014                    while ((line = in.readLine()) != null) {
22015                        if (line.contains("ignored: updated version")) continue;
22016                        pw.print("msg,");
22017                        pw.println(line);
22018                    }
22019                } catch (IOException ignored) {
22020                } finally {
22021                    IoUtils.closeQuietly(in);
22022                }
22023            }
22024        }
22025
22026        // PackageInstaller should be called outside of mPackages lock
22027        if (!checkin && dumpState.isDumping(DumpState.DUMP_INSTALLS) && packageName == null) {
22028            // XXX should handle packageName != null by dumping only install data that
22029            // the given package is involved with.
22030            if (dumpState.onTitlePrinted()) pw.println();
22031            mInstallerService.dump(new IndentingPrintWriter(pw, "  ", 120));
22032        }
22033    }
22034
22035    private void dumpProto(FileDescriptor fd) {
22036        final ProtoOutputStream proto = new ProtoOutputStream(fd);
22037
22038        synchronized (mPackages) {
22039            final long requiredVerifierPackageToken =
22040                    proto.start(PackageServiceDumpProto.REQUIRED_VERIFIER_PACKAGE);
22041            proto.write(PackageServiceDumpProto.PackageShortProto.NAME, mRequiredVerifierPackage);
22042            proto.write(
22043                    PackageServiceDumpProto.PackageShortProto.UID,
22044                    getPackageUid(
22045                            mRequiredVerifierPackage,
22046                            MATCH_DEBUG_TRIAGED_MISSING,
22047                            UserHandle.USER_SYSTEM));
22048            proto.end(requiredVerifierPackageToken);
22049
22050            if (mIntentFilterVerifierComponent != null) {
22051                String verifierPackageName = mIntentFilterVerifierComponent.getPackageName();
22052                final long verifierPackageToken =
22053                        proto.start(PackageServiceDumpProto.VERIFIER_PACKAGE);
22054                proto.write(PackageServiceDumpProto.PackageShortProto.NAME, verifierPackageName);
22055                proto.write(
22056                        PackageServiceDumpProto.PackageShortProto.UID,
22057                        getPackageUid(
22058                                verifierPackageName,
22059                                MATCH_DEBUG_TRIAGED_MISSING,
22060                                UserHandle.USER_SYSTEM));
22061                proto.end(verifierPackageToken);
22062            }
22063
22064            dumpSharedLibrariesProto(proto);
22065            dumpFeaturesProto(proto);
22066            mSettings.dumpPackagesProto(proto);
22067            mSettings.dumpSharedUsersProto(proto);
22068            dumpMessagesProto(proto);
22069        }
22070        proto.flush();
22071    }
22072
22073    private void dumpMessagesProto(ProtoOutputStream proto) {
22074        BufferedReader in = null;
22075        String line = null;
22076        try {
22077            in = new BufferedReader(new FileReader(getSettingsProblemFile()));
22078            while ((line = in.readLine()) != null) {
22079                if (line.contains("ignored: updated version")) continue;
22080                proto.write(PackageServiceDumpProto.MESSAGES, line);
22081            }
22082        } catch (IOException ignored) {
22083        } finally {
22084            IoUtils.closeQuietly(in);
22085        }
22086    }
22087
22088    private void dumpFeaturesProto(ProtoOutputStream proto) {
22089        synchronized (mAvailableFeatures) {
22090            final int count = mAvailableFeatures.size();
22091            for (int i = 0; i < count; i++) {
22092                final FeatureInfo feat = mAvailableFeatures.valueAt(i);
22093                final long featureToken = proto.start(PackageServiceDumpProto.FEATURES);
22094                proto.write(PackageServiceDumpProto.FeatureProto.NAME, feat.name);
22095                proto.write(PackageServiceDumpProto.FeatureProto.VERSION, feat.version);
22096                proto.end(featureToken);
22097            }
22098        }
22099    }
22100
22101    private void dumpSharedLibrariesProto(ProtoOutputStream proto) {
22102        final int count = mSharedLibraries.size();
22103        for (int i = 0; i < count; i++) {
22104            final String libName = mSharedLibraries.keyAt(i);
22105            SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(libName);
22106            if (versionedLib == null) {
22107                continue;
22108            }
22109            final int versionCount = versionedLib.size();
22110            for (int j = 0; j < versionCount; j++) {
22111                final SharedLibraryEntry libEntry = versionedLib.valueAt(j);
22112                final long sharedLibraryToken =
22113                        proto.start(PackageServiceDumpProto.SHARED_LIBRARIES);
22114                proto.write(PackageServiceDumpProto.SharedLibraryProto.NAME, libEntry.info.getName());
22115                final boolean isJar = (libEntry.path != null);
22116                proto.write(PackageServiceDumpProto.SharedLibraryProto.IS_JAR, isJar);
22117                if (isJar) {
22118                    proto.write(PackageServiceDumpProto.SharedLibraryProto.PATH, libEntry.path);
22119                } else {
22120                    proto.write(PackageServiceDumpProto.SharedLibraryProto.APK, libEntry.apk);
22121                }
22122                proto.end(sharedLibraryToken);
22123            }
22124        }
22125    }
22126
22127    private void dumpDexoptStateLPr(PrintWriter pw, String packageName) {
22128        final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, "  ", 120);
22129        ipw.println();
22130        ipw.println("Dexopt state:");
22131        ipw.increaseIndent();
22132        Collection<PackageParser.Package> packages = null;
22133        if (packageName != null) {
22134            PackageParser.Package targetPackage = mPackages.get(packageName);
22135            if (targetPackage != null) {
22136                packages = Collections.singletonList(targetPackage);
22137            } else {
22138                ipw.println("Unable to find package: " + packageName);
22139                return;
22140            }
22141        } else {
22142            packages = mPackages.values();
22143        }
22144
22145        for (PackageParser.Package pkg : packages) {
22146            ipw.println("[" + pkg.packageName + "]");
22147            ipw.increaseIndent();
22148            mPackageDexOptimizer.dumpDexoptState(ipw, pkg);
22149            ipw.decreaseIndent();
22150        }
22151    }
22152
22153    private void dumpCompilerStatsLPr(PrintWriter pw, String packageName) {
22154        final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, "  ", 120);
22155        ipw.println();
22156        ipw.println("Compiler stats:");
22157        ipw.increaseIndent();
22158        Collection<PackageParser.Package> packages = null;
22159        if (packageName != null) {
22160            PackageParser.Package targetPackage = mPackages.get(packageName);
22161            if (targetPackage != null) {
22162                packages = Collections.singletonList(targetPackage);
22163            } else {
22164                ipw.println("Unable to find package: " + packageName);
22165                return;
22166            }
22167        } else {
22168            packages = mPackages.values();
22169        }
22170
22171        for (PackageParser.Package pkg : packages) {
22172            ipw.println("[" + pkg.packageName + "]");
22173            ipw.increaseIndent();
22174
22175            CompilerStats.PackageStats stats = getCompilerPackageStats(pkg.packageName);
22176            if (stats == null) {
22177                ipw.println("(No recorded stats)");
22178            } else {
22179                stats.dump(ipw);
22180            }
22181            ipw.decreaseIndent();
22182        }
22183    }
22184
22185    private void dumpEnabledOverlaysLPr(PrintWriter pw) {
22186        pw.println("Enabled overlay paths:");
22187        final int N = mEnabledOverlayPaths.size();
22188        for (int i = 0; i < N; i++) {
22189            final int userId = mEnabledOverlayPaths.keyAt(i);
22190            pw.println(String.format("    User %d:", userId));
22191            final ArrayMap<String, ArrayList<String>> userSpecificOverlays =
22192                mEnabledOverlayPaths.valueAt(i);
22193            final int M = userSpecificOverlays.size();
22194            for (int j = 0; j < M; j++) {
22195                final String targetPackageName = userSpecificOverlays.keyAt(j);
22196                final ArrayList<String> overlayPackagePaths = userSpecificOverlays.valueAt(j);
22197                pw.println(String.format("        %s: %s", targetPackageName, overlayPackagePaths));
22198            }
22199        }
22200    }
22201
22202    private String dumpDomainString(String packageName) {
22203        List<IntentFilterVerificationInfo> iviList = getIntentFilterVerifications(packageName)
22204                .getList();
22205        List<IntentFilter> filters = getAllIntentFilters(packageName).getList();
22206
22207        ArraySet<String> result = new ArraySet<>();
22208        if (iviList.size() > 0) {
22209            for (IntentFilterVerificationInfo ivi : iviList) {
22210                for (String host : ivi.getDomains()) {
22211                    result.add(host);
22212                }
22213            }
22214        }
22215        if (filters != null && filters.size() > 0) {
22216            for (IntentFilter filter : filters) {
22217                if (filter.hasCategory(Intent.CATEGORY_BROWSABLE)
22218                        && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) ||
22219                                filter.hasDataScheme(IntentFilter.SCHEME_HTTPS))) {
22220                    result.addAll(filter.getHostsList());
22221                }
22222            }
22223        }
22224
22225        StringBuilder sb = new StringBuilder(result.size() * 16);
22226        for (String domain : result) {
22227            if (sb.length() > 0) sb.append(" ");
22228            sb.append(domain);
22229        }
22230        return sb.toString();
22231    }
22232
22233    // ------- apps on sdcard specific code -------
22234    static final boolean DEBUG_SD_INSTALL = false;
22235
22236    private static final String SD_ENCRYPTION_KEYSTORE_NAME = "AppsOnSD";
22237
22238    private static final String SD_ENCRYPTION_ALGORITHM = "AES";
22239
22240    private boolean mMediaMounted = false;
22241
22242    static String getEncryptKey() {
22243        try {
22244            String sdEncKey = SystemKeyStore.getInstance().retrieveKeyHexString(
22245                    SD_ENCRYPTION_KEYSTORE_NAME);
22246            if (sdEncKey == null) {
22247                sdEncKey = SystemKeyStore.getInstance().generateNewKeyHexString(128,
22248                        SD_ENCRYPTION_ALGORITHM, SD_ENCRYPTION_KEYSTORE_NAME);
22249                if (sdEncKey == null) {
22250                    Slog.e(TAG, "Failed to create encryption keys");
22251                    return null;
22252                }
22253            }
22254            return sdEncKey;
22255        } catch (NoSuchAlgorithmException nsae) {
22256            Slog.e(TAG, "Failed to create encryption keys with exception: " + nsae);
22257            return null;
22258        } catch (IOException ioe) {
22259            Slog.e(TAG, "Failed to retrieve encryption keys with exception: " + ioe);
22260            return null;
22261        }
22262    }
22263
22264    /*
22265     * Update media status on PackageManager.
22266     */
22267    @Override
22268    public void updateExternalMediaStatus(final boolean mediaStatus, final boolean reportStatus) {
22269        enforceSystemOrRoot("Media status can only be updated by the system");
22270        // reader; this apparently protects mMediaMounted, but should probably
22271        // be a different lock in that case.
22272        synchronized (mPackages) {
22273            Log.i(TAG, "Updating external media status from "
22274                    + (mMediaMounted ? "mounted" : "unmounted") + " to "
22275                    + (mediaStatus ? "mounted" : "unmounted"));
22276            if (DEBUG_SD_INSTALL)
22277                Log.i(TAG, "updateExternalMediaStatus:: mediaStatus=" + mediaStatus
22278                        + ", mMediaMounted=" + mMediaMounted);
22279            if (mediaStatus == mMediaMounted) {
22280                final Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1
22281                        : 0, -1);
22282                mHandler.sendMessage(msg);
22283                return;
22284            }
22285            mMediaMounted = mediaStatus;
22286        }
22287        // Queue up an async operation since the package installation may take a
22288        // little while.
22289        mHandler.post(new Runnable() {
22290            public void run() {
22291                updateExternalMediaStatusInner(mediaStatus, reportStatus, true);
22292            }
22293        });
22294    }
22295
22296    /**
22297     * Called by StorageManagerService when the initial ASECs to scan are available.
22298     * Should block until all the ASEC containers are finished being scanned.
22299     */
22300    public void scanAvailableAsecs() {
22301        updateExternalMediaStatusInner(true, false, false);
22302    }
22303
22304    /*
22305     * Collect information of applications on external media, map them against
22306     * existing containers and update information based on current mount status.
22307     * Please note that we always have to report status if reportStatus has been
22308     * set to true especially when unloading packages.
22309     */
22310    private void updateExternalMediaStatusInner(boolean isMounted, boolean reportStatus,
22311            boolean externalStorage) {
22312        ArrayMap<AsecInstallArgs, String> processCids = new ArrayMap<>();
22313        int[] uidArr = EmptyArray.INT;
22314
22315        final String[] list = PackageHelper.getSecureContainerList();
22316        if (ArrayUtils.isEmpty(list)) {
22317            Log.i(TAG, "No secure containers found");
22318        } else {
22319            // Process list of secure containers and categorize them
22320            // as active or stale based on their package internal state.
22321
22322            // reader
22323            synchronized (mPackages) {
22324                for (String cid : list) {
22325                    // Leave stages untouched for now; installer service owns them
22326                    if (PackageInstallerService.isStageName(cid)) continue;
22327
22328                    if (DEBUG_SD_INSTALL)
22329                        Log.i(TAG, "Processing container " + cid);
22330                    String pkgName = getAsecPackageName(cid);
22331                    if (pkgName == null) {
22332                        Slog.i(TAG, "Found stale container " + cid + " with no package name");
22333                        continue;
22334                    }
22335                    if (DEBUG_SD_INSTALL)
22336                        Log.i(TAG, "Looking for pkg : " + pkgName);
22337
22338                    final PackageSetting ps = mSettings.mPackages.get(pkgName);
22339                    if (ps == null) {
22340                        Slog.i(TAG, "Found stale container " + cid + " with no matching settings");
22341                        continue;
22342                    }
22343
22344                    /*
22345                     * Skip packages that are not external if we're unmounting
22346                     * external storage.
22347                     */
22348                    if (externalStorage && !isMounted && !isExternal(ps)) {
22349                        continue;
22350                    }
22351
22352                    final AsecInstallArgs args = new AsecInstallArgs(cid,
22353                            getAppDexInstructionSets(ps), ps.isForwardLocked());
22354                    // The package status is changed only if the code path
22355                    // matches between settings and the container id.
22356                    if (ps.codePathString != null
22357                            && ps.codePathString.startsWith(args.getCodePath())) {
22358                        if (DEBUG_SD_INSTALL) {
22359                            Log.i(TAG, "Container : " + cid + " corresponds to pkg : " + pkgName
22360                                    + " at code path: " + ps.codePathString);
22361                        }
22362
22363                        // We do have a valid package installed on sdcard
22364                        processCids.put(args, ps.codePathString);
22365                        final int uid = ps.appId;
22366                        if (uid != -1) {
22367                            uidArr = ArrayUtils.appendInt(uidArr, uid);
22368                        }
22369                    } else {
22370                        Slog.i(TAG, "Found stale container " + cid + ": expected codePath="
22371                                + ps.codePathString);
22372                    }
22373                }
22374            }
22375
22376            Arrays.sort(uidArr);
22377        }
22378
22379        // Process packages with valid entries.
22380        if (isMounted) {
22381            if (DEBUG_SD_INSTALL)
22382                Log.i(TAG, "Loading packages");
22383            loadMediaPackages(processCids, uidArr, externalStorage);
22384            startCleaningPackages();
22385            mInstallerService.onSecureContainersAvailable();
22386        } else {
22387            if (DEBUG_SD_INSTALL)
22388                Log.i(TAG, "Unloading packages");
22389            unloadMediaPackages(processCids, uidArr, reportStatus);
22390        }
22391    }
22392
22393    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
22394            ArrayList<ApplicationInfo> infos, IIntentReceiver finishedReceiver) {
22395        final int size = infos.size();
22396        final String[] packageNames = new String[size];
22397        final int[] packageUids = new int[size];
22398        for (int i = 0; i < size; i++) {
22399            final ApplicationInfo info = infos.get(i);
22400            packageNames[i] = info.packageName;
22401            packageUids[i] = info.uid;
22402        }
22403        sendResourcesChangedBroadcast(mediaStatus, replacing, packageNames, packageUids,
22404                finishedReceiver);
22405    }
22406
22407    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
22408            ArrayList<String> pkgList, int uidArr[], IIntentReceiver finishedReceiver) {
22409        sendResourcesChangedBroadcast(mediaStatus, replacing,
22410                pkgList.toArray(new String[pkgList.size()]), uidArr, finishedReceiver);
22411    }
22412
22413    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
22414            String[] pkgList, int uidArr[], IIntentReceiver finishedReceiver) {
22415        int size = pkgList.length;
22416        if (size > 0) {
22417            // Send broadcasts here
22418            Bundle extras = new Bundle();
22419            extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList);
22420            if (uidArr != null) {
22421                extras.putIntArray(Intent.EXTRA_CHANGED_UID_LIST, uidArr);
22422            }
22423            if (replacing) {
22424                extras.putBoolean(Intent.EXTRA_REPLACING, replacing);
22425            }
22426            String action = mediaStatus ? Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE
22427                    : Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE;
22428            sendPackageBroadcast(action, null, extras, 0, null, finishedReceiver, null);
22429        }
22430    }
22431
22432   /*
22433     * Look at potentially valid container ids from processCids If package
22434     * information doesn't match the one on record or package scanning fails,
22435     * the cid is added to list of removeCids. We currently don't delete stale
22436     * containers.
22437     */
22438    private void loadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int[] uidArr,
22439            boolean externalStorage) {
22440        ArrayList<String> pkgList = new ArrayList<String>();
22441        Set<AsecInstallArgs> keys = processCids.keySet();
22442
22443        for (AsecInstallArgs args : keys) {
22444            String codePath = processCids.get(args);
22445            if (DEBUG_SD_INSTALL)
22446                Log.i(TAG, "Loading container : " + args.cid);
22447            int retCode = PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
22448            try {
22449                // Make sure there are no container errors first.
22450                if (args.doPreInstall(PackageManager.INSTALL_SUCCEEDED) != PackageManager.INSTALL_SUCCEEDED) {
22451                    Slog.e(TAG, "Failed to mount cid : " + args.cid
22452                            + " when installing from sdcard");
22453                    continue;
22454                }
22455                // Check code path here.
22456                if (codePath == null || !codePath.startsWith(args.getCodePath())) {
22457                    Slog.e(TAG, "Container " + args.cid + " cachepath " + args.getCodePath()
22458                            + " does not match one in settings " + codePath);
22459                    continue;
22460                }
22461                // Parse package
22462                int parseFlags = mDefParseFlags;
22463                if (args.isExternalAsec()) {
22464                    parseFlags |= PackageParser.PARSE_EXTERNAL_STORAGE;
22465                }
22466                if (args.isFwdLocked()) {
22467                    parseFlags |= PackageParser.PARSE_FORWARD_LOCK;
22468                }
22469
22470                synchronized (mInstallLock) {
22471                    PackageParser.Package pkg = null;
22472                    try {
22473                        // Sadly we don't know the package name yet to freeze it
22474                        pkg = scanPackageTracedLI(new File(codePath), parseFlags,
22475                                SCAN_IGNORE_FROZEN, 0, null);
22476                    } catch (PackageManagerException e) {
22477                        Slog.w(TAG, "Failed to scan " + codePath + ": " + e.getMessage());
22478                    }
22479                    // Scan the package
22480                    if (pkg != null) {
22481                        /*
22482                         * TODO why is the lock being held? doPostInstall is
22483                         * called in other places without the lock. This needs
22484                         * to be straightened out.
22485                         */
22486                        // writer
22487                        synchronized (mPackages) {
22488                            retCode = PackageManager.INSTALL_SUCCEEDED;
22489                            pkgList.add(pkg.packageName);
22490                            // Post process args
22491                            args.doPostInstall(PackageManager.INSTALL_SUCCEEDED,
22492                                    pkg.applicationInfo.uid);
22493                        }
22494                    } else {
22495                        Slog.i(TAG, "Failed to install pkg from  " + codePath + " from sdcard");
22496                    }
22497                }
22498
22499            } finally {
22500                if (retCode != PackageManager.INSTALL_SUCCEEDED) {
22501                    Log.w(TAG, "Container " + args.cid + " is stale, retCode=" + retCode);
22502                }
22503            }
22504        }
22505        // writer
22506        synchronized (mPackages) {
22507            // If the platform SDK has changed since the last time we booted,
22508            // we need to re-grant app permission to catch any new ones that
22509            // appear. This is really a hack, and means that apps can in some
22510            // cases get permissions that the user didn't initially explicitly
22511            // allow... it would be nice to have some better way to handle
22512            // this situation.
22513            final VersionInfo ver = externalStorage ? mSettings.getExternalVersion()
22514                    : mSettings.getInternalVersion();
22515            final String volumeUuid = externalStorage ? StorageManager.UUID_PRIMARY_PHYSICAL
22516                    : StorageManager.UUID_PRIVATE_INTERNAL;
22517
22518            int updateFlags = UPDATE_PERMISSIONS_ALL;
22519            if (ver.sdkVersion != mSdkVersion) {
22520                logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to "
22521                        + mSdkVersion + "; regranting permissions for external");
22522                updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL;
22523            }
22524            updatePermissionsLPw(null, null, volumeUuid, updateFlags);
22525
22526            // Yay, everything is now upgraded
22527            ver.forceCurrent();
22528
22529            // can downgrade to reader
22530            // Persist settings
22531            mSettings.writeLPr();
22532        }
22533        // Send a broadcast to let everyone know we are done processing
22534        if (pkgList.size() > 0) {
22535            sendResourcesChangedBroadcast(true, false, pkgList, uidArr, null);
22536        }
22537    }
22538
22539   /*
22540     * Utility method to unload a list of specified containers
22541     */
22542    private void unloadAllContainers(Set<AsecInstallArgs> cidArgs) {
22543        // Just unmount all valid containers.
22544        for (AsecInstallArgs arg : cidArgs) {
22545            synchronized (mInstallLock) {
22546                arg.doPostDeleteLI(false);
22547           }
22548       }
22549   }
22550
22551    /*
22552     * Unload packages mounted on external media. This involves deleting package
22553     * data from internal structures, sending broadcasts about disabled packages,
22554     * gc'ing to free up references, unmounting all secure containers
22555     * corresponding to packages on external media, and posting a
22556     * UPDATED_MEDIA_STATUS message if status has been requested. Please note
22557     * that we always have to post this message if status has been requested no
22558     * matter what.
22559     */
22560    private void unloadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int uidArr[],
22561            final boolean reportStatus) {
22562        if (DEBUG_SD_INSTALL)
22563            Log.i(TAG, "unloading media packages");
22564        ArrayList<String> pkgList = new ArrayList<String>();
22565        ArrayList<AsecInstallArgs> failedList = new ArrayList<AsecInstallArgs>();
22566        final Set<AsecInstallArgs> keys = processCids.keySet();
22567        for (AsecInstallArgs args : keys) {
22568            String pkgName = args.getPackageName();
22569            if (DEBUG_SD_INSTALL)
22570                Log.i(TAG, "Trying to unload pkg : " + pkgName);
22571            // Delete package internally
22572            PackageRemovedInfo outInfo = new PackageRemovedInfo(this);
22573            synchronized (mInstallLock) {
22574                final int deleteFlags = PackageManager.DELETE_KEEP_DATA;
22575                final boolean res;
22576                try (PackageFreezer freezer = freezePackageForDelete(pkgName, deleteFlags,
22577                        "unloadMediaPackages")) {
22578                    res = deletePackageLIF(pkgName, null, false, null, deleteFlags, outInfo, false,
22579                            null);
22580                }
22581                if (res) {
22582                    pkgList.add(pkgName);
22583                } else {
22584                    Slog.e(TAG, "Failed to delete pkg from sdcard : " + pkgName);
22585                    failedList.add(args);
22586                }
22587            }
22588        }
22589
22590        // reader
22591        synchronized (mPackages) {
22592            // We didn't update the settings after removing each package;
22593            // write them now for all packages.
22594            mSettings.writeLPr();
22595        }
22596
22597        // We have to absolutely send UPDATED_MEDIA_STATUS only
22598        // after confirming that all the receivers processed the ordered
22599        // broadcast when packages get disabled, force a gc to clean things up.
22600        // and unload all the containers.
22601        if (pkgList.size() > 0) {
22602            sendResourcesChangedBroadcast(false, false, pkgList, uidArr,
22603                    new IIntentReceiver.Stub() {
22604                public void performReceive(Intent intent, int resultCode, String data,
22605                        Bundle extras, boolean ordered, boolean sticky,
22606                        int sendingUser) throws RemoteException {
22607                    Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS,
22608                            reportStatus ? 1 : 0, 1, keys);
22609                    mHandler.sendMessage(msg);
22610                }
22611            });
22612        } else {
22613            Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 : 0, -1,
22614                    keys);
22615            mHandler.sendMessage(msg);
22616        }
22617    }
22618
22619    private void loadPrivatePackages(final VolumeInfo vol) {
22620        mHandler.post(new Runnable() {
22621            @Override
22622            public void run() {
22623                loadPrivatePackagesInner(vol);
22624            }
22625        });
22626    }
22627
22628    private void loadPrivatePackagesInner(VolumeInfo vol) {
22629        final String volumeUuid = vol.fsUuid;
22630        if (TextUtils.isEmpty(volumeUuid)) {
22631            Slog.e(TAG, "Loading internal storage is probably a mistake; ignoring");
22632            return;
22633        }
22634
22635        final ArrayList<PackageFreezer> freezers = new ArrayList<>();
22636        final ArrayList<ApplicationInfo> loaded = new ArrayList<>();
22637        final int parseFlags = mDefParseFlags | PackageParser.PARSE_EXTERNAL_STORAGE;
22638
22639        final VersionInfo ver;
22640        final List<PackageSetting> packages;
22641        synchronized (mPackages) {
22642            ver = mSettings.findOrCreateVersion(volumeUuid);
22643            packages = mSettings.getVolumePackagesLPr(volumeUuid);
22644        }
22645
22646        for (PackageSetting ps : packages) {
22647            freezers.add(freezePackage(ps.name, "loadPrivatePackagesInner"));
22648            synchronized (mInstallLock) {
22649                final PackageParser.Package pkg;
22650                try {
22651                    pkg = scanPackageTracedLI(ps.codePath, parseFlags, SCAN_INITIAL, 0, null);
22652                    loaded.add(pkg.applicationInfo);
22653
22654                } catch (PackageManagerException e) {
22655                    Slog.w(TAG, "Failed to scan " + ps.codePath + ": " + e.getMessage());
22656                }
22657
22658                if (!Build.FINGERPRINT.equals(ver.fingerprint)) {
22659                    clearAppDataLIF(ps.pkg, UserHandle.USER_ALL,
22660                            StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE
22661                                    | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
22662                }
22663            }
22664        }
22665
22666        // Reconcile app data for all started/unlocked users
22667        final StorageManager sm = mContext.getSystemService(StorageManager.class);
22668        final UserManager um = mContext.getSystemService(UserManager.class);
22669        UserManagerInternal umInternal = getUserManagerInternal();
22670        for (UserInfo user : um.getUsers()) {
22671            final int flags;
22672            if (umInternal.isUserUnlockingOrUnlocked(user.id)) {
22673                flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
22674            } else if (umInternal.isUserRunning(user.id)) {
22675                flags = StorageManager.FLAG_STORAGE_DE;
22676            } else {
22677                continue;
22678            }
22679
22680            try {
22681                sm.prepareUserStorage(volumeUuid, user.id, user.serialNumber, flags);
22682                synchronized (mInstallLock) {
22683                    reconcileAppsDataLI(volumeUuid, user.id, flags, true /* migrateAppData */);
22684                }
22685            } catch (IllegalStateException e) {
22686                // Device was probably ejected, and we'll process that event momentarily
22687                Slog.w(TAG, "Failed to prepare storage: " + e);
22688            }
22689        }
22690
22691        synchronized (mPackages) {
22692            int updateFlags = UPDATE_PERMISSIONS_ALL;
22693            if (ver.sdkVersion != mSdkVersion) {
22694                logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to "
22695                        + mSdkVersion + "; regranting permissions for " + volumeUuid);
22696                updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL;
22697            }
22698            updatePermissionsLPw(null, null, volumeUuid, updateFlags);
22699
22700            // Yay, everything is now upgraded
22701            ver.forceCurrent();
22702
22703            mSettings.writeLPr();
22704        }
22705
22706        for (PackageFreezer freezer : freezers) {
22707            freezer.close();
22708        }
22709
22710        if (DEBUG_INSTALL) Slog.d(TAG, "Loaded packages " + loaded);
22711        sendResourcesChangedBroadcast(true, false, loaded, null);
22712    }
22713
22714    private void unloadPrivatePackages(final VolumeInfo vol) {
22715        mHandler.post(new Runnable() {
22716            @Override
22717            public void run() {
22718                unloadPrivatePackagesInner(vol);
22719            }
22720        });
22721    }
22722
22723    private void unloadPrivatePackagesInner(VolumeInfo vol) {
22724        final String volumeUuid = vol.fsUuid;
22725        if (TextUtils.isEmpty(volumeUuid)) {
22726            Slog.e(TAG, "Unloading internal storage is probably a mistake; ignoring");
22727            return;
22728        }
22729
22730        final ArrayList<ApplicationInfo> unloaded = new ArrayList<>();
22731        synchronized (mInstallLock) {
22732        synchronized (mPackages) {
22733            final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(volumeUuid);
22734            for (PackageSetting ps : packages) {
22735                if (ps.pkg == null) continue;
22736
22737                final ApplicationInfo info = ps.pkg.applicationInfo;
22738                final int deleteFlags = PackageManager.DELETE_KEEP_DATA;
22739                final PackageRemovedInfo outInfo = new PackageRemovedInfo(this);
22740
22741                try (PackageFreezer freezer = freezePackageForDelete(ps.name, deleteFlags,
22742                        "unloadPrivatePackagesInner")) {
22743                    if (deletePackageLIF(ps.name, null, false, null, deleteFlags, outInfo,
22744                            false, null)) {
22745                        unloaded.add(info);
22746                    } else {
22747                        Slog.w(TAG, "Failed to unload " + ps.codePath);
22748                    }
22749                }
22750
22751                // Try very hard to release any references to this package
22752                // so we don't risk the system server being killed due to
22753                // open FDs
22754                AttributeCache.instance().removePackage(ps.name);
22755            }
22756
22757            mSettings.writeLPr();
22758        }
22759        }
22760
22761        if (DEBUG_INSTALL) Slog.d(TAG, "Unloaded packages " + unloaded);
22762        sendResourcesChangedBroadcast(false, false, unloaded, null);
22763
22764        // Try very hard to release any references to this path so we don't risk
22765        // the system server being killed due to open FDs
22766        ResourcesManager.getInstance().invalidatePath(vol.getPath().getAbsolutePath());
22767
22768        for (int i = 0; i < 3; i++) {
22769            System.gc();
22770            System.runFinalization();
22771        }
22772    }
22773
22774    private void assertPackageKnown(String volumeUuid, String packageName)
22775            throws PackageManagerException {
22776        synchronized (mPackages) {
22777            // Normalize package name to handle renamed packages
22778            packageName = normalizePackageNameLPr(packageName);
22779
22780            final PackageSetting ps = mSettings.mPackages.get(packageName);
22781            if (ps == null) {
22782                throw new PackageManagerException("Package " + packageName + " is unknown");
22783            } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) {
22784                throw new PackageManagerException(
22785                        "Package " + packageName + " found on unknown volume " + volumeUuid
22786                                + "; expected volume " + ps.volumeUuid);
22787            }
22788        }
22789    }
22790
22791    private void assertPackageKnownAndInstalled(String volumeUuid, String packageName, int userId)
22792            throws PackageManagerException {
22793        synchronized (mPackages) {
22794            // Normalize package name to handle renamed packages
22795            packageName = normalizePackageNameLPr(packageName);
22796
22797            final PackageSetting ps = mSettings.mPackages.get(packageName);
22798            if (ps == null) {
22799                throw new PackageManagerException("Package " + packageName + " is unknown");
22800            } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) {
22801                throw new PackageManagerException(
22802                        "Package " + packageName + " found on unknown volume " + volumeUuid
22803                                + "; expected volume " + ps.volumeUuid);
22804            } else if (!ps.getInstalled(userId)) {
22805                throw new PackageManagerException(
22806                        "Package " + packageName + " not installed for user " + userId);
22807            }
22808        }
22809    }
22810
22811    private List<String> collectAbsoluteCodePaths() {
22812        synchronized (mPackages) {
22813            List<String> codePaths = new ArrayList<>();
22814            final int packageCount = mSettings.mPackages.size();
22815            for (int i = 0; i < packageCount; i++) {
22816                final PackageSetting ps = mSettings.mPackages.valueAt(i);
22817                codePaths.add(ps.codePath.getAbsolutePath());
22818            }
22819            return codePaths;
22820        }
22821    }
22822
22823    /**
22824     * Examine all apps present on given mounted volume, and destroy apps that
22825     * aren't expected, either due to uninstallation or reinstallation on
22826     * another volume.
22827     */
22828    private void reconcileApps(String volumeUuid) {
22829        List<String> absoluteCodePaths = collectAbsoluteCodePaths();
22830        List<File> filesToDelete = null;
22831
22832        final File[] files = FileUtils.listFilesOrEmpty(
22833                Environment.getDataAppDirectory(volumeUuid));
22834        for (File file : files) {
22835            final boolean isPackage = (isApkFile(file) || file.isDirectory())
22836                    && !PackageInstallerService.isStageName(file.getName());
22837            if (!isPackage) {
22838                // Ignore entries which are not packages
22839                continue;
22840            }
22841
22842            String absolutePath = file.getAbsolutePath();
22843
22844            boolean pathValid = false;
22845            final int absoluteCodePathCount = absoluteCodePaths.size();
22846            for (int i = 0; i < absoluteCodePathCount; i++) {
22847                String absoluteCodePath = absoluteCodePaths.get(i);
22848                if (absolutePath.startsWith(absoluteCodePath)) {
22849                    pathValid = true;
22850                    break;
22851                }
22852            }
22853
22854            if (!pathValid) {
22855                if (filesToDelete == null) {
22856                    filesToDelete = new ArrayList<>();
22857                }
22858                filesToDelete.add(file);
22859            }
22860        }
22861
22862        if (filesToDelete != null) {
22863            final int fileToDeleteCount = filesToDelete.size();
22864            for (int i = 0; i < fileToDeleteCount; i++) {
22865                File fileToDelete = filesToDelete.get(i);
22866                logCriticalInfo(Log.WARN, "Destroying orphaned" + fileToDelete);
22867                synchronized (mInstallLock) {
22868                    removeCodePathLI(fileToDelete);
22869                }
22870            }
22871        }
22872    }
22873
22874    /**
22875     * Reconcile all app data for the given user.
22876     * <p>
22877     * Verifies that directories exist and that ownership and labeling is
22878     * correct for all installed apps on all mounted volumes.
22879     */
22880    void reconcileAppsData(int userId, int flags, boolean migrateAppsData) {
22881        final StorageManager storage = mContext.getSystemService(StorageManager.class);
22882        for (VolumeInfo vol : storage.getWritablePrivateVolumes()) {
22883            final String volumeUuid = vol.getFsUuid();
22884            synchronized (mInstallLock) {
22885                reconcileAppsDataLI(volumeUuid, userId, flags, migrateAppsData);
22886            }
22887        }
22888    }
22889
22890    private void reconcileAppsDataLI(String volumeUuid, int userId, int flags,
22891            boolean migrateAppData) {
22892        reconcileAppsDataLI(volumeUuid, userId, flags, migrateAppData, false /* onlyCoreApps */);
22893    }
22894
22895    /**
22896     * Reconcile all app data on given mounted volume.
22897     * <p>
22898     * Destroys app data that isn't expected, either due to uninstallation or
22899     * reinstallation on another volume.
22900     * <p>
22901     * Verifies that directories exist and that ownership and labeling is
22902     * correct for all installed apps.
22903     * @returns list of skipped non-core packages (if {@code onlyCoreApps} is true)
22904     */
22905    private List<String> reconcileAppsDataLI(String volumeUuid, int userId, int flags,
22906            boolean migrateAppData, boolean onlyCoreApps) {
22907        Slog.v(TAG, "reconcileAppsData for " + volumeUuid + " u" + userId + " 0x"
22908                + Integer.toHexString(flags) + " migrateAppData=" + migrateAppData);
22909        List<String> result = onlyCoreApps ? new ArrayList<>() : null;
22910
22911        final File ceDir = Environment.getDataUserCeDirectory(volumeUuid, userId);
22912        final File deDir = Environment.getDataUserDeDirectory(volumeUuid, userId);
22913
22914        // First look for stale data that doesn't belong, and check if things
22915        // have changed since we did our last restorecon
22916        if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) {
22917            if (StorageManager.isFileEncryptedNativeOrEmulated()
22918                    && !StorageManager.isUserKeyUnlocked(userId)) {
22919                throw new RuntimeException(
22920                        "Yikes, someone asked us to reconcile CE storage while " + userId
22921                                + " was still locked; this would have caused massive data loss!");
22922            }
22923
22924            final File[] files = FileUtils.listFilesOrEmpty(ceDir);
22925            for (File file : files) {
22926                final String packageName = file.getName();
22927                try {
22928                    assertPackageKnownAndInstalled(volumeUuid, packageName, userId);
22929                } catch (PackageManagerException e) {
22930                    logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e);
22931                    try {
22932                        mInstaller.destroyAppData(volumeUuid, packageName, userId,
22933                                StorageManager.FLAG_STORAGE_CE, 0);
22934                    } catch (InstallerException e2) {
22935                        logCriticalInfo(Log.WARN, "Failed to destroy: " + e2);
22936                    }
22937                }
22938            }
22939        }
22940        if ((flags & StorageManager.FLAG_STORAGE_DE) != 0) {
22941            final File[] files = FileUtils.listFilesOrEmpty(deDir);
22942            for (File file : files) {
22943                final String packageName = file.getName();
22944                try {
22945                    assertPackageKnownAndInstalled(volumeUuid, packageName, userId);
22946                } catch (PackageManagerException e) {
22947                    logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e);
22948                    try {
22949                        mInstaller.destroyAppData(volumeUuid, packageName, userId,
22950                                StorageManager.FLAG_STORAGE_DE, 0);
22951                    } catch (InstallerException e2) {
22952                        logCriticalInfo(Log.WARN, "Failed to destroy: " + e2);
22953                    }
22954                }
22955            }
22956        }
22957
22958        // Ensure that data directories are ready to roll for all packages
22959        // installed for this volume and user
22960        final List<PackageSetting> packages;
22961        synchronized (mPackages) {
22962            packages = mSettings.getVolumePackagesLPr(volumeUuid);
22963        }
22964        int preparedCount = 0;
22965        for (PackageSetting ps : packages) {
22966            final String packageName = ps.name;
22967            if (ps.pkg == null) {
22968                Slog.w(TAG, "Odd, missing scanned package " + packageName);
22969                // TODO: might be due to legacy ASEC apps; we should circle back
22970                // and reconcile again once they're scanned
22971                continue;
22972            }
22973            // Skip non-core apps if requested
22974            if (onlyCoreApps && !ps.pkg.coreApp) {
22975                result.add(packageName);
22976                continue;
22977            }
22978
22979            if (ps.getInstalled(userId)) {
22980                prepareAppDataAndMigrateLIF(ps.pkg, userId, flags, migrateAppData);
22981                preparedCount++;
22982            }
22983        }
22984
22985        Slog.v(TAG, "reconcileAppsData finished " + preparedCount + " packages");
22986        return result;
22987    }
22988
22989    /**
22990     * Prepare app data for the given app just after it was installed or
22991     * upgraded. This method carefully only touches users that it's installed
22992     * for, and it forces a restorecon to handle any seinfo changes.
22993     * <p>
22994     * Verifies that directories exist and that ownership and labeling is
22995     * correct for all installed apps. If there is an ownership mismatch, it
22996     * will try recovering system apps by wiping data; third-party app data is
22997     * left intact.
22998     * <p>
22999     * <em>Note: To avoid a deadlock, do not call this method with {@code mPackages} lock held</em>
23000     */
23001    private void prepareAppDataAfterInstallLIF(PackageParser.Package pkg) {
23002        final PackageSetting ps;
23003        synchronized (mPackages) {
23004            ps = mSettings.mPackages.get(pkg.packageName);
23005            mSettings.writeKernelMappingLPr(ps);
23006        }
23007
23008        final UserManager um = mContext.getSystemService(UserManager.class);
23009        UserManagerInternal umInternal = getUserManagerInternal();
23010        for (UserInfo user : um.getUsers()) {
23011            final int flags;
23012            if (umInternal.isUserUnlockingOrUnlocked(user.id)) {
23013                flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
23014            } else if (umInternal.isUserRunning(user.id)) {
23015                flags = StorageManager.FLAG_STORAGE_DE;
23016            } else {
23017                continue;
23018            }
23019
23020            if (ps.getInstalled(user.id)) {
23021                // TODO: when user data is locked, mark that we're still dirty
23022                prepareAppDataLIF(pkg, user.id, flags);
23023            }
23024        }
23025    }
23026
23027    /**
23028     * Prepare app data for the given app.
23029     * <p>
23030     * Verifies that directories exist and that ownership and labeling is
23031     * correct for all installed apps. If there is an ownership mismatch, this
23032     * will try recovering system apps by wiping data; third-party app data is
23033     * left intact.
23034     */
23035    private void prepareAppDataLIF(PackageParser.Package pkg, int userId, int flags) {
23036        if (pkg == null) {
23037            Slog.wtf(TAG, "Package was null!", new Throwable());
23038            return;
23039        }
23040        prepareAppDataLeafLIF(pkg, userId, flags);
23041        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
23042        for (int i = 0; i < childCount; i++) {
23043            prepareAppDataLeafLIF(pkg.childPackages.get(i), userId, flags);
23044        }
23045    }
23046
23047    private void prepareAppDataAndMigrateLIF(PackageParser.Package pkg, int userId, int flags,
23048            boolean maybeMigrateAppData) {
23049        prepareAppDataLIF(pkg, userId, flags);
23050
23051        if (maybeMigrateAppData && maybeMigrateAppDataLIF(pkg, userId)) {
23052            // We may have just shuffled around app data directories, so
23053            // prepare them one more time
23054            prepareAppDataLIF(pkg, userId, flags);
23055        }
23056    }
23057
23058    private void prepareAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) {
23059        if (DEBUG_APP_DATA) {
23060            Slog.v(TAG, "prepareAppData for " + pkg.packageName + " u" + userId + " 0x"
23061                    + Integer.toHexString(flags));
23062        }
23063
23064        final String volumeUuid = pkg.volumeUuid;
23065        final String packageName = pkg.packageName;
23066        final ApplicationInfo app = pkg.applicationInfo;
23067        final int appId = UserHandle.getAppId(app.uid);
23068
23069        Preconditions.checkNotNull(app.seInfo);
23070
23071        long ceDataInode = -1;
23072        try {
23073            ceDataInode = mInstaller.createAppData(volumeUuid, packageName, userId, flags,
23074                    appId, app.seInfo, app.targetSdkVersion);
23075        } catch (InstallerException e) {
23076            if (app.isSystemApp()) {
23077                logCriticalInfo(Log.ERROR, "Failed to create app data for " + packageName
23078                        + ", but trying to recover: " + e);
23079                destroyAppDataLeafLIF(pkg, userId, flags);
23080                try {
23081                    ceDataInode = mInstaller.createAppData(volumeUuid, packageName, userId, flags,
23082                            appId, app.seInfo, app.targetSdkVersion);
23083                    logCriticalInfo(Log.DEBUG, "Recovery succeeded!");
23084                } catch (InstallerException e2) {
23085                    logCriticalInfo(Log.DEBUG, "Recovery failed!");
23086                }
23087            } else {
23088                Slog.e(TAG, "Failed to create app data for " + packageName + ": " + e);
23089            }
23090        }
23091
23092        if ((flags & StorageManager.FLAG_STORAGE_CE) != 0 && ceDataInode != -1) {
23093            // TODO: mark this structure as dirty so we persist it!
23094            synchronized (mPackages) {
23095                final PackageSetting ps = mSettings.mPackages.get(packageName);
23096                if (ps != null) {
23097                    ps.setCeDataInode(ceDataInode, userId);
23098                }
23099            }
23100        }
23101
23102        prepareAppDataContentsLeafLIF(pkg, userId, flags);
23103    }
23104
23105    private void prepareAppDataContentsLIF(PackageParser.Package pkg, int userId, int flags) {
23106        if (pkg == null) {
23107            Slog.wtf(TAG, "Package was null!", new Throwable());
23108            return;
23109        }
23110        prepareAppDataContentsLeafLIF(pkg, userId, flags);
23111        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
23112        for (int i = 0; i < childCount; i++) {
23113            prepareAppDataContentsLeafLIF(pkg.childPackages.get(i), userId, flags);
23114        }
23115    }
23116
23117    private void prepareAppDataContentsLeafLIF(PackageParser.Package pkg, int userId, int flags) {
23118        final String volumeUuid = pkg.volumeUuid;
23119        final String packageName = pkg.packageName;
23120        final ApplicationInfo app = pkg.applicationInfo;
23121
23122        if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) {
23123            // Create a native library symlink only if we have native libraries
23124            // and if the native libraries are 32 bit libraries. We do not provide
23125            // this symlink for 64 bit libraries.
23126            if (app.primaryCpuAbi != null && !VMRuntime.is64BitAbi(app.primaryCpuAbi)) {
23127                final String nativeLibPath = app.nativeLibraryDir;
23128                try {
23129                    mInstaller.linkNativeLibraryDirectory(volumeUuid, packageName,
23130                            nativeLibPath, userId);
23131                } catch (InstallerException e) {
23132                    Slog.e(TAG, "Failed to link native for " + packageName + ": " + e);
23133                }
23134            }
23135        }
23136    }
23137
23138    /**
23139     * For system apps on non-FBE devices, this method migrates any existing
23140     * CE/DE data to match the {@code defaultToDeviceProtectedStorage} flag
23141     * requested by the app.
23142     */
23143    private boolean maybeMigrateAppDataLIF(PackageParser.Package pkg, int userId) {
23144        if (pkg.isSystemApp() && !StorageManager.isFileEncryptedNativeOrEmulated()
23145                && PackageManager.APPLY_DEFAULT_TO_DEVICE_PROTECTED_STORAGE) {
23146            final int storageTarget = pkg.applicationInfo.isDefaultToDeviceProtectedStorage()
23147                    ? StorageManager.FLAG_STORAGE_DE : StorageManager.FLAG_STORAGE_CE;
23148            try {
23149                mInstaller.migrateAppData(pkg.volumeUuid, pkg.packageName, userId,
23150                        storageTarget);
23151            } catch (InstallerException e) {
23152                logCriticalInfo(Log.WARN,
23153                        "Failed to migrate " + pkg.packageName + ": " + e.getMessage());
23154            }
23155            return true;
23156        } else {
23157            return false;
23158        }
23159    }
23160
23161    public PackageFreezer freezePackage(String packageName, String killReason) {
23162        return freezePackage(packageName, UserHandle.USER_ALL, killReason);
23163    }
23164
23165    public PackageFreezer freezePackage(String packageName, int userId, String killReason) {
23166        return new PackageFreezer(packageName, userId, killReason);
23167    }
23168
23169    public PackageFreezer freezePackageForInstall(String packageName, int installFlags,
23170            String killReason) {
23171        return freezePackageForInstall(packageName, UserHandle.USER_ALL, installFlags, killReason);
23172    }
23173
23174    public PackageFreezer freezePackageForInstall(String packageName, int userId, int installFlags,
23175            String killReason) {
23176        if ((installFlags & PackageManager.INSTALL_DONT_KILL_APP) != 0) {
23177            return new PackageFreezer();
23178        } else {
23179            return freezePackage(packageName, userId, killReason);
23180        }
23181    }
23182
23183    public PackageFreezer freezePackageForDelete(String packageName, int deleteFlags,
23184            String killReason) {
23185        return freezePackageForDelete(packageName, UserHandle.USER_ALL, deleteFlags, killReason);
23186    }
23187
23188    public PackageFreezer freezePackageForDelete(String packageName, int userId, int deleteFlags,
23189            String killReason) {
23190        if ((deleteFlags & PackageManager.DELETE_DONT_KILL_APP) != 0) {
23191            return new PackageFreezer();
23192        } else {
23193            return freezePackage(packageName, userId, killReason);
23194        }
23195    }
23196
23197    /**
23198     * Class that freezes and kills the given package upon creation, and
23199     * unfreezes it upon closing. This is typically used when doing surgery on
23200     * app code/data to prevent the app from running while you're working.
23201     */
23202    private class PackageFreezer implements AutoCloseable {
23203        private final String mPackageName;
23204        private final PackageFreezer[] mChildren;
23205
23206        private final boolean mWeFroze;
23207
23208        private final AtomicBoolean mClosed = new AtomicBoolean();
23209        private final CloseGuard mCloseGuard = CloseGuard.get();
23210
23211        /**
23212         * Create and return a stub freezer that doesn't actually do anything,
23213         * typically used when someone requested
23214         * {@link PackageManager#INSTALL_DONT_KILL_APP} or
23215         * {@link PackageManager#DELETE_DONT_KILL_APP}.
23216         */
23217        public PackageFreezer() {
23218            mPackageName = null;
23219            mChildren = null;
23220            mWeFroze = false;
23221            mCloseGuard.open("close");
23222        }
23223
23224        public PackageFreezer(String packageName, int userId, String killReason) {
23225            synchronized (mPackages) {
23226                mPackageName = packageName;
23227                mWeFroze = mFrozenPackages.add(mPackageName);
23228
23229                final PackageSetting ps = mSettings.mPackages.get(mPackageName);
23230                if (ps != null) {
23231                    killApplication(ps.name, ps.appId, userId, killReason);
23232                }
23233
23234                final PackageParser.Package p = mPackages.get(packageName);
23235                if (p != null && p.childPackages != null) {
23236                    final int N = p.childPackages.size();
23237                    mChildren = new PackageFreezer[N];
23238                    for (int i = 0; i < N; i++) {
23239                        mChildren[i] = new PackageFreezer(p.childPackages.get(i).packageName,
23240                                userId, killReason);
23241                    }
23242                } else {
23243                    mChildren = null;
23244                }
23245            }
23246            mCloseGuard.open("close");
23247        }
23248
23249        @Override
23250        protected void finalize() throws Throwable {
23251            try {
23252                mCloseGuard.warnIfOpen();
23253                close();
23254            } finally {
23255                super.finalize();
23256            }
23257        }
23258
23259        @Override
23260        public void close() {
23261            mCloseGuard.close();
23262            if (mClosed.compareAndSet(false, true)) {
23263                synchronized (mPackages) {
23264                    if (mWeFroze) {
23265                        mFrozenPackages.remove(mPackageName);
23266                    }
23267
23268                    if (mChildren != null) {
23269                        for (PackageFreezer freezer : mChildren) {
23270                            freezer.close();
23271                        }
23272                    }
23273                }
23274            }
23275        }
23276    }
23277
23278    /**
23279     * Verify that given package is currently frozen.
23280     */
23281    private void checkPackageFrozen(String packageName) {
23282        synchronized (mPackages) {
23283            if (!mFrozenPackages.contains(packageName)) {
23284                Slog.wtf(TAG, "Expected " + packageName + " to be frozen!", new Throwable());
23285            }
23286        }
23287    }
23288
23289    @Override
23290    public int movePackage(final String packageName, final String volumeUuid) {
23291        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null);
23292
23293        final UserHandle user = new UserHandle(UserHandle.getCallingUserId());
23294        final int moveId = mNextMoveId.getAndIncrement();
23295        mHandler.post(new Runnable() {
23296            @Override
23297            public void run() {
23298                try {
23299                    movePackageInternal(packageName, volumeUuid, moveId, user);
23300                } catch (PackageManagerException e) {
23301                    Slog.w(TAG, "Failed to move " + packageName, e);
23302                    mMoveCallbacks.notifyStatusChanged(moveId,
23303                            PackageManager.MOVE_FAILED_INTERNAL_ERROR);
23304                }
23305            }
23306        });
23307        return moveId;
23308    }
23309
23310    private void movePackageInternal(final String packageName, final String volumeUuid,
23311            final int moveId, UserHandle user) throws PackageManagerException {
23312        final StorageManager storage = mContext.getSystemService(StorageManager.class);
23313        final PackageManager pm = mContext.getPackageManager();
23314
23315        final boolean currentAsec;
23316        final String currentVolumeUuid;
23317        final File codeFile;
23318        final String installerPackageName;
23319        final String packageAbiOverride;
23320        final int appId;
23321        final String seinfo;
23322        final String label;
23323        final int targetSdkVersion;
23324        final PackageFreezer freezer;
23325        final int[] installedUserIds;
23326
23327        // reader
23328        synchronized (mPackages) {
23329            final PackageParser.Package pkg = mPackages.get(packageName);
23330            final PackageSetting ps = mSettings.mPackages.get(packageName);
23331            if (pkg == null || ps == null) {
23332                throw new PackageManagerException(MOVE_FAILED_DOESNT_EXIST, "Missing package");
23333            }
23334
23335            if (pkg.applicationInfo.isSystemApp()) {
23336                throw new PackageManagerException(MOVE_FAILED_SYSTEM_PACKAGE,
23337                        "Cannot move system application");
23338            }
23339
23340            final boolean isInternalStorage = VolumeInfo.ID_PRIVATE_INTERNAL.equals(volumeUuid);
23341            final boolean allow3rdPartyOnInternal = mContext.getResources().getBoolean(
23342                    com.android.internal.R.bool.config_allow3rdPartyAppOnInternal);
23343            if (isInternalStorage && !allow3rdPartyOnInternal) {
23344                throw new PackageManagerException(MOVE_FAILED_3RD_PARTY_NOT_ALLOWED_ON_INTERNAL,
23345                        "3rd party apps are not allowed on internal storage");
23346            }
23347
23348            if (pkg.applicationInfo.isExternalAsec()) {
23349                currentAsec = true;
23350                currentVolumeUuid = StorageManager.UUID_PRIMARY_PHYSICAL;
23351            } else if (pkg.applicationInfo.isForwardLocked()) {
23352                currentAsec = true;
23353                currentVolumeUuid = "forward_locked";
23354            } else {
23355                currentAsec = false;
23356                currentVolumeUuid = ps.volumeUuid;
23357
23358                final File probe = new File(pkg.codePath);
23359                final File probeOat = new File(probe, "oat");
23360                if (!probe.isDirectory() || !probeOat.isDirectory()) {
23361                    throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
23362                            "Move only supported for modern cluster style installs");
23363                }
23364            }
23365
23366            if (Objects.equals(currentVolumeUuid, volumeUuid)) {
23367                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
23368                        "Package already moved to " + volumeUuid);
23369            }
23370            if (pkg.applicationInfo.isInternal() && isPackageDeviceAdminOnAnyUser(packageName)) {
23371                throw new PackageManagerException(MOVE_FAILED_DEVICE_ADMIN,
23372                        "Device admin cannot be moved");
23373            }
23374
23375            if (mFrozenPackages.contains(packageName)) {
23376                throw new PackageManagerException(MOVE_FAILED_OPERATION_PENDING,
23377                        "Failed to move already frozen package");
23378            }
23379
23380            codeFile = new File(pkg.codePath);
23381            installerPackageName = ps.installerPackageName;
23382            packageAbiOverride = ps.cpuAbiOverrideString;
23383            appId = UserHandle.getAppId(pkg.applicationInfo.uid);
23384            seinfo = pkg.applicationInfo.seInfo;
23385            label = String.valueOf(pm.getApplicationLabel(pkg.applicationInfo));
23386            targetSdkVersion = pkg.applicationInfo.targetSdkVersion;
23387            freezer = freezePackage(packageName, "movePackageInternal");
23388            installedUserIds = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
23389        }
23390
23391        final Bundle extras = new Bundle();
23392        extras.putString(Intent.EXTRA_PACKAGE_NAME, packageName);
23393        extras.putString(Intent.EXTRA_TITLE, label);
23394        mMoveCallbacks.notifyCreated(moveId, extras);
23395
23396        int installFlags;
23397        final boolean moveCompleteApp;
23398        final File measurePath;
23399
23400        if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, volumeUuid)) {
23401            installFlags = INSTALL_INTERNAL;
23402            moveCompleteApp = !currentAsec;
23403            measurePath = Environment.getDataAppDirectory(volumeUuid);
23404        } else if (Objects.equals(StorageManager.UUID_PRIMARY_PHYSICAL, volumeUuid)) {
23405            installFlags = INSTALL_EXTERNAL;
23406            moveCompleteApp = false;
23407            measurePath = storage.getPrimaryPhysicalVolume().getPath();
23408        } else {
23409            final VolumeInfo volume = storage.findVolumeByUuid(volumeUuid);
23410            if (volume == null || volume.getType() != VolumeInfo.TYPE_PRIVATE
23411                    || !volume.isMountedWritable()) {
23412                freezer.close();
23413                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
23414                        "Move location not mounted private volume");
23415            }
23416
23417            Preconditions.checkState(!currentAsec);
23418
23419            installFlags = INSTALL_INTERNAL;
23420            moveCompleteApp = true;
23421            measurePath = Environment.getDataAppDirectory(volumeUuid);
23422        }
23423
23424        final PackageStats stats = new PackageStats(null, -1);
23425        synchronized (mInstaller) {
23426            for (int userId : installedUserIds) {
23427                if (!getPackageSizeInfoLI(packageName, userId, stats)) {
23428                    freezer.close();
23429                    throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
23430                            "Failed to measure package size");
23431                }
23432            }
23433        }
23434
23435        if (DEBUG_INSTALL) Slog.d(TAG, "Measured code size " + stats.codeSize + ", data size "
23436                + stats.dataSize);
23437
23438        final long startFreeBytes = measurePath.getUsableSpace();
23439        final long sizeBytes;
23440        if (moveCompleteApp) {
23441            sizeBytes = stats.codeSize + stats.dataSize;
23442        } else {
23443            sizeBytes = stats.codeSize;
23444        }
23445
23446        if (sizeBytes > storage.getStorageBytesUntilLow(measurePath)) {
23447            freezer.close();
23448            throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
23449                    "Not enough free space to move");
23450        }
23451
23452        mMoveCallbacks.notifyStatusChanged(moveId, 10);
23453
23454        final CountDownLatch installedLatch = new CountDownLatch(1);
23455        final IPackageInstallObserver2 installObserver = new IPackageInstallObserver2.Stub() {
23456            @Override
23457            public void onUserActionRequired(Intent intent) throws RemoteException {
23458                throw new IllegalStateException();
23459            }
23460
23461            @Override
23462            public void onPackageInstalled(String basePackageName, int returnCode, String msg,
23463                    Bundle extras) throws RemoteException {
23464                if (DEBUG_INSTALL) Slog.d(TAG, "Install result for move: "
23465                        + PackageManager.installStatusToString(returnCode, msg));
23466
23467                installedLatch.countDown();
23468                freezer.close();
23469
23470                final int status = PackageManager.installStatusToPublicStatus(returnCode);
23471                switch (status) {
23472                    case PackageInstaller.STATUS_SUCCESS:
23473                        mMoveCallbacks.notifyStatusChanged(moveId,
23474                                PackageManager.MOVE_SUCCEEDED);
23475                        break;
23476                    case PackageInstaller.STATUS_FAILURE_STORAGE:
23477                        mMoveCallbacks.notifyStatusChanged(moveId,
23478                                PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE);
23479                        break;
23480                    default:
23481                        mMoveCallbacks.notifyStatusChanged(moveId,
23482                                PackageManager.MOVE_FAILED_INTERNAL_ERROR);
23483                        break;
23484                }
23485            }
23486        };
23487
23488        final MoveInfo move;
23489        if (moveCompleteApp) {
23490            // Kick off a thread to report progress estimates
23491            new Thread() {
23492                @Override
23493                public void run() {
23494                    while (true) {
23495                        try {
23496                            if (installedLatch.await(1, TimeUnit.SECONDS)) {
23497                                break;
23498                            }
23499                        } catch (InterruptedException ignored) {
23500                        }
23501
23502                        final long deltaFreeBytes = startFreeBytes - measurePath.getUsableSpace();
23503                        final int progress = 10 + (int) MathUtils.constrain(
23504                                ((deltaFreeBytes * 80) / sizeBytes), 0, 80);
23505                        mMoveCallbacks.notifyStatusChanged(moveId, progress);
23506                    }
23507                }
23508            }.start();
23509
23510            final String dataAppName = codeFile.getName();
23511            move = new MoveInfo(moveId, currentVolumeUuid, volumeUuid, packageName,
23512                    dataAppName, appId, seinfo, targetSdkVersion);
23513        } else {
23514            move = null;
23515        }
23516
23517        installFlags |= PackageManager.INSTALL_REPLACE_EXISTING;
23518
23519        final Message msg = mHandler.obtainMessage(INIT_COPY);
23520        final OriginInfo origin = OriginInfo.fromExistingFile(codeFile);
23521        final InstallParams params = new InstallParams(origin, move, installObserver, installFlags,
23522                installerPackageName, volumeUuid, null /*verificationInfo*/, user,
23523                packageAbiOverride, null /*grantedPermissions*/, null /*certificates*/,
23524                PackageManager.INSTALL_REASON_UNKNOWN);
23525        params.setTraceMethod("movePackage").setTraceCookie(System.identityHashCode(params));
23526        msg.obj = params;
23527
23528        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "movePackage",
23529                System.identityHashCode(msg.obj));
23530        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
23531                System.identityHashCode(msg.obj));
23532
23533        mHandler.sendMessage(msg);
23534    }
23535
23536    @Override
23537    public int movePrimaryStorage(String volumeUuid) throws RemoteException {
23538        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null);
23539
23540        final int realMoveId = mNextMoveId.getAndIncrement();
23541        final Bundle extras = new Bundle();
23542        extras.putString(VolumeRecord.EXTRA_FS_UUID, volumeUuid);
23543        mMoveCallbacks.notifyCreated(realMoveId, extras);
23544
23545        final IPackageMoveObserver callback = new IPackageMoveObserver.Stub() {
23546            @Override
23547            public void onCreated(int moveId, Bundle extras) {
23548                // Ignored
23549            }
23550
23551            @Override
23552            public void onStatusChanged(int moveId, int status, long estMillis) {
23553                mMoveCallbacks.notifyStatusChanged(realMoveId, status, estMillis);
23554            }
23555        };
23556
23557        final StorageManager storage = mContext.getSystemService(StorageManager.class);
23558        storage.setPrimaryStorageUuid(volumeUuid, callback);
23559        return realMoveId;
23560    }
23561
23562    @Override
23563    public int getMoveStatus(int moveId) {
23564        mContext.enforceCallingOrSelfPermission(
23565                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
23566        return mMoveCallbacks.mLastStatus.get(moveId);
23567    }
23568
23569    @Override
23570    public void registerMoveCallback(IPackageMoveObserver callback) {
23571        mContext.enforceCallingOrSelfPermission(
23572                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
23573        mMoveCallbacks.register(callback);
23574    }
23575
23576    @Override
23577    public void unregisterMoveCallback(IPackageMoveObserver callback) {
23578        mContext.enforceCallingOrSelfPermission(
23579                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
23580        mMoveCallbacks.unregister(callback);
23581    }
23582
23583    @Override
23584    public boolean setInstallLocation(int loc) {
23585        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WRITE_SECURE_SETTINGS,
23586                null);
23587        if (getInstallLocation() == loc) {
23588            return true;
23589        }
23590        if (loc == PackageHelper.APP_INSTALL_AUTO || loc == PackageHelper.APP_INSTALL_INTERNAL
23591                || loc == PackageHelper.APP_INSTALL_EXTERNAL) {
23592            android.provider.Settings.Global.putInt(mContext.getContentResolver(),
23593                    android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, loc);
23594            return true;
23595        }
23596        return false;
23597   }
23598
23599    @Override
23600    public int getInstallLocation() {
23601        // allow instant app access
23602        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
23603                android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION,
23604                PackageHelper.APP_INSTALL_AUTO);
23605    }
23606
23607    /** Called by UserManagerService */
23608    void cleanUpUser(UserManagerService userManager, int userHandle) {
23609        synchronized (mPackages) {
23610            mDirtyUsers.remove(userHandle);
23611            mUserNeedsBadging.delete(userHandle);
23612            mSettings.removeUserLPw(userHandle);
23613            mPendingBroadcasts.remove(userHandle);
23614            mInstantAppRegistry.onUserRemovedLPw(userHandle);
23615            removeUnusedPackagesLPw(userManager, userHandle);
23616        }
23617    }
23618
23619    /**
23620     * We're removing userHandle and would like to remove any downloaded packages
23621     * that are no longer in use by any other user.
23622     * @param userHandle the user being removed
23623     */
23624    private void removeUnusedPackagesLPw(UserManagerService userManager, final int userHandle) {
23625        final boolean DEBUG_CLEAN_APKS = false;
23626        int [] users = userManager.getUserIds();
23627        Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator();
23628        while (psit.hasNext()) {
23629            PackageSetting ps = psit.next();
23630            if (ps.pkg == null) {
23631                continue;
23632            }
23633            final String packageName = ps.pkg.packageName;
23634            // Skip over if system app
23635            if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0) {
23636                continue;
23637            }
23638            if (DEBUG_CLEAN_APKS) {
23639                Slog.i(TAG, "Checking package " + packageName);
23640            }
23641            boolean keep = shouldKeepUninstalledPackageLPr(packageName);
23642            if (keep) {
23643                if (DEBUG_CLEAN_APKS) {
23644                    Slog.i(TAG, "  Keeping package " + packageName + " - requested by DO");
23645                }
23646            } else {
23647                for (int i = 0; i < users.length; i++) {
23648                    if (users[i] != userHandle && ps.getInstalled(users[i])) {
23649                        keep = true;
23650                        if (DEBUG_CLEAN_APKS) {
23651                            Slog.i(TAG, "  Keeping package " + packageName + " for user "
23652                                    + users[i]);
23653                        }
23654                        break;
23655                    }
23656                }
23657            }
23658            if (!keep) {
23659                if (DEBUG_CLEAN_APKS) {
23660                    Slog.i(TAG, "  Removing package " + packageName);
23661                }
23662                mHandler.post(new Runnable() {
23663                    public void run() {
23664                        deletePackageX(packageName, PackageManager.VERSION_CODE_HIGHEST,
23665                                userHandle, 0);
23666                    } //end run
23667                });
23668            }
23669        }
23670    }
23671
23672    /** Called by UserManagerService */
23673    void createNewUser(int userId, String[] disallowedPackages) {
23674        synchronized (mInstallLock) {
23675            mSettings.createNewUserLI(this, mInstaller, userId, disallowedPackages);
23676        }
23677        synchronized (mPackages) {
23678            scheduleWritePackageRestrictionsLocked(userId);
23679            scheduleWritePackageListLocked(userId);
23680            applyFactoryDefaultBrowserLPw(userId);
23681            primeDomainVerificationsLPw(userId);
23682        }
23683    }
23684
23685    void onNewUserCreated(final int userId) {
23686        mDefaultPermissionPolicy.grantDefaultPermissions(userId);
23687        // If permission review for legacy apps is required, we represent
23688        // dagerous permissions for such apps as always granted runtime
23689        // permissions to keep per user flag state whether review is needed.
23690        // Hence, if a new user is added we have to propagate dangerous
23691        // permission grants for these legacy apps.
23692        if (mPermissionReviewRequired) {
23693            updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL
23694                    | UPDATE_PERMISSIONS_REPLACE_ALL);
23695        }
23696    }
23697
23698    @Override
23699    public VerifierDeviceIdentity getVerifierDeviceIdentity() throws RemoteException {
23700        mContext.enforceCallingOrSelfPermission(
23701                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
23702                "Only package verification agents can read the verifier device identity");
23703
23704        synchronized (mPackages) {
23705            return mSettings.getVerifierDeviceIdentityLPw();
23706        }
23707    }
23708
23709    @Override
23710    public void setPermissionEnforced(String permission, boolean enforced) {
23711        // TODO: Now that we no longer change GID for storage, this should to away.
23712        mContext.enforceCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS,
23713                "setPermissionEnforced");
23714        if (READ_EXTERNAL_STORAGE.equals(permission)) {
23715            synchronized (mPackages) {
23716                if (mSettings.mReadExternalStorageEnforced == null
23717                        || mSettings.mReadExternalStorageEnforced != enforced) {
23718                    mSettings.mReadExternalStorageEnforced = enforced;
23719                    mSettings.writeLPr();
23720                }
23721            }
23722            // kill any non-foreground processes so we restart them and
23723            // grant/revoke the GID.
23724            final IActivityManager am = ActivityManager.getService();
23725            if (am != null) {
23726                final long token = Binder.clearCallingIdentity();
23727                try {
23728                    am.killProcessesBelowForeground("setPermissionEnforcement");
23729                } catch (RemoteException e) {
23730                } finally {
23731                    Binder.restoreCallingIdentity(token);
23732                }
23733            }
23734        } else {
23735            throw new IllegalArgumentException("No selective enforcement for " + permission);
23736        }
23737    }
23738
23739    @Override
23740    @Deprecated
23741    public boolean isPermissionEnforced(String permission) {
23742        // allow instant applications
23743        return true;
23744    }
23745
23746    @Override
23747    public boolean isStorageLow() {
23748        // allow instant applications
23749        final long token = Binder.clearCallingIdentity();
23750        try {
23751            final DeviceStorageMonitorInternal
23752                    dsm = LocalServices.getService(DeviceStorageMonitorInternal.class);
23753            if (dsm != null) {
23754                return dsm.isMemoryLow();
23755            } else {
23756                return false;
23757            }
23758        } finally {
23759            Binder.restoreCallingIdentity(token);
23760        }
23761    }
23762
23763    @Override
23764    public IPackageInstaller getPackageInstaller() {
23765        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
23766            return null;
23767        }
23768        return mInstallerService;
23769    }
23770
23771    private boolean userNeedsBadging(int userId) {
23772        int index = mUserNeedsBadging.indexOfKey(userId);
23773        if (index < 0) {
23774            final UserInfo userInfo;
23775            final long token = Binder.clearCallingIdentity();
23776            try {
23777                userInfo = sUserManager.getUserInfo(userId);
23778            } finally {
23779                Binder.restoreCallingIdentity(token);
23780            }
23781            final boolean b;
23782            if (userInfo != null && userInfo.isManagedProfile()) {
23783                b = true;
23784            } else {
23785                b = false;
23786            }
23787            mUserNeedsBadging.put(userId, b);
23788            return b;
23789        }
23790        return mUserNeedsBadging.valueAt(index);
23791    }
23792
23793    @Override
23794    public KeySet getKeySetByAlias(String packageName, String alias) {
23795        if (packageName == null || alias == null) {
23796            return null;
23797        }
23798        synchronized(mPackages) {
23799            final PackageParser.Package pkg = mPackages.get(packageName);
23800            if (pkg == null) {
23801                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
23802                throw new IllegalArgumentException("Unknown package: " + packageName);
23803            }
23804            KeySetManagerService ksms = mSettings.mKeySetManagerService;
23805            return new KeySet(ksms.getKeySetByAliasAndPackageNameLPr(packageName, alias));
23806        }
23807    }
23808
23809    @Override
23810    public KeySet getSigningKeySet(String packageName) {
23811        if (packageName == null) {
23812            return null;
23813        }
23814        synchronized(mPackages) {
23815            final int callingUid = Binder.getCallingUid();
23816            final int callingUserId = UserHandle.getUserId(callingUid);
23817            final PackageParser.Package pkg = mPackages.get(packageName);
23818            if (pkg == null) {
23819                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
23820                throw new IllegalArgumentException("Unknown package: " + packageName);
23821            }
23822            final PackageSetting ps = (PackageSetting) pkg.mExtras;
23823            if (filterAppAccessLPr(ps, callingUid, callingUserId)) {
23824                // filter and pretend the package doesn't exist
23825                Slog.w(TAG, "KeySet requested for filtered package: " + packageName
23826                        + ", uid:" + callingUid);
23827                throw new IllegalArgumentException("Unknown package: " + packageName);
23828            }
23829            if (pkg.applicationInfo.uid != callingUid
23830                    && Process.SYSTEM_UID != callingUid) {
23831                throw new SecurityException("May not access signing KeySet of other apps.");
23832            }
23833            KeySetManagerService ksms = mSettings.mKeySetManagerService;
23834            return new KeySet(ksms.getSigningKeySetByPackageNameLPr(packageName));
23835        }
23836    }
23837
23838    @Override
23839    public boolean isPackageSignedByKeySet(String packageName, KeySet ks) {
23840        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
23841            return false;
23842        }
23843        if (packageName == null || ks == null) {
23844            return false;
23845        }
23846        synchronized(mPackages) {
23847            final PackageParser.Package pkg = mPackages.get(packageName);
23848            if (pkg == null) {
23849                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
23850                throw new IllegalArgumentException("Unknown package: " + packageName);
23851            }
23852            IBinder ksh = ks.getToken();
23853            if (ksh instanceof KeySetHandle) {
23854                KeySetManagerService ksms = mSettings.mKeySetManagerService;
23855                return ksms.packageIsSignedByLPr(packageName, (KeySetHandle) ksh);
23856            }
23857            return false;
23858        }
23859    }
23860
23861    @Override
23862    public boolean isPackageSignedByKeySetExactly(String packageName, KeySet ks) {
23863        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
23864            return false;
23865        }
23866        if (packageName == null || ks == null) {
23867            return false;
23868        }
23869        synchronized(mPackages) {
23870            final PackageParser.Package pkg = mPackages.get(packageName);
23871            if (pkg == null) {
23872                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
23873                throw new IllegalArgumentException("Unknown package: " + packageName);
23874            }
23875            IBinder ksh = ks.getToken();
23876            if (ksh instanceof KeySetHandle) {
23877                KeySetManagerService ksms = mSettings.mKeySetManagerService;
23878                return ksms.packageIsSignedByExactlyLPr(packageName, (KeySetHandle) ksh);
23879            }
23880            return false;
23881        }
23882    }
23883
23884    private void deletePackageIfUnusedLPr(final String packageName) {
23885        PackageSetting ps = mSettings.mPackages.get(packageName);
23886        if (ps == null) {
23887            return;
23888        }
23889        if (!ps.isAnyInstalled(sUserManager.getUserIds())) {
23890            // TODO Implement atomic delete if package is unused
23891            // It is currently possible that the package will be deleted even if it is installed
23892            // after this method returns.
23893            mHandler.post(new Runnable() {
23894                public void run() {
23895                    deletePackageX(packageName, PackageManager.VERSION_CODE_HIGHEST,
23896                            0, PackageManager.DELETE_ALL_USERS);
23897                }
23898            });
23899        }
23900    }
23901
23902    /**
23903     * Check and throw if the given before/after packages would be considered a
23904     * downgrade.
23905     */
23906    private static void checkDowngrade(PackageParser.Package before, PackageInfoLite after)
23907            throws PackageManagerException {
23908        if (after.versionCode < before.mVersionCode) {
23909            throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
23910                    "Update version code " + after.versionCode + " is older than current "
23911                    + before.mVersionCode);
23912        } else if (after.versionCode == before.mVersionCode) {
23913            if (after.baseRevisionCode < before.baseRevisionCode) {
23914                throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
23915                        "Update base revision code " + after.baseRevisionCode
23916                        + " is older than current " + before.baseRevisionCode);
23917            }
23918
23919            if (!ArrayUtils.isEmpty(after.splitNames)) {
23920                for (int i = 0; i < after.splitNames.length; i++) {
23921                    final String splitName = after.splitNames[i];
23922                    final int j = ArrayUtils.indexOf(before.splitNames, splitName);
23923                    if (j != -1) {
23924                        if (after.splitRevisionCodes[i] < before.splitRevisionCodes[j]) {
23925                            throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
23926                                    "Update split " + splitName + " revision code "
23927                                    + after.splitRevisionCodes[i] + " is older than current "
23928                                    + before.splitRevisionCodes[j]);
23929                        }
23930                    }
23931                }
23932            }
23933        }
23934    }
23935
23936    private static class MoveCallbacks extends Handler {
23937        private static final int MSG_CREATED = 1;
23938        private static final int MSG_STATUS_CHANGED = 2;
23939
23940        private final RemoteCallbackList<IPackageMoveObserver>
23941                mCallbacks = new RemoteCallbackList<>();
23942
23943        private final SparseIntArray mLastStatus = new SparseIntArray();
23944
23945        public MoveCallbacks(Looper looper) {
23946            super(looper);
23947        }
23948
23949        public void register(IPackageMoveObserver callback) {
23950            mCallbacks.register(callback);
23951        }
23952
23953        public void unregister(IPackageMoveObserver callback) {
23954            mCallbacks.unregister(callback);
23955        }
23956
23957        @Override
23958        public void handleMessage(Message msg) {
23959            final SomeArgs args = (SomeArgs) msg.obj;
23960            final int n = mCallbacks.beginBroadcast();
23961            for (int i = 0; i < n; i++) {
23962                final IPackageMoveObserver callback = mCallbacks.getBroadcastItem(i);
23963                try {
23964                    invokeCallback(callback, msg.what, args);
23965                } catch (RemoteException ignored) {
23966                }
23967            }
23968            mCallbacks.finishBroadcast();
23969            args.recycle();
23970        }
23971
23972        private void invokeCallback(IPackageMoveObserver callback, int what, SomeArgs args)
23973                throws RemoteException {
23974            switch (what) {
23975                case MSG_CREATED: {
23976                    callback.onCreated(args.argi1, (Bundle) args.arg2);
23977                    break;
23978                }
23979                case MSG_STATUS_CHANGED: {
23980                    callback.onStatusChanged(args.argi1, args.argi2, (long) args.arg3);
23981                    break;
23982                }
23983            }
23984        }
23985
23986        private void notifyCreated(int moveId, Bundle extras) {
23987            Slog.v(TAG, "Move " + moveId + " created " + extras.toString());
23988
23989            final SomeArgs args = SomeArgs.obtain();
23990            args.argi1 = moveId;
23991            args.arg2 = extras;
23992            obtainMessage(MSG_CREATED, args).sendToTarget();
23993        }
23994
23995        private void notifyStatusChanged(int moveId, int status) {
23996            notifyStatusChanged(moveId, status, -1);
23997        }
23998
23999        private void notifyStatusChanged(int moveId, int status, long estMillis) {
24000            Slog.v(TAG, "Move " + moveId + " status " + status);
24001
24002            final SomeArgs args = SomeArgs.obtain();
24003            args.argi1 = moveId;
24004            args.argi2 = status;
24005            args.arg3 = estMillis;
24006            obtainMessage(MSG_STATUS_CHANGED, args).sendToTarget();
24007
24008            synchronized (mLastStatus) {
24009                mLastStatus.put(moveId, status);
24010            }
24011        }
24012    }
24013
24014    private final static class OnPermissionChangeListeners extends Handler {
24015        private static final int MSG_ON_PERMISSIONS_CHANGED = 1;
24016
24017        private final RemoteCallbackList<IOnPermissionsChangeListener> mPermissionListeners =
24018                new RemoteCallbackList<>();
24019
24020        public OnPermissionChangeListeners(Looper looper) {
24021            super(looper);
24022        }
24023
24024        @Override
24025        public void handleMessage(Message msg) {
24026            switch (msg.what) {
24027                case MSG_ON_PERMISSIONS_CHANGED: {
24028                    final int uid = msg.arg1;
24029                    handleOnPermissionsChanged(uid);
24030                } break;
24031            }
24032        }
24033
24034        public void addListenerLocked(IOnPermissionsChangeListener listener) {
24035            mPermissionListeners.register(listener);
24036
24037        }
24038
24039        public void removeListenerLocked(IOnPermissionsChangeListener listener) {
24040            mPermissionListeners.unregister(listener);
24041        }
24042
24043        public void onPermissionsChanged(int uid) {
24044            if (mPermissionListeners.getRegisteredCallbackCount() > 0) {
24045                obtainMessage(MSG_ON_PERMISSIONS_CHANGED, uid, 0).sendToTarget();
24046            }
24047        }
24048
24049        private void handleOnPermissionsChanged(int uid) {
24050            final int count = mPermissionListeners.beginBroadcast();
24051            try {
24052                for (int i = 0; i < count; i++) {
24053                    IOnPermissionsChangeListener callback = mPermissionListeners
24054                            .getBroadcastItem(i);
24055                    try {
24056                        callback.onPermissionsChanged(uid);
24057                    } catch (RemoteException e) {
24058                        Log.e(TAG, "Permission listener is dead", e);
24059                    }
24060                }
24061            } finally {
24062                mPermissionListeners.finishBroadcast();
24063            }
24064        }
24065    }
24066
24067    private class PackageManagerInternalImpl extends PackageManagerInternal {
24068        @Override
24069        public void setLocationPackagesProvider(PackagesProvider provider) {
24070            synchronized (mPackages) {
24071                mDefaultPermissionPolicy.setLocationPackagesProviderLPw(provider);
24072            }
24073        }
24074
24075        @Override
24076        public void setVoiceInteractionPackagesProvider(PackagesProvider provider) {
24077            synchronized (mPackages) {
24078                mDefaultPermissionPolicy.setVoiceInteractionPackagesProviderLPw(provider);
24079            }
24080        }
24081
24082        @Override
24083        public void setSmsAppPackagesProvider(PackagesProvider provider) {
24084            synchronized (mPackages) {
24085                mDefaultPermissionPolicy.setSmsAppPackagesProviderLPw(provider);
24086            }
24087        }
24088
24089        @Override
24090        public void setDialerAppPackagesProvider(PackagesProvider provider) {
24091            synchronized (mPackages) {
24092                mDefaultPermissionPolicy.setDialerAppPackagesProviderLPw(provider);
24093            }
24094        }
24095
24096        @Override
24097        public void setSimCallManagerPackagesProvider(PackagesProvider provider) {
24098            synchronized (mPackages) {
24099                mDefaultPermissionPolicy.setSimCallManagerPackagesProviderLPw(provider);
24100            }
24101        }
24102
24103        @Override
24104        public void setSyncAdapterPackagesprovider(SyncAdapterPackagesProvider provider) {
24105            synchronized (mPackages) {
24106                mDefaultPermissionPolicy.setSyncAdapterPackagesProviderLPw(provider);
24107            }
24108        }
24109
24110        @Override
24111        public void grantDefaultPermissionsToDefaultSmsApp(String packageName, int userId) {
24112            synchronized (mPackages) {
24113                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSmsAppLPr(
24114                        packageName, userId);
24115            }
24116        }
24117
24118        @Override
24119        public void grantDefaultPermissionsToDefaultDialerApp(String packageName, int userId) {
24120            synchronized (mPackages) {
24121                mSettings.setDefaultDialerPackageNameLPw(packageName, userId);
24122                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultDialerAppLPr(
24123                        packageName, userId);
24124            }
24125        }
24126
24127        @Override
24128        public void grantDefaultPermissionsToDefaultSimCallManager(String packageName, int userId) {
24129            synchronized (mPackages) {
24130                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSimCallManagerLPr(
24131                        packageName, userId);
24132            }
24133        }
24134
24135        @Override
24136        public void setKeepUninstalledPackages(final List<String> packageList) {
24137            Preconditions.checkNotNull(packageList);
24138            List<String> removedFromList = null;
24139            synchronized (mPackages) {
24140                if (mKeepUninstalledPackages != null) {
24141                    final int packagesCount = mKeepUninstalledPackages.size();
24142                    for (int i = 0; i < packagesCount; i++) {
24143                        String oldPackage = mKeepUninstalledPackages.get(i);
24144                        if (packageList != null && packageList.contains(oldPackage)) {
24145                            continue;
24146                        }
24147                        if (removedFromList == null) {
24148                            removedFromList = new ArrayList<>();
24149                        }
24150                        removedFromList.add(oldPackage);
24151                    }
24152                }
24153                mKeepUninstalledPackages = new ArrayList<>(packageList);
24154                if (removedFromList != null) {
24155                    final int removedCount = removedFromList.size();
24156                    for (int i = 0; i < removedCount; i++) {
24157                        deletePackageIfUnusedLPr(removedFromList.get(i));
24158                    }
24159                }
24160            }
24161        }
24162
24163        @Override
24164        public boolean isPermissionsReviewRequired(String packageName, int userId) {
24165            synchronized (mPackages) {
24166                // If we do not support permission review, done.
24167                if (!mPermissionReviewRequired) {
24168                    return false;
24169                }
24170
24171                PackageSetting packageSetting = mSettings.mPackages.get(packageName);
24172                if (packageSetting == null) {
24173                    return false;
24174                }
24175
24176                // Permission review applies only to apps not supporting the new permission model.
24177                if (packageSetting.pkg.applicationInfo.targetSdkVersion >= Build.VERSION_CODES.M) {
24178                    return false;
24179                }
24180
24181                // Legacy apps have the permission and get user consent on launch.
24182                PermissionsState permissionsState = packageSetting.getPermissionsState();
24183                return permissionsState.isPermissionReviewRequired(userId);
24184            }
24185        }
24186
24187        @Override
24188        public ApplicationInfo getApplicationInfo(String packageName, int userId) {
24189            return PackageManagerService.this.getApplicationInfo(packageName, 0 /*flags*/, userId);
24190        }
24191
24192        @Override
24193        public ComponentName getHomeActivitiesAsUser(List<ResolveInfo> allHomeCandidates,
24194                int userId) {
24195            return PackageManagerService.this.getHomeActivitiesAsUser(allHomeCandidates, userId);
24196        }
24197
24198        @Override
24199        public void setDeviceAndProfileOwnerPackages(
24200                int deviceOwnerUserId, String deviceOwnerPackage,
24201                SparseArray<String> profileOwnerPackages) {
24202            mProtectedPackages.setDeviceAndProfileOwnerPackages(
24203                    deviceOwnerUserId, deviceOwnerPackage, profileOwnerPackages);
24204        }
24205
24206        @Override
24207        public boolean isPackageDataProtected(int userId, String packageName) {
24208            return mProtectedPackages.isPackageDataProtected(userId, packageName);
24209        }
24210
24211        @Override
24212        public boolean isPackageEphemeral(int userId, String packageName) {
24213            synchronized (mPackages) {
24214                final PackageSetting ps = mSettings.mPackages.get(packageName);
24215                return ps != null ? ps.getInstantApp(userId) : false;
24216            }
24217        }
24218
24219        @Override
24220        public boolean wasPackageEverLaunched(String packageName, int userId) {
24221            synchronized (mPackages) {
24222                return mSettings.wasPackageEverLaunchedLPr(packageName, userId);
24223            }
24224        }
24225
24226        @Override
24227        public void grantRuntimePermission(String packageName, String name, int userId,
24228                boolean overridePolicy) {
24229            PackageManagerService.this.grantRuntimePermission(packageName, name, userId,
24230                    overridePolicy);
24231        }
24232
24233        @Override
24234        public void revokeRuntimePermission(String packageName, String name, int userId,
24235                boolean overridePolicy) {
24236            PackageManagerService.this.revokeRuntimePermission(packageName, name, userId,
24237                    overridePolicy);
24238        }
24239
24240        @Override
24241        public String getNameForUid(int uid) {
24242            return PackageManagerService.this.getNameForUid(uid);
24243        }
24244
24245        @Override
24246        public void requestInstantAppResolutionPhaseTwo(AuxiliaryResolveInfo responseObj,
24247                Intent origIntent, String resolvedType, String callingPackage,
24248                Bundle verificationBundle, int userId) {
24249            PackageManagerService.this.requestInstantAppResolutionPhaseTwo(
24250                    responseObj, origIntent, resolvedType, callingPackage, verificationBundle,
24251                    userId);
24252        }
24253
24254        @Override
24255        public void grantEphemeralAccess(int userId, Intent intent,
24256                int targetAppId, int ephemeralAppId) {
24257            synchronized (mPackages) {
24258                mInstantAppRegistry.grantInstantAccessLPw(userId, intent,
24259                        targetAppId, ephemeralAppId);
24260            }
24261        }
24262
24263        @Override
24264        public boolean isInstantAppInstallerComponent(ComponentName component) {
24265            synchronized (mPackages) {
24266                return mInstantAppInstallerActivity != null
24267                        && mInstantAppInstallerActivity.getComponentName().equals(component);
24268            }
24269        }
24270
24271        @Override
24272        public void pruneInstantApps() {
24273            synchronized (mPackages) {
24274                mInstantAppRegistry.pruneInstantAppsLPw();
24275            }
24276        }
24277
24278        @Override
24279        public String getSetupWizardPackageName() {
24280            return mSetupWizardPackage;
24281        }
24282
24283        public void setExternalSourcesPolicy(ExternalSourcesPolicy policy) {
24284            if (policy != null) {
24285                mExternalSourcesPolicy = policy;
24286            }
24287        }
24288
24289        @Override
24290        public boolean isPackagePersistent(String packageName) {
24291            synchronized (mPackages) {
24292                PackageParser.Package pkg = mPackages.get(packageName);
24293                return pkg != null
24294                        ? ((pkg.applicationInfo.flags&(ApplicationInfo.FLAG_SYSTEM
24295                                        | ApplicationInfo.FLAG_PERSISTENT)) ==
24296                                (ApplicationInfo.FLAG_SYSTEM | ApplicationInfo.FLAG_PERSISTENT))
24297                        : false;
24298            }
24299        }
24300
24301        @Override
24302        public List<PackageInfo> getOverlayPackages(int userId) {
24303            final ArrayList<PackageInfo> overlayPackages = new ArrayList<PackageInfo>();
24304            synchronized (mPackages) {
24305                for (PackageParser.Package p : mPackages.values()) {
24306                    if (p.mOverlayTarget != null) {
24307                        PackageInfo pkg = generatePackageInfo((PackageSetting)p.mExtras, 0, userId);
24308                        if (pkg != null) {
24309                            overlayPackages.add(pkg);
24310                        }
24311                    }
24312                }
24313            }
24314            return overlayPackages;
24315        }
24316
24317        @Override
24318        public List<String> getTargetPackageNames(int userId) {
24319            List<String> targetPackages = new ArrayList<>();
24320            synchronized (mPackages) {
24321                for (PackageParser.Package p : mPackages.values()) {
24322                    if (p.mOverlayTarget == null) {
24323                        targetPackages.add(p.packageName);
24324                    }
24325                }
24326            }
24327            return targetPackages;
24328        }
24329
24330        @Override
24331        public boolean setEnabledOverlayPackages(int userId, @NonNull String targetPackageName,
24332                @Nullable List<String> overlayPackageNames) {
24333            synchronized (mPackages) {
24334                if (targetPackageName == null || mPackages.get(targetPackageName) == null) {
24335                    Slog.e(TAG, "failed to find package " + targetPackageName);
24336                    return false;
24337                }
24338
24339                ArrayList<String> paths = null;
24340                if (overlayPackageNames != null) {
24341                    final int N = overlayPackageNames.size();
24342                    paths = new ArrayList<>(N);
24343                    for (int i = 0; i < N; i++) {
24344                        final String packageName = overlayPackageNames.get(i);
24345                        final PackageParser.Package pkg = mPackages.get(packageName);
24346                        if (pkg == null) {
24347                            Slog.e(TAG, "failed to find package " + packageName);
24348                            return false;
24349                        }
24350                        paths.add(pkg.baseCodePath);
24351                    }
24352                }
24353
24354                ArrayMap<String, ArrayList<String>> userSpecificOverlays =
24355                    mEnabledOverlayPaths.get(userId);
24356                if (userSpecificOverlays == null) {
24357                    userSpecificOverlays = new ArrayMap<>();
24358                    mEnabledOverlayPaths.put(userId, userSpecificOverlays);
24359                }
24360
24361                if (paths != null && paths.size() > 0) {
24362                    userSpecificOverlays.put(targetPackageName, paths);
24363                } else {
24364                    userSpecificOverlays.remove(targetPackageName);
24365                }
24366                return true;
24367            }
24368        }
24369
24370        @Override
24371        public ResolveInfo resolveIntent(Intent intent, String resolvedType,
24372                int flags, int userId) {
24373            return resolveIntentInternal(
24374                    intent, resolvedType, flags, userId, true /*resolveForStart*/);
24375        }
24376
24377        @Override
24378        public ResolveInfo resolveService(Intent intent, String resolvedType,
24379                int flags, int userId, int callingUid) {
24380            return resolveServiceInternal(intent, resolvedType, flags, userId, callingUid);
24381        }
24382
24383        @Override
24384        public void addIsolatedUid(int isolatedUid, int ownerUid) {
24385            synchronized (mPackages) {
24386                mIsolatedOwners.put(isolatedUid, ownerUid);
24387            }
24388        }
24389
24390        @Override
24391        public void removeIsolatedUid(int isolatedUid) {
24392            synchronized (mPackages) {
24393                mIsolatedOwners.delete(isolatedUid);
24394            }
24395        }
24396
24397        @Override
24398        public int getUidTargetSdkVersion(int uid) {
24399            synchronized (mPackages) {
24400                return getUidTargetSdkVersionLockedLPr(uid);
24401            }
24402        }
24403
24404        @Override
24405        public boolean canAccessInstantApps(int callingUid, int userId) {
24406            return PackageManagerService.this.canViewInstantApps(callingUid, userId);
24407        }
24408    }
24409
24410    @Override
24411    public void grantDefaultPermissionsToEnabledCarrierApps(String[] packageNames, int userId) {
24412        enforceSystemOrPhoneCaller("grantPermissionsToEnabledCarrierApps");
24413        synchronized (mPackages) {
24414            final long identity = Binder.clearCallingIdentity();
24415            try {
24416                mDefaultPermissionPolicy.grantDefaultPermissionsToEnabledCarrierAppsLPr(
24417                        packageNames, userId);
24418            } finally {
24419                Binder.restoreCallingIdentity(identity);
24420            }
24421        }
24422    }
24423
24424    @Override
24425    public void grantDefaultPermissionsToEnabledImsServices(String[] packageNames, int userId) {
24426        enforceSystemOrPhoneCaller("grantDefaultPermissionsToEnabledImsServices");
24427        synchronized (mPackages) {
24428            final long identity = Binder.clearCallingIdentity();
24429            try {
24430                mDefaultPermissionPolicy.grantDefaultPermissionsToEnabledImsServicesLPr(
24431                        packageNames, userId);
24432            } finally {
24433                Binder.restoreCallingIdentity(identity);
24434            }
24435        }
24436    }
24437
24438    private static void enforceSystemOrPhoneCaller(String tag) {
24439        int callingUid = Binder.getCallingUid();
24440        if (callingUid != Process.PHONE_UID && callingUid != Process.SYSTEM_UID) {
24441            throw new SecurityException(
24442                    "Cannot call " + tag + " from UID " + callingUid);
24443        }
24444    }
24445
24446    boolean isHistoricalPackageUsageAvailable() {
24447        return mPackageUsage.isHistoricalPackageUsageAvailable();
24448    }
24449
24450    /**
24451     * Return a <b>copy</b> of the collection of packages known to the package manager.
24452     * @return A copy of the values of mPackages.
24453     */
24454    Collection<PackageParser.Package> getPackages() {
24455        synchronized (mPackages) {
24456            return new ArrayList<>(mPackages.values());
24457        }
24458    }
24459
24460    /**
24461     * Logs process start information (including base APK hash) to the security log.
24462     * @hide
24463     */
24464    @Override
24465    public void logAppProcessStartIfNeeded(String processName, int uid, String seinfo,
24466            String apkFile, int pid) {
24467        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
24468            return;
24469        }
24470        if (!SecurityLog.isLoggingEnabled()) {
24471            return;
24472        }
24473        Bundle data = new Bundle();
24474        data.putLong("startTimestamp", System.currentTimeMillis());
24475        data.putString("processName", processName);
24476        data.putInt("uid", uid);
24477        data.putString("seinfo", seinfo);
24478        data.putString("apkFile", apkFile);
24479        data.putInt("pid", pid);
24480        Message msg = mProcessLoggingHandler.obtainMessage(
24481                ProcessLoggingHandler.LOG_APP_PROCESS_START_MSG);
24482        msg.setData(data);
24483        mProcessLoggingHandler.sendMessage(msg);
24484    }
24485
24486    public CompilerStats.PackageStats getCompilerPackageStats(String pkgName) {
24487        return mCompilerStats.getPackageStats(pkgName);
24488    }
24489
24490    public CompilerStats.PackageStats getOrCreateCompilerPackageStats(PackageParser.Package pkg) {
24491        return getOrCreateCompilerPackageStats(pkg.packageName);
24492    }
24493
24494    public CompilerStats.PackageStats getOrCreateCompilerPackageStats(String pkgName) {
24495        return mCompilerStats.getOrCreatePackageStats(pkgName);
24496    }
24497
24498    public void deleteCompilerPackageStats(String pkgName) {
24499        mCompilerStats.deletePackageStats(pkgName);
24500    }
24501
24502    @Override
24503    public int getInstallReason(String packageName, int userId) {
24504        final int callingUid = Binder.getCallingUid();
24505        enforceCrossUserPermission(callingUid, userId,
24506                true /* requireFullPermission */, false /* checkShell */,
24507                "get install reason");
24508        synchronized (mPackages) {
24509            final PackageSetting ps = mSettings.mPackages.get(packageName);
24510            if (filterAppAccessLPr(ps, callingUid, userId)) {
24511                return PackageManager.INSTALL_REASON_UNKNOWN;
24512            }
24513            if (ps != null) {
24514                return ps.getInstallReason(userId);
24515            }
24516        }
24517        return PackageManager.INSTALL_REASON_UNKNOWN;
24518    }
24519
24520    @Override
24521    public boolean canRequestPackageInstalls(String packageName, int userId) {
24522        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
24523            return false;
24524        }
24525        return canRequestPackageInstallsInternal(packageName, 0, userId,
24526                true /* throwIfPermNotDeclared*/);
24527    }
24528
24529    private boolean canRequestPackageInstallsInternal(String packageName, int flags, int userId,
24530            boolean throwIfPermNotDeclared) {
24531        int callingUid = Binder.getCallingUid();
24532        int uid = getPackageUid(packageName, 0, userId);
24533        if (callingUid != uid && callingUid != Process.ROOT_UID
24534                && callingUid != Process.SYSTEM_UID) {
24535            throw new SecurityException(
24536                    "Caller uid " + callingUid + " does not own package " + packageName);
24537        }
24538        ApplicationInfo info = getApplicationInfo(packageName, flags, userId);
24539        if (info == null) {
24540            return false;
24541        }
24542        if (info.targetSdkVersion < Build.VERSION_CODES.O) {
24543            return false;
24544        }
24545        String appOpPermission = Manifest.permission.REQUEST_INSTALL_PACKAGES;
24546        String[] packagesDeclaringPermission = getAppOpPermissionPackages(appOpPermission);
24547        if (!ArrayUtils.contains(packagesDeclaringPermission, packageName)) {
24548            if (throwIfPermNotDeclared) {
24549                throw new SecurityException("Need to declare " + appOpPermission
24550                        + " to call this api");
24551            } else {
24552                Slog.e(TAG, "Need to declare " + appOpPermission + " to call this api");
24553                return false;
24554            }
24555        }
24556        if (sUserManager.hasUserRestriction(UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES, userId)) {
24557            return false;
24558        }
24559        if (mExternalSourcesPolicy != null) {
24560            int isTrusted = mExternalSourcesPolicy.getPackageTrustedToInstallApps(packageName, uid);
24561            if (isTrusted != PackageManagerInternal.ExternalSourcesPolicy.USER_DEFAULT) {
24562                return isTrusted == PackageManagerInternal.ExternalSourcesPolicy.USER_TRUSTED;
24563            }
24564        }
24565        return checkUidPermission(appOpPermission, uid) == PERMISSION_GRANTED;
24566    }
24567
24568    @Override
24569    public ComponentName getInstantAppResolverSettingsComponent() {
24570        return mInstantAppResolverSettingsComponent;
24571    }
24572
24573    @Override
24574    public ComponentName getInstantAppInstallerComponent() {
24575        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
24576            return null;
24577        }
24578        return mInstantAppInstallerActivity == null
24579                ? null : mInstantAppInstallerActivity.getComponentName();
24580    }
24581
24582    @Override
24583    public String getInstantAppAndroidId(String packageName, int userId) {
24584        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.ACCESS_INSTANT_APPS,
24585                "getInstantAppAndroidId");
24586        enforceCrossUserPermission(Binder.getCallingUid(), userId,
24587                true /* requireFullPermission */, false /* checkShell */,
24588                "getInstantAppAndroidId");
24589        // Make sure the target is an Instant App.
24590        if (!isInstantApp(packageName, userId)) {
24591            return null;
24592        }
24593        synchronized (mPackages) {
24594            return mInstantAppRegistry.getInstantAppAndroidIdLPw(packageName, userId);
24595        }
24596    }
24597}
24598
24599interface PackageSender {
24600    void sendPackageBroadcast(final String action, final String pkg,
24601        final Bundle extras, final int flags, final String targetPkg,
24602        final IIntentReceiver finishedReceiver, final int[] userIds);
24603    void sendPackageAddedForNewUsers(String packageName, boolean isSystem,
24604        int appId, int... userIds);
24605}
24606