PackageManagerService.java revision 23a2a0dae0b10d12cbf5f79bdcaa6fba537779bf
1/*
2 * Copyright (C) 2006 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 *      http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17package com.android.server.pm;
18
19import static android.Manifest.permission.DELETE_PACKAGES;
20import static android.Manifest.permission.INSTALL_PACKAGES;
21import static android.Manifest.permission.MANAGE_PROFILE_AND_DEVICE_OWNERS;
22import static android.Manifest.permission.READ_EXTERNAL_STORAGE;
23import static android.Manifest.permission.REQUEST_DELETE_PACKAGES;
24import static android.Manifest.permission.WRITE_EXTERNAL_STORAGE;
25import static android.Manifest.permission.WRITE_MEDIA_STORAGE;
26import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DEFAULT;
27import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED;
28import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED;
29import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED_USER;
30import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_ENABLED;
31import static android.content.pm.PackageManager.DELETE_KEEP_DATA;
32import static android.content.pm.PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT;
33import static android.content.pm.PackageManager.FLAG_PERMISSION_POLICY_FIXED;
34import static android.content.pm.PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED;
35import static android.content.pm.PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE;
36import static android.content.pm.PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
37import static android.content.pm.PackageManager.FLAG_PERMISSION_USER_FIXED;
38import static android.content.pm.PackageManager.FLAG_PERMISSION_USER_SET;
39import static android.content.pm.PackageManager.INSTALL_EXTERNAL;
40import static android.content.pm.PackageManager.INSTALL_FAILED_ALREADY_EXISTS;
41import static android.content.pm.PackageManager.INSTALL_FAILED_CONFLICTING_PROVIDER;
42import static android.content.pm.PackageManager.INSTALL_FAILED_DUPLICATE_PACKAGE;
43import static android.content.pm.PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION;
44import static android.content.pm.PackageManager.INSTALL_FAILED_INSTANT_APP_INVALID;
45import static android.content.pm.PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
46import static android.content.pm.PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
47import static android.content.pm.PackageManager.INSTALL_FAILED_INVALID_APK;
48import static android.content.pm.PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
49import static android.content.pm.PackageManager.INSTALL_FAILED_MISSING_SHARED_LIBRARY;
50import static android.content.pm.PackageManager.INSTALL_FAILED_PACKAGE_CHANGED;
51import static android.content.pm.PackageManager.INSTALL_FAILED_REPLACE_COULDNT_DELETE;
52import static android.content.pm.PackageManager.INSTALL_FAILED_SANDBOX_VERSION_DOWNGRADE;
53import static android.content.pm.PackageManager.INSTALL_FAILED_SHARED_USER_INCOMPATIBLE;
54import static android.content.pm.PackageManager.INSTALL_FAILED_TEST_ONLY;
55import static android.content.pm.PackageManager.INSTALL_FAILED_UPDATE_INCOMPATIBLE;
56import static android.content.pm.PackageManager.INSTALL_FAILED_USER_RESTRICTED;
57import static android.content.pm.PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE;
58import static android.content.pm.PackageManager.INSTALL_FORWARD_LOCK;
59import static android.content.pm.PackageManager.INSTALL_INTERNAL;
60import static android.content.pm.PackageManager.INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES;
61import static android.content.pm.PackageManager.INSTALL_PARSE_FAILED_MANIFEST_MALFORMED;
62import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS;
63import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK;
64import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK;
65import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER;
66import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED;
67import static android.content.pm.PackageManager.MATCH_ALL;
68import static android.content.pm.PackageManager.MATCH_ANY_USER;
69import static android.content.pm.PackageManager.MATCH_DEBUG_TRIAGED_MISSING;
70import static android.content.pm.PackageManager.MATCH_DIRECT_BOOT_AWARE;
71import static android.content.pm.PackageManager.MATCH_DIRECT_BOOT_UNAWARE;
72import static android.content.pm.PackageManager.MATCH_DISABLED_COMPONENTS;
73import static android.content.pm.PackageManager.MATCH_FACTORY_ONLY;
74import static android.content.pm.PackageManager.MATCH_KNOWN_PACKAGES;
75import static android.content.pm.PackageManager.MATCH_SYSTEM_ONLY;
76import static android.content.pm.PackageManager.MATCH_UNINSTALLED_PACKAGES;
77import static android.content.pm.PackageManager.MOVE_FAILED_3RD_PARTY_NOT_ALLOWED_ON_INTERNAL;
78import static android.content.pm.PackageManager.MOVE_FAILED_DEVICE_ADMIN;
79import static android.content.pm.PackageManager.MOVE_FAILED_DOESNT_EXIST;
80import static android.content.pm.PackageManager.MOVE_FAILED_INTERNAL_ERROR;
81import static android.content.pm.PackageManager.MOVE_FAILED_OPERATION_PENDING;
82import static android.content.pm.PackageManager.MOVE_FAILED_SYSTEM_PACKAGE;
83import static android.content.pm.PackageManager.PERMISSION_DENIED;
84import static android.content.pm.PackageManager.PERMISSION_GRANTED;
85import static android.content.pm.PackageParser.PARSE_IS_PRIVILEGED;
86import static android.content.pm.PackageParser.isApkFile;
87import static android.os.Trace.TRACE_TAG_PACKAGE_MANAGER;
88import static android.system.OsConstants.O_CREAT;
89import static android.system.OsConstants.O_RDWR;
90import static com.android.internal.app.IntentForwarderActivity.FORWARD_INTENT_TO_MANAGED_PROFILE;
91import static com.android.internal.app.IntentForwarderActivity.FORWARD_INTENT_TO_PARENT;
92import static com.android.internal.content.NativeLibraryHelper.LIB64_DIR_NAME;
93import static com.android.internal.content.NativeLibraryHelper.LIB_DIR_NAME;
94import static com.android.internal.util.ArrayUtils.appendInt;
95import static com.android.server.pm.InstructionSets.getAppDexInstructionSets;
96import static com.android.server.pm.InstructionSets.getDexCodeInstructionSet;
97import static com.android.server.pm.InstructionSets.getDexCodeInstructionSets;
98import static com.android.server.pm.InstructionSets.getPreferredInstructionSet;
99import static com.android.server.pm.InstructionSets.getPrimaryInstructionSet;
100import static com.android.server.pm.PackageManagerServiceCompilerMapping.getCompilerFilterForReason;
101import static com.android.server.pm.PackageManagerServiceCompilerMapping.getDefaultCompilerFilter;
102import static com.android.server.pm.PermissionsState.PERMISSION_OPERATION_FAILURE;
103import static com.android.server.pm.PermissionsState.PERMISSION_OPERATION_SUCCESS;
104import static com.android.server.pm.PermissionsState.PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED;
105import static dalvik.system.DexFile.getNonProfileGuidedCompilerFilter;
106
107import android.Manifest;
108import android.annotation.IntDef;
109import android.annotation.NonNull;
110import android.annotation.Nullable;
111import android.app.ActivityManager;
112import android.app.AppOpsManager;
113import android.app.IActivityManager;
114import android.app.ResourcesManager;
115import android.app.admin.IDevicePolicyManager;
116import android.app.admin.SecurityLog;
117import android.app.backup.IBackupManager;
118import android.content.BroadcastReceiver;
119import android.content.ComponentName;
120import android.content.ContentResolver;
121import android.content.Context;
122import android.content.IIntentReceiver;
123import android.content.Intent;
124import android.content.IntentFilter;
125import android.content.IntentSender;
126import android.content.IntentSender.SendIntentException;
127import android.content.ServiceConnection;
128import android.content.pm.ActivityInfo;
129import android.content.pm.ApplicationInfo;
130import android.content.pm.AppsQueryHelper;
131import android.content.pm.AuxiliaryResolveInfo;
132import android.content.pm.ChangedPackages;
133import android.content.pm.FallbackCategoryProvider;
134import android.content.pm.FeatureInfo;
135import android.content.pm.IDexModuleRegisterCallback;
136import android.content.pm.IOnPermissionsChangeListener;
137import android.content.pm.IPackageDataObserver;
138import android.content.pm.IPackageDeleteObserver;
139import android.content.pm.IPackageDeleteObserver2;
140import android.content.pm.IPackageInstallObserver2;
141import android.content.pm.IPackageInstaller;
142import android.content.pm.IPackageManager;
143import android.content.pm.IPackageMoveObserver;
144import android.content.pm.IPackageStatsObserver;
145import android.content.pm.InstantAppInfo;
146import android.content.pm.InstantAppRequest;
147import android.content.pm.InstantAppResolveInfo;
148import android.content.pm.InstrumentationInfo;
149import android.content.pm.IntentFilterVerificationInfo;
150import android.content.pm.KeySet;
151import android.content.pm.PackageCleanItem;
152import android.content.pm.PackageInfo;
153import android.content.pm.PackageInfoLite;
154import android.content.pm.PackageInstaller;
155import android.content.pm.PackageManager;
156import android.content.pm.PackageManager.LegacyPackageDeleteObserver;
157import android.content.pm.PackageManagerInternal;
158import android.content.pm.PackageParser;
159import android.content.pm.PackageParser.ActivityIntentInfo;
160import android.content.pm.PackageParser.PackageLite;
161import android.content.pm.PackageParser.PackageParserException;
162import android.content.pm.PackageStats;
163import android.content.pm.PackageUserState;
164import android.content.pm.ParceledListSlice;
165import android.content.pm.PermissionGroupInfo;
166import android.content.pm.PermissionInfo;
167import android.content.pm.ProviderInfo;
168import android.content.pm.ResolveInfo;
169import android.content.pm.ServiceInfo;
170import android.content.pm.SharedLibraryInfo;
171import android.content.pm.Signature;
172import android.content.pm.UserInfo;
173import android.content.pm.VerifierDeviceIdentity;
174import android.content.pm.VerifierInfo;
175import android.content.pm.VersionedPackage;
176import android.content.res.Resources;
177import android.database.ContentObserver;
178import android.graphics.Bitmap;
179import android.hardware.display.DisplayManager;
180import android.net.Uri;
181import android.os.Binder;
182import android.os.Build;
183import android.os.Bundle;
184import android.os.Debug;
185import android.os.Environment;
186import android.os.Environment.UserEnvironment;
187import android.os.FileUtils;
188import android.os.Handler;
189import android.os.IBinder;
190import android.os.Looper;
191import android.os.Message;
192import android.os.Parcel;
193import android.os.ParcelFileDescriptor;
194import android.os.PatternMatcher;
195import android.os.Process;
196import android.os.RemoteCallbackList;
197import android.os.RemoteException;
198import android.os.ResultReceiver;
199import android.os.SELinux;
200import android.os.ServiceManager;
201import android.os.ShellCallback;
202import android.os.SystemClock;
203import android.os.SystemProperties;
204import android.os.Trace;
205import android.os.UserHandle;
206import android.os.UserManager;
207import android.os.UserManagerInternal;
208import android.os.storage.IStorageManager;
209import android.os.storage.StorageEventListener;
210import android.os.storage.StorageManager;
211import android.os.storage.StorageManagerInternal;
212import android.os.storage.VolumeInfo;
213import android.os.storage.VolumeRecord;
214import android.provider.Settings.Global;
215import android.provider.Settings.Secure;
216import android.security.KeyStore;
217import android.security.SystemKeyStore;
218import android.service.pm.PackageServiceDumpProto;
219import android.system.ErrnoException;
220import android.system.Os;
221import android.text.TextUtils;
222import android.text.format.DateUtils;
223import android.util.ArrayMap;
224import android.util.ArraySet;
225import android.util.Base64;
226import android.util.BootTimingsTraceLog;
227import android.util.DisplayMetrics;
228import android.util.EventLog;
229import android.util.ExceptionUtils;
230import android.util.Log;
231import android.util.LogPrinter;
232import android.util.MathUtils;
233import android.util.PackageUtils;
234import android.util.Pair;
235import android.util.PrintStreamPrinter;
236import android.util.Slog;
237import android.util.SparseArray;
238import android.util.SparseBooleanArray;
239import android.util.SparseIntArray;
240import android.util.Xml;
241import android.util.jar.StrictJarFile;
242import android.util.proto.ProtoOutputStream;
243import android.view.Display;
244
245import com.android.internal.R;
246import com.android.internal.annotations.GuardedBy;
247import com.android.internal.app.IMediaContainerService;
248import com.android.internal.app.ResolverActivity;
249import com.android.internal.content.NativeLibraryHelper;
250import com.android.internal.content.PackageHelper;
251import com.android.internal.logging.MetricsLogger;
252import com.android.internal.logging.nano.MetricsProto.MetricsEvent;
253import com.android.internal.os.IParcelFileDescriptorFactory;
254import com.android.internal.os.RoSystemProperties;
255import com.android.internal.os.SomeArgs;
256import com.android.internal.os.Zygote;
257import com.android.internal.telephony.CarrierAppUtils;
258import com.android.internal.util.ArrayUtils;
259import com.android.internal.util.ConcurrentUtils;
260import com.android.internal.util.DumpUtils;
261import com.android.internal.util.FastPrintWriter;
262import com.android.internal.util.FastXmlSerializer;
263import com.android.internal.util.IndentingPrintWriter;
264import com.android.internal.util.Preconditions;
265import com.android.internal.util.XmlUtils;
266import com.android.server.AttributeCache;
267import com.android.server.DeviceIdleController;
268import com.android.server.EventLogTags;
269import com.android.server.FgThread;
270import com.android.server.IntentResolver;
271import com.android.server.LocalServices;
272import com.android.server.LockGuard;
273import com.android.server.ServiceThread;
274import com.android.server.SystemConfig;
275import com.android.server.SystemServerInitThreadPool;
276import com.android.server.Watchdog;
277import com.android.server.net.NetworkPolicyManagerInternal;
278import com.android.server.pm.Installer.InstallerException;
279import com.android.server.pm.PermissionsState.PermissionState;
280import com.android.server.pm.Settings.DatabaseVersion;
281import com.android.server.pm.Settings.VersionInfo;
282import com.android.server.pm.dex.DexManager;
283import com.android.server.storage.DeviceStorageMonitorInternal;
284
285import dalvik.system.CloseGuard;
286import dalvik.system.DexFile;
287import dalvik.system.VMRuntime;
288
289import libcore.io.IoUtils;
290import libcore.util.EmptyArray;
291
292import org.xmlpull.v1.XmlPullParser;
293import org.xmlpull.v1.XmlPullParserException;
294import org.xmlpull.v1.XmlSerializer;
295
296import java.io.BufferedOutputStream;
297import java.io.BufferedReader;
298import java.io.ByteArrayInputStream;
299import java.io.ByteArrayOutputStream;
300import java.io.File;
301import java.io.FileDescriptor;
302import java.io.FileInputStream;
303import java.io.FileOutputStream;
304import java.io.FileReader;
305import java.io.FilenameFilter;
306import java.io.IOException;
307import java.io.PrintWriter;
308import java.lang.annotation.Retention;
309import java.lang.annotation.RetentionPolicy;
310import java.nio.charset.StandardCharsets;
311import java.security.DigestInputStream;
312import java.security.MessageDigest;
313import java.security.NoSuchAlgorithmException;
314import java.security.PublicKey;
315import java.security.SecureRandom;
316import java.security.cert.Certificate;
317import java.security.cert.CertificateEncodingException;
318import java.security.cert.CertificateException;
319import java.text.SimpleDateFormat;
320import java.util.ArrayList;
321import java.util.Arrays;
322import java.util.Collection;
323import java.util.Collections;
324import java.util.Comparator;
325import java.util.Date;
326import java.util.HashMap;
327import java.util.HashSet;
328import java.util.Iterator;
329import java.util.List;
330import java.util.Map;
331import java.util.Objects;
332import java.util.Set;
333import java.util.concurrent.CountDownLatch;
334import java.util.concurrent.Future;
335import java.util.concurrent.TimeUnit;
336import java.util.concurrent.atomic.AtomicBoolean;
337import java.util.concurrent.atomic.AtomicInteger;
338
339/**
340 * Keep track of all those APKs everywhere.
341 * <p>
342 * Internally there are two important locks:
343 * <ul>
344 * <li>{@link #mPackages} is used to guard all in-memory parsed package details
345 * and other related state. It is a fine-grained lock that should only be held
346 * momentarily, as it's one of the most contended locks in the system.
347 * <li>{@link #mInstallLock} is used to guard all {@code installd} access, whose
348 * operations typically involve heavy lifting of application data on disk. Since
349 * {@code installd} is single-threaded, and it's operations can often be slow,
350 * this lock should never be acquired while already holding {@link #mPackages}.
351 * Conversely, it's safe to acquire {@link #mPackages} momentarily while already
352 * holding {@link #mInstallLock}.
353 * </ul>
354 * Many internal methods rely on the caller to hold the appropriate locks, and
355 * this contract is expressed through method name suffixes:
356 * <ul>
357 * <li>fooLI(): the caller must hold {@link #mInstallLock}
358 * <li>fooLIF(): the caller must hold {@link #mInstallLock} and the package
359 * being modified must be frozen
360 * <li>fooLPr(): the caller must hold {@link #mPackages} for reading
361 * <li>fooLPw(): the caller must hold {@link #mPackages} for writing
362 * </ul>
363 * <p>
364 * Because this class is very central to the platform's security; please run all
365 * CTS and unit tests whenever making modifications:
366 *
367 * <pre>
368 * $ runtest -c android.content.pm.PackageManagerTests frameworks-core
369 * $ cts-tradefed run commandAndExit cts -m CtsAppSecurityHostTestCases
370 * </pre>
371 */
372public class PackageManagerService extends IPackageManager.Stub
373        implements PackageSender {
374    static final String TAG = "PackageManager";
375    static final boolean DEBUG_SETTINGS = false;
376    static final boolean DEBUG_PREFERRED = false;
377    static final boolean DEBUG_UPGRADE = false;
378    static final boolean DEBUG_DOMAIN_VERIFICATION = false;
379    private static final boolean DEBUG_BACKUP = false;
380    private static final boolean DEBUG_INSTALL = false;
381    private static final boolean DEBUG_REMOVE = false;
382    private static final boolean DEBUG_BROADCASTS = false;
383    private static final boolean DEBUG_SHOW_INFO = false;
384    private static final boolean DEBUG_PACKAGE_INFO = false;
385    private static final boolean DEBUG_INTENT_MATCHING = false;
386    private static final boolean DEBUG_PACKAGE_SCANNING = false;
387    private static final boolean DEBUG_VERIFY = false;
388    private static final boolean DEBUG_FILTERS = false;
389    private static final boolean DEBUG_PERMISSIONS = false;
390    private static final boolean DEBUG_SHARED_LIBRARIES = false;
391
392    // Debug output for dexopting. This is shared between PackageManagerService, OtaDexoptService
393    // and PackageDexOptimizer. All these classes have their own flag to allow switching a single
394    // user, but by default initialize to this.
395    public static final boolean DEBUG_DEXOPT = false;
396
397    private static final boolean DEBUG_ABI_SELECTION = false;
398    private static final boolean DEBUG_EPHEMERAL = Build.IS_DEBUGGABLE;
399    private static final boolean DEBUG_TRIAGED_MISSING = false;
400    private static final boolean DEBUG_APP_DATA = false;
401
402    /** REMOVE. According to Svet, this was only used to reset permissions during development. */
403    static final boolean CLEAR_RUNTIME_PERMISSIONS_ON_UPGRADE = false;
404
405    private static final boolean HIDE_EPHEMERAL_APIS = false;
406
407    private static final boolean ENABLE_FREE_CACHE_V2 =
408            SystemProperties.getBoolean("fw.free_cache_v2", true);
409
410    private static final int RADIO_UID = Process.PHONE_UID;
411    private static final int LOG_UID = Process.LOG_UID;
412    private static final int NFC_UID = Process.NFC_UID;
413    private static final int BLUETOOTH_UID = Process.BLUETOOTH_UID;
414    private static final int SHELL_UID = Process.SHELL_UID;
415
416    // Cap the size of permission trees that 3rd party apps can define
417    private static final int MAX_PERMISSION_TREE_FOOTPRINT = 32768;     // characters of text
418
419    // Suffix used during package installation when copying/moving
420    // package apks to install directory.
421    private static final String INSTALL_PACKAGE_SUFFIX = "-";
422
423    static final int SCAN_NO_DEX = 1<<1;
424    static final int SCAN_FORCE_DEX = 1<<2;
425    static final int SCAN_UPDATE_SIGNATURE = 1<<3;
426    static final int SCAN_NEW_INSTALL = 1<<4;
427    static final int SCAN_UPDATE_TIME = 1<<5;
428    static final int SCAN_BOOTING = 1<<6;
429    static final int SCAN_TRUSTED_OVERLAY = 1<<7;
430    static final int SCAN_DELETE_DATA_ON_FAILURES = 1<<8;
431    static final int SCAN_REPLACING = 1<<9;
432    static final int SCAN_REQUIRE_KNOWN = 1<<10;
433    static final int SCAN_MOVE = 1<<11;
434    static final int SCAN_INITIAL = 1<<12;
435    static final int SCAN_CHECK_ONLY = 1<<13;
436    static final int SCAN_DONT_KILL_APP = 1<<14;
437    static final int SCAN_IGNORE_FROZEN = 1<<15;
438    static final int SCAN_FIRST_BOOT_OR_UPGRADE = 1<<16;
439    static final int SCAN_AS_INSTANT_APP = 1<<17;
440    static final int SCAN_AS_FULL_APP = 1<<18;
441    /** Should not be with the scan flags */
442    static final int FLAGS_REMOVE_CHATTY = 1<<31;
443
444    private static final String STATIC_SHARED_LIB_DELIMITER = "_";
445
446    private static final int[] EMPTY_INT_ARRAY = new int[0];
447
448    private static final int TYPE_UNKNOWN = 0;
449    private static final int TYPE_ACTIVITY = 1;
450    private static final int TYPE_RECEIVER = 2;
451    private static final int TYPE_SERVICE = 3;
452    private static final int TYPE_PROVIDER = 4;
453    @IntDef(prefix = { "TYPE_" }, value = {
454            TYPE_UNKNOWN,
455            TYPE_ACTIVITY,
456            TYPE_RECEIVER,
457            TYPE_SERVICE,
458            TYPE_PROVIDER,
459    })
460    @Retention(RetentionPolicy.SOURCE)
461    public @interface ComponentType {}
462
463    /**
464     * Timeout (in milliseconds) after which the watchdog should declare that
465     * our handler thread is wedged.  The usual default for such things is one
466     * minute but we sometimes do very lengthy I/O operations on this thread,
467     * such as installing multi-gigabyte applications, so ours needs to be longer.
468     */
469    static final long WATCHDOG_TIMEOUT = 1000*60*10;     // ten minutes
470
471    /**
472     * Wall-clock timeout (in milliseconds) after which we *require* that an fstrim
473     * be run on this device.  We use the value in the Settings.Global.MANDATORY_FSTRIM_INTERVAL
474     * settings entry if available, otherwise we use the hardcoded default.  If it's been
475     * more than this long since the last fstrim, we force one during the boot sequence.
476     *
477     * This backstops other fstrim scheduling:  if the device is alive at midnight+idle,
478     * one gets run at the next available charging+idle time.  This final mandatory
479     * no-fstrim check kicks in only of the other scheduling criteria is never met.
480     */
481    private static final long DEFAULT_MANDATORY_FSTRIM_INTERVAL = 3 * DateUtils.DAY_IN_MILLIS;
482
483    /**
484     * Whether verification is enabled by default.
485     */
486    private static final boolean DEFAULT_VERIFY_ENABLE = true;
487
488    /**
489     * The default maximum time to wait for the verification agent to return in
490     * milliseconds.
491     */
492    private static final long DEFAULT_VERIFICATION_TIMEOUT = 10 * 1000;
493
494    /**
495     * The default response for package verification timeout.
496     *
497     * This can be either PackageManager.VERIFICATION_ALLOW or
498     * PackageManager.VERIFICATION_REJECT.
499     */
500    private static final int DEFAULT_VERIFICATION_RESPONSE = PackageManager.VERIFICATION_ALLOW;
501
502    static final String PLATFORM_PACKAGE_NAME = "android";
503
504    static final String DEFAULT_CONTAINER_PACKAGE = "com.android.defcontainer";
505
506    static final ComponentName DEFAULT_CONTAINER_COMPONENT = new ComponentName(
507            DEFAULT_CONTAINER_PACKAGE,
508            "com.android.defcontainer.DefaultContainerService");
509
510    private static final String KILL_APP_REASON_GIDS_CHANGED =
511            "permission grant or revoke changed gids";
512
513    private static final String KILL_APP_REASON_PERMISSIONS_REVOKED =
514            "permissions revoked";
515
516    private static final String PACKAGE_MIME_TYPE = "application/vnd.android.package-archive";
517
518    private static final String PACKAGE_SCHEME = "package";
519
520    private static final String VENDOR_OVERLAY_DIR = "/vendor/overlay";
521
522    /** Permission grant: not grant the permission. */
523    private static final int GRANT_DENIED = 1;
524
525    /** Permission grant: grant the permission as an install permission. */
526    private static final int GRANT_INSTALL = 2;
527
528    /** Permission grant: grant the permission as a runtime one. */
529    private static final int GRANT_RUNTIME = 3;
530
531    /** Permission grant: grant as runtime a permission that was granted as an install time one. */
532    private static final int GRANT_UPGRADE = 4;
533
534    /** Canonical intent used to identify what counts as a "web browser" app */
535    private static final Intent sBrowserIntent;
536    static {
537        sBrowserIntent = new Intent();
538        sBrowserIntent.setAction(Intent.ACTION_VIEW);
539        sBrowserIntent.addCategory(Intent.CATEGORY_BROWSABLE);
540        sBrowserIntent.setData(Uri.parse("http:"));
541    }
542
543    /**
544     * The set of all protected actions [i.e. those actions for which a high priority
545     * intent filter is disallowed].
546     */
547    private static final Set<String> PROTECTED_ACTIONS = new ArraySet<>();
548    static {
549        PROTECTED_ACTIONS.add(Intent.ACTION_SEND);
550        PROTECTED_ACTIONS.add(Intent.ACTION_SENDTO);
551        PROTECTED_ACTIONS.add(Intent.ACTION_SEND_MULTIPLE);
552        PROTECTED_ACTIONS.add(Intent.ACTION_VIEW);
553    }
554
555    // Compilation reasons.
556    public static final int REASON_FIRST_BOOT = 0;
557    public static final int REASON_BOOT = 1;
558    public static final int REASON_INSTALL = 2;
559    public static final int REASON_BACKGROUND_DEXOPT = 3;
560    public static final int REASON_AB_OTA = 4;
561
562    public static final int REASON_LAST = REASON_AB_OTA;
563
564    /** All dangerous permission names in the same order as the events in MetricsEvent */
565    private static final List<String> ALL_DANGEROUS_PERMISSIONS = Arrays.asList(
566            Manifest.permission.READ_CALENDAR,
567            Manifest.permission.WRITE_CALENDAR,
568            Manifest.permission.CAMERA,
569            Manifest.permission.READ_CONTACTS,
570            Manifest.permission.WRITE_CONTACTS,
571            Manifest.permission.GET_ACCOUNTS,
572            Manifest.permission.ACCESS_FINE_LOCATION,
573            Manifest.permission.ACCESS_COARSE_LOCATION,
574            Manifest.permission.RECORD_AUDIO,
575            Manifest.permission.READ_PHONE_STATE,
576            Manifest.permission.CALL_PHONE,
577            Manifest.permission.READ_CALL_LOG,
578            Manifest.permission.WRITE_CALL_LOG,
579            Manifest.permission.ADD_VOICEMAIL,
580            Manifest.permission.USE_SIP,
581            Manifest.permission.PROCESS_OUTGOING_CALLS,
582            Manifest.permission.READ_CELL_BROADCASTS,
583            Manifest.permission.BODY_SENSORS,
584            Manifest.permission.SEND_SMS,
585            Manifest.permission.RECEIVE_SMS,
586            Manifest.permission.READ_SMS,
587            Manifest.permission.RECEIVE_WAP_PUSH,
588            Manifest.permission.RECEIVE_MMS,
589            Manifest.permission.READ_EXTERNAL_STORAGE,
590            Manifest.permission.WRITE_EXTERNAL_STORAGE,
591            Manifest.permission.READ_PHONE_NUMBERS,
592            Manifest.permission.ANSWER_PHONE_CALLS);
593
594
595    /**
596     * Version number for the package parser cache. Increment this whenever the format or
597     * extent of cached data changes. See {@code PackageParser#setCacheDir}.
598     */
599    private static final String PACKAGE_PARSER_CACHE_VERSION = "1";
600
601    /**
602     * Whether the package parser cache is enabled.
603     */
604    private static final boolean DEFAULT_PACKAGE_PARSER_CACHE_ENABLED = true;
605
606    final ServiceThread mHandlerThread;
607
608    final PackageHandler mHandler;
609
610    private final ProcessLoggingHandler mProcessLoggingHandler;
611
612    /**
613     * Messages for {@link #mHandler} that need to wait for system ready before
614     * being dispatched.
615     */
616    private ArrayList<Message> mPostSystemReadyMessages;
617
618    final int mSdkVersion = Build.VERSION.SDK_INT;
619
620    final Context mContext;
621    final boolean mFactoryTest;
622    final boolean mOnlyCore;
623    final DisplayMetrics mMetrics;
624    final int mDefParseFlags;
625    final String[] mSeparateProcesses;
626    final boolean mIsUpgrade;
627    final boolean mIsPreNUpgrade;
628    final boolean mIsPreNMR1Upgrade;
629
630    // Have we told the Activity Manager to whitelist the default container service by uid yet?
631    @GuardedBy("mPackages")
632    boolean mDefaultContainerWhitelisted = false;
633
634    @GuardedBy("mPackages")
635    private boolean mDexOptDialogShown;
636
637    /** The location for ASEC container files on internal storage. */
638    final String mAsecInternalPath;
639
640    // Used for privilege escalation. MUST NOT BE CALLED WITH mPackages
641    // LOCK HELD.  Can be called with mInstallLock held.
642    @GuardedBy("mInstallLock")
643    final Installer mInstaller;
644
645    /** Directory where installed third-party apps stored */
646    final File mAppInstallDir;
647
648    /**
649     * Directory to which applications installed internally have their
650     * 32 bit native libraries copied.
651     */
652    private File mAppLib32InstallDir;
653
654    // Directory containing the private parts (e.g. code and non-resource assets) of forward-locked
655    // apps.
656    final File mDrmAppPrivateInstallDir;
657
658    // ----------------------------------------------------------------
659
660    // Lock for state used when installing and doing other long running
661    // operations.  Methods that must be called with this lock held have
662    // the suffix "LI".
663    final Object mInstallLock = new Object();
664
665    // ----------------------------------------------------------------
666
667    // Keys are String (package name), values are Package.  This also serves
668    // as the lock for the global state.  Methods that must be called with
669    // this lock held have the prefix "LP".
670    @GuardedBy("mPackages")
671    final ArrayMap<String, PackageParser.Package> mPackages =
672            new ArrayMap<String, PackageParser.Package>();
673
674    final ArrayMap<String, Set<String>> mKnownCodebase =
675            new ArrayMap<String, Set<String>>();
676
677    // Keys are isolated uids and values are the uid of the application
678    // that created the isolated proccess.
679    @GuardedBy("mPackages")
680    final SparseIntArray mIsolatedOwners = new SparseIntArray();
681
682    /**
683     * Tracks new system packages [received in an OTA] that we expect to
684     * find updated user-installed versions. Keys are package name, values
685     * are package location.
686     */
687    final private ArrayMap<String, File> mExpectingBetter = new ArrayMap<>();
688    /**
689     * Tracks high priority intent filters for protected actions. During boot, certain
690     * filter actions are protected and should never be allowed to have a high priority
691     * intent filter for them. However, there is one, and only one exception -- the
692     * setup wizard. It must be able to define a high priority intent filter for these
693     * actions to ensure there are no escapes from the wizard. We need to delay processing
694     * of these during boot as we need to look at all of the system packages in order
695     * to know which component is the setup wizard.
696     */
697    private final List<PackageParser.ActivityIntentInfo> mProtectedFilters = new ArrayList<>();
698    /**
699     * Whether or not processing protected filters should be deferred.
700     */
701    private boolean mDeferProtectedFilters = true;
702
703    /**
704     * Tracks existing system packages prior to receiving an OTA. Keys are package name.
705     */
706    final private ArraySet<String> mExistingSystemPackages = new ArraySet<>();
707    /**
708     * Whether or not system app permissions should be promoted from install to runtime.
709     */
710    boolean mPromoteSystemApps;
711
712    @GuardedBy("mPackages")
713    final Settings mSettings;
714
715    /**
716     * Set of package names that are currently "frozen", which means active
717     * surgery is being done on the code/data for that package. The platform
718     * will refuse to launch frozen packages to avoid race conditions.
719     *
720     * @see PackageFreezer
721     */
722    @GuardedBy("mPackages")
723    final ArraySet<String> mFrozenPackages = new ArraySet<>();
724
725    final ProtectedPackages mProtectedPackages;
726
727    boolean mFirstBoot;
728
729    PackageManagerInternal.ExternalSourcesPolicy mExternalSourcesPolicy;
730
731    // System configuration read by SystemConfig.
732    final int[] mGlobalGids;
733    final SparseArray<ArraySet<String>> mSystemPermissions;
734    @GuardedBy("mAvailableFeatures")
735    final ArrayMap<String, FeatureInfo> mAvailableFeatures;
736
737    // If mac_permissions.xml was found for seinfo labeling.
738    boolean mFoundPolicyFile;
739
740    private final InstantAppRegistry mInstantAppRegistry;
741
742    @GuardedBy("mPackages")
743    int mChangedPackagesSequenceNumber;
744    /**
745     * List of changed [installed, removed or updated] packages.
746     * mapping from user id -> sequence number -> package name
747     */
748    @GuardedBy("mPackages")
749    final SparseArray<SparseArray<String>> mChangedPackages = new SparseArray<>();
750    /**
751     * The sequence number of the last change to a package.
752     * mapping from user id -> package name -> sequence number
753     */
754    @GuardedBy("mPackages")
755    final SparseArray<Map<String, Integer>> mChangedPackagesSequenceNumbers = new SparseArray<>();
756
757    class PackageParserCallback implements PackageParser.Callback {
758        @Override public final boolean hasFeature(String feature) {
759            return PackageManagerService.this.hasSystemFeature(feature, 0);
760        }
761
762        final List<PackageParser.Package> getStaticOverlayPackagesLocked(
763                Collection<PackageParser.Package> allPackages, String targetPackageName) {
764            List<PackageParser.Package> overlayPackages = null;
765            for (PackageParser.Package p : allPackages) {
766                if (targetPackageName.equals(p.mOverlayTarget) && p.mIsStaticOverlay) {
767                    if (overlayPackages == null) {
768                        overlayPackages = new ArrayList<PackageParser.Package>();
769                    }
770                    overlayPackages.add(p);
771                }
772            }
773            if (overlayPackages != null) {
774                Comparator<PackageParser.Package> cmp = new Comparator<PackageParser.Package>() {
775                    public int compare(PackageParser.Package p1, PackageParser.Package p2) {
776                        return p1.mOverlayPriority - p2.mOverlayPriority;
777                    }
778                };
779                Collections.sort(overlayPackages, cmp);
780            }
781            return overlayPackages;
782        }
783
784        final String[] getStaticOverlayPathsLocked(Collection<PackageParser.Package> allPackages,
785                String targetPackageName, String targetPath) {
786            if ("android".equals(targetPackageName)) {
787                // Static RROs targeting to "android", ie framework-res.apk, are already applied by
788                // native AssetManager.
789                return null;
790            }
791            List<PackageParser.Package> overlayPackages =
792                    getStaticOverlayPackagesLocked(allPackages, targetPackageName);
793            if (overlayPackages == null || overlayPackages.isEmpty()) {
794                return null;
795            }
796            List<String> overlayPathList = null;
797            for (PackageParser.Package overlayPackage : overlayPackages) {
798                if (targetPath == null) {
799                    if (overlayPathList == null) {
800                        overlayPathList = new ArrayList<String>();
801                    }
802                    overlayPathList.add(overlayPackage.baseCodePath);
803                    continue;
804                }
805
806                try {
807                    // Creates idmaps for system to parse correctly the Android manifest of the
808                    // target package.
809                    //
810                    // OverlayManagerService will update each of them with a correct gid from its
811                    // target package app id.
812                    mInstaller.idmap(targetPath, overlayPackage.baseCodePath,
813                            UserHandle.getSharedAppGid(
814                                    UserHandle.getUserGid(UserHandle.USER_SYSTEM)));
815                    if (overlayPathList == null) {
816                        overlayPathList = new ArrayList<String>();
817                    }
818                    overlayPathList.add(overlayPackage.baseCodePath);
819                } catch (InstallerException e) {
820                    Slog.e(TAG, "Failed to generate idmap for " + targetPath + " and " +
821                            overlayPackage.baseCodePath);
822                }
823            }
824            return overlayPathList == null ? null : overlayPathList.toArray(new String[0]);
825        }
826
827        String[] getStaticOverlayPaths(String targetPackageName, String targetPath) {
828            synchronized (mPackages) {
829                return getStaticOverlayPathsLocked(
830                        mPackages.values(), targetPackageName, targetPath);
831            }
832        }
833
834        @Override public final String[] getOverlayApks(String targetPackageName) {
835            return getStaticOverlayPaths(targetPackageName, null);
836        }
837
838        @Override public final String[] getOverlayPaths(String targetPackageName,
839                String targetPath) {
840            return getStaticOverlayPaths(targetPackageName, targetPath);
841        }
842    };
843
844    class ParallelPackageParserCallback extends PackageParserCallback {
845        List<PackageParser.Package> mOverlayPackages = null;
846
847        void findStaticOverlayPackages() {
848            synchronized (mPackages) {
849                for (PackageParser.Package p : mPackages.values()) {
850                    if (p.mIsStaticOverlay) {
851                        if (mOverlayPackages == null) {
852                            mOverlayPackages = new ArrayList<PackageParser.Package>();
853                        }
854                        mOverlayPackages.add(p);
855                    }
856                }
857            }
858        }
859
860        @Override
861        synchronized String[] getStaticOverlayPaths(String targetPackageName, String targetPath) {
862            // We can trust mOverlayPackages without holding mPackages because package uninstall
863            // can't happen while running parallel parsing.
864            // Moreover holding mPackages on each parsing thread causes dead-lock.
865            return mOverlayPackages == null ? null :
866                    getStaticOverlayPathsLocked(mOverlayPackages, targetPackageName, targetPath);
867        }
868    }
869
870    final PackageParser.Callback mPackageParserCallback = new PackageParserCallback();
871    final ParallelPackageParserCallback mParallelPackageParserCallback =
872            new ParallelPackageParserCallback();
873
874    public static final class SharedLibraryEntry {
875        public final @Nullable String path;
876        public final @Nullable String apk;
877        public final @NonNull SharedLibraryInfo info;
878
879        SharedLibraryEntry(String _path, String _apk, String name, int version, int type,
880                String declaringPackageName, int declaringPackageVersionCode) {
881            path = _path;
882            apk = _apk;
883            info = new SharedLibraryInfo(name, version, type, new VersionedPackage(
884                    declaringPackageName, declaringPackageVersionCode), null);
885        }
886    }
887
888    // Currently known shared libraries.
889    final ArrayMap<String, SparseArray<SharedLibraryEntry>> mSharedLibraries = new ArrayMap<>();
890    final ArrayMap<String, SparseArray<SharedLibraryEntry>> mStaticLibsByDeclaringPackage =
891            new ArrayMap<>();
892
893    // All available activities, for your resolving pleasure.
894    final ActivityIntentResolver mActivities =
895            new ActivityIntentResolver();
896
897    // All available receivers, for your resolving pleasure.
898    final ActivityIntentResolver mReceivers =
899            new ActivityIntentResolver();
900
901    // All available services, for your resolving pleasure.
902    final ServiceIntentResolver mServices = new ServiceIntentResolver();
903
904    // All available providers, for your resolving pleasure.
905    final ProviderIntentResolver mProviders = new ProviderIntentResolver();
906
907    // Mapping from provider base names (first directory in content URI codePath)
908    // to the provider information.
909    final ArrayMap<String, PackageParser.Provider> mProvidersByAuthority =
910            new ArrayMap<String, PackageParser.Provider>();
911
912    // Mapping from instrumentation class names to info about them.
913    final ArrayMap<ComponentName, PackageParser.Instrumentation> mInstrumentation =
914            new ArrayMap<ComponentName, PackageParser.Instrumentation>();
915
916    // Mapping from permission names to info about them.
917    final ArrayMap<String, PackageParser.PermissionGroup> mPermissionGroups =
918            new ArrayMap<String, PackageParser.PermissionGroup>();
919
920    // Packages whose data we have transfered into another package, thus
921    // should no longer exist.
922    final ArraySet<String> mTransferedPackages = new ArraySet<String>();
923
924    // Broadcast actions that are only available to the system.
925    final ArraySet<String> mProtectedBroadcasts = new ArraySet<String>();
926
927    /** List of packages waiting for verification. */
928    final SparseArray<PackageVerificationState> mPendingVerification
929            = new SparseArray<PackageVerificationState>();
930
931    /** Set of packages associated with each app op permission. */
932    final ArrayMap<String, ArraySet<String>> mAppOpPermissionPackages = new ArrayMap<>();
933
934    final PackageInstallerService mInstallerService;
935
936    private final PackageDexOptimizer mPackageDexOptimizer;
937    // DexManager handles the usage of dex files (e.g. secondary files, whether or not a package
938    // is used by other apps).
939    private final DexManager mDexManager;
940
941    private AtomicInteger mNextMoveId = new AtomicInteger();
942    private final MoveCallbacks mMoveCallbacks;
943
944    private final OnPermissionChangeListeners mOnPermissionChangeListeners;
945
946    // Cache of users who need badging.
947    SparseBooleanArray mUserNeedsBadging = new SparseBooleanArray();
948
949    /** Token for keys in mPendingVerification. */
950    private int mPendingVerificationToken = 0;
951
952    volatile boolean mSystemReady;
953    volatile boolean mSafeMode;
954    volatile boolean mHasSystemUidErrors;
955    private volatile boolean mEphemeralAppsDisabled;
956
957    ApplicationInfo mAndroidApplication;
958    final ActivityInfo mResolveActivity = new ActivityInfo();
959    final ResolveInfo mResolveInfo = new ResolveInfo();
960    ComponentName mResolveComponentName;
961    PackageParser.Package mPlatformPackage;
962    ComponentName mCustomResolverComponentName;
963
964    boolean mResolverReplaced = false;
965
966    private final @Nullable ComponentName mIntentFilterVerifierComponent;
967    private final @Nullable IntentFilterVerifier<ActivityIntentInfo> mIntentFilterVerifier;
968
969    private int mIntentFilterVerificationToken = 0;
970
971    /** The service connection to the ephemeral resolver */
972    final EphemeralResolverConnection mInstantAppResolverConnection;
973    /** Component used to show resolver settings for Instant Apps */
974    final ComponentName mInstantAppResolverSettingsComponent;
975
976    /** Activity used to install instant applications */
977    ActivityInfo mInstantAppInstallerActivity;
978    final ResolveInfo mInstantAppInstallerInfo = new ResolveInfo();
979
980    final SparseArray<IntentFilterVerificationState> mIntentFilterVerificationStates
981            = new SparseArray<IntentFilterVerificationState>();
982
983    final DefaultPermissionGrantPolicy mDefaultPermissionPolicy;
984
985    // List of packages names to keep cached, even if they are uninstalled for all users
986    private List<String> mKeepUninstalledPackages;
987
988    private UserManagerInternal mUserManagerInternal;
989
990    private DeviceIdleController.LocalService mDeviceIdleController;
991
992    private File mCacheDir;
993
994    private ArraySet<String> mPrivappPermissionsViolations;
995
996    private Future<?> mPrepareAppDataFuture;
997
998    private static class IFVerificationParams {
999        PackageParser.Package pkg;
1000        boolean replacing;
1001        int userId;
1002        int verifierUid;
1003
1004        public IFVerificationParams(PackageParser.Package _pkg, boolean _replacing,
1005                int _userId, int _verifierUid) {
1006            pkg = _pkg;
1007            replacing = _replacing;
1008            userId = _userId;
1009            replacing = _replacing;
1010            verifierUid = _verifierUid;
1011        }
1012    }
1013
1014    private interface IntentFilterVerifier<T extends IntentFilter> {
1015        boolean addOneIntentFilterVerification(int verifierId, int userId, int verificationId,
1016                                               T filter, String packageName);
1017        void startVerifications(int userId);
1018        void receiveVerificationResponse(int verificationId);
1019    }
1020
1021    private class IntentVerifierProxy implements IntentFilterVerifier<ActivityIntentInfo> {
1022        private Context mContext;
1023        private ComponentName mIntentFilterVerifierComponent;
1024        private ArrayList<Integer> mCurrentIntentFilterVerifications = new ArrayList<Integer>();
1025
1026        public IntentVerifierProxy(Context context, ComponentName verifierComponent) {
1027            mContext = context;
1028            mIntentFilterVerifierComponent = verifierComponent;
1029        }
1030
1031        private String getDefaultScheme() {
1032            return IntentFilter.SCHEME_HTTPS;
1033        }
1034
1035        @Override
1036        public void startVerifications(int userId) {
1037            // Launch verifications requests
1038            int count = mCurrentIntentFilterVerifications.size();
1039            for (int n=0; n<count; n++) {
1040                int verificationId = mCurrentIntentFilterVerifications.get(n);
1041                final IntentFilterVerificationState ivs =
1042                        mIntentFilterVerificationStates.get(verificationId);
1043
1044                String packageName = ivs.getPackageName();
1045
1046                ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters();
1047                final int filterCount = filters.size();
1048                ArraySet<String> domainsSet = new ArraySet<>();
1049                for (int m=0; m<filterCount; m++) {
1050                    PackageParser.ActivityIntentInfo filter = filters.get(m);
1051                    domainsSet.addAll(filter.getHostsList());
1052                }
1053                synchronized (mPackages) {
1054                    if (mSettings.createIntentFilterVerificationIfNeededLPw(
1055                            packageName, domainsSet) != null) {
1056                        scheduleWriteSettingsLocked();
1057                    }
1058                }
1059                sendVerificationRequest(userId, verificationId, ivs);
1060            }
1061            mCurrentIntentFilterVerifications.clear();
1062        }
1063
1064        private void sendVerificationRequest(int userId, int verificationId,
1065                IntentFilterVerificationState ivs) {
1066
1067            Intent verificationIntent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION);
1068            verificationIntent.putExtra(
1069                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_ID,
1070                    verificationId);
1071            verificationIntent.putExtra(
1072                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_URI_SCHEME,
1073                    getDefaultScheme());
1074            verificationIntent.putExtra(
1075                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_HOSTS,
1076                    ivs.getHostsString());
1077            verificationIntent.putExtra(
1078                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_PACKAGE_NAME,
1079                    ivs.getPackageName());
1080            verificationIntent.setComponent(mIntentFilterVerifierComponent);
1081            verificationIntent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
1082
1083            DeviceIdleController.LocalService idleController = getDeviceIdleController();
1084            idleController.addPowerSaveTempWhitelistApp(Process.myUid(),
1085                    mIntentFilterVerifierComponent.getPackageName(), getVerificationTimeout(),
1086                    userId, false, "intent filter verifier");
1087
1088            UserHandle user = new UserHandle(userId);
1089            mContext.sendBroadcastAsUser(verificationIntent, user);
1090            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1091                    "Sending IntentFilter verification broadcast");
1092        }
1093
1094        public void receiveVerificationResponse(int verificationId) {
1095            IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId);
1096
1097            final boolean verified = ivs.isVerified();
1098
1099            ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters();
1100            final int count = filters.size();
1101            if (DEBUG_DOMAIN_VERIFICATION) {
1102                Slog.i(TAG, "Received verification response " + verificationId
1103                        + " for " + count + " filters, verified=" + verified);
1104            }
1105            for (int n=0; n<count; n++) {
1106                PackageParser.ActivityIntentInfo filter = filters.get(n);
1107                filter.setVerified(verified);
1108
1109                if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "IntentFilter " + filter.toString()
1110                        + " verified with result:" + verified + " and hosts:"
1111                        + ivs.getHostsString());
1112            }
1113
1114            mIntentFilterVerificationStates.remove(verificationId);
1115
1116            final String packageName = ivs.getPackageName();
1117            IntentFilterVerificationInfo ivi = null;
1118
1119            synchronized (mPackages) {
1120                ivi = mSettings.getIntentFilterVerificationLPr(packageName);
1121            }
1122            if (ivi == null) {
1123                Slog.w(TAG, "IntentFilterVerificationInfo not found for verificationId:"
1124                        + verificationId + " packageName:" + packageName);
1125                return;
1126            }
1127            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1128                    "Updating IntentFilterVerificationInfo for package " + packageName
1129                            +" verificationId:" + verificationId);
1130
1131            synchronized (mPackages) {
1132                if (verified) {
1133                    ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS);
1134                } else {
1135                    ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK);
1136                }
1137                scheduleWriteSettingsLocked();
1138
1139                final int userId = ivs.getUserId();
1140                if (userId != UserHandle.USER_ALL) {
1141                    final int userStatus =
1142                            mSettings.getIntentFilterVerificationStatusLPr(packageName, userId);
1143
1144                    int updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED;
1145                    boolean needUpdate = false;
1146
1147                    // We cannot override the STATUS_ALWAYS / STATUS_NEVER states if they have
1148                    // already been set by the User thru the Disambiguation dialog
1149                    switch (userStatus) {
1150                        case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED:
1151                            if (verified) {
1152                                updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS;
1153                            } else {
1154                                updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK;
1155                            }
1156                            needUpdate = true;
1157                            break;
1158
1159                        case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK:
1160                            if (verified) {
1161                                updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS;
1162                                needUpdate = true;
1163                            }
1164                            break;
1165
1166                        default:
1167                            // Nothing to do
1168                    }
1169
1170                    if (needUpdate) {
1171                        mSettings.updateIntentFilterVerificationStatusLPw(
1172                                packageName, updatedStatus, userId);
1173                        scheduleWritePackageRestrictionsLocked(userId);
1174                    }
1175                }
1176            }
1177        }
1178
1179        @Override
1180        public boolean addOneIntentFilterVerification(int verifierUid, int userId, int verificationId,
1181                    ActivityIntentInfo filter, String packageName) {
1182            if (!hasValidDomains(filter)) {
1183                return false;
1184            }
1185            IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId);
1186            if (ivs == null) {
1187                ivs = createDomainVerificationState(verifierUid, userId, verificationId,
1188                        packageName);
1189            }
1190            if (DEBUG_DOMAIN_VERIFICATION) {
1191                Slog.d(TAG, "Adding verification filter for " + packageName + ": " + filter);
1192            }
1193            ivs.addFilter(filter);
1194            return true;
1195        }
1196
1197        private IntentFilterVerificationState createDomainVerificationState(int verifierUid,
1198                int userId, int verificationId, String packageName) {
1199            IntentFilterVerificationState ivs = new IntentFilterVerificationState(
1200                    verifierUid, userId, packageName);
1201            ivs.setPendingState();
1202            synchronized (mPackages) {
1203                mIntentFilterVerificationStates.append(verificationId, ivs);
1204                mCurrentIntentFilterVerifications.add(verificationId);
1205            }
1206            return ivs;
1207        }
1208    }
1209
1210    private static boolean hasValidDomains(ActivityIntentInfo filter) {
1211        return filter.hasCategory(Intent.CATEGORY_BROWSABLE)
1212                && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) ||
1213                        filter.hasDataScheme(IntentFilter.SCHEME_HTTPS));
1214    }
1215
1216    // Set of pending broadcasts for aggregating enable/disable of components.
1217    static class PendingPackageBroadcasts {
1218        // for each user id, a map of <package name -> components within that package>
1219        final SparseArray<ArrayMap<String, ArrayList<String>>> mUidMap;
1220
1221        public PendingPackageBroadcasts() {
1222            mUidMap = new SparseArray<ArrayMap<String, ArrayList<String>>>(2);
1223        }
1224
1225        public ArrayList<String> get(int userId, String packageName) {
1226            ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId);
1227            return packages.get(packageName);
1228        }
1229
1230        public void put(int userId, String packageName, ArrayList<String> components) {
1231            ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId);
1232            packages.put(packageName, components);
1233        }
1234
1235        public void remove(int userId, String packageName) {
1236            ArrayMap<String, ArrayList<String>> packages = mUidMap.get(userId);
1237            if (packages != null) {
1238                packages.remove(packageName);
1239            }
1240        }
1241
1242        public void remove(int userId) {
1243            mUidMap.remove(userId);
1244        }
1245
1246        public int userIdCount() {
1247            return mUidMap.size();
1248        }
1249
1250        public int userIdAt(int n) {
1251            return mUidMap.keyAt(n);
1252        }
1253
1254        public ArrayMap<String, ArrayList<String>> packagesForUserId(int userId) {
1255            return mUidMap.get(userId);
1256        }
1257
1258        public int size() {
1259            // total number of pending broadcast entries across all userIds
1260            int num = 0;
1261            for (int i = 0; i< mUidMap.size(); i++) {
1262                num += mUidMap.valueAt(i).size();
1263            }
1264            return num;
1265        }
1266
1267        public void clear() {
1268            mUidMap.clear();
1269        }
1270
1271        private ArrayMap<String, ArrayList<String>> getOrAllocate(int userId) {
1272            ArrayMap<String, ArrayList<String>> map = mUidMap.get(userId);
1273            if (map == null) {
1274                map = new ArrayMap<String, ArrayList<String>>();
1275                mUidMap.put(userId, map);
1276            }
1277            return map;
1278        }
1279    }
1280    final PendingPackageBroadcasts mPendingBroadcasts = new PendingPackageBroadcasts();
1281
1282    // Service Connection to remote media container service to copy
1283    // package uri's from external media onto secure containers
1284    // or internal storage.
1285    private IMediaContainerService mContainerService = null;
1286
1287    static final int SEND_PENDING_BROADCAST = 1;
1288    static final int MCS_BOUND = 3;
1289    static final int END_COPY = 4;
1290    static final int INIT_COPY = 5;
1291    static final int MCS_UNBIND = 6;
1292    static final int START_CLEANING_PACKAGE = 7;
1293    static final int FIND_INSTALL_LOC = 8;
1294    static final int POST_INSTALL = 9;
1295    static final int MCS_RECONNECT = 10;
1296    static final int MCS_GIVE_UP = 11;
1297    static final int UPDATED_MEDIA_STATUS = 12;
1298    static final int WRITE_SETTINGS = 13;
1299    static final int WRITE_PACKAGE_RESTRICTIONS = 14;
1300    static final int PACKAGE_VERIFIED = 15;
1301    static final int CHECK_PENDING_VERIFICATION = 16;
1302    static final int START_INTENT_FILTER_VERIFICATIONS = 17;
1303    static final int INTENT_FILTER_VERIFIED = 18;
1304    static final int WRITE_PACKAGE_LIST = 19;
1305    static final int INSTANT_APP_RESOLUTION_PHASE_TWO = 20;
1306
1307    static final int WRITE_SETTINGS_DELAY = 10*1000;  // 10 seconds
1308
1309    // Delay time in millisecs
1310    static final int BROADCAST_DELAY = 10 * 1000;
1311
1312    private static final long DEFAULT_UNUSED_STATIC_SHARED_LIB_MIN_CACHE_PERIOD =
1313            2 * 60 * 60 * 1000L; /* two hours */
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        PackageSetting ps = (PackageSetting) pkg.mExtras;
2187        if (ps == null) {
2188            return;
2189        }
2190
2191        PermissionsState permissionsState = ps.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            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_READY,
2947                    SystemClock.uptimeMillis());
2948
2949            if (!mOnlyCore) {
2950                mRequiredVerifierPackage = getRequiredButNotReallyRequiredVerifierLPr();
2951                mRequiredInstallerPackage = getRequiredInstallerLPr();
2952                mRequiredUninstallerPackage = getRequiredUninstallerLPr();
2953                mIntentFilterVerifierComponent = getIntentFilterVerifierComponentNameLPr();
2954                if (mIntentFilterVerifierComponent != null) {
2955                    mIntentFilterVerifier = new IntentVerifierProxy(mContext,
2956                            mIntentFilterVerifierComponent);
2957                } else {
2958                    mIntentFilterVerifier = null;
2959                }
2960                mServicesSystemSharedLibraryPackageName = getRequiredSharedLibraryLPr(
2961                        PackageManager.SYSTEM_SHARED_LIBRARY_SERVICES,
2962                        SharedLibraryInfo.VERSION_UNDEFINED);
2963                mSharedSystemSharedLibraryPackageName = getRequiredSharedLibraryLPr(
2964                        PackageManager.SYSTEM_SHARED_LIBRARY_SHARED,
2965                        SharedLibraryInfo.VERSION_UNDEFINED);
2966            } else {
2967                mRequiredVerifierPackage = null;
2968                mRequiredInstallerPackage = null;
2969                mRequiredUninstallerPackage = null;
2970                mIntentFilterVerifierComponent = null;
2971                mIntentFilterVerifier = null;
2972                mServicesSystemSharedLibraryPackageName = null;
2973                mSharedSystemSharedLibraryPackageName = null;
2974            }
2975
2976            mInstallerService = new PackageInstallerService(context, this);
2977            final Pair<ComponentName, String> instantAppResolverComponent =
2978                    getInstantAppResolverLPr();
2979            if (instantAppResolverComponent != null) {
2980                if (DEBUG_EPHEMERAL) {
2981                    Slog.d(TAG, "Set ephemeral resolver: " + instantAppResolverComponent);
2982                }
2983                mInstantAppResolverConnection = new EphemeralResolverConnection(
2984                        mContext, instantAppResolverComponent.first,
2985                        instantAppResolverComponent.second);
2986                mInstantAppResolverSettingsComponent =
2987                        getInstantAppResolverSettingsLPr(instantAppResolverComponent.first);
2988            } else {
2989                mInstantAppResolverConnection = null;
2990                mInstantAppResolverSettingsComponent = null;
2991            }
2992            updateInstantAppInstallerLocked(null);
2993
2994            // Read and update the usage of dex files.
2995            // Do this at the end of PM init so that all the packages have their
2996            // data directory reconciled.
2997            // At this point we know the code paths of the packages, so we can validate
2998            // the disk file and build the internal cache.
2999            // The usage file is expected to be small so loading and verifying it
3000            // should take a fairly small time compare to the other activities (e.g. package
3001            // scanning).
3002            final Map<Integer, List<PackageInfo>> userPackages = new HashMap<>();
3003            final int[] currentUserIds = UserManagerService.getInstance().getUserIds();
3004            for (int userId : currentUserIds) {
3005                userPackages.put(userId, getInstalledPackages(/*flags*/ 0, userId).getList());
3006            }
3007            mDexManager.load(userPackages);
3008        } // synchronized (mPackages)
3009        } // synchronized (mInstallLock)
3010
3011        // Now after opening every single application zip, make sure they
3012        // are all flushed.  Not really needed, but keeps things nice and
3013        // tidy.
3014        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "GC");
3015        Runtime.getRuntime().gc();
3016        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
3017
3018        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "loadFallbacks");
3019        FallbackCategoryProvider.loadFallbacks();
3020        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
3021
3022        // The initial scanning above does many calls into installd while
3023        // holding the mPackages lock, but we're mostly interested in yelling
3024        // once we have a booted system.
3025        mInstaller.setWarnIfHeld(mPackages);
3026
3027        // Expose private service for system components to use.
3028        LocalServices.addService(PackageManagerInternal.class, new PackageManagerInternalImpl());
3029        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
3030    }
3031
3032    private void updateInstantAppInstallerLocked(String modifiedPackage) {
3033        // we're only interested in updating the installer appliction when 1) it's not
3034        // already set or 2) the modified package is the installer
3035        if (mInstantAppInstallerActivity != null
3036                && !mInstantAppInstallerActivity.getComponentName().getPackageName()
3037                        .equals(modifiedPackage)) {
3038            return;
3039        }
3040        setUpInstantAppInstallerActivityLP(getInstantAppInstallerLPr());
3041    }
3042
3043    private static File preparePackageParserCache(boolean isUpgrade) {
3044        if (!DEFAULT_PACKAGE_PARSER_CACHE_ENABLED) {
3045            return null;
3046        }
3047
3048        // Disable package parsing on eng builds to allow for faster incremental development.
3049        if ("eng".equals(Build.TYPE)) {
3050            return null;
3051        }
3052
3053        if (SystemProperties.getBoolean("pm.boot.disable_package_cache", false)) {
3054            Slog.i(TAG, "Disabling package parser cache due to system property.");
3055            return null;
3056        }
3057
3058        // The base directory for the package parser cache lives under /data/system/.
3059        final File cacheBaseDir = FileUtils.createDir(Environment.getDataSystemDirectory(),
3060                "package_cache");
3061        if (cacheBaseDir == null) {
3062            return null;
3063        }
3064
3065        // If this is a system upgrade scenario, delete the contents of the package cache dir.
3066        // This also serves to "GC" unused entries when the package cache version changes (which
3067        // can only happen during upgrades).
3068        if (isUpgrade) {
3069            FileUtils.deleteContents(cacheBaseDir);
3070        }
3071
3072
3073        // Return the versioned package cache directory. This is something like
3074        // "/data/system/package_cache/1"
3075        File cacheDir = FileUtils.createDir(cacheBaseDir, PACKAGE_PARSER_CACHE_VERSION);
3076
3077        // The following is a workaround to aid development on non-numbered userdebug
3078        // builds or cases where "adb sync" is used on userdebug builds. If we detect that
3079        // the system partition is newer.
3080        //
3081        // NOTE: When no BUILD_NUMBER is set by the build system, it defaults to a build
3082        // that starts with "eng." to signify that this is an engineering build and not
3083        // destined for release.
3084        if ("userdebug".equals(Build.TYPE) && Build.VERSION.INCREMENTAL.startsWith("eng.")) {
3085            Slog.w(TAG, "Wiping cache directory because the system partition changed.");
3086
3087            // Heuristic: If the /system directory has been modified recently due to an "adb sync"
3088            // or a regular make, then blow away the cache. Note that mtimes are *NOT* reliable
3089            // in general and should not be used for production changes. In this specific case,
3090            // we know that they will work.
3091            File frameworkDir = new File(Environment.getRootDirectory(), "framework");
3092            if (cacheDir.lastModified() < frameworkDir.lastModified()) {
3093                FileUtils.deleteContents(cacheBaseDir);
3094                cacheDir = FileUtils.createDir(cacheBaseDir, PACKAGE_PARSER_CACHE_VERSION);
3095            }
3096        }
3097
3098        return cacheDir;
3099    }
3100
3101    @Override
3102    public boolean isFirstBoot() {
3103        // allow instant applications
3104        return mFirstBoot;
3105    }
3106
3107    @Override
3108    public boolean isOnlyCoreApps() {
3109        // allow instant applications
3110        return mOnlyCore;
3111    }
3112
3113    @Override
3114    public boolean isUpgrade() {
3115        // allow instant applications
3116        return mIsUpgrade;
3117    }
3118
3119    private @Nullable String getRequiredButNotReallyRequiredVerifierLPr() {
3120        final Intent intent = new Intent(Intent.ACTION_PACKAGE_NEEDS_VERIFICATION);
3121
3122        final List<ResolveInfo> matches = queryIntentReceiversInternal(intent, PACKAGE_MIME_TYPE,
3123                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
3124                UserHandle.USER_SYSTEM);
3125        if (matches.size() == 1) {
3126            return matches.get(0).getComponentInfo().packageName;
3127        } else if (matches.size() == 0) {
3128            Log.e(TAG, "There should probably be a verifier, but, none were found");
3129            return null;
3130        }
3131        throw new RuntimeException("There must be exactly one verifier; found " + matches);
3132    }
3133
3134    private @NonNull String getRequiredSharedLibraryLPr(String name, int version) {
3135        synchronized (mPackages) {
3136            SharedLibraryEntry libraryEntry = getSharedLibraryEntryLPr(name, version);
3137            if (libraryEntry == null) {
3138                throw new IllegalStateException("Missing required shared library:" + name);
3139            }
3140            return libraryEntry.apk;
3141        }
3142    }
3143
3144    private @NonNull String getRequiredInstallerLPr() {
3145        final Intent intent = new Intent(Intent.ACTION_INSTALL_PACKAGE);
3146        intent.addCategory(Intent.CATEGORY_DEFAULT);
3147        intent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE);
3148
3149        final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, PACKAGE_MIME_TYPE,
3150                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
3151                UserHandle.USER_SYSTEM);
3152        if (matches.size() == 1) {
3153            ResolveInfo resolveInfo = matches.get(0);
3154            if (!resolveInfo.activityInfo.applicationInfo.isPrivilegedApp()) {
3155                throw new RuntimeException("The installer must be a privileged app");
3156            }
3157            return matches.get(0).getComponentInfo().packageName;
3158        } else {
3159            throw new RuntimeException("There must be exactly one installer; found " + matches);
3160        }
3161    }
3162
3163    private @NonNull String getRequiredUninstallerLPr() {
3164        final Intent intent = new Intent(Intent.ACTION_UNINSTALL_PACKAGE);
3165        intent.addCategory(Intent.CATEGORY_DEFAULT);
3166        intent.setData(Uri.fromParts(PACKAGE_SCHEME, "foo.bar", null));
3167
3168        final ResolveInfo resolveInfo = resolveIntent(intent, null,
3169                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
3170                UserHandle.USER_SYSTEM);
3171        if (resolveInfo == null ||
3172                mResolveActivity.name.equals(resolveInfo.getComponentInfo().name)) {
3173            throw new RuntimeException("There must be exactly one uninstaller; found "
3174                    + resolveInfo);
3175        }
3176        return resolveInfo.getComponentInfo().packageName;
3177    }
3178
3179    private @NonNull ComponentName getIntentFilterVerifierComponentNameLPr() {
3180        final Intent intent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION);
3181
3182        final List<ResolveInfo> matches = queryIntentReceiversInternal(intent, PACKAGE_MIME_TYPE,
3183                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
3184                UserHandle.USER_SYSTEM);
3185        ResolveInfo best = null;
3186        final int N = matches.size();
3187        for (int i = 0; i < N; i++) {
3188            final ResolveInfo cur = matches.get(i);
3189            final String packageName = cur.getComponentInfo().packageName;
3190            if (checkPermission(android.Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT,
3191                    packageName, UserHandle.USER_SYSTEM) != PackageManager.PERMISSION_GRANTED) {
3192                continue;
3193            }
3194
3195            if (best == null || cur.priority > best.priority) {
3196                best = cur;
3197            }
3198        }
3199
3200        if (best != null) {
3201            return best.getComponentInfo().getComponentName();
3202        }
3203        Slog.w(TAG, "Intent filter verifier not found");
3204        return null;
3205    }
3206
3207    @Override
3208    public @Nullable ComponentName getInstantAppResolverComponent() {
3209        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
3210            return null;
3211        }
3212        synchronized (mPackages) {
3213            final Pair<ComponentName, String> instantAppResolver = getInstantAppResolverLPr();
3214            if (instantAppResolver == null) {
3215                return null;
3216            }
3217            return instantAppResolver.first;
3218        }
3219    }
3220
3221    private @Nullable Pair<ComponentName, String> getInstantAppResolverLPr() {
3222        final String[] packageArray =
3223                mContext.getResources().getStringArray(R.array.config_ephemeralResolverPackage);
3224        if (packageArray.length == 0 && !Build.IS_DEBUGGABLE) {
3225            if (DEBUG_EPHEMERAL) {
3226                Slog.d(TAG, "Ephemeral resolver NOT found; empty package list");
3227            }
3228            return null;
3229        }
3230
3231        final int callingUid = Binder.getCallingUid();
3232        final int resolveFlags =
3233                MATCH_DIRECT_BOOT_AWARE
3234                | MATCH_DIRECT_BOOT_UNAWARE
3235                | (!Build.IS_DEBUGGABLE ? MATCH_SYSTEM_ONLY : 0);
3236        String actionName = Intent.ACTION_RESOLVE_INSTANT_APP_PACKAGE;
3237        final Intent resolverIntent = new Intent(actionName);
3238        List<ResolveInfo> resolvers = queryIntentServicesInternal(resolverIntent, null,
3239                resolveFlags, UserHandle.USER_SYSTEM, callingUid, false /*includeInstantApps*/);
3240        // temporarily look for the old action
3241        if (resolvers.size() == 0) {
3242            if (DEBUG_EPHEMERAL) {
3243                Slog.d(TAG, "Ephemeral resolver not found with new action; try old one");
3244            }
3245            actionName = Intent.ACTION_RESOLVE_EPHEMERAL_PACKAGE;
3246            resolverIntent.setAction(actionName);
3247            resolvers = queryIntentServicesInternal(resolverIntent, null,
3248                    resolveFlags, UserHandle.USER_SYSTEM, callingUid, false /*includeInstantApps*/);
3249        }
3250        final int N = resolvers.size();
3251        if (N == 0) {
3252            if (DEBUG_EPHEMERAL) {
3253                Slog.d(TAG, "Ephemeral resolver NOT found; no matching intent filters");
3254            }
3255            return null;
3256        }
3257
3258        final Set<String> possiblePackages = new ArraySet<>(Arrays.asList(packageArray));
3259        for (int i = 0; i < N; i++) {
3260            final ResolveInfo info = resolvers.get(i);
3261
3262            if (info.serviceInfo == null) {
3263                continue;
3264            }
3265
3266            final String packageName = info.serviceInfo.packageName;
3267            if (!possiblePackages.contains(packageName) && !Build.IS_DEBUGGABLE) {
3268                if (DEBUG_EPHEMERAL) {
3269                    Slog.d(TAG, "Ephemeral resolver not in allowed package list;"
3270                            + " pkg: " + packageName + ", info:" + info);
3271                }
3272                continue;
3273            }
3274
3275            if (DEBUG_EPHEMERAL) {
3276                Slog.v(TAG, "Ephemeral resolver found;"
3277                        + " pkg: " + packageName + ", info:" + info);
3278            }
3279            return new Pair<>(new ComponentName(packageName, info.serviceInfo.name), actionName);
3280        }
3281        if (DEBUG_EPHEMERAL) {
3282            Slog.v(TAG, "Ephemeral resolver NOT found");
3283        }
3284        return null;
3285    }
3286
3287    private @Nullable ActivityInfo getInstantAppInstallerLPr() {
3288        final Intent intent = new Intent(Intent.ACTION_INSTALL_INSTANT_APP_PACKAGE);
3289        intent.addCategory(Intent.CATEGORY_DEFAULT);
3290        intent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE);
3291
3292        final int resolveFlags =
3293                MATCH_DIRECT_BOOT_AWARE
3294                | MATCH_DIRECT_BOOT_UNAWARE
3295                | (!Build.IS_DEBUGGABLE ? MATCH_SYSTEM_ONLY : 0);
3296        List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, PACKAGE_MIME_TYPE,
3297                resolveFlags, UserHandle.USER_SYSTEM);
3298        // temporarily look for the old action
3299        if (matches.isEmpty()) {
3300            if (DEBUG_EPHEMERAL) {
3301                Slog.d(TAG, "Ephemeral installer not found with new action; try old one");
3302            }
3303            intent.setAction(Intent.ACTION_INSTALL_EPHEMERAL_PACKAGE);
3304            matches = queryIntentActivitiesInternal(intent, PACKAGE_MIME_TYPE,
3305                    resolveFlags, UserHandle.USER_SYSTEM);
3306        }
3307        Iterator<ResolveInfo> iter = matches.iterator();
3308        while (iter.hasNext()) {
3309            final ResolveInfo rInfo = iter.next();
3310            final PackageSetting ps = mSettings.mPackages.get(rInfo.activityInfo.packageName);
3311            if (ps != null) {
3312                final PermissionsState permissionsState = ps.getPermissionsState();
3313                if (permissionsState.hasPermission(Manifest.permission.INSTALL_PACKAGES, 0)) {
3314                    continue;
3315                }
3316            }
3317            iter.remove();
3318        }
3319        if (matches.size() == 0) {
3320            return null;
3321        } else if (matches.size() == 1) {
3322            return (ActivityInfo) matches.get(0).getComponentInfo();
3323        } else {
3324            throw new RuntimeException(
3325                    "There must be at most one ephemeral installer; found " + matches);
3326        }
3327    }
3328
3329    private @Nullable ComponentName getInstantAppResolverSettingsLPr(
3330            @NonNull ComponentName resolver) {
3331        final Intent intent =  new Intent(Intent.ACTION_INSTANT_APP_RESOLVER_SETTINGS)
3332                .addCategory(Intent.CATEGORY_DEFAULT)
3333                .setPackage(resolver.getPackageName());
3334        final int resolveFlags = MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE;
3335        List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, null, resolveFlags,
3336                UserHandle.USER_SYSTEM);
3337        // temporarily look for the old action
3338        if (matches.isEmpty()) {
3339            if (DEBUG_EPHEMERAL) {
3340                Slog.d(TAG, "Ephemeral resolver settings not found with new action; try old one");
3341            }
3342            intent.setAction(Intent.ACTION_EPHEMERAL_RESOLVER_SETTINGS);
3343            matches = queryIntentActivitiesInternal(intent, null, resolveFlags,
3344                    UserHandle.USER_SYSTEM);
3345        }
3346        if (matches.isEmpty()) {
3347            return null;
3348        }
3349        return matches.get(0).getComponentInfo().getComponentName();
3350    }
3351
3352    private void primeDomainVerificationsLPw(int userId) {
3353        if (DEBUG_DOMAIN_VERIFICATION) {
3354            Slog.d(TAG, "Priming domain verifications in user " + userId);
3355        }
3356
3357        SystemConfig systemConfig = SystemConfig.getInstance();
3358        ArraySet<String> packages = systemConfig.getLinkedApps();
3359
3360        for (String packageName : packages) {
3361            PackageParser.Package pkg = mPackages.get(packageName);
3362            if (pkg != null) {
3363                if (!pkg.isSystemApp()) {
3364                    Slog.w(TAG, "Non-system app '" + packageName + "' in sysconfig <app-link>");
3365                    continue;
3366                }
3367
3368                ArraySet<String> domains = null;
3369                for (PackageParser.Activity a : pkg.activities) {
3370                    for (ActivityIntentInfo filter : a.intents) {
3371                        if (hasValidDomains(filter)) {
3372                            if (domains == null) {
3373                                domains = new ArraySet<String>();
3374                            }
3375                            domains.addAll(filter.getHostsList());
3376                        }
3377                    }
3378                }
3379
3380                if (domains != null && domains.size() > 0) {
3381                    if (DEBUG_DOMAIN_VERIFICATION) {
3382                        Slog.v(TAG, "      + " + packageName);
3383                    }
3384                    // 'Undefined' in the global IntentFilterVerificationInfo, i.e. the usual
3385                    // state w.r.t. the formal app-linkage "no verification attempted" state;
3386                    // and then 'always' in the per-user state actually used for intent resolution.
3387                    final IntentFilterVerificationInfo ivi;
3388                    ivi = mSettings.createIntentFilterVerificationIfNeededLPw(packageName, domains);
3389                    ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED);
3390                    mSettings.updateIntentFilterVerificationStatusLPw(packageName,
3391                            INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS, userId);
3392                } else {
3393                    Slog.w(TAG, "Sysconfig <app-link> package '" + packageName
3394                            + "' does not handle web links");
3395                }
3396            } else {
3397                Slog.w(TAG, "Unknown package " + packageName + " in sysconfig <app-link>");
3398            }
3399        }
3400
3401        scheduleWritePackageRestrictionsLocked(userId);
3402        scheduleWriteSettingsLocked();
3403    }
3404
3405    private void applyFactoryDefaultBrowserLPw(int userId) {
3406        // The default browser app's package name is stored in a string resource,
3407        // with a product-specific overlay used for vendor customization.
3408        String browserPkg = mContext.getResources().getString(
3409                com.android.internal.R.string.default_browser);
3410        if (!TextUtils.isEmpty(browserPkg)) {
3411            // non-empty string => required to be a known package
3412            PackageSetting ps = mSettings.mPackages.get(browserPkg);
3413            if (ps == null) {
3414                Slog.e(TAG, "Product default browser app does not exist: " + browserPkg);
3415                browserPkg = null;
3416            } else {
3417                mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId);
3418            }
3419        }
3420
3421        // Nothing valid explicitly set? Make the factory-installed browser the explicit
3422        // default.  If there's more than one, just leave everything alone.
3423        if (browserPkg == null) {
3424            calculateDefaultBrowserLPw(userId);
3425        }
3426    }
3427
3428    private void calculateDefaultBrowserLPw(int userId) {
3429        List<String> allBrowsers = resolveAllBrowserApps(userId);
3430        final String browserPkg = (allBrowsers.size() == 1) ? allBrowsers.get(0) : null;
3431        mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId);
3432    }
3433
3434    private List<String> resolveAllBrowserApps(int userId) {
3435        // Resolve the canonical browser intent and check that the handleAllWebDataURI boolean is set
3436        List<ResolveInfo> list = queryIntentActivitiesInternal(sBrowserIntent, null,
3437                PackageManager.MATCH_ALL, userId);
3438
3439        final int count = list.size();
3440        List<String> result = new ArrayList<String>(count);
3441        for (int i=0; i<count; i++) {
3442            ResolveInfo info = list.get(i);
3443            if (info.activityInfo == null
3444                    || !info.handleAllWebDataURI
3445                    || (info.activityInfo.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) == 0
3446                    || result.contains(info.activityInfo.packageName)) {
3447                continue;
3448            }
3449            result.add(info.activityInfo.packageName);
3450        }
3451
3452        return result;
3453    }
3454
3455    private boolean packageIsBrowser(String packageName, int userId) {
3456        List<ResolveInfo> list = queryIntentActivitiesInternal(sBrowserIntent, null,
3457                PackageManager.MATCH_ALL, userId);
3458        final int N = list.size();
3459        for (int i = 0; i < N; i++) {
3460            ResolveInfo info = list.get(i);
3461            if (packageName.equals(info.activityInfo.packageName)) {
3462                return true;
3463            }
3464        }
3465        return false;
3466    }
3467
3468    private void checkDefaultBrowser() {
3469        final int myUserId = UserHandle.myUserId();
3470        final String packageName = getDefaultBrowserPackageName(myUserId);
3471        if (packageName != null) {
3472            PackageInfo info = getPackageInfo(packageName, 0, myUserId);
3473            if (info == null) {
3474                Slog.w(TAG, "Default browser no longer installed: " + packageName);
3475                synchronized (mPackages) {
3476                    applyFactoryDefaultBrowserLPw(myUserId);    // leaves ambiguous when > 1
3477                }
3478            }
3479        }
3480    }
3481
3482    @Override
3483    public boolean onTransact(int code, Parcel data, Parcel reply, int flags)
3484            throws RemoteException {
3485        try {
3486            return super.onTransact(code, data, reply, flags);
3487        } catch (RuntimeException e) {
3488            if (!(e instanceof SecurityException) && !(e instanceof IllegalArgumentException)) {
3489                Slog.wtf(TAG, "Package Manager Crash", e);
3490            }
3491            throw e;
3492        }
3493    }
3494
3495    static int[] appendInts(int[] cur, int[] add) {
3496        if (add == null) return cur;
3497        if (cur == null) return add;
3498        final int N = add.length;
3499        for (int i=0; i<N; i++) {
3500            cur = appendInt(cur, add[i]);
3501        }
3502        return cur;
3503    }
3504
3505    /**
3506     * Returns whether or not a full application can see an instant application.
3507     * <p>
3508     * Currently, there are three cases in which this can occur:
3509     * <ol>
3510     * <li>The calling application is a "special" process. The special
3511     *     processes are {@link Process#SYSTEM_UID}, {@link Process#SHELL_UID}
3512     *     and {@code 0}</li>
3513     * <li>The calling application has the permission
3514     *     {@link android.Manifest.permission#ACCESS_INSTANT_APPS}</li>
3515     * <li>The calling application is the default launcher on the
3516     *     system partition.</li>
3517     * </ol>
3518     */
3519    private boolean canViewInstantApps(int callingUid, int userId) {
3520        if (callingUid == Process.SYSTEM_UID
3521                || callingUid == Process.SHELL_UID
3522                || callingUid == Process.ROOT_UID) {
3523            return true;
3524        }
3525        if (mContext.checkCallingOrSelfPermission(
3526                android.Manifest.permission.ACCESS_INSTANT_APPS) == PERMISSION_GRANTED) {
3527            return true;
3528        }
3529        if (mContext.checkCallingOrSelfPermission(
3530                android.Manifest.permission.VIEW_INSTANT_APPS) == PERMISSION_GRANTED) {
3531            final ComponentName homeComponent = getDefaultHomeActivity(userId);
3532            if (homeComponent != null
3533                    && isCallerSameApp(homeComponent.getPackageName(), callingUid)) {
3534                return true;
3535            }
3536        }
3537        return false;
3538    }
3539
3540    private PackageInfo generatePackageInfo(PackageSetting ps, int flags, int userId) {
3541        if (!sUserManager.exists(userId)) return null;
3542        if (ps == null) {
3543            return null;
3544        }
3545        PackageParser.Package p = ps.pkg;
3546        if (p == null) {
3547            return null;
3548        }
3549        final int callingUid = Binder.getCallingUid();
3550        // Filter out ephemeral app metadata:
3551        //   * The system/shell/root can see metadata for any app
3552        //   * An installed app can see metadata for 1) other installed apps
3553        //     and 2) ephemeral apps that have explicitly interacted with it
3554        //   * Ephemeral apps can only see their own data and exposed installed apps
3555        //   * Holding a signature permission allows seeing instant apps
3556        if (filterAppAccessLPr(ps, callingUid, userId)) {
3557            return null;
3558        }
3559
3560        final PermissionsState permissionsState = ps.getPermissionsState();
3561
3562        // Compute GIDs only if requested
3563        final int[] gids = (flags & PackageManager.GET_GIDS) == 0
3564                ? EMPTY_INT_ARRAY : permissionsState.computeGids(userId);
3565        // Compute granted permissions only if package has requested permissions
3566        final Set<String> permissions = ArrayUtils.isEmpty(p.requestedPermissions)
3567                ? Collections.<String>emptySet() : permissionsState.getPermissions(userId);
3568        final PackageUserState state = ps.readUserState(userId);
3569
3570        if ((flags & MATCH_UNINSTALLED_PACKAGES) != 0
3571                && ps.isSystem()) {
3572            flags |= MATCH_ANY_USER;
3573        }
3574
3575        PackageInfo packageInfo = PackageParser.generatePackageInfo(p, gids, flags,
3576                ps.firstInstallTime, ps.lastUpdateTime, permissions, state, userId);
3577
3578        if (packageInfo == null) {
3579            return null;
3580        }
3581
3582        packageInfo.packageName = packageInfo.applicationInfo.packageName =
3583                resolveExternalPackageNameLPr(p);
3584
3585        return packageInfo;
3586    }
3587
3588    @Override
3589    public void checkPackageStartable(String packageName, int userId) {
3590        final int callingUid = Binder.getCallingUid();
3591        if (getInstantAppPackageName(callingUid) != null) {
3592            throw new SecurityException("Instant applications don't have access to this method");
3593        }
3594        final boolean userKeyUnlocked = StorageManager.isUserKeyUnlocked(userId);
3595        synchronized (mPackages) {
3596            final PackageSetting ps = mSettings.mPackages.get(packageName);
3597            if (ps == null || filterAppAccessLPr(ps, callingUid, userId)) {
3598                throw new SecurityException("Package " + packageName + " was not found!");
3599            }
3600
3601            if (!ps.getInstalled(userId)) {
3602                throw new SecurityException(
3603                        "Package " + packageName + " was not installed for user " + userId + "!");
3604            }
3605
3606            if (mSafeMode && !ps.isSystem()) {
3607                throw new SecurityException("Package " + packageName + " not a system app!");
3608            }
3609
3610            if (mFrozenPackages.contains(packageName)) {
3611                throw new SecurityException("Package " + packageName + " is currently frozen!");
3612            }
3613
3614            if (!userKeyUnlocked && !(ps.pkg.applicationInfo.isDirectBootAware()
3615                    || ps.pkg.applicationInfo.isPartiallyDirectBootAware())) {
3616                throw new SecurityException("Package " + packageName + " is not encryption aware!");
3617            }
3618        }
3619    }
3620
3621    @Override
3622    public boolean isPackageAvailable(String packageName, int userId) {
3623        if (!sUserManager.exists(userId)) return false;
3624        final int callingUid = Binder.getCallingUid();
3625        enforceCrossUserPermission(callingUid, userId,
3626                false /*requireFullPermission*/, false /*checkShell*/, "is package available");
3627        synchronized (mPackages) {
3628            PackageParser.Package p = mPackages.get(packageName);
3629            if (p != null) {
3630                final PackageSetting ps = (PackageSetting) p.mExtras;
3631                if (filterAppAccessLPr(ps, callingUid, userId)) {
3632                    return false;
3633                }
3634                if (ps != null) {
3635                    final PackageUserState state = ps.readUserState(userId);
3636                    if (state != null) {
3637                        return PackageParser.isAvailable(state);
3638                    }
3639                }
3640            }
3641        }
3642        return false;
3643    }
3644
3645    @Override
3646    public PackageInfo getPackageInfo(String packageName, int flags, int userId) {
3647        return getPackageInfoInternal(packageName, PackageManager.VERSION_CODE_HIGHEST,
3648                flags, Binder.getCallingUid(), userId);
3649    }
3650
3651    @Override
3652    public PackageInfo getPackageInfoVersioned(VersionedPackage versionedPackage,
3653            int flags, int userId) {
3654        return getPackageInfoInternal(versionedPackage.getPackageName(),
3655                versionedPackage.getVersionCode(), flags, Binder.getCallingUid(), userId);
3656    }
3657
3658    /**
3659     * Important: The provided filterCallingUid is used exclusively to filter out packages
3660     * that can be seen based on user state. It's typically the original caller uid prior
3661     * to clearing. Because it can only be provided by trusted code, it's value can be
3662     * trusted and will be used as-is; unlike userId which will be validated by this method.
3663     */
3664    private PackageInfo getPackageInfoInternal(String packageName, int versionCode,
3665            int flags, int filterCallingUid, int userId) {
3666        if (!sUserManager.exists(userId)) return null;
3667        flags = updateFlagsForPackage(flags, userId, packageName);
3668        enforceCrossUserPermission(Binder.getCallingUid(), userId,
3669                false /* requireFullPermission */, false /* checkShell */, "get package info");
3670
3671        // reader
3672        synchronized (mPackages) {
3673            // Normalize package name to handle renamed packages and static libs
3674            packageName = resolveInternalPackageNameLPr(packageName, versionCode);
3675
3676            final boolean matchFactoryOnly = (flags & MATCH_FACTORY_ONLY) != 0;
3677            if (matchFactoryOnly) {
3678                final PackageSetting ps = mSettings.getDisabledSystemPkgLPr(packageName);
3679                if (ps != null) {
3680                    if (filterSharedLibPackageLPr(ps, filterCallingUid, userId, flags)) {
3681                        return null;
3682                    }
3683                    if (filterAppAccessLPr(ps, filterCallingUid, userId)) {
3684                        return null;
3685                    }
3686                    return generatePackageInfo(ps, flags, userId);
3687                }
3688            }
3689
3690            PackageParser.Package p = mPackages.get(packageName);
3691            if (matchFactoryOnly && p != null && !isSystemApp(p)) {
3692                return null;
3693            }
3694            if (DEBUG_PACKAGE_INFO)
3695                Log.v(TAG, "getPackageInfo " + packageName + ": " + p);
3696            if (p != null) {
3697                final PackageSetting ps = (PackageSetting) p.mExtras;
3698                if (filterSharedLibPackageLPr(ps, filterCallingUid, userId, flags)) {
3699                    return null;
3700                }
3701                if (ps != null && filterAppAccessLPr(ps, filterCallingUid, userId)) {
3702                    return null;
3703                }
3704                return generatePackageInfo((PackageSetting)p.mExtras, flags, userId);
3705            }
3706            if (!matchFactoryOnly && (flags & MATCH_KNOWN_PACKAGES) != 0) {
3707                final PackageSetting ps = mSettings.mPackages.get(packageName);
3708                if (ps == null) return null;
3709                if (filterSharedLibPackageLPr(ps, filterCallingUid, userId, flags)) {
3710                    return null;
3711                }
3712                if (filterAppAccessLPr(ps, filterCallingUid, userId)) {
3713                    return null;
3714                }
3715                return generatePackageInfo(ps, flags, userId);
3716            }
3717        }
3718        return null;
3719    }
3720
3721    private boolean isComponentVisibleToInstantApp(@Nullable ComponentName component) {
3722        if (isComponentVisibleToInstantApp(component, TYPE_ACTIVITY)) {
3723            return true;
3724        }
3725        if (isComponentVisibleToInstantApp(component, TYPE_SERVICE)) {
3726            return true;
3727        }
3728        if (isComponentVisibleToInstantApp(component, TYPE_PROVIDER)) {
3729            return true;
3730        }
3731        return false;
3732    }
3733
3734    private boolean isComponentVisibleToInstantApp(
3735            @Nullable ComponentName component, @ComponentType int type) {
3736        if (type == TYPE_ACTIVITY) {
3737            final PackageParser.Activity activity = mActivities.mActivities.get(component);
3738            return activity != null
3739                    ? (activity.info.flags & ActivityInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0
3740                    : false;
3741        } else if (type == TYPE_RECEIVER) {
3742            final PackageParser.Activity activity = mReceivers.mActivities.get(component);
3743            return activity != null
3744                    ? (activity.info.flags & ActivityInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0
3745                    : false;
3746        } else if (type == TYPE_SERVICE) {
3747            final PackageParser.Service service = mServices.mServices.get(component);
3748            return service != null
3749                    ? (service.info.flags & ServiceInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0
3750                    : false;
3751        } else if (type == TYPE_PROVIDER) {
3752            final PackageParser.Provider provider = mProviders.mProviders.get(component);
3753            return provider != null
3754                    ? (provider.info.flags & ProviderInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0
3755                    : false;
3756        } else if (type == TYPE_UNKNOWN) {
3757            return isComponentVisibleToInstantApp(component);
3758        }
3759        return false;
3760    }
3761
3762    /**
3763     * Returns whether or not access to the application should be filtered.
3764     * <p>
3765     * Access may be limited based upon whether the calling or target applications
3766     * are instant applications.
3767     *
3768     * @see #canAccessInstantApps(int)
3769     */
3770    private boolean filterAppAccessLPr(@Nullable PackageSetting ps, int callingUid,
3771            @Nullable ComponentName component, @ComponentType int componentType, int userId) {
3772        // if we're in an isolated process, get the real calling UID
3773        if (Process.isIsolated(callingUid)) {
3774            callingUid = mIsolatedOwners.get(callingUid);
3775        }
3776        final String instantAppPkgName = getInstantAppPackageName(callingUid);
3777        final boolean callerIsInstantApp = instantAppPkgName != null;
3778        if (ps == null) {
3779            if (callerIsInstantApp) {
3780                // pretend the application exists, but, needs to be filtered
3781                return true;
3782            }
3783            return false;
3784        }
3785        // if the target and caller are the same application, don't filter
3786        if (isCallerSameApp(ps.name, callingUid)) {
3787            return false;
3788        }
3789        if (callerIsInstantApp) {
3790            // request for a specific component; if it hasn't been explicitly exposed, filter
3791            if (component != null) {
3792                return !isComponentVisibleToInstantApp(component, componentType);
3793            }
3794            // request for application; if no components have been explicitly exposed, filter
3795            return ps.getInstantApp(userId) || !ps.pkg.visibleToInstantApps;
3796        }
3797        if (ps.getInstantApp(userId)) {
3798            // caller can see all components of all instant applications, don't filter
3799            if (canViewInstantApps(callingUid, userId)) {
3800                return false;
3801            }
3802            // request for a specific instant application component, filter
3803            if (component != null) {
3804                return true;
3805            }
3806            // request for an instant application; if the caller hasn't been granted access, filter
3807            return !mInstantAppRegistry.isInstantAccessGranted(
3808                    userId, UserHandle.getAppId(callingUid), ps.appId);
3809        }
3810        return false;
3811    }
3812
3813    /**
3814     * @see #filterAppAccessLPr(PackageSetting, int, ComponentName, boolean, int)
3815     */
3816    private boolean filterAppAccessLPr(@Nullable PackageSetting ps, int callingUid, int userId) {
3817        return filterAppAccessLPr(ps, callingUid, null, TYPE_UNKNOWN, userId);
3818    }
3819
3820    private boolean filterSharedLibPackageLPr(@Nullable PackageSetting ps, int uid, int userId,
3821            int flags) {
3822        // Callers can access only the libs they depend on, otherwise they need to explicitly
3823        // ask for the shared libraries given the caller is allowed to access all static libs.
3824        if ((flags & PackageManager.MATCH_STATIC_SHARED_LIBRARIES) != 0) {
3825            // System/shell/root get to see all static libs
3826            final int appId = UserHandle.getAppId(uid);
3827            if (appId == Process.SYSTEM_UID || appId == Process.SHELL_UID
3828                    || appId == Process.ROOT_UID) {
3829                return false;
3830            }
3831        }
3832
3833        // No package means no static lib as it is always on internal storage
3834        if (ps == null || ps.pkg == null || !ps.pkg.applicationInfo.isStaticSharedLibrary()) {
3835            return false;
3836        }
3837
3838        final SharedLibraryEntry libEntry = getSharedLibraryEntryLPr(ps.pkg.staticSharedLibName,
3839                ps.pkg.staticSharedLibVersion);
3840        if (libEntry == null) {
3841            return false;
3842        }
3843
3844        final int resolvedUid = UserHandle.getUid(userId, UserHandle.getAppId(uid));
3845        final String[] uidPackageNames = getPackagesForUid(resolvedUid);
3846        if (uidPackageNames == null) {
3847            return true;
3848        }
3849
3850        for (String uidPackageName : uidPackageNames) {
3851            if (ps.name.equals(uidPackageName)) {
3852                return false;
3853            }
3854            PackageSetting uidPs = mSettings.getPackageLPr(uidPackageName);
3855            if (uidPs != null) {
3856                final int index = ArrayUtils.indexOf(uidPs.usesStaticLibraries,
3857                        libEntry.info.getName());
3858                if (index < 0) {
3859                    continue;
3860                }
3861                if (uidPs.pkg.usesStaticLibrariesVersions[index] == libEntry.info.getVersion()) {
3862                    return false;
3863                }
3864            }
3865        }
3866        return true;
3867    }
3868
3869    @Override
3870    public String[] currentToCanonicalPackageNames(String[] names) {
3871        final int callingUid = Binder.getCallingUid();
3872        if (getInstantAppPackageName(callingUid) != null) {
3873            return names;
3874        }
3875        final String[] out = new String[names.length];
3876        // reader
3877        synchronized (mPackages) {
3878            final int callingUserId = UserHandle.getUserId(callingUid);
3879            final boolean canViewInstantApps = canViewInstantApps(callingUid, callingUserId);
3880            for (int i=names.length-1; i>=0; i--) {
3881                final PackageSetting ps = mSettings.mPackages.get(names[i]);
3882                boolean translateName = false;
3883                if (ps != null && ps.realName != null) {
3884                    final boolean targetIsInstantApp = ps.getInstantApp(callingUserId);
3885                    translateName = !targetIsInstantApp
3886                            || canViewInstantApps
3887                            || mInstantAppRegistry.isInstantAccessGranted(callingUserId,
3888                                    UserHandle.getAppId(callingUid), ps.appId);
3889                }
3890                out[i] = translateName ? ps.realName : names[i];
3891            }
3892        }
3893        return out;
3894    }
3895
3896    @Override
3897    public String[] canonicalToCurrentPackageNames(String[] names) {
3898        final int callingUid = Binder.getCallingUid();
3899        if (getInstantAppPackageName(callingUid) != null) {
3900            return names;
3901        }
3902        final String[] out = new String[names.length];
3903        // reader
3904        synchronized (mPackages) {
3905            final int callingUserId = UserHandle.getUserId(callingUid);
3906            final boolean canViewInstantApps = canViewInstantApps(callingUid, callingUserId);
3907            for (int i=names.length-1; i>=0; i--) {
3908                final String cur = mSettings.getRenamedPackageLPr(names[i]);
3909                boolean translateName = false;
3910                if (cur != null) {
3911                    final PackageSetting ps = mSettings.mPackages.get(names[i]);
3912                    final boolean targetIsInstantApp =
3913                            ps != null && ps.getInstantApp(callingUserId);
3914                    translateName = !targetIsInstantApp
3915                            || canViewInstantApps
3916                            || mInstantAppRegistry.isInstantAccessGranted(callingUserId,
3917                                    UserHandle.getAppId(callingUid), ps.appId);
3918                }
3919                out[i] = translateName ? cur : names[i];
3920            }
3921        }
3922        return out;
3923    }
3924
3925    @Override
3926    public int getPackageUid(String packageName, int flags, int userId) {
3927        if (!sUserManager.exists(userId)) return -1;
3928        final int callingUid = Binder.getCallingUid();
3929        flags = updateFlagsForPackage(flags, userId, packageName);
3930        enforceCrossUserPermission(callingUid, userId,
3931                false /*requireFullPermission*/, false /*checkShell*/, "getPackageUid");
3932
3933        // reader
3934        synchronized (mPackages) {
3935            final PackageParser.Package p = mPackages.get(packageName);
3936            if (p != null && p.isMatch(flags)) {
3937                PackageSetting ps = (PackageSetting) p.mExtras;
3938                if (filterAppAccessLPr(ps, callingUid, userId)) {
3939                    return -1;
3940                }
3941                return UserHandle.getUid(userId, p.applicationInfo.uid);
3942            }
3943            if ((flags & MATCH_KNOWN_PACKAGES) != 0) {
3944                final PackageSetting ps = mSettings.mPackages.get(packageName);
3945                if (ps != null && ps.isMatch(flags)
3946                        && !filterAppAccessLPr(ps, callingUid, userId)) {
3947                    return UserHandle.getUid(userId, ps.appId);
3948                }
3949            }
3950        }
3951
3952        return -1;
3953    }
3954
3955    @Override
3956    public int[] getPackageGids(String packageName, int flags, int userId) {
3957        if (!sUserManager.exists(userId)) return null;
3958        final int callingUid = Binder.getCallingUid();
3959        flags = updateFlagsForPackage(flags, userId, packageName);
3960        enforceCrossUserPermission(callingUid, userId,
3961                false /*requireFullPermission*/, false /*checkShell*/, "getPackageGids");
3962
3963        // reader
3964        synchronized (mPackages) {
3965            final PackageParser.Package p = mPackages.get(packageName);
3966            if (p != null && p.isMatch(flags)) {
3967                PackageSetting ps = (PackageSetting) p.mExtras;
3968                if (filterAppAccessLPr(ps, callingUid, userId)) {
3969                    return null;
3970                }
3971                // TODO: Shouldn't this be checking for package installed state for userId and
3972                // return null?
3973                return ps.getPermissionsState().computeGids(userId);
3974            }
3975            if ((flags & MATCH_KNOWN_PACKAGES) != 0) {
3976                final PackageSetting ps = mSettings.mPackages.get(packageName);
3977                if (ps != null && ps.isMatch(flags)
3978                        && !filterAppAccessLPr(ps, callingUid, userId)) {
3979                    return ps.getPermissionsState().computeGids(userId);
3980                }
3981            }
3982        }
3983
3984        return null;
3985    }
3986
3987    static PermissionInfo generatePermissionInfo(BasePermission bp, int flags) {
3988        if (bp.perm != null) {
3989            return PackageParser.generatePermissionInfo(bp.perm, flags);
3990        }
3991        PermissionInfo pi = new PermissionInfo();
3992        pi.name = bp.name;
3993        pi.packageName = bp.sourcePackage;
3994        pi.nonLocalizedLabel = bp.name;
3995        pi.protectionLevel = bp.protectionLevel;
3996        return pi;
3997    }
3998
3999    @Override
4000    public PermissionInfo getPermissionInfo(String name, String packageName, int flags) {
4001        final int callingUid = Binder.getCallingUid();
4002        if (getInstantAppPackageName(callingUid) != null) {
4003            return null;
4004        }
4005        // reader
4006        synchronized (mPackages) {
4007            final BasePermission p = mSettings.mPermissions.get(name);
4008            if (p == null) {
4009                return null;
4010            }
4011            // If the caller is an app that targets pre 26 SDK drop protection flags.
4012            final PermissionInfo permissionInfo = generatePermissionInfo(p, flags);
4013            if (permissionInfo != null) {
4014                permissionInfo.protectionLevel = adjustPermissionProtectionFlagsLPr(
4015                        permissionInfo.protectionLevel, packageName, callingUid);
4016            }
4017            return permissionInfo;
4018        }
4019    }
4020
4021    private int adjustPermissionProtectionFlagsLPr(int protectionLevel,
4022            String packageName, int uid) {
4023        // Signature permission flags area always reported
4024        final int protectionLevelMasked = protectionLevel
4025                & (PermissionInfo.PROTECTION_NORMAL
4026                | PermissionInfo.PROTECTION_DANGEROUS
4027                | PermissionInfo.PROTECTION_SIGNATURE);
4028        if (protectionLevelMasked == PermissionInfo.PROTECTION_SIGNATURE) {
4029            return protectionLevel;
4030        }
4031
4032        // System sees all flags.
4033        final int appId = UserHandle.getAppId(uid);
4034        if (appId == Process.SYSTEM_UID || appId == Process.ROOT_UID
4035                || appId == Process.SHELL_UID) {
4036            return protectionLevel;
4037        }
4038
4039        // Normalize package name to handle renamed packages and static libs
4040        packageName = resolveInternalPackageNameLPr(packageName,
4041                PackageManager.VERSION_CODE_HIGHEST);
4042
4043        // Apps that target O see flags for all protection levels.
4044        final PackageSetting ps = mSettings.mPackages.get(packageName);
4045        if (ps == null) {
4046            return protectionLevel;
4047        }
4048        if (ps.appId != appId) {
4049            return protectionLevel;
4050        }
4051
4052        final PackageParser.Package pkg = mPackages.get(packageName);
4053        if (pkg == null) {
4054            return protectionLevel;
4055        }
4056        if (pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.O) {
4057            return protectionLevelMasked;
4058        }
4059
4060        return protectionLevel;
4061    }
4062
4063    @Override
4064    public @Nullable ParceledListSlice<PermissionInfo> queryPermissionsByGroup(String group,
4065            int flags) {
4066        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
4067            return null;
4068        }
4069        // reader
4070        synchronized (mPackages) {
4071            if (group != null && !mPermissionGroups.containsKey(group)) {
4072                // This is thrown as NameNotFoundException
4073                return null;
4074            }
4075
4076            ArrayList<PermissionInfo> out = new ArrayList<PermissionInfo>(10);
4077            for (BasePermission p : mSettings.mPermissions.values()) {
4078                if (group == null) {
4079                    if (p.perm == null || p.perm.info.group == null) {
4080                        out.add(generatePermissionInfo(p, flags));
4081                    }
4082                } else {
4083                    if (p.perm != null && group.equals(p.perm.info.group)) {
4084                        out.add(PackageParser.generatePermissionInfo(p.perm, flags));
4085                    }
4086                }
4087            }
4088            return new ParceledListSlice<>(out);
4089        }
4090    }
4091
4092    @Override
4093    public PermissionGroupInfo getPermissionGroupInfo(String name, int flags) {
4094        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
4095            return null;
4096        }
4097        // reader
4098        synchronized (mPackages) {
4099            return PackageParser.generatePermissionGroupInfo(
4100                    mPermissionGroups.get(name), flags);
4101        }
4102    }
4103
4104    @Override
4105    public @NonNull ParceledListSlice<PermissionGroupInfo> getAllPermissionGroups(int flags) {
4106        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
4107            return ParceledListSlice.emptyList();
4108        }
4109        // reader
4110        synchronized (mPackages) {
4111            final int N = mPermissionGroups.size();
4112            ArrayList<PermissionGroupInfo> out
4113                    = new ArrayList<PermissionGroupInfo>(N);
4114            for (PackageParser.PermissionGroup pg : mPermissionGroups.values()) {
4115                out.add(PackageParser.generatePermissionGroupInfo(pg, flags));
4116            }
4117            return new ParceledListSlice<>(out);
4118        }
4119    }
4120
4121    private ApplicationInfo generateApplicationInfoFromSettingsLPw(String packageName, int flags,
4122            int filterCallingUid, int userId) {
4123        if (!sUserManager.exists(userId)) return null;
4124        PackageSetting ps = mSettings.mPackages.get(packageName);
4125        if (ps != null) {
4126            if (filterSharedLibPackageLPr(ps, filterCallingUid, userId, flags)) {
4127                return null;
4128            }
4129            if (filterAppAccessLPr(ps, filterCallingUid, userId)) {
4130                return null;
4131            }
4132            if (ps.pkg == null) {
4133                final PackageInfo pInfo = generatePackageInfo(ps, flags, userId);
4134                if (pInfo != null) {
4135                    return pInfo.applicationInfo;
4136                }
4137                return null;
4138            }
4139            ApplicationInfo ai = PackageParser.generateApplicationInfo(ps.pkg, flags,
4140                    ps.readUserState(userId), userId);
4141            if (ai != null) {
4142                ai.packageName = resolveExternalPackageNameLPr(ps.pkg);
4143            }
4144            return ai;
4145        }
4146        return null;
4147    }
4148
4149    @Override
4150    public ApplicationInfo getApplicationInfo(String packageName, int flags, int userId) {
4151        return getApplicationInfoInternal(packageName, flags, Binder.getCallingUid(), userId);
4152    }
4153
4154    /**
4155     * Important: The provided filterCallingUid is used exclusively to filter out applications
4156     * that can be seen based on user state. It's typically the original caller uid prior
4157     * to clearing. Because it can only be provided by trusted code, it's value can be
4158     * trusted and will be used as-is; unlike userId which will be validated by this method.
4159     */
4160    private ApplicationInfo getApplicationInfoInternal(String packageName, int flags,
4161            int filterCallingUid, int userId) {
4162        if (!sUserManager.exists(userId)) return null;
4163        flags = updateFlagsForApplication(flags, userId, packageName);
4164        enforceCrossUserPermission(Binder.getCallingUid(), userId,
4165                false /* requireFullPermission */, false /* checkShell */, "get application info");
4166
4167        // writer
4168        synchronized (mPackages) {
4169            // Normalize package name to handle renamed packages and static libs
4170            packageName = resolveInternalPackageNameLPr(packageName,
4171                    PackageManager.VERSION_CODE_HIGHEST);
4172
4173            PackageParser.Package p = mPackages.get(packageName);
4174            if (DEBUG_PACKAGE_INFO) Log.v(
4175                    TAG, "getApplicationInfo " + packageName
4176                    + ": " + p);
4177            if (p != null) {
4178                PackageSetting ps = mSettings.mPackages.get(packageName);
4179                if (ps == null) return null;
4180                if (filterSharedLibPackageLPr(ps, filterCallingUid, userId, flags)) {
4181                    return null;
4182                }
4183                if (filterAppAccessLPr(ps, filterCallingUid, userId)) {
4184                    return null;
4185                }
4186                // Note: isEnabledLP() does not apply here - always return info
4187                ApplicationInfo ai = PackageParser.generateApplicationInfo(
4188                        p, flags, ps.readUserState(userId), userId);
4189                if (ai != null) {
4190                    ai.packageName = resolveExternalPackageNameLPr(p);
4191                }
4192                return ai;
4193            }
4194            if ("android".equals(packageName)||"system".equals(packageName)) {
4195                return mAndroidApplication;
4196            }
4197            if ((flags & MATCH_KNOWN_PACKAGES) != 0) {
4198                // Already generates the external package name
4199                return generateApplicationInfoFromSettingsLPw(packageName,
4200                        flags, filterCallingUid, userId);
4201            }
4202        }
4203        return null;
4204    }
4205
4206    private String normalizePackageNameLPr(String packageName) {
4207        String normalizedPackageName = mSettings.getRenamedPackageLPr(packageName);
4208        return normalizedPackageName != null ? normalizedPackageName : packageName;
4209    }
4210
4211    @Override
4212    public void deletePreloadsFileCache() {
4213        if (!UserHandle.isSameApp(Binder.getCallingUid(), Process.SYSTEM_UID)) {
4214            throw new SecurityException("Only system or settings may call deletePreloadsFileCache");
4215        }
4216        File dir = Environment.getDataPreloadsFileCacheDirectory();
4217        Slog.i(TAG, "Deleting preloaded file cache " + dir);
4218        FileUtils.deleteContents(dir);
4219    }
4220
4221    @Override
4222    public void freeStorageAndNotify(final String volumeUuid, final long freeStorageSize,
4223            final int storageFlags, final IPackageDataObserver observer) {
4224        mContext.enforceCallingOrSelfPermission(
4225                android.Manifest.permission.CLEAR_APP_CACHE, null);
4226        mHandler.post(() -> {
4227            boolean success = false;
4228            try {
4229                freeStorage(volumeUuid, freeStorageSize, storageFlags);
4230                success = true;
4231            } catch (IOException e) {
4232                Slog.w(TAG, e);
4233            }
4234            if (observer != null) {
4235                try {
4236                    observer.onRemoveCompleted(null, success);
4237                } catch (RemoteException e) {
4238                    Slog.w(TAG, e);
4239                }
4240            }
4241        });
4242    }
4243
4244    @Override
4245    public void freeStorage(final String volumeUuid, final long freeStorageSize,
4246            final int storageFlags, final IntentSender pi) {
4247        mContext.enforceCallingOrSelfPermission(
4248                android.Manifest.permission.CLEAR_APP_CACHE, TAG);
4249        mHandler.post(() -> {
4250            boolean success = false;
4251            try {
4252                freeStorage(volumeUuid, freeStorageSize, storageFlags);
4253                success = true;
4254            } catch (IOException e) {
4255                Slog.w(TAG, e);
4256            }
4257            if (pi != null) {
4258                try {
4259                    pi.sendIntent(null, success ? 1 : 0, null, null, null);
4260                } catch (SendIntentException e) {
4261                    Slog.w(TAG, e);
4262                }
4263            }
4264        });
4265    }
4266
4267    /**
4268     * Blocking call to clear various types of cached data across the system
4269     * until the requested bytes are available.
4270     */
4271    public void freeStorage(String volumeUuid, long bytes, int storageFlags) throws IOException {
4272        final StorageManager storage = mContext.getSystemService(StorageManager.class);
4273        final File file = storage.findPathForUuid(volumeUuid);
4274        if (file.getUsableSpace() >= bytes) return;
4275
4276        if (ENABLE_FREE_CACHE_V2) {
4277            final boolean internalVolume = Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL,
4278                    volumeUuid);
4279            final boolean aggressive = (storageFlags
4280                    & StorageManager.FLAG_ALLOCATE_AGGRESSIVE) != 0;
4281            final long reservedBytes = storage.getStorageCacheBytes(file, storageFlags);
4282
4283            // 1. Pre-flight to determine if we have any chance to succeed
4284            // 2. Consider preloaded data (after 1w honeymoon, unless aggressive)
4285            if (internalVolume && (aggressive || SystemProperties
4286                    .getBoolean("persist.sys.preloads.file_cache_expired", false))) {
4287                deletePreloadsFileCache();
4288                if (file.getUsableSpace() >= bytes) return;
4289            }
4290
4291            // 3. Consider parsed APK data (aggressive only)
4292            if (internalVolume && aggressive) {
4293                FileUtils.deleteContents(mCacheDir);
4294                if (file.getUsableSpace() >= bytes) return;
4295            }
4296
4297            // 4. Consider cached app data (above quotas)
4298            try {
4299                mInstaller.freeCache(volumeUuid, bytes, reservedBytes,
4300                        Installer.FLAG_FREE_CACHE_V2);
4301            } catch (InstallerException ignored) {
4302            }
4303            if (file.getUsableSpace() >= bytes) return;
4304
4305            // 5. Consider shared libraries with refcount=0 and age>min cache period
4306            if (internalVolume && pruneUnusedStaticSharedLibraries(bytes,
4307                    android.provider.Settings.Global.getLong(mContext.getContentResolver(),
4308                            Global.UNUSED_STATIC_SHARED_LIB_MIN_CACHE_PERIOD,
4309                            DEFAULT_UNUSED_STATIC_SHARED_LIB_MIN_CACHE_PERIOD))) {
4310                return;
4311            }
4312
4313            // 6. Consider dexopt output (aggressive only)
4314            // TODO: Implement
4315
4316            // 7. Consider installed instant apps unused longer than min cache period
4317            if (internalVolume && mInstantAppRegistry.pruneInstalledInstantApps(bytes,
4318                    android.provider.Settings.Global.getLong(mContext.getContentResolver(),
4319                            Global.INSTALLED_INSTANT_APP_MIN_CACHE_PERIOD,
4320                            InstantAppRegistry.DEFAULT_INSTALLED_INSTANT_APP_MIN_CACHE_PERIOD))) {
4321                return;
4322            }
4323
4324            // 8. Consider cached app data (below quotas)
4325            try {
4326                mInstaller.freeCache(volumeUuid, bytes, reservedBytes,
4327                        Installer.FLAG_FREE_CACHE_V2 | Installer.FLAG_FREE_CACHE_V2_DEFY_QUOTA);
4328            } catch (InstallerException ignored) {
4329            }
4330            if (file.getUsableSpace() >= bytes) return;
4331
4332            // 9. Consider DropBox entries
4333            // TODO: Implement
4334
4335            // 10. Consider instant meta-data (uninstalled apps) older that min cache period
4336            if (internalVolume && mInstantAppRegistry.pruneUninstalledInstantApps(bytes,
4337                    android.provider.Settings.Global.getLong(mContext.getContentResolver(),
4338                            Global.UNINSTALLED_INSTANT_APP_MIN_CACHE_PERIOD,
4339                            InstantAppRegistry.DEFAULT_UNINSTALLED_INSTANT_APP_MIN_CACHE_PERIOD))) {
4340                return;
4341            }
4342        } else {
4343            try {
4344                mInstaller.freeCache(volumeUuid, bytes, 0, 0);
4345            } catch (InstallerException ignored) {
4346            }
4347            if (file.getUsableSpace() >= bytes) return;
4348        }
4349
4350        throw new IOException("Failed to free " + bytes + " on storage device at " + file);
4351    }
4352
4353    private boolean pruneUnusedStaticSharedLibraries(long neededSpace, long maxCachePeriod)
4354            throws IOException {
4355        final StorageManager storage = mContext.getSystemService(StorageManager.class);
4356        final File volume = storage.findPathForUuid(StorageManager.UUID_PRIVATE_INTERNAL);
4357
4358        List<VersionedPackage> packagesToDelete = null;
4359        final long now = System.currentTimeMillis();
4360
4361        synchronized (mPackages) {
4362            final int[] allUsers = sUserManager.getUserIds();
4363            final int libCount = mSharedLibraries.size();
4364            for (int i = 0; i < libCount; i++) {
4365                final SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.valueAt(i);
4366                if (versionedLib == null) {
4367                    continue;
4368                }
4369                final int versionCount = versionedLib.size();
4370                for (int j = 0; j < versionCount; j++) {
4371                    SharedLibraryInfo libInfo = versionedLib.valueAt(j).info;
4372                    // Skip packages that are not static shared libs.
4373                    if (!libInfo.isStatic()) {
4374                        break;
4375                    }
4376                    // Important: We skip static shared libs used for some user since
4377                    // in such a case we need to keep the APK on the device. The check for
4378                    // a lib being used for any user is performed by the uninstall call.
4379                    final VersionedPackage declaringPackage = libInfo.getDeclaringPackage();
4380                    // Resolve the package name - we use synthetic package names internally
4381                    final String internalPackageName = resolveInternalPackageNameLPr(
4382                            declaringPackage.getPackageName(), declaringPackage.getVersionCode());
4383                    final PackageSetting ps = mSettings.getPackageLPr(internalPackageName);
4384                    // Skip unused static shared libs cached less than the min period
4385                    // to prevent pruning a lib needed by a subsequently installed package.
4386                    if (ps == null || now - ps.lastUpdateTime < maxCachePeriod) {
4387                        continue;
4388                    }
4389                    if (packagesToDelete == null) {
4390                        packagesToDelete = new ArrayList<>();
4391                    }
4392                    packagesToDelete.add(new VersionedPackage(internalPackageName,
4393                            declaringPackage.getVersionCode()));
4394                }
4395            }
4396        }
4397
4398        if (packagesToDelete != null) {
4399            final int packageCount = packagesToDelete.size();
4400            for (int i = 0; i < packageCount; i++) {
4401                final VersionedPackage pkgToDelete = packagesToDelete.get(i);
4402                // Delete the package synchronously (will fail of the lib used for any user).
4403                if (deletePackageX(pkgToDelete.getPackageName(), pkgToDelete.getVersionCode(),
4404                        UserHandle.USER_SYSTEM, PackageManager.DELETE_ALL_USERS)
4405                                == PackageManager.DELETE_SUCCEEDED) {
4406                    if (volume.getUsableSpace() >= neededSpace) {
4407                        return true;
4408                    }
4409                }
4410            }
4411        }
4412
4413        return false;
4414    }
4415
4416    /**
4417     * Update given flags based on encryption status of current user.
4418     */
4419    private int updateFlags(int flags, int userId) {
4420        if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE
4421                | PackageManager.MATCH_DIRECT_BOOT_AWARE)) != 0) {
4422            // Caller expressed an explicit opinion about what encryption
4423            // aware/unaware components they want to see, so fall through and
4424            // give them what they want
4425        } else {
4426            // Caller expressed no opinion, so match based on user state
4427            if (getUserManagerInternal().isUserUnlockingOrUnlocked(userId)) {
4428                flags |= PackageManager.MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE;
4429            } else {
4430                flags |= PackageManager.MATCH_DIRECT_BOOT_AWARE;
4431            }
4432        }
4433        return flags;
4434    }
4435
4436    private UserManagerInternal getUserManagerInternal() {
4437        if (mUserManagerInternal == null) {
4438            mUserManagerInternal = LocalServices.getService(UserManagerInternal.class);
4439        }
4440        return mUserManagerInternal;
4441    }
4442
4443    private DeviceIdleController.LocalService getDeviceIdleController() {
4444        if (mDeviceIdleController == null) {
4445            mDeviceIdleController =
4446                    LocalServices.getService(DeviceIdleController.LocalService.class);
4447        }
4448        return mDeviceIdleController;
4449    }
4450
4451    /**
4452     * Update given flags when being used to request {@link PackageInfo}.
4453     */
4454    private int updateFlagsForPackage(int flags, int userId, Object cookie) {
4455        final boolean isCallerSystemUser = UserHandle.getCallingUserId() == UserHandle.USER_SYSTEM;
4456        boolean triaged = true;
4457        if ((flags & (PackageManager.GET_ACTIVITIES | PackageManager.GET_RECEIVERS
4458                | PackageManager.GET_SERVICES | PackageManager.GET_PROVIDERS)) != 0) {
4459            // Caller is asking for component details, so they'd better be
4460            // asking for specific encryption matching behavior, or be triaged
4461            if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE
4462                    | PackageManager.MATCH_DIRECT_BOOT_AWARE
4463                    | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) {
4464                triaged = false;
4465            }
4466        }
4467        if ((flags & (PackageManager.MATCH_UNINSTALLED_PACKAGES
4468                | PackageManager.MATCH_SYSTEM_ONLY
4469                | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) {
4470            triaged = false;
4471        }
4472        if ((flags & PackageManager.MATCH_ANY_USER) != 0) {
4473            enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false,
4474                    "MATCH_ANY_USER flag requires INTERACT_ACROSS_USERS permission at "
4475                    + Debug.getCallers(5));
4476        } else if ((flags & PackageManager.MATCH_UNINSTALLED_PACKAGES) != 0 && isCallerSystemUser
4477                && sUserManager.hasManagedProfile(UserHandle.USER_SYSTEM)) {
4478            // If the caller wants all packages and has a restricted profile associated with it,
4479            // then match all users. This is to make sure that launchers that need to access work
4480            // profile apps don't start breaking. TODO: Remove this hack when launchers stop using
4481            // MATCH_UNINSTALLED_PACKAGES to query apps in other profiles. b/31000380
4482            flags |= PackageManager.MATCH_ANY_USER;
4483        }
4484        if (DEBUG_TRIAGED_MISSING && (Binder.getCallingUid() == Process.SYSTEM_UID) && !triaged) {
4485            Log.w(TAG, "Caller hasn't been triaged for missing apps; they asked about " + cookie
4486                    + " with flags 0x" + Integer.toHexString(flags), new Throwable());
4487        }
4488        return updateFlags(flags, userId);
4489    }
4490
4491    /**
4492     * Update given flags when being used to request {@link ApplicationInfo}.
4493     */
4494    private int updateFlagsForApplication(int flags, int userId, Object cookie) {
4495        return updateFlagsForPackage(flags, userId, cookie);
4496    }
4497
4498    /**
4499     * Update given flags when being used to request {@link ComponentInfo}.
4500     */
4501    private int updateFlagsForComponent(int flags, int userId, Object cookie) {
4502        if (cookie instanceof Intent) {
4503            if ((((Intent) cookie).getFlags() & Intent.FLAG_DEBUG_TRIAGED_MISSING) != 0) {
4504                flags |= PackageManager.MATCH_DEBUG_TRIAGED_MISSING;
4505            }
4506        }
4507
4508        boolean triaged = true;
4509        // Caller is asking for component details, so they'd better be
4510        // asking for specific encryption matching behavior, or be triaged
4511        if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE
4512                | PackageManager.MATCH_DIRECT_BOOT_AWARE
4513                | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) {
4514            triaged = false;
4515        }
4516        if (DEBUG_TRIAGED_MISSING && (Binder.getCallingUid() == Process.SYSTEM_UID) && !triaged) {
4517            Log.w(TAG, "Caller hasn't been triaged for missing apps; they asked about " + cookie
4518                    + " with flags 0x" + Integer.toHexString(flags), new Throwable());
4519        }
4520
4521        return updateFlags(flags, userId);
4522    }
4523
4524    /**
4525     * Update given intent when being used to request {@link ResolveInfo}.
4526     */
4527    private Intent updateIntentForResolve(Intent intent) {
4528        if (intent.getSelector() != null) {
4529            intent = intent.getSelector();
4530        }
4531        if (DEBUG_PREFERRED) {
4532            intent.addFlags(Intent.FLAG_DEBUG_LOG_RESOLUTION);
4533        }
4534        return intent;
4535    }
4536
4537    /**
4538     * Update given flags when being used to request {@link ResolveInfo}.
4539     * <p>Instant apps are resolved specially, depending upon context. Minimally,
4540     * {@code}flags{@code} must have the {@link PackageManager#MATCH_INSTANT}
4541     * flag set. However, this flag is only honoured in three circumstances:
4542     * <ul>
4543     * <li>when called from a system process</li>
4544     * <li>when the caller holds the permission {@code android.permission.ACCESS_INSTANT_APPS}</li>
4545     * <li>when resolution occurs to start an activity with a {@code android.intent.action.VIEW}
4546     * action and a {@code android.intent.category.BROWSABLE} category</li>
4547     * </ul>
4548     */
4549    int updateFlagsForResolve(int flags, int userId, Intent intent, int callingUid) {
4550        return updateFlagsForResolve(flags, userId, intent, callingUid,
4551                false /*wantInstantApps*/, false /*onlyExposedExplicitly*/);
4552    }
4553    int updateFlagsForResolve(int flags, int userId, Intent intent, int callingUid,
4554            boolean wantInstantApps) {
4555        return updateFlagsForResolve(flags, userId, intent, callingUid,
4556                wantInstantApps, false /*onlyExposedExplicitly*/);
4557    }
4558    int updateFlagsForResolve(int flags, int userId, Intent intent, int callingUid,
4559            boolean wantInstantApps, boolean onlyExposedExplicitly) {
4560        // Safe mode means we shouldn't match any third-party components
4561        if (mSafeMode) {
4562            flags |= PackageManager.MATCH_SYSTEM_ONLY;
4563        }
4564        if (getInstantAppPackageName(callingUid) != null) {
4565            // But, ephemeral apps see both ephemeral and exposed, non-ephemeral components
4566            if (onlyExposedExplicitly) {
4567                flags |= PackageManager.MATCH_EXPLICITLY_VISIBLE_ONLY;
4568            }
4569            flags |= PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY;
4570            flags |= PackageManager.MATCH_INSTANT;
4571        } else {
4572            final boolean wantMatchInstant = (flags & PackageManager.MATCH_INSTANT) != 0;
4573            final boolean allowMatchInstant =
4574                    (wantInstantApps
4575                            && Intent.ACTION_VIEW.equals(intent.getAction())
4576                            && hasWebURI(intent))
4577                    || (wantMatchInstant && canViewInstantApps(callingUid, userId));
4578            flags &= ~(PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY
4579                    | PackageManager.MATCH_EXPLICITLY_VISIBLE_ONLY);
4580            if (!allowMatchInstant) {
4581                flags &= ~PackageManager.MATCH_INSTANT;
4582            }
4583        }
4584        return updateFlagsForComponent(flags, userId, intent /*cookie*/);
4585    }
4586
4587    @Override
4588    public ActivityInfo getActivityInfo(ComponentName component, int flags, int userId) {
4589        return getActivityInfoInternal(component, flags, Binder.getCallingUid(), userId);
4590    }
4591
4592    /**
4593     * Important: The provided filterCallingUid is used exclusively to filter out activities
4594     * that can be seen based on user state. It's typically the original caller uid prior
4595     * to clearing. Because it can only be provided by trusted code, it's value can be
4596     * trusted and will be used as-is; unlike userId which will be validated by this method.
4597     */
4598    private ActivityInfo getActivityInfoInternal(ComponentName component, int flags,
4599            int filterCallingUid, int userId) {
4600        if (!sUserManager.exists(userId)) return null;
4601        flags = updateFlagsForComponent(flags, userId, component);
4602        enforceCrossUserPermission(Binder.getCallingUid(), userId,
4603                false /* requireFullPermission */, false /* checkShell */, "get activity info");
4604        synchronized (mPackages) {
4605            PackageParser.Activity a = mActivities.mActivities.get(component);
4606
4607            if (DEBUG_PACKAGE_INFO) Log.v(TAG, "getActivityInfo " + component + ": " + a);
4608            if (a != null && mSettings.isEnabledAndMatchLPr(a.info, flags, userId)) {
4609                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
4610                if (ps == null) return null;
4611                if (filterAppAccessLPr(ps, filterCallingUid, component, TYPE_ACTIVITY, userId)) {
4612                    return null;
4613                }
4614                return PackageParser.generateActivityInfo(
4615                        a, flags, ps.readUserState(userId), userId);
4616            }
4617            if (mResolveComponentName.equals(component)) {
4618                return PackageParser.generateActivityInfo(
4619                        mResolveActivity, flags, new PackageUserState(), userId);
4620            }
4621        }
4622        return null;
4623    }
4624
4625    @Override
4626    public boolean activitySupportsIntent(ComponentName component, Intent intent,
4627            String resolvedType) {
4628        synchronized (mPackages) {
4629            if (component.equals(mResolveComponentName)) {
4630                // The resolver supports EVERYTHING!
4631                return true;
4632            }
4633            final int callingUid = Binder.getCallingUid();
4634            final int callingUserId = UserHandle.getUserId(callingUid);
4635            PackageParser.Activity a = mActivities.mActivities.get(component);
4636            if (a == null) {
4637                return false;
4638            }
4639            PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
4640            if (ps == null) {
4641                return false;
4642            }
4643            if (filterAppAccessLPr(ps, callingUid, component, TYPE_ACTIVITY, callingUserId)) {
4644                return false;
4645            }
4646            for (int i=0; i<a.intents.size(); i++) {
4647                if (a.intents.get(i).match(intent.getAction(), resolvedType, intent.getScheme(),
4648                        intent.getData(), intent.getCategories(), TAG) >= 0) {
4649                    return true;
4650                }
4651            }
4652            return false;
4653        }
4654    }
4655
4656    @Override
4657    public ActivityInfo getReceiverInfo(ComponentName component, int flags, int userId) {
4658        if (!sUserManager.exists(userId)) return null;
4659        final int callingUid = Binder.getCallingUid();
4660        flags = updateFlagsForComponent(flags, userId, component);
4661        enforceCrossUserPermission(callingUid, userId,
4662                false /* requireFullPermission */, false /* checkShell */, "get receiver info");
4663        synchronized (mPackages) {
4664            PackageParser.Activity a = mReceivers.mActivities.get(component);
4665            if (DEBUG_PACKAGE_INFO) Log.v(
4666                TAG, "getReceiverInfo " + component + ": " + a);
4667            if (a != null && mSettings.isEnabledAndMatchLPr(a.info, flags, userId)) {
4668                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
4669                if (ps == null) return null;
4670                if (filterAppAccessLPr(ps, callingUid, component, TYPE_RECEIVER, userId)) {
4671                    return null;
4672                }
4673                return PackageParser.generateActivityInfo(
4674                        a, flags, ps.readUserState(userId), userId);
4675            }
4676        }
4677        return null;
4678    }
4679
4680    @Override
4681    public ParceledListSlice<SharedLibraryInfo> getSharedLibraries(String packageName,
4682            int flags, int userId) {
4683        if (!sUserManager.exists(userId)) return null;
4684        Preconditions.checkArgumentNonnegative(userId, "userId must be >= 0");
4685        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
4686            return null;
4687        }
4688
4689        flags = updateFlagsForPackage(flags, userId, null);
4690
4691        final boolean canSeeStaticLibraries =
4692                mContext.checkCallingOrSelfPermission(INSTALL_PACKAGES)
4693                        == PERMISSION_GRANTED
4694                || mContext.checkCallingOrSelfPermission(DELETE_PACKAGES)
4695                        == PERMISSION_GRANTED
4696                || canRequestPackageInstallsInternal(packageName,
4697                        PackageManager.MATCH_STATIC_SHARED_LIBRARIES, userId,
4698                        false  /* throwIfPermNotDeclared*/)
4699                || mContext.checkCallingOrSelfPermission(REQUEST_DELETE_PACKAGES)
4700                        == PERMISSION_GRANTED;
4701
4702        synchronized (mPackages) {
4703            List<SharedLibraryInfo> result = null;
4704
4705            final int libCount = mSharedLibraries.size();
4706            for (int i = 0; i < libCount; i++) {
4707                SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.valueAt(i);
4708                if (versionedLib == null) {
4709                    continue;
4710                }
4711
4712                final int versionCount = versionedLib.size();
4713                for (int j = 0; j < versionCount; j++) {
4714                    SharedLibraryInfo libInfo = versionedLib.valueAt(j).info;
4715                    if (!canSeeStaticLibraries && libInfo.isStatic()) {
4716                        break;
4717                    }
4718                    final long identity = Binder.clearCallingIdentity();
4719                    try {
4720                        PackageInfo packageInfo = getPackageInfoVersioned(
4721                                libInfo.getDeclaringPackage(), flags
4722                                        | PackageManager.MATCH_STATIC_SHARED_LIBRARIES, userId);
4723                        if (packageInfo == null) {
4724                            continue;
4725                        }
4726                    } finally {
4727                        Binder.restoreCallingIdentity(identity);
4728                    }
4729
4730                    SharedLibraryInfo resLibInfo = new SharedLibraryInfo(libInfo.getName(),
4731                            libInfo.getVersion(), libInfo.getType(),
4732                            libInfo.getDeclaringPackage(), getPackagesUsingSharedLibraryLPr(libInfo,
4733                            flags, userId));
4734
4735                    if (result == null) {
4736                        result = new ArrayList<>();
4737                    }
4738                    result.add(resLibInfo);
4739                }
4740            }
4741
4742            return result != null ? new ParceledListSlice<>(result) : null;
4743        }
4744    }
4745
4746    private List<VersionedPackage> getPackagesUsingSharedLibraryLPr(
4747            SharedLibraryInfo libInfo, int flags, int userId) {
4748        List<VersionedPackage> versionedPackages = null;
4749        final int packageCount = mSettings.mPackages.size();
4750        for (int i = 0; i < packageCount; i++) {
4751            PackageSetting ps = mSettings.mPackages.valueAt(i);
4752
4753            if (ps == null) {
4754                continue;
4755            }
4756
4757            if (!ps.getUserState().get(userId).isAvailable(flags)) {
4758                continue;
4759            }
4760
4761            final String libName = libInfo.getName();
4762            if (libInfo.isStatic()) {
4763                final int libIdx = ArrayUtils.indexOf(ps.usesStaticLibraries, libName);
4764                if (libIdx < 0) {
4765                    continue;
4766                }
4767                if (ps.usesStaticLibrariesVersions[libIdx] != libInfo.getVersion()) {
4768                    continue;
4769                }
4770                if (versionedPackages == null) {
4771                    versionedPackages = new ArrayList<>();
4772                }
4773                // If the dependent is a static shared lib, use the public package name
4774                String dependentPackageName = ps.name;
4775                if (ps.pkg != null && ps.pkg.applicationInfo.isStaticSharedLibrary()) {
4776                    dependentPackageName = ps.pkg.manifestPackageName;
4777                }
4778                versionedPackages.add(new VersionedPackage(dependentPackageName, ps.versionCode));
4779            } else if (ps.pkg != null) {
4780                if (ArrayUtils.contains(ps.pkg.usesLibraries, libName)
4781                        || ArrayUtils.contains(ps.pkg.usesOptionalLibraries, libName)) {
4782                    if (versionedPackages == null) {
4783                        versionedPackages = new ArrayList<>();
4784                    }
4785                    versionedPackages.add(new VersionedPackage(ps.name, ps.versionCode));
4786                }
4787            }
4788        }
4789
4790        return versionedPackages;
4791    }
4792
4793    @Override
4794    public ServiceInfo getServiceInfo(ComponentName component, int flags, int userId) {
4795        if (!sUserManager.exists(userId)) return null;
4796        final int callingUid = Binder.getCallingUid();
4797        flags = updateFlagsForComponent(flags, userId, component);
4798        enforceCrossUserPermission(callingUid, userId,
4799                false /* requireFullPermission */, false /* checkShell */, "get service info");
4800        synchronized (mPackages) {
4801            PackageParser.Service s = mServices.mServices.get(component);
4802            if (DEBUG_PACKAGE_INFO) Log.v(
4803                TAG, "getServiceInfo " + component + ": " + s);
4804            if (s != null && mSettings.isEnabledAndMatchLPr(s.info, flags, userId)) {
4805                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
4806                if (ps == null) return null;
4807                if (filterAppAccessLPr(ps, callingUid, component, TYPE_SERVICE, userId)) {
4808                    return null;
4809                }
4810                return PackageParser.generateServiceInfo(
4811                        s, flags, ps.readUserState(userId), userId);
4812            }
4813        }
4814        return null;
4815    }
4816
4817    @Override
4818    public ProviderInfo getProviderInfo(ComponentName component, int flags, int userId) {
4819        if (!sUserManager.exists(userId)) return null;
4820        final int callingUid = Binder.getCallingUid();
4821        flags = updateFlagsForComponent(flags, userId, component);
4822        enforceCrossUserPermission(callingUid, userId,
4823                false /* requireFullPermission */, false /* checkShell */, "get provider info");
4824        synchronized (mPackages) {
4825            PackageParser.Provider p = mProviders.mProviders.get(component);
4826            if (DEBUG_PACKAGE_INFO) Log.v(
4827                TAG, "getProviderInfo " + component + ": " + p);
4828            if (p != null && mSettings.isEnabledAndMatchLPr(p.info, flags, userId)) {
4829                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
4830                if (ps == null) return null;
4831                if (filterAppAccessLPr(ps, callingUid, component, TYPE_PROVIDER, userId)) {
4832                    return null;
4833                }
4834                return PackageParser.generateProviderInfo(
4835                        p, flags, ps.readUserState(userId), userId);
4836            }
4837        }
4838        return null;
4839    }
4840
4841    @Override
4842    public String[] getSystemSharedLibraryNames() {
4843        // allow instant applications
4844        synchronized (mPackages) {
4845            Set<String> libs = null;
4846            final int libCount = mSharedLibraries.size();
4847            for (int i = 0; i < libCount; i++) {
4848                SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.valueAt(i);
4849                if (versionedLib == null) {
4850                    continue;
4851                }
4852                final int versionCount = versionedLib.size();
4853                for (int j = 0; j < versionCount; j++) {
4854                    SharedLibraryEntry libEntry = versionedLib.valueAt(j);
4855                    if (!libEntry.info.isStatic()) {
4856                        if (libs == null) {
4857                            libs = new ArraySet<>();
4858                        }
4859                        libs.add(libEntry.info.getName());
4860                        break;
4861                    }
4862                    PackageSetting ps = mSettings.getPackageLPr(libEntry.apk);
4863                    if (ps != null && !filterSharedLibPackageLPr(ps, Binder.getCallingUid(),
4864                            UserHandle.getUserId(Binder.getCallingUid()),
4865                            PackageManager.MATCH_STATIC_SHARED_LIBRARIES)) {
4866                        if (libs == null) {
4867                            libs = new ArraySet<>();
4868                        }
4869                        libs.add(libEntry.info.getName());
4870                        break;
4871                    }
4872                }
4873            }
4874
4875            if (libs != null) {
4876                String[] libsArray = new String[libs.size()];
4877                libs.toArray(libsArray);
4878                return libsArray;
4879            }
4880
4881            return null;
4882        }
4883    }
4884
4885    @Override
4886    public @NonNull String getServicesSystemSharedLibraryPackageName() {
4887        // allow instant applications
4888        synchronized (mPackages) {
4889            return mServicesSystemSharedLibraryPackageName;
4890        }
4891    }
4892
4893    @Override
4894    public @NonNull String getSharedSystemSharedLibraryPackageName() {
4895        // allow instant applications
4896        synchronized (mPackages) {
4897            return mSharedSystemSharedLibraryPackageName;
4898        }
4899    }
4900
4901    private void updateSequenceNumberLP(PackageSetting pkgSetting, int[] userList) {
4902        for (int i = userList.length - 1; i >= 0; --i) {
4903            final int userId = userList[i];
4904            // don't add instant app to the list of updates
4905            if (pkgSetting.getInstantApp(userId)) {
4906                continue;
4907            }
4908            SparseArray<String> changedPackages = mChangedPackages.get(userId);
4909            if (changedPackages == null) {
4910                changedPackages = new SparseArray<>();
4911                mChangedPackages.put(userId, changedPackages);
4912            }
4913            Map<String, Integer> sequenceNumbers = mChangedPackagesSequenceNumbers.get(userId);
4914            if (sequenceNumbers == null) {
4915                sequenceNumbers = new HashMap<>();
4916                mChangedPackagesSequenceNumbers.put(userId, sequenceNumbers);
4917            }
4918            final Integer sequenceNumber = sequenceNumbers.get(pkgSetting.name);
4919            if (sequenceNumber != null) {
4920                changedPackages.remove(sequenceNumber);
4921            }
4922            changedPackages.put(mChangedPackagesSequenceNumber, pkgSetting.name);
4923            sequenceNumbers.put(pkgSetting.name, mChangedPackagesSequenceNumber);
4924        }
4925        mChangedPackagesSequenceNumber++;
4926    }
4927
4928    @Override
4929    public ChangedPackages getChangedPackages(int sequenceNumber, int userId) {
4930        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
4931            return null;
4932        }
4933        synchronized (mPackages) {
4934            if (sequenceNumber >= mChangedPackagesSequenceNumber) {
4935                return null;
4936            }
4937            final SparseArray<String> changedPackages = mChangedPackages.get(userId);
4938            if (changedPackages == null) {
4939                return null;
4940            }
4941            final List<String> packageNames =
4942                    new ArrayList<>(mChangedPackagesSequenceNumber - sequenceNumber);
4943            for (int i = sequenceNumber; i < mChangedPackagesSequenceNumber; i++) {
4944                final String packageName = changedPackages.get(i);
4945                if (packageName != null) {
4946                    packageNames.add(packageName);
4947                }
4948            }
4949            return packageNames.isEmpty()
4950                    ? null : new ChangedPackages(mChangedPackagesSequenceNumber, packageNames);
4951        }
4952    }
4953
4954    @Override
4955    public @NonNull ParceledListSlice<FeatureInfo> getSystemAvailableFeatures() {
4956        // allow instant applications
4957        ArrayList<FeatureInfo> res;
4958        synchronized (mAvailableFeatures) {
4959            res = new ArrayList<>(mAvailableFeatures.size() + 1);
4960            res.addAll(mAvailableFeatures.values());
4961        }
4962        final FeatureInfo fi = new FeatureInfo();
4963        fi.reqGlEsVersion = SystemProperties.getInt("ro.opengles.version",
4964                FeatureInfo.GL_ES_VERSION_UNDEFINED);
4965        res.add(fi);
4966
4967        return new ParceledListSlice<>(res);
4968    }
4969
4970    @Override
4971    public boolean hasSystemFeature(String name, int version) {
4972        // allow instant applications
4973        synchronized (mAvailableFeatures) {
4974            final FeatureInfo feat = mAvailableFeatures.get(name);
4975            if (feat == null) {
4976                return false;
4977            } else {
4978                return feat.version >= version;
4979            }
4980        }
4981    }
4982
4983    @Override
4984    public int checkPermission(String permName, String pkgName, int userId) {
4985        if (!sUserManager.exists(userId)) {
4986            return PackageManager.PERMISSION_DENIED;
4987        }
4988        final int callingUid = Binder.getCallingUid();
4989
4990        synchronized (mPackages) {
4991            final PackageParser.Package p = mPackages.get(pkgName);
4992            if (p != null && p.mExtras != null) {
4993                final PackageSetting ps = (PackageSetting) p.mExtras;
4994                if (filterAppAccessLPr(ps, callingUid, userId)) {
4995                    return PackageManager.PERMISSION_DENIED;
4996                }
4997                final boolean instantApp = ps.getInstantApp(userId);
4998                final PermissionsState permissionsState = ps.getPermissionsState();
4999                if (permissionsState.hasPermission(permName, userId)) {
5000                    if (instantApp) {
5001                        BasePermission bp = mSettings.mPermissions.get(permName);
5002                        if (bp != null && bp.isInstant()) {
5003                            return PackageManager.PERMISSION_GRANTED;
5004                        }
5005                    } else {
5006                        return PackageManager.PERMISSION_GRANTED;
5007                    }
5008                }
5009                // Special case: ACCESS_FINE_LOCATION permission includes ACCESS_COARSE_LOCATION
5010                if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && permissionsState
5011                        .hasPermission(Manifest.permission.ACCESS_FINE_LOCATION, userId)) {
5012                    return PackageManager.PERMISSION_GRANTED;
5013                }
5014            }
5015        }
5016
5017        return PackageManager.PERMISSION_DENIED;
5018    }
5019
5020    @Override
5021    public int checkUidPermission(String permName, int uid) {
5022        final int callingUid = Binder.getCallingUid();
5023        final int callingUserId = UserHandle.getUserId(callingUid);
5024        final boolean isCallerInstantApp = getInstantAppPackageName(callingUid) != null;
5025        final boolean isUidInstantApp = getInstantAppPackageName(uid) != null;
5026        final int userId = UserHandle.getUserId(uid);
5027        if (!sUserManager.exists(userId)) {
5028            return PackageManager.PERMISSION_DENIED;
5029        }
5030
5031        synchronized (mPackages) {
5032            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
5033            if (obj != null) {
5034                if (obj instanceof SharedUserSetting) {
5035                    if (isCallerInstantApp) {
5036                        return PackageManager.PERMISSION_DENIED;
5037                    }
5038                } else if (obj instanceof PackageSetting) {
5039                    final PackageSetting ps = (PackageSetting) obj;
5040                    if (filterAppAccessLPr(ps, callingUid, callingUserId)) {
5041                        return PackageManager.PERMISSION_DENIED;
5042                    }
5043                }
5044                final SettingBase settingBase = (SettingBase) obj;
5045                final PermissionsState permissionsState = settingBase.getPermissionsState();
5046                if (permissionsState.hasPermission(permName, userId)) {
5047                    if (isUidInstantApp) {
5048                        BasePermission bp = mSettings.mPermissions.get(permName);
5049                        if (bp != null && bp.isInstant()) {
5050                            return PackageManager.PERMISSION_GRANTED;
5051                        }
5052                    } else {
5053                        return PackageManager.PERMISSION_GRANTED;
5054                    }
5055                }
5056                // Special case: ACCESS_FINE_LOCATION permission includes ACCESS_COARSE_LOCATION
5057                if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && permissionsState
5058                        .hasPermission(Manifest.permission.ACCESS_FINE_LOCATION, userId)) {
5059                    return PackageManager.PERMISSION_GRANTED;
5060                }
5061            } else {
5062                ArraySet<String> perms = mSystemPermissions.get(uid);
5063                if (perms != null) {
5064                    if (perms.contains(permName)) {
5065                        return PackageManager.PERMISSION_GRANTED;
5066                    }
5067                    if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && perms
5068                            .contains(Manifest.permission.ACCESS_FINE_LOCATION)) {
5069                        return PackageManager.PERMISSION_GRANTED;
5070                    }
5071                }
5072            }
5073        }
5074
5075        return PackageManager.PERMISSION_DENIED;
5076    }
5077
5078    @Override
5079    public boolean isPermissionRevokedByPolicy(String permission, String packageName, int userId) {
5080        if (UserHandle.getCallingUserId() != userId) {
5081            mContext.enforceCallingPermission(
5082                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
5083                    "isPermissionRevokedByPolicy for user " + userId);
5084        }
5085
5086        if (checkPermission(permission, packageName, userId)
5087                == PackageManager.PERMISSION_GRANTED) {
5088            return false;
5089        }
5090
5091        final int callingUid = Binder.getCallingUid();
5092        if (getInstantAppPackageName(callingUid) != null) {
5093            if (!isCallerSameApp(packageName, callingUid)) {
5094                return false;
5095            }
5096        } else {
5097            if (isInstantApp(packageName, userId)) {
5098                return false;
5099            }
5100        }
5101
5102        final long identity = Binder.clearCallingIdentity();
5103        try {
5104            final int flags = getPermissionFlags(permission, packageName, userId);
5105            return (flags & PackageManager.FLAG_PERMISSION_POLICY_FIXED) != 0;
5106        } finally {
5107            Binder.restoreCallingIdentity(identity);
5108        }
5109    }
5110
5111    @Override
5112    public String getPermissionControllerPackageName() {
5113        synchronized (mPackages) {
5114            return mRequiredInstallerPackage;
5115        }
5116    }
5117
5118    /**
5119     * Checks if the request is from the system or an app that has INTERACT_ACROSS_USERS
5120     * or INTERACT_ACROSS_USERS_FULL permissions, if the userid is not for the caller.
5121     * @param checkShell whether to prevent shell from access if there's a debugging restriction
5122     * @param message the message to log on security exception
5123     */
5124    void enforceCrossUserPermission(int callingUid, int userId, boolean requireFullPermission,
5125            boolean checkShell, String message) {
5126        if (userId < 0) {
5127            throw new IllegalArgumentException("Invalid userId " + userId);
5128        }
5129        if (checkShell) {
5130            enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, userId);
5131        }
5132        if (userId == UserHandle.getUserId(callingUid)) return;
5133        if (callingUid != Process.SYSTEM_UID && callingUid != 0) {
5134            if (requireFullPermission) {
5135                mContext.enforceCallingOrSelfPermission(
5136                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message);
5137            } else {
5138                try {
5139                    mContext.enforceCallingOrSelfPermission(
5140                            android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message);
5141                } catch (SecurityException se) {
5142                    mContext.enforceCallingOrSelfPermission(
5143                            android.Manifest.permission.INTERACT_ACROSS_USERS, message);
5144                }
5145            }
5146        }
5147    }
5148
5149    void enforceShellRestriction(String restriction, int callingUid, int userHandle) {
5150        if (callingUid == Process.SHELL_UID) {
5151            if (userHandle >= 0
5152                    && sUserManager.hasUserRestriction(restriction, userHandle)) {
5153                throw new SecurityException("Shell does not have permission to access user "
5154                        + userHandle);
5155            } else if (userHandle < 0) {
5156                Slog.e(TAG, "Unable to check shell permission for user " + userHandle + "\n\t"
5157                        + Debug.getCallers(3));
5158            }
5159        }
5160    }
5161
5162    private BasePermission findPermissionTreeLP(String permName) {
5163        for(BasePermission bp : mSettings.mPermissionTrees.values()) {
5164            if (permName.startsWith(bp.name) &&
5165                    permName.length() > bp.name.length() &&
5166                    permName.charAt(bp.name.length()) == '.') {
5167                return bp;
5168            }
5169        }
5170        return null;
5171    }
5172
5173    private BasePermission checkPermissionTreeLP(String permName) {
5174        if (permName != null) {
5175            BasePermission bp = findPermissionTreeLP(permName);
5176            if (bp != null) {
5177                if (bp.uid == UserHandle.getAppId(Binder.getCallingUid())) {
5178                    return bp;
5179                }
5180                throw new SecurityException("Calling uid "
5181                        + Binder.getCallingUid()
5182                        + " is not allowed to add to permission tree "
5183                        + bp.name + " owned by uid " + bp.uid);
5184            }
5185        }
5186        throw new SecurityException("No permission tree found for " + permName);
5187    }
5188
5189    static boolean compareStrings(CharSequence s1, CharSequence s2) {
5190        if (s1 == null) {
5191            return s2 == null;
5192        }
5193        if (s2 == null) {
5194            return false;
5195        }
5196        if (s1.getClass() != s2.getClass()) {
5197            return false;
5198        }
5199        return s1.equals(s2);
5200    }
5201
5202    static boolean comparePermissionInfos(PermissionInfo pi1, PermissionInfo pi2) {
5203        if (pi1.icon != pi2.icon) return false;
5204        if (pi1.logo != pi2.logo) return false;
5205        if (pi1.protectionLevel != pi2.protectionLevel) return false;
5206        if (!compareStrings(pi1.name, pi2.name)) return false;
5207        if (!compareStrings(pi1.nonLocalizedLabel, pi2.nonLocalizedLabel)) return false;
5208        // We'll take care of setting this one.
5209        if (!compareStrings(pi1.packageName, pi2.packageName)) return false;
5210        // These are not currently stored in settings.
5211        //if (!compareStrings(pi1.group, pi2.group)) return false;
5212        //if (!compareStrings(pi1.nonLocalizedDescription, pi2.nonLocalizedDescription)) return false;
5213        //if (pi1.labelRes != pi2.labelRes) return false;
5214        //if (pi1.descriptionRes != pi2.descriptionRes) return false;
5215        return true;
5216    }
5217
5218    int permissionInfoFootprint(PermissionInfo info) {
5219        int size = info.name.length();
5220        if (info.nonLocalizedLabel != null) size += info.nonLocalizedLabel.length();
5221        if (info.nonLocalizedDescription != null) size += info.nonLocalizedDescription.length();
5222        return size;
5223    }
5224
5225    int calculateCurrentPermissionFootprintLocked(BasePermission tree) {
5226        int size = 0;
5227        for (BasePermission perm : mSettings.mPermissions.values()) {
5228            if (perm.uid == tree.uid) {
5229                size += perm.name.length() + permissionInfoFootprint(perm.perm.info);
5230            }
5231        }
5232        return size;
5233    }
5234
5235    void enforcePermissionCapLocked(PermissionInfo info, BasePermission tree) {
5236        // We calculate the max size of permissions defined by this uid and throw
5237        // if that plus the size of 'info' would exceed our stated maximum.
5238        if (tree.uid != Process.SYSTEM_UID) {
5239            final int curTreeSize = calculateCurrentPermissionFootprintLocked(tree);
5240            if (curTreeSize + permissionInfoFootprint(info) > MAX_PERMISSION_TREE_FOOTPRINT) {
5241                throw new SecurityException("Permission tree size cap exceeded");
5242            }
5243        }
5244    }
5245
5246    boolean addPermissionLocked(PermissionInfo info, boolean async) {
5247        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
5248            throw new SecurityException("Instant apps can't add permissions");
5249        }
5250        if (info.labelRes == 0 && info.nonLocalizedLabel == null) {
5251            throw new SecurityException("Label must be specified in permission");
5252        }
5253        BasePermission tree = checkPermissionTreeLP(info.name);
5254        BasePermission bp = mSettings.mPermissions.get(info.name);
5255        boolean added = bp == null;
5256        boolean changed = true;
5257        int fixedLevel = PermissionInfo.fixProtectionLevel(info.protectionLevel);
5258        if (added) {
5259            enforcePermissionCapLocked(info, tree);
5260            bp = new BasePermission(info.name, tree.sourcePackage,
5261                    BasePermission.TYPE_DYNAMIC);
5262        } else if (bp.type != BasePermission.TYPE_DYNAMIC) {
5263            throw new SecurityException(
5264                    "Not allowed to modify non-dynamic permission "
5265                    + info.name);
5266        } else {
5267            if (bp.protectionLevel == fixedLevel
5268                    && bp.perm.owner.equals(tree.perm.owner)
5269                    && bp.uid == tree.uid
5270                    && comparePermissionInfos(bp.perm.info, info)) {
5271                changed = false;
5272            }
5273        }
5274        bp.protectionLevel = fixedLevel;
5275        info = new PermissionInfo(info);
5276        info.protectionLevel = fixedLevel;
5277        bp.perm = new PackageParser.Permission(tree.perm.owner, info);
5278        bp.perm.info.packageName = tree.perm.info.packageName;
5279        bp.uid = tree.uid;
5280        if (added) {
5281            mSettings.mPermissions.put(info.name, bp);
5282        }
5283        if (changed) {
5284            if (!async) {
5285                mSettings.writeLPr();
5286            } else {
5287                scheduleWriteSettingsLocked();
5288            }
5289        }
5290        return added;
5291    }
5292
5293    @Override
5294    public boolean addPermission(PermissionInfo info) {
5295        synchronized (mPackages) {
5296            return addPermissionLocked(info, false);
5297        }
5298    }
5299
5300    @Override
5301    public boolean addPermissionAsync(PermissionInfo info) {
5302        synchronized (mPackages) {
5303            return addPermissionLocked(info, true);
5304        }
5305    }
5306
5307    @Override
5308    public void removePermission(String name) {
5309        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
5310            throw new SecurityException("Instant applications don't have access to this method");
5311        }
5312        synchronized (mPackages) {
5313            checkPermissionTreeLP(name);
5314            BasePermission bp = mSettings.mPermissions.get(name);
5315            if (bp != null) {
5316                if (bp.type != BasePermission.TYPE_DYNAMIC) {
5317                    throw new SecurityException(
5318                            "Not allowed to modify non-dynamic permission "
5319                            + name);
5320                }
5321                mSettings.mPermissions.remove(name);
5322                mSettings.writeLPr();
5323            }
5324        }
5325    }
5326
5327    private static void enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(
5328            PackageParser.Package pkg, BasePermission bp) {
5329        int index = pkg.requestedPermissions.indexOf(bp.name);
5330        if (index == -1) {
5331            throw new SecurityException("Package " + pkg.packageName
5332                    + " has not requested permission " + bp.name);
5333        }
5334        if (!bp.isRuntime() && !bp.isDevelopment()) {
5335            throw new SecurityException("Permission " + bp.name
5336                    + " is not a changeable permission type");
5337        }
5338    }
5339
5340    @Override
5341    public void grantRuntimePermission(String packageName, String name, final int userId) {
5342        grantRuntimePermission(packageName, name, userId, false /* Only if not fixed by policy */);
5343    }
5344
5345    private void grantRuntimePermission(String packageName, String name, final int userId,
5346            boolean overridePolicy) {
5347        if (!sUserManager.exists(userId)) {
5348            Log.e(TAG, "No such user:" + userId);
5349            return;
5350        }
5351        final int callingUid = Binder.getCallingUid();
5352
5353        mContext.enforceCallingOrSelfPermission(
5354                android.Manifest.permission.GRANT_RUNTIME_PERMISSIONS,
5355                "grantRuntimePermission");
5356
5357        enforceCrossUserPermission(callingUid, userId,
5358                true /* requireFullPermission */, true /* checkShell */,
5359                "grantRuntimePermission");
5360
5361        final int uid;
5362        final PackageSetting ps;
5363
5364        synchronized (mPackages) {
5365            final PackageParser.Package pkg = mPackages.get(packageName);
5366            if (pkg == null) {
5367                throw new IllegalArgumentException("Unknown package: " + packageName);
5368            }
5369            final BasePermission bp = mSettings.mPermissions.get(name);
5370            if (bp == null) {
5371                throw new IllegalArgumentException("Unknown permission: " + name);
5372            }
5373            ps = (PackageSetting) pkg.mExtras;
5374            if (ps == null
5375                    || filterAppAccessLPr(ps, callingUid, userId)) {
5376                throw new IllegalArgumentException("Unknown package: " + packageName);
5377            }
5378
5379            enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(pkg, bp);
5380
5381            // If a permission review is required for legacy apps we represent
5382            // their permissions as always granted runtime ones since we need
5383            // to keep the review required permission flag per user while an
5384            // install permission's state is shared across all users.
5385            if (mPermissionReviewRequired
5386                    && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M
5387                    && bp.isRuntime()) {
5388                return;
5389            }
5390
5391            uid = UserHandle.getUid(userId, pkg.applicationInfo.uid);
5392
5393            final PermissionsState permissionsState = ps.getPermissionsState();
5394
5395            final int flags = permissionsState.getPermissionFlags(name, userId);
5396            if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) {
5397                throw new SecurityException("Cannot grant system fixed permission "
5398                        + name + " for package " + packageName);
5399            }
5400            if (!overridePolicy && (flags & PackageManager.FLAG_PERMISSION_POLICY_FIXED) != 0) {
5401                throw new SecurityException("Cannot grant policy fixed permission "
5402                        + name + " for package " + packageName);
5403            }
5404
5405            if (bp.isDevelopment()) {
5406                // Development permissions must be handled specially, since they are not
5407                // normal runtime permissions.  For now they apply to all users.
5408                if (permissionsState.grantInstallPermission(bp) !=
5409                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
5410                    scheduleWriteSettingsLocked();
5411                }
5412                return;
5413            }
5414
5415            if (ps.getInstantApp(userId) && !bp.isInstant()) {
5416                throw new SecurityException("Cannot grant non-ephemeral permission"
5417                        + name + " for package " + packageName);
5418            }
5419
5420            if (pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) {
5421                Slog.w(TAG, "Cannot grant runtime permission to a legacy app");
5422                return;
5423            }
5424
5425            final int result = permissionsState.grantRuntimePermission(bp, userId);
5426            switch (result) {
5427                case PermissionsState.PERMISSION_OPERATION_FAILURE: {
5428                    return;
5429                }
5430
5431                case PermissionsState.PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: {
5432                    final int appId = UserHandle.getAppId(pkg.applicationInfo.uid);
5433                    mHandler.post(new Runnable() {
5434                        @Override
5435                        public void run() {
5436                            killUid(appId, userId, KILL_APP_REASON_GIDS_CHANGED);
5437                        }
5438                    });
5439                }
5440                break;
5441            }
5442
5443            if (bp.isRuntime()) {
5444                logPermissionGranted(mContext, name, packageName);
5445            }
5446
5447            mOnPermissionChangeListeners.onPermissionsChanged(uid);
5448
5449            // Not critical if that is lost - app has to request again.
5450            mSettings.writeRuntimePermissionsForUserLPr(userId, false);
5451        }
5452
5453        // Only need to do this if user is initialized. Otherwise it's a new user
5454        // and there are no processes running as the user yet and there's no need
5455        // to make an expensive call to remount processes for the changed permissions.
5456        if (READ_EXTERNAL_STORAGE.equals(name)
5457                || WRITE_EXTERNAL_STORAGE.equals(name)) {
5458            final long token = Binder.clearCallingIdentity();
5459            try {
5460                if (sUserManager.isInitialized(userId)) {
5461                    StorageManagerInternal storageManagerInternal = LocalServices.getService(
5462                            StorageManagerInternal.class);
5463                    storageManagerInternal.onExternalStoragePolicyChanged(uid, packageName);
5464                }
5465            } finally {
5466                Binder.restoreCallingIdentity(token);
5467            }
5468        }
5469    }
5470
5471    @Override
5472    public void revokeRuntimePermission(String packageName, String name, int userId) {
5473        revokeRuntimePermission(packageName, name, userId, false /* Only if not fixed by policy */);
5474    }
5475
5476    private void revokeRuntimePermission(String packageName, String name, int userId,
5477            boolean overridePolicy) {
5478        if (!sUserManager.exists(userId)) {
5479            Log.e(TAG, "No such user:" + userId);
5480            return;
5481        }
5482
5483        mContext.enforceCallingOrSelfPermission(
5484                android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS,
5485                "revokeRuntimePermission");
5486
5487        enforceCrossUserPermission(Binder.getCallingUid(), userId,
5488                true /* requireFullPermission */, true /* checkShell */,
5489                "revokeRuntimePermission");
5490
5491        final int appId;
5492
5493        synchronized (mPackages) {
5494            final PackageParser.Package pkg = mPackages.get(packageName);
5495            if (pkg == null) {
5496                throw new IllegalArgumentException("Unknown package: " + packageName);
5497            }
5498            final PackageSetting ps = (PackageSetting) pkg.mExtras;
5499            if (ps == null
5500                    || filterAppAccessLPr(ps, Binder.getCallingUid(), userId)) {
5501                throw new IllegalArgumentException("Unknown package: " + packageName);
5502            }
5503            final BasePermission bp = mSettings.mPermissions.get(name);
5504            if (bp == null) {
5505                throw new IllegalArgumentException("Unknown permission: " + name);
5506            }
5507
5508            enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(pkg, bp);
5509
5510            // If a permission review is required for legacy apps we represent
5511            // their permissions as always granted runtime ones since we need
5512            // to keep the review required permission flag per user while an
5513            // install permission's state is shared across all users.
5514            if (mPermissionReviewRequired
5515                    && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M
5516                    && bp.isRuntime()) {
5517                return;
5518            }
5519
5520            final PermissionsState permissionsState = ps.getPermissionsState();
5521
5522            final int flags = permissionsState.getPermissionFlags(name, userId);
5523            if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) {
5524                throw new SecurityException("Cannot revoke system fixed permission "
5525                        + name + " for package " + packageName);
5526            }
5527            if (!overridePolicy && (flags & PackageManager.FLAG_PERMISSION_POLICY_FIXED) != 0) {
5528                throw new SecurityException("Cannot revoke policy fixed permission "
5529                        + name + " for package " + packageName);
5530            }
5531
5532            if (bp.isDevelopment()) {
5533                // Development permissions must be handled specially, since they are not
5534                // normal runtime permissions.  For now they apply to all users.
5535                if (permissionsState.revokeInstallPermission(bp) !=
5536                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
5537                    scheduleWriteSettingsLocked();
5538                }
5539                return;
5540            }
5541
5542            if (permissionsState.revokeRuntimePermission(bp, userId) ==
5543                    PermissionsState.PERMISSION_OPERATION_FAILURE) {
5544                return;
5545            }
5546
5547            if (bp.isRuntime()) {
5548                logPermissionRevoked(mContext, name, packageName);
5549            }
5550
5551            mOnPermissionChangeListeners.onPermissionsChanged(pkg.applicationInfo.uid);
5552
5553            // Critical, after this call app should never have the permission.
5554            mSettings.writeRuntimePermissionsForUserLPr(userId, true);
5555
5556            appId = UserHandle.getAppId(pkg.applicationInfo.uid);
5557        }
5558
5559        killUid(appId, userId, KILL_APP_REASON_PERMISSIONS_REVOKED);
5560    }
5561
5562    /**
5563     * Get the first event id for the permission.
5564     *
5565     * <p>There are four events for each permission: <ul>
5566     *     <li>Request permission: first id + 0</li>
5567     *     <li>Grant permission: first id + 1</li>
5568     *     <li>Request for permission denied: first id + 2</li>
5569     *     <li>Revoke permission: first id + 3</li>
5570     * </ul></p>
5571     *
5572     * @param name name of the permission
5573     *
5574     * @return The first event id for the permission
5575     */
5576    private static int getBaseEventId(@NonNull String name) {
5577        int eventIdIndex = ALL_DANGEROUS_PERMISSIONS.indexOf(name);
5578
5579        if (eventIdIndex == -1) {
5580            if (AppOpsManager.permissionToOpCode(name) == AppOpsManager.OP_NONE
5581                    || "user".equals(Build.TYPE)) {
5582                Log.i(TAG, "Unknown permission " + name);
5583
5584                return MetricsEvent.ACTION_PERMISSION_REQUEST_UNKNOWN;
5585            } else {
5586                // Most likely #ALL_DANGEROUS_PERMISSIONS needs to be updated.
5587                //
5588                // Also update
5589                // - EventLogger#ALL_DANGEROUS_PERMISSIONS
5590                // - metrics_constants.proto
5591                throw new IllegalStateException("Unknown permission " + name);
5592            }
5593        }
5594
5595        return MetricsEvent.ACTION_PERMISSION_REQUEST_READ_CALENDAR + eventIdIndex * 4;
5596    }
5597
5598    /**
5599     * Log that a permission was revoked.
5600     *
5601     * @param context Context of the caller
5602     * @param name name of the permission
5603     * @param packageName package permission if for
5604     */
5605    private static void logPermissionRevoked(@NonNull Context context, @NonNull String name,
5606            @NonNull String packageName) {
5607        MetricsLogger.action(context, getBaseEventId(name) + 3, packageName);
5608    }
5609
5610    /**
5611     * Log that a permission request was granted.
5612     *
5613     * @param context Context of the caller
5614     * @param name name of the permission
5615     * @param packageName package permission if for
5616     */
5617    private static void logPermissionGranted(@NonNull Context context, @NonNull String name,
5618            @NonNull String packageName) {
5619        MetricsLogger.action(context, getBaseEventId(name) + 1, packageName);
5620    }
5621
5622    @Override
5623    public void resetRuntimePermissions() {
5624        mContext.enforceCallingOrSelfPermission(
5625                android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS,
5626                "revokeRuntimePermission");
5627
5628        int callingUid = Binder.getCallingUid();
5629        if (callingUid != Process.SYSTEM_UID && callingUid != 0) {
5630            mContext.enforceCallingOrSelfPermission(
5631                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
5632                    "resetRuntimePermissions");
5633        }
5634
5635        synchronized (mPackages) {
5636            updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL);
5637            for (int userId : UserManagerService.getInstance().getUserIds()) {
5638                final int packageCount = mPackages.size();
5639                for (int i = 0; i < packageCount; i++) {
5640                    PackageParser.Package pkg = mPackages.valueAt(i);
5641                    if (!(pkg.mExtras instanceof PackageSetting)) {
5642                        continue;
5643                    }
5644                    PackageSetting ps = (PackageSetting) pkg.mExtras;
5645                    resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
5646                }
5647            }
5648        }
5649    }
5650
5651    @Override
5652    public int getPermissionFlags(String name, String packageName, int userId) {
5653        if (!sUserManager.exists(userId)) {
5654            return 0;
5655        }
5656
5657        enforceGrantRevokeRuntimePermissionPermissions("getPermissionFlags");
5658
5659        final int callingUid = Binder.getCallingUid();
5660        enforceCrossUserPermission(callingUid, userId,
5661                true /* requireFullPermission */, false /* checkShell */,
5662                "getPermissionFlags");
5663
5664        synchronized (mPackages) {
5665            final PackageParser.Package pkg = mPackages.get(packageName);
5666            if (pkg == null) {
5667                return 0;
5668            }
5669            final BasePermission bp = mSettings.mPermissions.get(name);
5670            if (bp == null) {
5671                return 0;
5672            }
5673            final PackageSetting ps = (PackageSetting) pkg.mExtras;
5674            if (ps == null
5675                    || filterAppAccessLPr(ps, callingUid, userId)) {
5676                return 0;
5677            }
5678            PermissionsState permissionsState = ps.getPermissionsState();
5679            return permissionsState.getPermissionFlags(name, userId);
5680        }
5681    }
5682
5683    @Override
5684    public void updatePermissionFlags(String name, String packageName, int flagMask,
5685            int flagValues, int userId) {
5686        if (!sUserManager.exists(userId)) {
5687            return;
5688        }
5689
5690        enforceGrantRevokeRuntimePermissionPermissions("updatePermissionFlags");
5691
5692        final int callingUid = Binder.getCallingUid();
5693        enforceCrossUserPermission(callingUid, userId,
5694                true /* requireFullPermission */, true /* checkShell */,
5695                "updatePermissionFlags");
5696
5697        // Only the system can change these flags and nothing else.
5698        if (getCallingUid() != Process.SYSTEM_UID) {
5699            flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
5700            flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
5701            flagMask &= ~PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT;
5702            flagValues &= ~PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT;
5703            flagValues &= ~PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED;
5704        }
5705
5706        synchronized (mPackages) {
5707            final PackageParser.Package pkg = mPackages.get(packageName);
5708            if (pkg == null) {
5709                throw new IllegalArgumentException("Unknown package: " + packageName);
5710            }
5711            final PackageSetting ps = (PackageSetting) pkg.mExtras;
5712            if (ps == null
5713                    || filterAppAccessLPr(ps, callingUid, userId)) {
5714                throw new IllegalArgumentException("Unknown package: " + packageName);
5715            }
5716
5717            final BasePermission bp = mSettings.mPermissions.get(name);
5718            if (bp == null) {
5719                throw new IllegalArgumentException("Unknown permission: " + name);
5720            }
5721
5722            PermissionsState permissionsState = ps.getPermissionsState();
5723
5724            boolean hadState = permissionsState.getRuntimePermissionState(name, userId) != null;
5725
5726            if (permissionsState.updatePermissionFlags(bp, userId, flagMask, flagValues)) {
5727                // Install and runtime permissions are stored in different places,
5728                // so figure out what permission changed and persist the change.
5729                if (permissionsState.getInstallPermissionState(name) != null) {
5730                    scheduleWriteSettingsLocked();
5731                } else if (permissionsState.getRuntimePermissionState(name, userId) != null
5732                        || hadState) {
5733                    mSettings.writeRuntimePermissionsForUserLPr(userId, false);
5734                }
5735            }
5736        }
5737    }
5738
5739    /**
5740     * Update the permission flags for all packages and runtime permissions of a user in order
5741     * to allow device or profile owner to remove POLICY_FIXED.
5742     */
5743    @Override
5744    public void updatePermissionFlagsForAllApps(int flagMask, int flagValues, int userId) {
5745        if (!sUserManager.exists(userId)) {
5746            return;
5747        }
5748
5749        enforceGrantRevokeRuntimePermissionPermissions("updatePermissionFlagsForAllApps");
5750
5751        enforceCrossUserPermission(Binder.getCallingUid(), userId,
5752                true /* requireFullPermission */, true /* checkShell */,
5753                "updatePermissionFlagsForAllApps");
5754
5755        // Only the system can change system fixed flags.
5756        if (getCallingUid() != Process.SYSTEM_UID) {
5757            flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
5758            flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
5759        }
5760
5761        synchronized (mPackages) {
5762            boolean changed = false;
5763            final int packageCount = mPackages.size();
5764            for (int pkgIndex = 0; pkgIndex < packageCount; pkgIndex++) {
5765                final PackageParser.Package pkg = mPackages.valueAt(pkgIndex);
5766                final PackageSetting ps = (PackageSetting) pkg.mExtras;
5767                if (ps == null) {
5768                    continue;
5769                }
5770                PermissionsState permissionsState = ps.getPermissionsState();
5771                changed |= permissionsState.updatePermissionFlagsForAllPermissions(
5772                        userId, flagMask, flagValues);
5773            }
5774            if (changed) {
5775                mSettings.writeRuntimePermissionsForUserLPr(userId, false);
5776            }
5777        }
5778    }
5779
5780    private void enforceGrantRevokeRuntimePermissionPermissions(String message) {
5781        if (mContext.checkCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS)
5782                != PackageManager.PERMISSION_GRANTED
5783            && mContext.checkCallingOrSelfPermission(Manifest.permission.REVOKE_RUNTIME_PERMISSIONS)
5784                != PackageManager.PERMISSION_GRANTED) {
5785            throw new SecurityException(message + " requires "
5786                    + Manifest.permission.GRANT_RUNTIME_PERMISSIONS + " or "
5787                    + Manifest.permission.REVOKE_RUNTIME_PERMISSIONS);
5788        }
5789    }
5790
5791    @Override
5792    public boolean shouldShowRequestPermissionRationale(String permissionName,
5793            String packageName, int userId) {
5794        if (UserHandle.getCallingUserId() != userId) {
5795            mContext.enforceCallingPermission(
5796                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
5797                    "canShowRequestPermissionRationale for user " + userId);
5798        }
5799
5800        final int uid = getPackageUid(packageName, MATCH_DEBUG_TRIAGED_MISSING, userId);
5801        if (UserHandle.getAppId(getCallingUid()) != UserHandle.getAppId(uid)) {
5802            return false;
5803        }
5804
5805        if (checkPermission(permissionName, packageName, userId)
5806                == PackageManager.PERMISSION_GRANTED) {
5807            return false;
5808        }
5809
5810        final int flags;
5811
5812        final long identity = Binder.clearCallingIdentity();
5813        try {
5814            flags = getPermissionFlags(permissionName,
5815                    packageName, userId);
5816        } finally {
5817            Binder.restoreCallingIdentity(identity);
5818        }
5819
5820        final int fixedFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED
5821                | PackageManager.FLAG_PERMISSION_POLICY_FIXED
5822                | PackageManager.FLAG_PERMISSION_USER_FIXED;
5823
5824        if ((flags & fixedFlags) != 0) {
5825            return false;
5826        }
5827
5828        return (flags & PackageManager.FLAG_PERMISSION_USER_SET) != 0;
5829    }
5830
5831    @Override
5832    public void addOnPermissionsChangeListener(IOnPermissionsChangeListener listener) {
5833        mContext.enforceCallingOrSelfPermission(
5834                Manifest.permission.OBSERVE_GRANT_REVOKE_PERMISSIONS,
5835                "addOnPermissionsChangeListener");
5836
5837        synchronized (mPackages) {
5838            mOnPermissionChangeListeners.addListenerLocked(listener);
5839        }
5840    }
5841
5842    @Override
5843    public void removeOnPermissionsChangeListener(IOnPermissionsChangeListener listener) {
5844        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
5845            throw new SecurityException("Instant applications don't have access to this method");
5846        }
5847        synchronized (mPackages) {
5848            mOnPermissionChangeListeners.removeListenerLocked(listener);
5849        }
5850    }
5851
5852    @Override
5853    public boolean isProtectedBroadcast(String actionName) {
5854        // allow instant applications
5855        synchronized (mPackages) {
5856            if (mProtectedBroadcasts.contains(actionName)) {
5857                return true;
5858            } else if (actionName != null) {
5859                // TODO: remove these terrible hacks
5860                if (actionName.startsWith("android.net.netmon.lingerExpired")
5861                        || actionName.startsWith("com.android.server.sip.SipWakeupTimer")
5862                        || actionName.startsWith("com.android.internal.telephony.data-reconnect")
5863                        || actionName.startsWith("android.net.netmon.launchCaptivePortalApp")) {
5864                    return true;
5865                }
5866            }
5867        }
5868        return false;
5869    }
5870
5871    @Override
5872    public int checkSignatures(String pkg1, String pkg2) {
5873        synchronized (mPackages) {
5874            final PackageParser.Package p1 = mPackages.get(pkg1);
5875            final PackageParser.Package p2 = mPackages.get(pkg2);
5876            if (p1 == null || p1.mExtras == null
5877                    || p2 == null || p2.mExtras == null) {
5878                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5879            }
5880            final int callingUid = Binder.getCallingUid();
5881            final int callingUserId = UserHandle.getUserId(callingUid);
5882            final PackageSetting ps1 = (PackageSetting) p1.mExtras;
5883            final PackageSetting ps2 = (PackageSetting) p2.mExtras;
5884            if (filterAppAccessLPr(ps1, callingUid, callingUserId)
5885                    || filterAppAccessLPr(ps2, callingUid, callingUserId)) {
5886                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5887            }
5888            return compareSignatures(p1.mSignatures, p2.mSignatures);
5889        }
5890    }
5891
5892    @Override
5893    public int checkUidSignatures(int uid1, int uid2) {
5894        final int callingUid = Binder.getCallingUid();
5895        final int callingUserId = UserHandle.getUserId(callingUid);
5896        final boolean isCallerInstantApp = getInstantAppPackageName(callingUid) != null;
5897        // Map to base uids.
5898        uid1 = UserHandle.getAppId(uid1);
5899        uid2 = UserHandle.getAppId(uid2);
5900        // reader
5901        synchronized (mPackages) {
5902            Signature[] s1;
5903            Signature[] s2;
5904            Object obj = mSettings.getUserIdLPr(uid1);
5905            if (obj != null) {
5906                if (obj instanceof SharedUserSetting) {
5907                    if (isCallerInstantApp) {
5908                        return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5909                    }
5910                    s1 = ((SharedUserSetting)obj).signatures.mSignatures;
5911                } else if (obj instanceof PackageSetting) {
5912                    final PackageSetting ps = (PackageSetting) obj;
5913                    if (filterAppAccessLPr(ps, callingUid, callingUserId)) {
5914                        return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5915                    }
5916                    s1 = ps.signatures.mSignatures;
5917                } else {
5918                    return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5919                }
5920            } else {
5921                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5922            }
5923            obj = mSettings.getUserIdLPr(uid2);
5924            if (obj != null) {
5925                if (obj instanceof SharedUserSetting) {
5926                    if (isCallerInstantApp) {
5927                        return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5928                    }
5929                    s2 = ((SharedUserSetting)obj).signatures.mSignatures;
5930                } else if (obj instanceof PackageSetting) {
5931                    final PackageSetting ps = (PackageSetting) obj;
5932                    if (filterAppAccessLPr(ps, callingUid, callingUserId)) {
5933                        return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5934                    }
5935                    s2 = ps.signatures.mSignatures;
5936                } else {
5937                    return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5938                }
5939            } else {
5940                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5941            }
5942            return compareSignatures(s1, s2);
5943        }
5944    }
5945
5946    /**
5947     * This method should typically only be used when granting or revoking
5948     * permissions, since the app may immediately restart after this call.
5949     * <p>
5950     * If you're doing surgery on app code/data, use {@link PackageFreezer} to
5951     * guard your work against the app being relaunched.
5952     */
5953    private void killUid(int appId, int userId, String reason) {
5954        final long identity = Binder.clearCallingIdentity();
5955        try {
5956            IActivityManager am = ActivityManager.getService();
5957            if (am != null) {
5958                try {
5959                    am.killUid(appId, userId, reason);
5960                } catch (RemoteException e) {
5961                    /* ignore - same process */
5962                }
5963            }
5964        } finally {
5965            Binder.restoreCallingIdentity(identity);
5966        }
5967    }
5968
5969    /**
5970     * Compares two sets of signatures. Returns:
5971     * <br />
5972     * {@link PackageManager#SIGNATURE_NEITHER_SIGNED}: if both signature sets are null,
5973     * <br />
5974     * {@link PackageManager#SIGNATURE_FIRST_NOT_SIGNED}: if the first signature set is null,
5975     * <br />
5976     * {@link PackageManager#SIGNATURE_SECOND_NOT_SIGNED}: if the second signature set is null,
5977     * <br />
5978     * {@link PackageManager#SIGNATURE_MATCH}: if the two signature sets are identical,
5979     * <br />
5980     * {@link PackageManager#SIGNATURE_NO_MATCH}: if the two signature sets differ.
5981     */
5982    static int compareSignatures(Signature[] s1, Signature[] s2) {
5983        if (s1 == null) {
5984            return s2 == null
5985                    ? PackageManager.SIGNATURE_NEITHER_SIGNED
5986                    : PackageManager.SIGNATURE_FIRST_NOT_SIGNED;
5987        }
5988
5989        if (s2 == null) {
5990            return PackageManager.SIGNATURE_SECOND_NOT_SIGNED;
5991        }
5992
5993        if (s1.length != s2.length) {
5994            return PackageManager.SIGNATURE_NO_MATCH;
5995        }
5996
5997        // Since both signature sets are of size 1, we can compare without HashSets.
5998        if (s1.length == 1) {
5999            return s1[0].equals(s2[0]) ?
6000                    PackageManager.SIGNATURE_MATCH :
6001                    PackageManager.SIGNATURE_NO_MATCH;
6002        }
6003
6004        ArraySet<Signature> set1 = new ArraySet<Signature>();
6005        for (Signature sig : s1) {
6006            set1.add(sig);
6007        }
6008        ArraySet<Signature> set2 = new ArraySet<Signature>();
6009        for (Signature sig : s2) {
6010            set2.add(sig);
6011        }
6012        // Make sure s2 contains all signatures in s1.
6013        if (set1.equals(set2)) {
6014            return PackageManager.SIGNATURE_MATCH;
6015        }
6016        return PackageManager.SIGNATURE_NO_MATCH;
6017    }
6018
6019    /**
6020     * If the database version for this type of package (internal storage or
6021     * external storage) is less than the version where package signatures
6022     * were updated, return true.
6023     */
6024    private boolean isCompatSignatureUpdateNeeded(PackageParser.Package scannedPkg) {
6025        final VersionInfo ver = getSettingsVersionForPackage(scannedPkg);
6026        return ver.databaseVersion < DatabaseVersion.SIGNATURE_END_ENTITY;
6027    }
6028
6029    /**
6030     * Used for backward compatibility to make sure any packages with
6031     * certificate chains get upgraded to the new style. {@code existingSigs}
6032     * will be in the old format (since they were stored on disk from before the
6033     * system upgrade) and {@code scannedSigs} will be in the newer format.
6034     */
6035    private int compareSignaturesCompat(PackageSignatures existingSigs,
6036            PackageParser.Package scannedPkg) {
6037        if (!isCompatSignatureUpdateNeeded(scannedPkg)) {
6038            return PackageManager.SIGNATURE_NO_MATCH;
6039        }
6040
6041        ArraySet<Signature> existingSet = new ArraySet<Signature>();
6042        for (Signature sig : existingSigs.mSignatures) {
6043            existingSet.add(sig);
6044        }
6045        ArraySet<Signature> scannedCompatSet = new ArraySet<Signature>();
6046        for (Signature sig : scannedPkg.mSignatures) {
6047            try {
6048                Signature[] chainSignatures = sig.getChainSignatures();
6049                for (Signature chainSig : chainSignatures) {
6050                    scannedCompatSet.add(chainSig);
6051                }
6052            } catch (CertificateEncodingException e) {
6053                scannedCompatSet.add(sig);
6054            }
6055        }
6056        /*
6057         * Make sure the expanded scanned set contains all signatures in the
6058         * existing one.
6059         */
6060        if (scannedCompatSet.equals(existingSet)) {
6061            // Migrate the old signatures to the new scheme.
6062            existingSigs.assignSignatures(scannedPkg.mSignatures);
6063            // The new KeySets will be re-added later in the scanning process.
6064            synchronized (mPackages) {
6065                mSettings.mKeySetManagerService.removeAppKeySetDataLPw(scannedPkg.packageName);
6066            }
6067            return PackageManager.SIGNATURE_MATCH;
6068        }
6069        return PackageManager.SIGNATURE_NO_MATCH;
6070    }
6071
6072    private boolean isRecoverSignatureUpdateNeeded(PackageParser.Package scannedPkg) {
6073        final VersionInfo ver = getSettingsVersionForPackage(scannedPkg);
6074        return ver.databaseVersion < DatabaseVersion.SIGNATURE_MALFORMED_RECOVER;
6075    }
6076
6077    private int compareSignaturesRecover(PackageSignatures existingSigs,
6078            PackageParser.Package scannedPkg) {
6079        if (!isRecoverSignatureUpdateNeeded(scannedPkg)) {
6080            return PackageManager.SIGNATURE_NO_MATCH;
6081        }
6082
6083        String msg = null;
6084        try {
6085            if (Signature.areEffectiveMatch(existingSigs.mSignatures, scannedPkg.mSignatures)) {
6086                logCriticalInfo(Log.INFO, "Recovered effectively matching certificates for "
6087                        + scannedPkg.packageName);
6088                return PackageManager.SIGNATURE_MATCH;
6089            }
6090        } catch (CertificateException e) {
6091            msg = e.getMessage();
6092        }
6093
6094        logCriticalInfo(Log.INFO,
6095                "Failed to recover certificates for " + scannedPkg.packageName + ": " + msg);
6096        return PackageManager.SIGNATURE_NO_MATCH;
6097    }
6098
6099    @Override
6100    public List<String> getAllPackages() {
6101        final int callingUid = Binder.getCallingUid();
6102        final int callingUserId = UserHandle.getUserId(callingUid);
6103        synchronized (mPackages) {
6104            if (canViewInstantApps(callingUid, callingUserId)) {
6105                return new ArrayList<String>(mPackages.keySet());
6106            }
6107            final String instantAppPkgName = getInstantAppPackageName(callingUid);
6108            final List<String> result = new ArrayList<>();
6109            if (instantAppPkgName != null) {
6110                // caller is an instant application; filter unexposed applications
6111                for (PackageParser.Package pkg : mPackages.values()) {
6112                    if (!pkg.visibleToInstantApps) {
6113                        continue;
6114                    }
6115                    result.add(pkg.packageName);
6116                }
6117            } else {
6118                // caller is a normal application; filter instant applications
6119                for (PackageParser.Package pkg : mPackages.values()) {
6120                    final PackageSetting ps =
6121                            pkg.mExtras != null ? (PackageSetting) pkg.mExtras : null;
6122                    if (ps != null
6123                            && ps.getInstantApp(callingUserId)
6124                            && !mInstantAppRegistry.isInstantAccessGranted(
6125                                    callingUserId, UserHandle.getAppId(callingUid), ps.appId)) {
6126                        continue;
6127                    }
6128                    result.add(pkg.packageName);
6129                }
6130            }
6131            return result;
6132        }
6133    }
6134
6135    @Override
6136    public String[] getPackagesForUid(int uid) {
6137        final int callingUid = Binder.getCallingUid();
6138        final boolean isCallerInstantApp = getInstantAppPackageName(callingUid) != null;
6139        final int userId = UserHandle.getUserId(uid);
6140        uid = UserHandle.getAppId(uid);
6141        // reader
6142        synchronized (mPackages) {
6143            Object obj = mSettings.getUserIdLPr(uid);
6144            if (obj instanceof SharedUserSetting) {
6145                if (isCallerInstantApp) {
6146                    return null;
6147                }
6148                final SharedUserSetting sus = (SharedUserSetting) obj;
6149                final int N = sus.packages.size();
6150                String[] res = new String[N];
6151                final Iterator<PackageSetting> it = sus.packages.iterator();
6152                int i = 0;
6153                while (it.hasNext()) {
6154                    PackageSetting ps = it.next();
6155                    if (ps.getInstalled(userId)) {
6156                        res[i++] = ps.name;
6157                    } else {
6158                        res = ArrayUtils.removeElement(String.class, res, res[i]);
6159                    }
6160                }
6161                return res;
6162            } else if (obj instanceof PackageSetting) {
6163                final PackageSetting ps = (PackageSetting) obj;
6164                if (ps.getInstalled(userId) && !filterAppAccessLPr(ps, callingUid, userId)) {
6165                    return new String[]{ps.name};
6166                }
6167            }
6168        }
6169        return null;
6170    }
6171
6172    @Override
6173    public String getNameForUid(int uid) {
6174        final int callingUid = Binder.getCallingUid();
6175        if (getInstantAppPackageName(callingUid) != null) {
6176            return null;
6177        }
6178        synchronized (mPackages) {
6179            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
6180            if (obj instanceof SharedUserSetting) {
6181                final SharedUserSetting sus = (SharedUserSetting) obj;
6182                return sus.name + ":" + sus.userId;
6183            } else if (obj instanceof PackageSetting) {
6184                final PackageSetting ps = (PackageSetting) obj;
6185                if (filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
6186                    return null;
6187                }
6188                return ps.name;
6189            }
6190        }
6191        return null;
6192    }
6193
6194    @Override
6195    public int getUidForSharedUser(String sharedUserName) {
6196        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
6197            return -1;
6198        }
6199        if (sharedUserName == null) {
6200            return -1;
6201        }
6202        // reader
6203        synchronized (mPackages) {
6204            SharedUserSetting suid;
6205            try {
6206                suid = mSettings.getSharedUserLPw(sharedUserName, 0, 0, false);
6207                if (suid != null) {
6208                    return suid.userId;
6209                }
6210            } catch (PackageManagerException ignore) {
6211                // can't happen, but, still need to catch it
6212            }
6213            return -1;
6214        }
6215    }
6216
6217    @Override
6218    public int getFlagsForUid(int uid) {
6219        final int callingUid = Binder.getCallingUid();
6220        if (getInstantAppPackageName(callingUid) != null) {
6221            return 0;
6222        }
6223        synchronized (mPackages) {
6224            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
6225            if (obj instanceof SharedUserSetting) {
6226                final SharedUserSetting sus = (SharedUserSetting) obj;
6227                return sus.pkgFlags;
6228            } else if (obj instanceof PackageSetting) {
6229                final PackageSetting ps = (PackageSetting) obj;
6230                if (filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
6231                    return 0;
6232                }
6233                return ps.pkgFlags;
6234            }
6235        }
6236        return 0;
6237    }
6238
6239    @Override
6240    public int getPrivateFlagsForUid(int uid) {
6241        final int callingUid = Binder.getCallingUid();
6242        if (getInstantAppPackageName(callingUid) != null) {
6243            return 0;
6244        }
6245        synchronized (mPackages) {
6246            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
6247            if (obj instanceof SharedUserSetting) {
6248                final SharedUserSetting sus = (SharedUserSetting) obj;
6249                return sus.pkgPrivateFlags;
6250            } else if (obj instanceof PackageSetting) {
6251                final PackageSetting ps = (PackageSetting) obj;
6252                if (filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
6253                    return 0;
6254                }
6255                return ps.pkgPrivateFlags;
6256            }
6257        }
6258        return 0;
6259    }
6260
6261    @Override
6262    public boolean isUidPrivileged(int uid) {
6263        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
6264            return false;
6265        }
6266        uid = UserHandle.getAppId(uid);
6267        // reader
6268        synchronized (mPackages) {
6269            Object obj = mSettings.getUserIdLPr(uid);
6270            if (obj instanceof SharedUserSetting) {
6271                final SharedUserSetting sus = (SharedUserSetting) obj;
6272                final Iterator<PackageSetting> it = sus.packages.iterator();
6273                while (it.hasNext()) {
6274                    if (it.next().isPrivileged()) {
6275                        return true;
6276                    }
6277                }
6278            } else if (obj instanceof PackageSetting) {
6279                final PackageSetting ps = (PackageSetting) obj;
6280                return ps.isPrivileged();
6281            }
6282        }
6283        return false;
6284    }
6285
6286    @Override
6287    public String[] getAppOpPermissionPackages(String permissionName) {
6288        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
6289            return null;
6290        }
6291        synchronized (mPackages) {
6292            ArraySet<String> pkgs = mAppOpPermissionPackages.get(permissionName);
6293            if (pkgs == null) {
6294                return null;
6295            }
6296            return pkgs.toArray(new String[pkgs.size()]);
6297        }
6298    }
6299
6300    @Override
6301    public ResolveInfo resolveIntent(Intent intent, String resolvedType,
6302            int flags, int userId) {
6303        return resolveIntentInternal(
6304                intent, resolvedType, flags, userId, false /*includeInstantApps*/);
6305    }
6306
6307    private ResolveInfo resolveIntentInternal(Intent intent, String resolvedType,
6308            int flags, int userId, boolean resolveForStart) {
6309        try {
6310            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "resolveIntent");
6311
6312            if (!sUserManager.exists(userId)) return null;
6313            final int callingUid = Binder.getCallingUid();
6314            flags = updateFlagsForResolve(flags, userId, intent, callingUid, resolveForStart);
6315            enforceCrossUserPermission(callingUid, userId,
6316                    false /*requireFullPermission*/, false /*checkShell*/, "resolve intent");
6317
6318            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "queryIntentActivities");
6319            final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType,
6320                    flags, callingUid, userId, resolveForStart);
6321            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
6322
6323            final ResolveInfo bestChoice =
6324                    chooseBestActivity(intent, resolvedType, flags, query, userId);
6325            return bestChoice;
6326        } finally {
6327            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
6328        }
6329    }
6330
6331    @Override
6332    public ResolveInfo findPersistentPreferredActivity(Intent intent, int userId) {
6333        if (!UserHandle.isSameApp(Binder.getCallingUid(), Process.SYSTEM_UID)) {
6334            throw new SecurityException(
6335                    "findPersistentPreferredActivity can only be run by the system");
6336        }
6337        if (!sUserManager.exists(userId)) {
6338            return null;
6339        }
6340        final int callingUid = Binder.getCallingUid();
6341        intent = updateIntentForResolve(intent);
6342        final String resolvedType = intent.resolveTypeIfNeeded(mContext.getContentResolver());
6343        final int flags = updateFlagsForResolve(
6344                0, userId, intent, callingUid, false /*includeInstantApps*/);
6345        final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags,
6346                userId);
6347        synchronized (mPackages) {
6348            return findPersistentPreferredActivityLP(intent, resolvedType, flags, query, false,
6349                    userId);
6350        }
6351    }
6352
6353    @Override
6354    public void setLastChosenActivity(Intent intent, String resolvedType, int flags,
6355            IntentFilter filter, int match, ComponentName activity) {
6356        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
6357            return;
6358        }
6359        final int userId = UserHandle.getCallingUserId();
6360        if (DEBUG_PREFERRED) {
6361            Log.v(TAG, "setLastChosenActivity intent=" + intent
6362                + " resolvedType=" + resolvedType
6363                + " flags=" + flags
6364                + " filter=" + filter
6365                + " match=" + match
6366                + " activity=" + activity);
6367            filter.dump(new PrintStreamPrinter(System.out), "    ");
6368        }
6369        intent.setComponent(null);
6370        final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags,
6371                userId);
6372        // Find any earlier preferred or last chosen entries and nuke them
6373        findPreferredActivity(intent, resolvedType,
6374                flags, query, 0, false, true, false, userId);
6375        // Add the new activity as the last chosen for this filter
6376        addPreferredActivityInternal(filter, match, null, activity, false, userId,
6377                "Setting last chosen");
6378    }
6379
6380    @Override
6381    public ResolveInfo getLastChosenActivity(Intent intent, String resolvedType, int flags) {
6382        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
6383            return null;
6384        }
6385        final int userId = UserHandle.getCallingUserId();
6386        if (DEBUG_PREFERRED) Log.v(TAG, "Querying last chosen activity for " + intent);
6387        final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags,
6388                userId);
6389        return findPreferredActivity(intent, resolvedType, flags, query, 0,
6390                false, false, false, userId);
6391    }
6392
6393    /**
6394     * Returns whether or not instant apps have been disabled remotely.
6395     */
6396    private boolean isEphemeralDisabled() {
6397        return mEphemeralAppsDisabled;
6398    }
6399
6400    private boolean isInstantAppAllowed(
6401            Intent intent, List<ResolveInfo> resolvedActivities, int userId,
6402            boolean skipPackageCheck) {
6403        if (mInstantAppResolverConnection == null) {
6404            return false;
6405        }
6406        if (mInstantAppInstallerActivity == null) {
6407            return false;
6408        }
6409        if (intent.getComponent() != null) {
6410            return false;
6411        }
6412        if ((intent.getFlags() & Intent.FLAG_IGNORE_EPHEMERAL) != 0) {
6413            return false;
6414        }
6415        if (!skipPackageCheck && intent.getPackage() != null) {
6416            return false;
6417        }
6418        final boolean isWebUri = hasWebURI(intent);
6419        if (!isWebUri || intent.getData().getHost() == null) {
6420            return false;
6421        }
6422        // Deny ephemeral apps if the user chose _ALWAYS or _ALWAYS_ASK for intent resolution.
6423        // Or if there's already an ephemeral app installed that handles the action
6424        synchronized (mPackages) {
6425            final int count = (resolvedActivities == null ? 0 : resolvedActivities.size());
6426            for (int n = 0; n < count; n++) {
6427                final ResolveInfo info = resolvedActivities.get(n);
6428                final String packageName = info.activityInfo.packageName;
6429                final PackageSetting ps = mSettings.mPackages.get(packageName);
6430                if (ps != null) {
6431                    // only check domain verification status if the app is not a browser
6432                    if (!info.handleAllWebDataURI) {
6433                        // Try to get the status from User settings first
6434                        final long packedStatus = getDomainVerificationStatusLPr(ps, userId);
6435                        final int status = (int) (packedStatus >> 32);
6436                        if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS
6437                            || status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) {
6438                            if (DEBUG_EPHEMERAL) {
6439                                Slog.v(TAG, "DENY instant app;"
6440                                    + " pkg: " + packageName + ", status: " + status);
6441                            }
6442                            return false;
6443                        }
6444                    }
6445                    if (ps.getInstantApp(userId)) {
6446                        if (DEBUG_EPHEMERAL) {
6447                            Slog.v(TAG, "DENY instant app installed;"
6448                                    + " pkg: " + packageName);
6449                        }
6450                        return false;
6451                    }
6452                }
6453            }
6454        }
6455        // We've exhausted all ways to deny ephemeral application; let the system look for them.
6456        return true;
6457    }
6458
6459    private void requestInstantAppResolutionPhaseTwo(AuxiliaryResolveInfo responseObj,
6460            Intent origIntent, String resolvedType, String callingPackage,
6461            Bundle verificationBundle, int userId) {
6462        final Message msg = mHandler.obtainMessage(INSTANT_APP_RESOLUTION_PHASE_TWO,
6463                new InstantAppRequest(responseObj, origIntent, resolvedType,
6464                        callingPackage, userId, verificationBundle));
6465        mHandler.sendMessage(msg);
6466    }
6467
6468    private ResolveInfo chooseBestActivity(Intent intent, String resolvedType,
6469            int flags, List<ResolveInfo> query, int userId) {
6470        if (query != null) {
6471            final int N = query.size();
6472            if (N == 1) {
6473                return query.get(0);
6474            } else if (N > 1) {
6475                final boolean debug = ((intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0);
6476                // If there is more than one activity with the same priority,
6477                // then let the user decide between them.
6478                ResolveInfo r0 = query.get(0);
6479                ResolveInfo r1 = query.get(1);
6480                if (DEBUG_INTENT_MATCHING || debug) {
6481                    Slog.v(TAG, r0.activityInfo.name + "=" + r0.priority + " vs "
6482                            + r1.activityInfo.name + "=" + r1.priority);
6483                }
6484                // If the first activity has a higher priority, or a different
6485                // default, then it is always desirable to pick it.
6486                if (r0.priority != r1.priority
6487                        || r0.preferredOrder != r1.preferredOrder
6488                        || r0.isDefault != r1.isDefault) {
6489                    return query.get(0);
6490                }
6491                // If we have saved a preference for a preferred activity for
6492                // this Intent, use that.
6493                ResolveInfo ri = findPreferredActivity(intent, resolvedType,
6494                        flags, query, r0.priority, true, false, debug, userId);
6495                if (ri != null) {
6496                    return ri;
6497                }
6498                // If we have an ephemeral app, use it
6499                for (int i = 0; i < N; i++) {
6500                    ri = query.get(i);
6501                    if (ri.activityInfo.applicationInfo.isInstantApp()) {
6502                        final String packageName = ri.activityInfo.packageName;
6503                        final PackageSetting ps = mSettings.mPackages.get(packageName);
6504                        final long packedStatus = getDomainVerificationStatusLPr(ps, userId);
6505                        final int status = (int)(packedStatus >> 32);
6506                        if (status != INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) {
6507                            return ri;
6508                        }
6509                    }
6510                }
6511                ri = new ResolveInfo(mResolveInfo);
6512                ri.activityInfo = new ActivityInfo(ri.activityInfo);
6513                ri.activityInfo.labelRes = ResolverActivity.getLabelRes(intent.getAction());
6514                // If all of the options come from the same package, show the application's
6515                // label and icon instead of the generic resolver's.
6516                // Some calls like Intent.resolveActivityInfo query the ResolveInfo from here
6517                // and then throw away the ResolveInfo itself, meaning that the caller loses
6518                // the resolvePackageName. Therefore the activityInfo.labelRes above provides
6519                // a fallback for this case; we only set the target package's resources on
6520                // the ResolveInfo, not the ActivityInfo.
6521                final String intentPackage = intent.getPackage();
6522                if (!TextUtils.isEmpty(intentPackage) && allHavePackage(query, intentPackage)) {
6523                    final ApplicationInfo appi = query.get(0).activityInfo.applicationInfo;
6524                    ri.resolvePackageName = intentPackage;
6525                    if (userNeedsBadging(userId)) {
6526                        ri.noResourceId = true;
6527                    } else {
6528                        ri.icon = appi.icon;
6529                    }
6530                    ri.iconResourceId = appi.icon;
6531                    ri.labelRes = appi.labelRes;
6532                }
6533                ri.activityInfo.applicationInfo = new ApplicationInfo(
6534                        ri.activityInfo.applicationInfo);
6535                if (userId != 0) {
6536                    ri.activityInfo.applicationInfo.uid = UserHandle.getUid(userId,
6537                            UserHandle.getAppId(ri.activityInfo.applicationInfo.uid));
6538                }
6539                // Make sure that the resolver is displayable in car mode
6540                if (ri.activityInfo.metaData == null) ri.activityInfo.metaData = new Bundle();
6541                ri.activityInfo.metaData.putBoolean(Intent.METADATA_DOCK_HOME, true);
6542                return ri;
6543            }
6544        }
6545        return null;
6546    }
6547
6548    /**
6549     * Return true if the given list is not empty and all of its contents have
6550     * an activityInfo with the given package name.
6551     */
6552    private boolean allHavePackage(List<ResolveInfo> list, String packageName) {
6553        if (ArrayUtils.isEmpty(list)) {
6554            return false;
6555        }
6556        for (int i = 0, N = list.size(); i < N; i++) {
6557            final ResolveInfo ri = list.get(i);
6558            final ActivityInfo ai = ri != null ? ri.activityInfo : null;
6559            if (ai == null || !packageName.equals(ai.packageName)) {
6560                return false;
6561            }
6562        }
6563        return true;
6564    }
6565
6566    private ResolveInfo findPersistentPreferredActivityLP(Intent intent, String resolvedType,
6567            int flags, List<ResolveInfo> query, boolean debug, int userId) {
6568        final int N = query.size();
6569        PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities
6570                .get(userId);
6571        // Get the list of persistent preferred activities that handle the intent
6572        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for presistent preferred activities...");
6573        List<PersistentPreferredActivity> pprefs = ppir != null
6574                ? ppir.queryIntent(intent, resolvedType,
6575                        (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0,
6576                        userId)
6577                : null;
6578        if (pprefs != null && pprefs.size() > 0) {
6579            final int M = pprefs.size();
6580            for (int i=0; i<M; i++) {
6581                final PersistentPreferredActivity ppa = pprefs.get(i);
6582                if (DEBUG_PREFERRED || debug) {
6583                    Slog.v(TAG, "Checking PersistentPreferredActivity ds="
6584                            + (ppa.countDataSchemes() > 0 ? ppa.getDataScheme(0) : "<none>")
6585                            + "\n  component=" + ppa.mComponent);
6586                    ppa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
6587                }
6588                final ActivityInfo ai = getActivityInfo(ppa.mComponent,
6589                        flags | MATCH_DISABLED_COMPONENTS, userId);
6590                if (DEBUG_PREFERRED || debug) {
6591                    Slog.v(TAG, "Found persistent preferred activity:");
6592                    if (ai != null) {
6593                        ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
6594                    } else {
6595                        Slog.v(TAG, "  null");
6596                    }
6597                }
6598                if (ai == null) {
6599                    // This previously registered persistent preferred activity
6600                    // component is no longer known. Ignore it and do NOT remove it.
6601                    continue;
6602                }
6603                for (int j=0; j<N; j++) {
6604                    final ResolveInfo ri = query.get(j);
6605                    if (!ri.activityInfo.applicationInfo.packageName
6606                            .equals(ai.applicationInfo.packageName)) {
6607                        continue;
6608                    }
6609                    if (!ri.activityInfo.name.equals(ai.name)) {
6610                        continue;
6611                    }
6612                    //  Found a persistent preference that can handle the intent.
6613                    if (DEBUG_PREFERRED || debug) {
6614                        Slog.v(TAG, "Returning persistent preferred activity: " +
6615                                ri.activityInfo.packageName + "/" + ri.activityInfo.name);
6616                    }
6617                    return ri;
6618                }
6619            }
6620        }
6621        return null;
6622    }
6623
6624    // TODO: handle preferred activities missing while user has amnesia
6625    ResolveInfo findPreferredActivity(Intent intent, String resolvedType, int flags,
6626            List<ResolveInfo> query, int priority, boolean always,
6627            boolean removeMatches, boolean debug, int userId) {
6628        if (!sUserManager.exists(userId)) return null;
6629        final int callingUid = Binder.getCallingUid();
6630        flags = updateFlagsForResolve(
6631                flags, userId, intent, callingUid, false /*includeInstantApps*/);
6632        intent = updateIntentForResolve(intent);
6633        // writer
6634        synchronized (mPackages) {
6635            // Try to find a matching persistent preferred activity.
6636            ResolveInfo pri = findPersistentPreferredActivityLP(intent, resolvedType, flags, query,
6637                    debug, userId);
6638
6639            // If a persistent preferred activity matched, use it.
6640            if (pri != null) {
6641                return pri;
6642            }
6643
6644            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
6645            // Get the list of preferred activities that handle the intent
6646            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for preferred activities...");
6647            List<PreferredActivity> prefs = pir != null
6648                    ? pir.queryIntent(intent, resolvedType,
6649                            (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0,
6650                            userId)
6651                    : null;
6652            if (prefs != null && prefs.size() > 0) {
6653                boolean changed = false;
6654                try {
6655                    // First figure out how good the original match set is.
6656                    // We will only allow preferred activities that came
6657                    // from the same match quality.
6658                    int match = 0;
6659
6660                    if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Figuring out best match...");
6661
6662                    final int N = query.size();
6663                    for (int j=0; j<N; j++) {
6664                        final ResolveInfo ri = query.get(j);
6665                        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Match for " + ri.activityInfo
6666                                + ": 0x" + Integer.toHexString(match));
6667                        if (ri.match > match) {
6668                            match = ri.match;
6669                        }
6670                    }
6671
6672                    if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Best match: 0x"
6673                            + Integer.toHexString(match));
6674
6675                    match &= IntentFilter.MATCH_CATEGORY_MASK;
6676                    final int M = prefs.size();
6677                    for (int i=0; i<M; i++) {
6678                        final PreferredActivity pa = prefs.get(i);
6679                        if (DEBUG_PREFERRED || debug) {
6680                            Slog.v(TAG, "Checking PreferredActivity ds="
6681                                    + (pa.countDataSchemes() > 0 ? pa.getDataScheme(0) : "<none>")
6682                                    + "\n  component=" + pa.mPref.mComponent);
6683                            pa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
6684                        }
6685                        if (pa.mPref.mMatch != match) {
6686                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping bad match "
6687                                    + Integer.toHexString(pa.mPref.mMatch));
6688                            continue;
6689                        }
6690                        // If it's not an "always" type preferred activity and that's what we're
6691                        // looking for, skip it.
6692                        if (always && !pa.mPref.mAlways) {
6693                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping mAlways=false entry");
6694                            continue;
6695                        }
6696                        final ActivityInfo ai = getActivityInfo(
6697                                pa.mPref.mComponent, flags | MATCH_DISABLED_COMPONENTS
6698                                        | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
6699                                userId);
6700                        if (DEBUG_PREFERRED || debug) {
6701                            Slog.v(TAG, "Found preferred activity:");
6702                            if (ai != null) {
6703                                ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
6704                            } else {
6705                                Slog.v(TAG, "  null");
6706                            }
6707                        }
6708                        if (ai == null) {
6709                            // This previously registered preferred activity
6710                            // component is no longer known.  Most likely an update
6711                            // to the app was installed and in the new version this
6712                            // component no longer exists.  Clean it up by removing
6713                            // it from the preferred activities list, and skip it.
6714                            Slog.w(TAG, "Removing dangling preferred activity: "
6715                                    + pa.mPref.mComponent);
6716                            pir.removeFilter(pa);
6717                            changed = true;
6718                            continue;
6719                        }
6720                        for (int j=0; j<N; j++) {
6721                            final ResolveInfo ri = query.get(j);
6722                            if (!ri.activityInfo.applicationInfo.packageName
6723                                    .equals(ai.applicationInfo.packageName)) {
6724                                continue;
6725                            }
6726                            if (!ri.activityInfo.name.equals(ai.name)) {
6727                                continue;
6728                            }
6729
6730                            if (removeMatches) {
6731                                pir.removeFilter(pa);
6732                                changed = true;
6733                                if (DEBUG_PREFERRED) {
6734                                    Slog.v(TAG, "Removing match " + pa.mPref.mComponent);
6735                                }
6736                                break;
6737                            }
6738
6739                            // Okay we found a previously set preferred or last chosen app.
6740                            // If the result set is different from when this
6741                            // was created, we need to clear it and re-ask the
6742                            // user their preference, if we're looking for an "always" type entry.
6743                            if (always && !pa.mPref.sameSet(query)) {
6744                                Slog.i(TAG, "Result set changed, dropping preferred activity for "
6745                                        + intent + " type " + resolvedType);
6746                                if (DEBUG_PREFERRED) {
6747                                    Slog.v(TAG, "Removing preferred activity since set changed "
6748                                            + pa.mPref.mComponent);
6749                                }
6750                                pir.removeFilter(pa);
6751                                // Re-add the filter as a "last chosen" entry (!always)
6752                                PreferredActivity lastChosen = new PreferredActivity(
6753                                        pa, pa.mPref.mMatch, null, pa.mPref.mComponent, false);
6754                                pir.addFilter(lastChosen);
6755                                changed = true;
6756                                return null;
6757                            }
6758
6759                            // Yay! Either the set matched or we're looking for the last chosen
6760                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Returning preferred activity: "
6761                                    + ri.activityInfo.packageName + "/" + ri.activityInfo.name);
6762                            return ri;
6763                        }
6764                    }
6765                } finally {
6766                    if (changed) {
6767                        if (DEBUG_PREFERRED) {
6768                            Slog.v(TAG, "Preferred activity bookkeeping changed; writing restrictions");
6769                        }
6770                        scheduleWritePackageRestrictionsLocked(userId);
6771                    }
6772                }
6773            }
6774        }
6775        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "No preferred activity to return");
6776        return null;
6777    }
6778
6779    /*
6780     * Returns if intent can be forwarded from the sourceUserId to the targetUserId
6781     */
6782    @Override
6783    public boolean canForwardTo(Intent intent, String resolvedType, int sourceUserId,
6784            int targetUserId) {
6785        mContext.enforceCallingOrSelfPermission(
6786                android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
6787        List<CrossProfileIntentFilter> matches =
6788                getMatchingCrossProfileIntentFilters(intent, resolvedType, sourceUserId);
6789        if (matches != null) {
6790            int size = matches.size();
6791            for (int i = 0; i < size; i++) {
6792                if (matches.get(i).getTargetUserId() == targetUserId) return true;
6793            }
6794        }
6795        if (hasWebURI(intent)) {
6796            // cross-profile app linking works only towards the parent.
6797            final int callingUid = Binder.getCallingUid();
6798            final UserInfo parent = getProfileParent(sourceUserId);
6799            synchronized(mPackages) {
6800                int flags = updateFlagsForResolve(0, parent.id, intent, callingUid,
6801                        false /*includeInstantApps*/);
6802                CrossProfileDomainInfo xpDomainInfo = getCrossProfileDomainPreferredLpr(
6803                        intent, resolvedType, flags, sourceUserId, parent.id);
6804                return xpDomainInfo != null;
6805            }
6806        }
6807        return false;
6808    }
6809
6810    private UserInfo getProfileParent(int userId) {
6811        final long identity = Binder.clearCallingIdentity();
6812        try {
6813            return sUserManager.getProfileParent(userId);
6814        } finally {
6815            Binder.restoreCallingIdentity(identity);
6816        }
6817    }
6818
6819    private List<CrossProfileIntentFilter> getMatchingCrossProfileIntentFilters(Intent intent,
6820            String resolvedType, int userId) {
6821        CrossProfileIntentResolver resolver = mSettings.mCrossProfileIntentResolvers.get(userId);
6822        if (resolver != null) {
6823            return resolver.queryIntent(intent, resolvedType, false /*defaultOnly*/, userId);
6824        }
6825        return null;
6826    }
6827
6828    @Override
6829    public @NonNull ParceledListSlice<ResolveInfo> queryIntentActivities(Intent intent,
6830            String resolvedType, int flags, int userId) {
6831        try {
6832            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "queryIntentActivities");
6833
6834            return new ParceledListSlice<>(
6835                    queryIntentActivitiesInternal(intent, resolvedType, flags, userId));
6836        } finally {
6837            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
6838        }
6839    }
6840
6841    /**
6842     * Returns the package name of the calling Uid if it's an instant app. If it isn't
6843     * instant, returns {@code null}.
6844     */
6845    private String getInstantAppPackageName(int callingUid) {
6846        synchronized (mPackages) {
6847            // If the caller is an isolated app use the owner's uid for the lookup.
6848            if (Process.isIsolated(callingUid)) {
6849                callingUid = mIsolatedOwners.get(callingUid);
6850            }
6851            final int appId = UserHandle.getAppId(callingUid);
6852            final Object obj = mSettings.getUserIdLPr(appId);
6853            if (obj instanceof PackageSetting) {
6854                final PackageSetting ps = (PackageSetting) obj;
6855                final boolean isInstantApp = ps.getInstantApp(UserHandle.getUserId(callingUid));
6856                return isInstantApp ? ps.pkg.packageName : null;
6857            }
6858        }
6859        return null;
6860    }
6861
6862    private @NonNull List<ResolveInfo> queryIntentActivitiesInternal(Intent intent,
6863            String resolvedType, int flags, int userId) {
6864        return queryIntentActivitiesInternal(
6865                intent, resolvedType, flags, Binder.getCallingUid(), userId, false);
6866    }
6867
6868    private @NonNull List<ResolveInfo> queryIntentActivitiesInternal(Intent intent,
6869            String resolvedType, int flags, int filterCallingUid, int userId,
6870            boolean resolveForStart) {
6871        if (!sUserManager.exists(userId)) return Collections.emptyList();
6872        final String instantAppPkgName = getInstantAppPackageName(filterCallingUid);
6873        enforceCrossUserPermission(Binder.getCallingUid(), userId,
6874                false /* requireFullPermission */, false /* checkShell */,
6875                "query intent activities");
6876        final String pkgName = intent.getPackage();
6877        ComponentName comp = intent.getComponent();
6878        if (comp == null) {
6879            if (intent.getSelector() != null) {
6880                intent = intent.getSelector();
6881                comp = intent.getComponent();
6882            }
6883        }
6884
6885        flags = updateFlagsForResolve(flags, userId, intent, filterCallingUid, resolveForStart,
6886                comp != null || pkgName != null /*onlyExposedExplicitly*/);
6887        if (comp != null) {
6888            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
6889            final ActivityInfo ai = getActivityInfo(comp, flags, userId);
6890            if (ai != null) {
6891                // When specifying an explicit component, we prevent the activity from being
6892                // used when either 1) the calling package is normal and the activity is within
6893                // an ephemeral application or 2) the calling package is ephemeral and the
6894                // activity is not visible to ephemeral applications.
6895                final boolean matchInstantApp =
6896                        (flags & PackageManager.MATCH_INSTANT) != 0;
6897                final boolean matchVisibleToInstantAppOnly =
6898                        (flags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
6899                final boolean matchExplicitlyVisibleOnly =
6900                        (flags & PackageManager.MATCH_EXPLICITLY_VISIBLE_ONLY) != 0;
6901                final boolean isCallerInstantApp =
6902                        instantAppPkgName != null;
6903                final boolean isTargetSameInstantApp =
6904                        comp.getPackageName().equals(instantAppPkgName);
6905                final boolean isTargetInstantApp =
6906                        (ai.applicationInfo.privateFlags
6907                                & ApplicationInfo.PRIVATE_FLAG_INSTANT) != 0;
6908                final boolean isTargetVisibleToInstantApp =
6909                        (ai.flags & ActivityInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0;
6910                final boolean isTargetExplicitlyVisibleToInstantApp =
6911                        isTargetVisibleToInstantApp
6912                        && (ai.flags & ActivityInfo.FLAG_IMPLICITLY_VISIBLE_TO_INSTANT_APP) == 0;
6913                final boolean isTargetHiddenFromInstantApp =
6914                        !isTargetVisibleToInstantApp
6915                        || (matchExplicitlyVisibleOnly && !isTargetExplicitlyVisibleToInstantApp);
6916                final boolean blockResolution =
6917                        !isTargetSameInstantApp
6918                        && ((!matchInstantApp && !isCallerInstantApp && isTargetInstantApp)
6919                                || (matchVisibleToInstantAppOnly && isCallerInstantApp
6920                                        && isTargetHiddenFromInstantApp));
6921                if (!blockResolution) {
6922                    final ResolveInfo ri = new ResolveInfo();
6923                    ri.activityInfo = ai;
6924                    list.add(ri);
6925                }
6926            }
6927            return applyPostResolutionFilter(list, instantAppPkgName);
6928        }
6929
6930        // reader
6931        boolean sortResult = false;
6932        boolean addEphemeral = false;
6933        List<ResolveInfo> result;
6934        final boolean ephemeralDisabled = isEphemeralDisabled();
6935        synchronized (mPackages) {
6936            if (pkgName == null) {
6937                List<CrossProfileIntentFilter> matchingFilters =
6938                        getMatchingCrossProfileIntentFilters(intent, resolvedType, userId);
6939                // Check for results that need to skip the current profile.
6940                ResolveInfo xpResolveInfo  = querySkipCurrentProfileIntents(matchingFilters, intent,
6941                        resolvedType, flags, userId);
6942                if (xpResolveInfo != null) {
6943                    List<ResolveInfo> xpResult = new ArrayList<ResolveInfo>(1);
6944                    xpResult.add(xpResolveInfo);
6945                    return applyPostResolutionFilter(
6946                            filterIfNotSystemUser(xpResult, userId), instantAppPkgName);
6947                }
6948
6949                // Check for results in the current profile.
6950                result = filterIfNotSystemUser(mActivities.queryIntent(
6951                        intent, resolvedType, flags, userId), userId);
6952                addEphemeral = !ephemeralDisabled
6953                        && isInstantAppAllowed(intent, result, userId, false /*skipPackageCheck*/);
6954                // Check for cross profile results.
6955                boolean hasNonNegativePriorityResult = hasNonNegativePriority(result);
6956                xpResolveInfo = queryCrossProfileIntents(
6957                        matchingFilters, intent, resolvedType, flags, userId,
6958                        hasNonNegativePriorityResult);
6959                if (xpResolveInfo != null && isUserEnabled(xpResolveInfo.targetUserId)) {
6960                    boolean isVisibleToUser = filterIfNotSystemUser(
6961                            Collections.singletonList(xpResolveInfo), userId).size() > 0;
6962                    if (isVisibleToUser) {
6963                        result.add(xpResolveInfo);
6964                        sortResult = true;
6965                    }
6966                }
6967                if (hasWebURI(intent)) {
6968                    CrossProfileDomainInfo xpDomainInfo = null;
6969                    final UserInfo parent = getProfileParent(userId);
6970                    if (parent != null) {
6971                        xpDomainInfo = getCrossProfileDomainPreferredLpr(intent, resolvedType,
6972                                flags, userId, parent.id);
6973                    }
6974                    if (xpDomainInfo != null) {
6975                        if (xpResolveInfo != null) {
6976                            // If we didn't remove it, the cross-profile ResolveInfo would be twice
6977                            // in the result.
6978                            result.remove(xpResolveInfo);
6979                        }
6980                        if (result.size() == 0 && !addEphemeral) {
6981                            // No result in current profile, but found candidate in parent user.
6982                            // And we are not going to add emphemeral app, so we can return the
6983                            // result straight away.
6984                            result.add(xpDomainInfo.resolveInfo);
6985                            return applyPostResolutionFilter(result, instantAppPkgName);
6986                        }
6987                    } else if (result.size() <= 1 && !addEphemeral) {
6988                        // No result in parent user and <= 1 result in current profile, and we
6989                        // are not going to add emphemeral app, so we can return the result without
6990                        // further processing.
6991                        return applyPostResolutionFilter(result, instantAppPkgName);
6992                    }
6993                    // We have more than one candidate (combining results from current and parent
6994                    // profile), so we need filtering and sorting.
6995                    result = filterCandidatesWithDomainPreferredActivitiesLPr(
6996                            intent, flags, result, xpDomainInfo, userId);
6997                    sortResult = true;
6998                }
6999            } else {
7000                final PackageParser.Package pkg = mPackages.get(pkgName);
7001                result = null;
7002                if (pkg != null) {
7003                    result = filterIfNotSystemUser(
7004                            mActivities.queryIntentForPackage(
7005                                    intent, resolvedType, flags, pkg.activities, userId),
7006                            userId);
7007                }
7008                if (result == null || result.size() == 0) {
7009                    // the caller wants to resolve for a particular package; however, there
7010                    // were no installed results, so, try to find an ephemeral result
7011                    addEphemeral = !ephemeralDisabled
7012                            && isInstantAppAllowed(
7013                                    intent, null /*result*/, userId, true /*skipPackageCheck*/);
7014                    if (result == null) {
7015                        result = new ArrayList<>();
7016                    }
7017                }
7018            }
7019        }
7020        if (addEphemeral) {
7021            result = maybeAddInstantAppInstaller(result, intent, resolvedType, flags, userId);
7022        }
7023        if (sortResult) {
7024            Collections.sort(result, mResolvePrioritySorter);
7025        }
7026        return applyPostResolutionFilter(result, instantAppPkgName);
7027    }
7028
7029    private List<ResolveInfo> maybeAddInstantAppInstaller(List<ResolveInfo> result, Intent intent,
7030            String resolvedType, int flags, int userId) {
7031        // first, check to see if we've got an instant app already installed
7032        final boolean alreadyResolvedLocally = (flags & PackageManager.MATCH_INSTANT) != 0;
7033        ResolveInfo localInstantApp = null;
7034        boolean blockResolution = false;
7035        if (!alreadyResolvedLocally) {
7036            final List<ResolveInfo> instantApps = mActivities.queryIntent(intent, resolvedType,
7037                    flags
7038                        | PackageManager.GET_RESOLVED_FILTER
7039                        | PackageManager.MATCH_INSTANT
7040                        | PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY,
7041                    userId);
7042            for (int i = instantApps.size() - 1; i >= 0; --i) {
7043                final ResolveInfo info = instantApps.get(i);
7044                final String packageName = info.activityInfo.packageName;
7045                final PackageSetting ps = mSettings.mPackages.get(packageName);
7046                if (ps.getInstantApp(userId)) {
7047                    final long packedStatus = getDomainVerificationStatusLPr(ps, userId);
7048                    final int status = (int)(packedStatus >> 32);
7049                    final int linkGeneration = (int)(packedStatus & 0xFFFFFFFF);
7050                    if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
7051                        // there's a local instant application installed, but, the user has
7052                        // chosen to never use it; skip resolution and don't acknowledge
7053                        // an instant application is even available
7054                        if (DEBUG_EPHEMERAL) {
7055                            Slog.v(TAG, "Instant app marked to never run; pkg: " + packageName);
7056                        }
7057                        blockResolution = true;
7058                        break;
7059                    } else {
7060                        // we have a locally installed instant application; skip resolution
7061                        // but acknowledge there's an instant application available
7062                        if (DEBUG_EPHEMERAL) {
7063                            Slog.v(TAG, "Found installed instant app; pkg: " + packageName);
7064                        }
7065                        localInstantApp = info;
7066                        break;
7067                    }
7068                }
7069            }
7070        }
7071        // no app installed, let's see if one's available
7072        AuxiliaryResolveInfo auxiliaryResponse = null;
7073        if (!blockResolution) {
7074            if (localInstantApp == null) {
7075                // we don't have an instant app locally, resolve externally
7076                Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "resolveEphemeral");
7077                final InstantAppRequest requestObject = new InstantAppRequest(
7078                        null /*responseObj*/, intent /*origIntent*/, resolvedType,
7079                        null /*callingPackage*/, userId, null /*verificationBundle*/);
7080                auxiliaryResponse =
7081                        InstantAppResolver.doInstantAppResolutionPhaseOne(
7082                                mContext, mInstantAppResolverConnection, requestObject);
7083                Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
7084            } else {
7085                // we have an instant application locally, but, we can't admit that since
7086                // callers shouldn't be able to determine prior browsing. create a dummy
7087                // auxiliary response so the downstream code behaves as if there's an
7088                // instant application available externally. when it comes time to start
7089                // the instant application, we'll do the right thing.
7090                final ApplicationInfo ai = localInstantApp.activityInfo.applicationInfo;
7091                auxiliaryResponse = new AuxiliaryResolveInfo(
7092                        ai.packageName, null /*splitName*/, ai.versionCode, null /*failureIntent*/);
7093            }
7094        }
7095        if (auxiliaryResponse != null) {
7096            if (DEBUG_EPHEMERAL) {
7097                Slog.v(TAG, "Adding ephemeral installer to the ResolveInfo list");
7098            }
7099            final ResolveInfo ephemeralInstaller = new ResolveInfo(mInstantAppInstallerInfo);
7100            final PackageSetting ps =
7101                    mSettings.mPackages.get(mInstantAppInstallerActivity.packageName);
7102            if (ps != null) {
7103                ephemeralInstaller.activityInfo = PackageParser.generateActivityInfo(
7104                        mInstantAppInstallerActivity, 0, ps.readUserState(userId), userId);
7105                ephemeralInstaller.activityInfo.launchToken = auxiliaryResponse.token;
7106                ephemeralInstaller.auxiliaryInfo = auxiliaryResponse;
7107                // make sure this resolver is the default
7108                ephemeralInstaller.isDefault = true;
7109                ephemeralInstaller.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART
7110                        | IntentFilter.MATCH_ADJUSTMENT_NORMAL;
7111                // add a non-generic filter
7112                ephemeralInstaller.filter = new IntentFilter(intent.getAction());
7113                ephemeralInstaller.filter.addDataPath(
7114                        intent.getData().getPath(), PatternMatcher.PATTERN_LITERAL);
7115                ephemeralInstaller.isInstantAppAvailable = true;
7116                result.add(ephemeralInstaller);
7117            }
7118        }
7119        return result;
7120    }
7121
7122    private static class CrossProfileDomainInfo {
7123        /* ResolveInfo for IntentForwarderActivity to send the intent to the other profile */
7124        ResolveInfo resolveInfo;
7125        /* Best domain verification status of the activities found in the other profile */
7126        int bestDomainVerificationStatus;
7127    }
7128
7129    private CrossProfileDomainInfo getCrossProfileDomainPreferredLpr(Intent intent,
7130            String resolvedType, int flags, int sourceUserId, int parentUserId) {
7131        if (!sUserManager.hasUserRestriction(UserManager.ALLOW_PARENT_PROFILE_APP_LINKING,
7132                sourceUserId)) {
7133            return null;
7134        }
7135        List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent,
7136                resolvedType, flags, parentUserId);
7137
7138        if (resultTargetUser == null || resultTargetUser.isEmpty()) {
7139            return null;
7140        }
7141        CrossProfileDomainInfo result = null;
7142        int size = resultTargetUser.size();
7143        for (int i = 0; i < size; i++) {
7144            ResolveInfo riTargetUser = resultTargetUser.get(i);
7145            // Intent filter verification is only for filters that specify a host. So don't return
7146            // those that handle all web uris.
7147            if (riTargetUser.handleAllWebDataURI) {
7148                continue;
7149            }
7150            String packageName = riTargetUser.activityInfo.packageName;
7151            PackageSetting ps = mSettings.mPackages.get(packageName);
7152            if (ps == null) {
7153                continue;
7154            }
7155            long verificationState = getDomainVerificationStatusLPr(ps, parentUserId);
7156            int status = (int)(verificationState >> 32);
7157            if (result == null) {
7158                result = new CrossProfileDomainInfo();
7159                result.resolveInfo = createForwardingResolveInfoUnchecked(new IntentFilter(),
7160                        sourceUserId, parentUserId);
7161                result.bestDomainVerificationStatus = status;
7162            } else {
7163                result.bestDomainVerificationStatus = bestDomainVerificationStatus(status,
7164                        result.bestDomainVerificationStatus);
7165            }
7166        }
7167        // Don't consider matches with status NEVER across profiles.
7168        if (result != null && result.bestDomainVerificationStatus
7169                == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
7170            return null;
7171        }
7172        return result;
7173    }
7174
7175    /**
7176     * Verification statuses are ordered from the worse to the best, except for
7177     * INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER, which is the worse.
7178     */
7179    private int bestDomainVerificationStatus(int status1, int status2) {
7180        if (status1 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
7181            return status2;
7182        }
7183        if (status2 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
7184            return status1;
7185        }
7186        return (int) MathUtils.max(status1, status2);
7187    }
7188
7189    private boolean isUserEnabled(int userId) {
7190        long callingId = Binder.clearCallingIdentity();
7191        try {
7192            UserInfo userInfo = sUserManager.getUserInfo(userId);
7193            return userInfo != null && userInfo.isEnabled();
7194        } finally {
7195            Binder.restoreCallingIdentity(callingId);
7196        }
7197    }
7198
7199    /**
7200     * Filter out activities with systemUserOnly flag set, when current user is not System.
7201     *
7202     * @return filtered list
7203     */
7204    private List<ResolveInfo> filterIfNotSystemUser(List<ResolveInfo> resolveInfos, int userId) {
7205        if (userId == UserHandle.USER_SYSTEM) {
7206            return resolveInfos;
7207        }
7208        for (int i = resolveInfos.size() - 1; i >= 0; i--) {
7209            ResolveInfo info = resolveInfos.get(i);
7210            if ((info.activityInfo.flags & ActivityInfo.FLAG_SYSTEM_USER_ONLY) != 0) {
7211                resolveInfos.remove(i);
7212            }
7213        }
7214        return resolveInfos;
7215    }
7216
7217    /**
7218     * Filters out ephemeral activities.
7219     * <p>When resolving for an ephemeral app, only activities that 1) are defined in the
7220     * ephemeral app or 2) marked with {@code visibleToEphemeral} are returned.
7221     *
7222     * @param resolveInfos The pre-filtered list of resolved activities
7223     * @param ephemeralPkgName The ephemeral package name. If {@code null}, no filtering
7224     *          is performed.
7225     * @return A filtered list of resolved activities.
7226     */
7227    private List<ResolveInfo> applyPostResolutionFilter(List<ResolveInfo> resolveInfos,
7228            String ephemeralPkgName) {
7229        for (int i = resolveInfos.size() - 1; i >= 0; i--) {
7230            final ResolveInfo info = resolveInfos.get(i);
7231            final boolean isEphemeralApp = info.activityInfo.applicationInfo.isInstantApp();
7232            // TODO: When adding on-demand split support for non-instant apps, remove this check
7233            // and always apply post filtering
7234            // allow activities that are defined in the provided package
7235            if (isEphemeralApp) {
7236                if (info.activityInfo.splitName != null
7237                        && !ArrayUtils.contains(info.activityInfo.applicationInfo.splitNames,
7238                                info.activityInfo.splitName)) {
7239                    // requested activity is defined in a split that hasn't been installed yet.
7240                    // add the installer to the resolve list
7241                    if (DEBUG_EPHEMERAL) {
7242                        Slog.v(TAG, "Adding ephemeral installer to the ResolveInfo list");
7243                    }
7244                    final ResolveInfo installerInfo = new ResolveInfo(mInstantAppInstallerInfo);
7245                    installerInfo.auxiliaryInfo = new AuxiliaryResolveInfo(
7246                            info.activityInfo.packageName, info.activityInfo.splitName,
7247                            info.activityInfo.applicationInfo.versionCode, null /*failureIntent*/);
7248                    // make sure this resolver is the default
7249                    installerInfo.isDefault = true;
7250                    installerInfo.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART
7251                            | IntentFilter.MATCH_ADJUSTMENT_NORMAL;
7252                    // add a non-generic filter
7253                    installerInfo.filter = new IntentFilter();
7254                    // load resources from the correct package
7255                    installerInfo.resolvePackageName = info.getComponentInfo().packageName;
7256                    resolveInfos.set(i, installerInfo);
7257                    continue;
7258                }
7259            }
7260            // caller is a full app, don't need to apply any other filtering
7261            if (ephemeralPkgName == null) {
7262                continue;
7263            } else if (ephemeralPkgName.equals(info.activityInfo.packageName)) {
7264                // caller is same app; don't need to apply any other filtering
7265                continue;
7266            }
7267            // allow activities that have been explicitly exposed to ephemeral apps
7268            if (!isEphemeralApp
7269                    && ((info.activityInfo.flags & ActivityInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0)) {
7270                continue;
7271            }
7272            resolveInfos.remove(i);
7273        }
7274        return resolveInfos;
7275    }
7276
7277    /**
7278     * @param resolveInfos list of resolve infos in descending priority order
7279     * @return if the list contains a resolve info with non-negative priority
7280     */
7281    private boolean hasNonNegativePriority(List<ResolveInfo> resolveInfos) {
7282        return resolveInfos.size() > 0 && resolveInfos.get(0).priority >= 0;
7283    }
7284
7285    private static boolean hasWebURI(Intent intent) {
7286        if (intent.getData() == null) {
7287            return false;
7288        }
7289        final String scheme = intent.getScheme();
7290        if (TextUtils.isEmpty(scheme)) {
7291            return false;
7292        }
7293        return scheme.equals(IntentFilter.SCHEME_HTTP) || scheme.equals(IntentFilter.SCHEME_HTTPS);
7294    }
7295
7296    private List<ResolveInfo> filterCandidatesWithDomainPreferredActivitiesLPr(Intent intent,
7297            int matchFlags, List<ResolveInfo> candidates, CrossProfileDomainInfo xpDomainInfo,
7298            int userId) {
7299        final boolean debug = (intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0;
7300
7301        if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) {
7302            Slog.v(TAG, "Filtering results with preferred activities. Candidates count: " +
7303                    candidates.size());
7304        }
7305
7306        ArrayList<ResolveInfo> result = new ArrayList<ResolveInfo>();
7307        ArrayList<ResolveInfo> alwaysList = new ArrayList<ResolveInfo>();
7308        ArrayList<ResolveInfo> undefinedList = new ArrayList<ResolveInfo>();
7309        ArrayList<ResolveInfo> alwaysAskList = new ArrayList<ResolveInfo>();
7310        ArrayList<ResolveInfo> neverList = new ArrayList<ResolveInfo>();
7311        ArrayList<ResolveInfo> matchAllList = new ArrayList<ResolveInfo>();
7312
7313        synchronized (mPackages) {
7314            final int count = candidates.size();
7315            // First, try to use linked apps. Partition the candidates into four lists:
7316            // one for the final results, one for the "do not use ever", one for "undefined status"
7317            // and finally one for "browser app type".
7318            for (int n=0; n<count; n++) {
7319                ResolveInfo info = candidates.get(n);
7320                String packageName = info.activityInfo.packageName;
7321                PackageSetting ps = mSettings.mPackages.get(packageName);
7322                if (ps != null) {
7323                    // Add to the special match all list (Browser use case)
7324                    if (info.handleAllWebDataURI) {
7325                        matchAllList.add(info);
7326                        continue;
7327                    }
7328                    // Try to get the status from User settings first
7329                    long packedStatus = getDomainVerificationStatusLPr(ps, userId);
7330                    int status = (int)(packedStatus >> 32);
7331                    int linkGeneration = (int)(packedStatus & 0xFFFFFFFF);
7332                    if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS) {
7333                        if (DEBUG_DOMAIN_VERIFICATION || debug) {
7334                            Slog.i(TAG, "  + always: " + info.activityInfo.packageName
7335                                    + " : linkgen=" + linkGeneration);
7336                        }
7337                        // Use link-enabled generation as preferredOrder, i.e.
7338                        // prefer newly-enabled over earlier-enabled.
7339                        info.preferredOrder = linkGeneration;
7340                        alwaysList.add(info);
7341                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
7342                        if (DEBUG_DOMAIN_VERIFICATION || debug) {
7343                            Slog.i(TAG, "  + never: " + info.activityInfo.packageName);
7344                        }
7345                        neverList.add(info);
7346                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) {
7347                        if (DEBUG_DOMAIN_VERIFICATION || debug) {
7348                            Slog.i(TAG, "  + always-ask: " + info.activityInfo.packageName);
7349                        }
7350                        alwaysAskList.add(info);
7351                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED ||
7352                            status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK) {
7353                        if (DEBUG_DOMAIN_VERIFICATION || debug) {
7354                            Slog.i(TAG, "  + ask: " + info.activityInfo.packageName);
7355                        }
7356                        undefinedList.add(info);
7357                    }
7358                }
7359            }
7360
7361            // We'll want to include browser possibilities in a few cases
7362            boolean includeBrowser = false;
7363
7364            // First try to add the "always" resolution(s) for the current user, if any
7365            if (alwaysList.size() > 0) {
7366                result.addAll(alwaysList);
7367            } else {
7368                // Add all undefined apps as we want them to appear in the disambiguation dialog.
7369                result.addAll(undefinedList);
7370                // Maybe add one for the other profile.
7371                if (xpDomainInfo != null && (
7372                        xpDomainInfo.bestDomainVerificationStatus
7373                        != INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER)) {
7374                    result.add(xpDomainInfo.resolveInfo);
7375                }
7376                includeBrowser = true;
7377            }
7378
7379            // The presence of any 'always ask' alternatives means we'll also offer browsers.
7380            // If there were 'always' entries their preferred order has been set, so we also
7381            // back that off to make the alternatives equivalent
7382            if (alwaysAskList.size() > 0) {
7383                for (ResolveInfo i : result) {
7384                    i.preferredOrder = 0;
7385                }
7386                result.addAll(alwaysAskList);
7387                includeBrowser = true;
7388            }
7389
7390            if (includeBrowser) {
7391                // Also add browsers (all of them or only the default one)
7392                if (DEBUG_DOMAIN_VERIFICATION) {
7393                    Slog.v(TAG, "   ...including browsers in candidate set");
7394                }
7395                if ((matchFlags & MATCH_ALL) != 0) {
7396                    result.addAll(matchAllList);
7397                } else {
7398                    // Browser/generic handling case.  If there's a default browser, go straight
7399                    // to that (but only if there is no other higher-priority match).
7400                    final String defaultBrowserPackageName = getDefaultBrowserPackageName(userId);
7401                    int maxMatchPrio = 0;
7402                    ResolveInfo defaultBrowserMatch = null;
7403                    final int numCandidates = matchAllList.size();
7404                    for (int n = 0; n < numCandidates; n++) {
7405                        ResolveInfo info = matchAllList.get(n);
7406                        // track the highest overall match priority...
7407                        if (info.priority > maxMatchPrio) {
7408                            maxMatchPrio = info.priority;
7409                        }
7410                        // ...and the highest-priority default browser match
7411                        if (info.activityInfo.packageName.equals(defaultBrowserPackageName)) {
7412                            if (defaultBrowserMatch == null
7413                                    || (defaultBrowserMatch.priority < info.priority)) {
7414                                if (debug) {
7415                                    Slog.v(TAG, "Considering default browser match " + info);
7416                                }
7417                                defaultBrowserMatch = info;
7418                            }
7419                        }
7420                    }
7421                    if (defaultBrowserMatch != null
7422                            && defaultBrowserMatch.priority >= maxMatchPrio
7423                            && !TextUtils.isEmpty(defaultBrowserPackageName))
7424                    {
7425                        if (debug) {
7426                            Slog.v(TAG, "Default browser match " + defaultBrowserMatch);
7427                        }
7428                        result.add(defaultBrowserMatch);
7429                    } else {
7430                        result.addAll(matchAllList);
7431                    }
7432                }
7433
7434                // If there is nothing selected, add all candidates and remove the ones that the user
7435                // has explicitly put into the INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER state
7436                if (result.size() == 0) {
7437                    result.addAll(candidates);
7438                    result.removeAll(neverList);
7439                }
7440            }
7441        }
7442        if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) {
7443            Slog.v(TAG, "Filtered results with preferred activities. New candidates count: " +
7444                    result.size());
7445            for (ResolveInfo info : result) {
7446                Slog.v(TAG, "  + " + info.activityInfo);
7447            }
7448        }
7449        return result;
7450    }
7451
7452    // Returns a packed value as a long:
7453    //
7454    // high 'int'-sized word: link status: undefined/ask/never/always.
7455    // low 'int'-sized word: relative priority among 'always' results.
7456    private long getDomainVerificationStatusLPr(PackageSetting ps, int userId) {
7457        long result = ps.getDomainVerificationStatusForUser(userId);
7458        // if none available, get the master status
7459        if (result >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) {
7460            if (ps.getIntentFilterVerificationInfo() != null) {
7461                result = ((long)ps.getIntentFilterVerificationInfo().getStatus()) << 32;
7462            }
7463        }
7464        return result;
7465    }
7466
7467    private ResolveInfo querySkipCurrentProfileIntents(
7468            List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType,
7469            int flags, int sourceUserId) {
7470        if (matchingFilters != null) {
7471            int size = matchingFilters.size();
7472            for (int i = 0; i < size; i ++) {
7473                CrossProfileIntentFilter filter = matchingFilters.get(i);
7474                if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0) {
7475                    // Checking if there are activities in the target user that can handle the
7476                    // intent.
7477                    ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent,
7478                            resolvedType, flags, sourceUserId);
7479                    if (resolveInfo != null) {
7480                        return resolveInfo;
7481                    }
7482                }
7483            }
7484        }
7485        return null;
7486    }
7487
7488    // Return matching ResolveInfo in target user if any.
7489    private ResolveInfo queryCrossProfileIntents(
7490            List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType,
7491            int flags, int sourceUserId, boolean matchInCurrentProfile) {
7492        if (matchingFilters != null) {
7493            // Two {@link CrossProfileIntentFilter}s can have the same targetUserId and
7494            // match the same intent. For performance reasons, it is better not to
7495            // run queryIntent twice for the same userId
7496            SparseBooleanArray alreadyTriedUserIds = new SparseBooleanArray();
7497            int size = matchingFilters.size();
7498            for (int i = 0; i < size; i++) {
7499                CrossProfileIntentFilter filter = matchingFilters.get(i);
7500                int targetUserId = filter.getTargetUserId();
7501                boolean skipCurrentProfile =
7502                        (filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0;
7503                boolean skipCurrentProfileIfNoMatchFound =
7504                        (filter.getFlags() & PackageManager.ONLY_IF_NO_MATCH_FOUND) != 0;
7505                if (!skipCurrentProfile && !alreadyTriedUserIds.get(targetUserId)
7506                        && (!skipCurrentProfileIfNoMatchFound || !matchInCurrentProfile)) {
7507                    // Checking if there are activities in the target user that can handle the
7508                    // intent.
7509                    ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent,
7510                            resolvedType, flags, sourceUserId);
7511                    if (resolveInfo != null) return resolveInfo;
7512                    alreadyTriedUserIds.put(targetUserId, true);
7513                }
7514            }
7515        }
7516        return null;
7517    }
7518
7519    /**
7520     * If the filter's target user can handle the intent and is enabled: returns a ResolveInfo that
7521     * will forward the intent to the filter's target user.
7522     * Otherwise, returns null.
7523     */
7524    private ResolveInfo createForwardingResolveInfo(CrossProfileIntentFilter filter, Intent intent,
7525            String resolvedType, int flags, int sourceUserId) {
7526        int targetUserId = filter.getTargetUserId();
7527        List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent,
7528                resolvedType, flags, targetUserId);
7529        if (resultTargetUser != null && isUserEnabled(targetUserId)) {
7530            // If all the matches in the target profile are suspended, return null.
7531            for (int i = resultTargetUser.size() - 1; i >= 0; i--) {
7532                if ((resultTargetUser.get(i).activityInfo.applicationInfo.flags
7533                        & ApplicationInfo.FLAG_SUSPENDED) == 0) {
7534                    return createForwardingResolveInfoUnchecked(filter, sourceUserId,
7535                            targetUserId);
7536                }
7537            }
7538        }
7539        return null;
7540    }
7541
7542    private ResolveInfo createForwardingResolveInfoUnchecked(IntentFilter filter,
7543            int sourceUserId, int targetUserId) {
7544        ResolveInfo forwardingResolveInfo = new ResolveInfo();
7545        long ident = Binder.clearCallingIdentity();
7546        boolean targetIsProfile;
7547        try {
7548            targetIsProfile = sUserManager.getUserInfo(targetUserId).isManagedProfile();
7549        } finally {
7550            Binder.restoreCallingIdentity(ident);
7551        }
7552        String className;
7553        if (targetIsProfile) {
7554            className = FORWARD_INTENT_TO_MANAGED_PROFILE;
7555        } else {
7556            className = FORWARD_INTENT_TO_PARENT;
7557        }
7558        ComponentName forwardingActivityComponentName = new ComponentName(
7559                mAndroidApplication.packageName, className);
7560        ActivityInfo forwardingActivityInfo = getActivityInfo(forwardingActivityComponentName, 0,
7561                sourceUserId);
7562        if (!targetIsProfile) {
7563            forwardingActivityInfo.showUserIcon = targetUserId;
7564            forwardingResolveInfo.noResourceId = true;
7565        }
7566        forwardingResolveInfo.activityInfo = forwardingActivityInfo;
7567        forwardingResolveInfo.priority = 0;
7568        forwardingResolveInfo.preferredOrder = 0;
7569        forwardingResolveInfo.match = 0;
7570        forwardingResolveInfo.isDefault = true;
7571        forwardingResolveInfo.filter = filter;
7572        forwardingResolveInfo.targetUserId = targetUserId;
7573        return forwardingResolveInfo;
7574    }
7575
7576    @Override
7577    public @NonNull ParceledListSlice<ResolveInfo> queryIntentActivityOptions(ComponentName caller,
7578            Intent[] specifics, String[] specificTypes, Intent intent,
7579            String resolvedType, int flags, int userId) {
7580        return new ParceledListSlice<>(queryIntentActivityOptionsInternal(caller, specifics,
7581                specificTypes, intent, resolvedType, flags, userId));
7582    }
7583
7584    private @NonNull List<ResolveInfo> queryIntentActivityOptionsInternal(ComponentName caller,
7585            Intent[] specifics, String[] specificTypes, Intent intent,
7586            String resolvedType, int flags, int userId) {
7587        if (!sUserManager.exists(userId)) return Collections.emptyList();
7588        final int callingUid = Binder.getCallingUid();
7589        flags = updateFlagsForResolve(flags, userId, intent, callingUid,
7590                false /*includeInstantApps*/);
7591        enforceCrossUserPermission(callingUid, userId,
7592                false /*requireFullPermission*/, false /*checkShell*/,
7593                "query intent activity options");
7594        final String resultsAction = intent.getAction();
7595
7596        final List<ResolveInfo> results = queryIntentActivitiesInternal(intent, resolvedType, flags
7597                | PackageManager.GET_RESOLVED_FILTER, userId);
7598
7599        if (DEBUG_INTENT_MATCHING) {
7600            Log.v(TAG, "Query " + intent + ": " + results);
7601        }
7602
7603        int specificsPos = 0;
7604        int N;
7605
7606        // todo: note that the algorithm used here is O(N^2).  This
7607        // isn't a problem in our current environment, but if we start running
7608        // into situations where we have more than 5 or 10 matches then this
7609        // should probably be changed to something smarter...
7610
7611        // First we go through and resolve each of the specific items
7612        // that were supplied, taking care of removing any corresponding
7613        // duplicate items in the generic resolve list.
7614        if (specifics != null) {
7615            for (int i=0; i<specifics.length; i++) {
7616                final Intent sintent = specifics[i];
7617                if (sintent == null) {
7618                    continue;
7619                }
7620
7621                if (DEBUG_INTENT_MATCHING) {
7622                    Log.v(TAG, "Specific #" + i + ": " + sintent);
7623                }
7624
7625                String action = sintent.getAction();
7626                if (resultsAction != null && resultsAction.equals(action)) {
7627                    // If this action was explicitly requested, then don't
7628                    // remove things that have it.
7629                    action = null;
7630                }
7631
7632                ResolveInfo ri = null;
7633                ActivityInfo ai = null;
7634
7635                ComponentName comp = sintent.getComponent();
7636                if (comp == null) {
7637                    ri = resolveIntent(
7638                        sintent,
7639                        specificTypes != null ? specificTypes[i] : null,
7640                            flags, userId);
7641                    if (ri == null) {
7642                        continue;
7643                    }
7644                    if (ri == mResolveInfo) {
7645                        // ACK!  Must do something better with this.
7646                    }
7647                    ai = ri.activityInfo;
7648                    comp = new ComponentName(ai.applicationInfo.packageName,
7649                            ai.name);
7650                } else {
7651                    ai = getActivityInfo(comp, flags, userId);
7652                    if (ai == null) {
7653                        continue;
7654                    }
7655                }
7656
7657                // Look for any generic query activities that are duplicates
7658                // of this specific one, and remove them from the results.
7659                if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Specific #" + i + ": " + ai);
7660                N = results.size();
7661                int j;
7662                for (j=specificsPos; j<N; j++) {
7663                    ResolveInfo sri = results.get(j);
7664                    if ((sri.activityInfo.name.equals(comp.getClassName())
7665                            && sri.activityInfo.applicationInfo.packageName.equals(
7666                                    comp.getPackageName()))
7667                        || (action != null && sri.filter.matchAction(action))) {
7668                        results.remove(j);
7669                        if (DEBUG_INTENT_MATCHING) Log.v(
7670                            TAG, "Removing duplicate item from " + j
7671                            + " due to specific " + specificsPos);
7672                        if (ri == null) {
7673                            ri = sri;
7674                        }
7675                        j--;
7676                        N--;
7677                    }
7678                }
7679
7680                // Add this specific item to its proper place.
7681                if (ri == null) {
7682                    ri = new ResolveInfo();
7683                    ri.activityInfo = ai;
7684                }
7685                results.add(specificsPos, ri);
7686                ri.specificIndex = i;
7687                specificsPos++;
7688            }
7689        }
7690
7691        // Now we go through the remaining generic results and remove any
7692        // duplicate actions that are found here.
7693        N = results.size();
7694        for (int i=specificsPos; i<N-1; i++) {
7695            final ResolveInfo rii = results.get(i);
7696            if (rii.filter == null) {
7697                continue;
7698            }
7699
7700            // Iterate over all of the actions of this result's intent
7701            // filter...  typically this should be just one.
7702            final Iterator<String> it = rii.filter.actionsIterator();
7703            if (it == null) {
7704                continue;
7705            }
7706            while (it.hasNext()) {
7707                final String action = it.next();
7708                if (resultsAction != null && resultsAction.equals(action)) {
7709                    // If this action was explicitly requested, then don't
7710                    // remove things that have it.
7711                    continue;
7712                }
7713                for (int j=i+1; j<N; j++) {
7714                    final ResolveInfo rij = results.get(j);
7715                    if (rij.filter != null && rij.filter.hasAction(action)) {
7716                        results.remove(j);
7717                        if (DEBUG_INTENT_MATCHING) Log.v(
7718                            TAG, "Removing duplicate item from " + j
7719                            + " due to action " + action + " at " + i);
7720                        j--;
7721                        N--;
7722                    }
7723                }
7724            }
7725
7726            // If the caller didn't request filter information, drop it now
7727            // so we don't have to marshall/unmarshall it.
7728            if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
7729                rii.filter = null;
7730            }
7731        }
7732
7733        // Filter out the caller activity if so requested.
7734        if (caller != null) {
7735            N = results.size();
7736            for (int i=0; i<N; i++) {
7737                ActivityInfo ainfo = results.get(i).activityInfo;
7738                if (caller.getPackageName().equals(ainfo.applicationInfo.packageName)
7739                        && caller.getClassName().equals(ainfo.name)) {
7740                    results.remove(i);
7741                    break;
7742                }
7743            }
7744        }
7745
7746        // If the caller didn't request filter information,
7747        // drop them now so we don't have to
7748        // marshall/unmarshall it.
7749        if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
7750            N = results.size();
7751            for (int i=0; i<N; i++) {
7752                results.get(i).filter = null;
7753            }
7754        }
7755
7756        if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Result: " + results);
7757        return results;
7758    }
7759
7760    @Override
7761    public @NonNull ParceledListSlice<ResolveInfo> queryIntentReceivers(Intent intent,
7762            String resolvedType, int flags, int userId) {
7763        return new ParceledListSlice<>(
7764                queryIntentReceiversInternal(intent, resolvedType, flags, userId));
7765    }
7766
7767    private @NonNull List<ResolveInfo> queryIntentReceiversInternal(Intent intent,
7768            String resolvedType, int flags, int userId) {
7769        if (!sUserManager.exists(userId)) return Collections.emptyList();
7770        final int callingUid = Binder.getCallingUid();
7771        final String instantAppPkgName = getInstantAppPackageName(callingUid);
7772        flags = updateFlagsForResolve(flags, userId, intent, callingUid,
7773                false /*includeInstantApps*/);
7774        ComponentName comp = intent.getComponent();
7775        if (comp == null) {
7776            if (intent.getSelector() != null) {
7777                intent = intent.getSelector();
7778                comp = intent.getComponent();
7779            }
7780        }
7781        if (comp != null) {
7782            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
7783            final ActivityInfo ai = getReceiverInfo(comp, flags, userId);
7784            if (ai != null) {
7785                // When specifying an explicit component, we prevent the activity from being
7786                // used when either 1) the calling package is normal and the activity is within
7787                // an instant application or 2) the calling package is ephemeral and the
7788                // activity is not visible to instant applications.
7789                final boolean matchInstantApp =
7790                        (flags & PackageManager.MATCH_INSTANT) != 0;
7791                final boolean matchVisibleToInstantAppOnly =
7792                        (flags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
7793                final boolean matchExplicitlyVisibleOnly =
7794                        (flags & PackageManager.MATCH_EXPLICITLY_VISIBLE_ONLY) != 0;
7795                final boolean isCallerInstantApp =
7796                        instantAppPkgName != null;
7797                final boolean isTargetSameInstantApp =
7798                        comp.getPackageName().equals(instantAppPkgName);
7799                final boolean isTargetInstantApp =
7800                        (ai.applicationInfo.privateFlags
7801                                & ApplicationInfo.PRIVATE_FLAG_INSTANT) != 0;
7802                final boolean isTargetVisibleToInstantApp =
7803                        (ai.flags & ActivityInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0;
7804                final boolean isTargetExplicitlyVisibleToInstantApp =
7805                        isTargetVisibleToInstantApp
7806                        && (ai.flags & ActivityInfo.FLAG_IMPLICITLY_VISIBLE_TO_INSTANT_APP) == 0;
7807                final boolean isTargetHiddenFromInstantApp =
7808                        !isTargetVisibleToInstantApp
7809                        || (matchExplicitlyVisibleOnly && !isTargetExplicitlyVisibleToInstantApp);
7810                final boolean blockResolution =
7811                        !isTargetSameInstantApp
7812                        && ((!matchInstantApp && !isCallerInstantApp && isTargetInstantApp)
7813                                || (matchVisibleToInstantAppOnly && isCallerInstantApp
7814                                        && isTargetHiddenFromInstantApp));
7815                if (!blockResolution) {
7816                    ResolveInfo ri = new ResolveInfo();
7817                    ri.activityInfo = ai;
7818                    list.add(ri);
7819                }
7820            }
7821            return applyPostResolutionFilter(list, instantAppPkgName);
7822        }
7823
7824        // reader
7825        synchronized (mPackages) {
7826            String pkgName = intent.getPackage();
7827            if (pkgName == null) {
7828                final List<ResolveInfo> result =
7829                        mReceivers.queryIntent(intent, resolvedType, flags, userId);
7830                return applyPostResolutionFilter(result, instantAppPkgName);
7831            }
7832            final PackageParser.Package pkg = mPackages.get(pkgName);
7833            if (pkg != null) {
7834                final List<ResolveInfo> result = mReceivers.queryIntentForPackage(
7835                        intent, resolvedType, flags, pkg.receivers, userId);
7836                return applyPostResolutionFilter(result, instantAppPkgName);
7837            }
7838            return Collections.emptyList();
7839        }
7840    }
7841
7842    @Override
7843    public ResolveInfo resolveService(Intent intent, String resolvedType, int flags, int userId) {
7844        final int callingUid = Binder.getCallingUid();
7845        return resolveServiceInternal(intent, resolvedType, flags, userId, callingUid);
7846    }
7847
7848    private ResolveInfo resolveServiceInternal(Intent intent, String resolvedType, int flags,
7849            int userId, int callingUid) {
7850        if (!sUserManager.exists(userId)) return null;
7851        flags = updateFlagsForResolve(
7852                flags, userId, intent, callingUid, false /*includeInstantApps*/);
7853        List<ResolveInfo> query = queryIntentServicesInternal(
7854                intent, resolvedType, flags, userId, callingUid, false /*includeInstantApps*/);
7855        if (query != null) {
7856            if (query.size() >= 1) {
7857                // If there is more than one service with the same priority,
7858                // just arbitrarily pick the first one.
7859                return query.get(0);
7860            }
7861        }
7862        return null;
7863    }
7864
7865    @Override
7866    public @NonNull ParceledListSlice<ResolveInfo> queryIntentServices(Intent intent,
7867            String resolvedType, int flags, int userId) {
7868        final int callingUid = Binder.getCallingUid();
7869        return new ParceledListSlice<>(queryIntentServicesInternal(
7870                intent, resolvedType, flags, userId, callingUid, false /*includeInstantApps*/));
7871    }
7872
7873    private @NonNull List<ResolveInfo> queryIntentServicesInternal(Intent intent,
7874            String resolvedType, int flags, int userId, int callingUid,
7875            boolean includeInstantApps) {
7876        if (!sUserManager.exists(userId)) return Collections.emptyList();
7877        final String instantAppPkgName = getInstantAppPackageName(callingUid);
7878        flags = updateFlagsForResolve(flags, userId, intent, callingUid, includeInstantApps);
7879        ComponentName comp = intent.getComponent();
7880        if (comp == null) {
7881            if (intent.getSelector() != null) {
7882                intent = intent.getSelector();
7883                comp = intent.getComponent();
7884            }
7885        }
7886        if (comp != null) {
7887            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
7888            final ServiceInfo si = getServiceInfo(comp, flags, userId);
7889            if (si != null) {
7890                // When specifying an explicit component, we prevent the service from being
7891                // used when either 1) the service is in an instant application and the
7892                // caller is not the same instant application or 2) the calling package is
7893                // ephemeral and the activity is not visible to ephemeral applications.
7894                final boolean matchInstantApp =
7895                        (flags & PackageManager.MATCH_INSTANT) != 0;
7896                final boolean matchVisibleToInstantAppOnly =
7897                        (flags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
7898                final boolean isCallerInstantApp =
7899                        instantAppPkgName != null;
7900                final boolean isTargetSameInstantApp =
7901                        comp.getPackageName().equals(instantAppPkgName);
7902                final boolean isTargetInstantApp =
7903                        (si.applicationInfo.privateFlags
7904                                & ApplicationInfo.PRIVATE_FLAG_INSTANT) != 0;
7905                final boolean isTargetHiddenFromInstantApp =
7906                        (si.flags & ServiceInfo.FLAG_VISIBLE_TO_INSTANT_APP) == 0;
7907                final boolean blockResolution =
7908                        !isTargetSameInstantApp
7909                        && ((!matchInstantApp && !isCallerInstantApp && isTargetInstantApp)
7910                                || (matchVisibleToInstantAppOnly && isCallerInstantApp
7911                                        && isTargetHiddenFromInstantApp));
7912                if (!blockResolution) {
7913                    final ResolveInfo ri = new ResolveInfo();
7914                    ri.serviceInfo = si;
7915                    list.add(ri);
7916                }
7917            }
7918            return list;
7919        }
7920
7921        // reader
7922        synchronized (mPackages) {
7923            String pkgName = intent.getPackage();
7924            if (pkgName == null) {
7925                return applyPostServiceResolutionFilter(
7926                        mServices.queryIntent(intent, resolvedType, flags, userId),
7927                        instantAppPkgName);
7928            }
7929            final PackageParser.Package pkg = mPackages.get(pkgName);
7930            if (pkg != null) {
7931                return applyPostServiceResolutionFilter(
7932                        mServices.queryIntentForPackage(intent, resolvedType, flags, pkg.services,
7933                                userId),
7934                        instantAppPkgName);
7935            }
7936            return Collections.emptyList();
7937        }
7938    }
7939
7940    private List<ResolveInfo> applyPostServiceResolutionFilter(List<ResolveInfo> resolveInfos,
7941            String instantAppPkgName) {
7942        // TODO: When adding on-demand split support for non-instant apps, remove this check
7943        // and always apply post filtering
7944        if (instantAppPkgName == null) {
7945            return resolveInfos;
7946        }
7947        for (int i = resolveInfos.size() - 1; i >= 0; i--) {
7948            final ResolveInfo info = resolveInfos.get(i);
7949            final boolean isEphemeralApp = info.serviceInfo.applicationInfo.isInstantApp();
7950            // allow services that are defined in the provided package
7951            if (isEphemeralApp && instantAppPkgName.equals(info.serviceInfo.packageName)) {
7952                if (info.serviceInfo.splitName != null
7953                        && !ArrayUtils.contains(info.serviceInfo.applicationInfo.splitNames,
7954                                info.serviceInfo.splitName)) {
7955                    // requested service is defined in a split that hasn't been installed yet.
7956                    // add the installer to the resolve list
7957                    if (DEBUG_EPHEMERAL) {
7958                        Slog.v(TAG, "Adding ephemeral installer to the ResolveInfo list");
7959                    }
7960                    final ResolveInfo installerInfo = new ResolveInfo(mInstantAppInstallerInfo);
7961                    installerInfo.auxiliaryInfo = new AuxiliaryResolveInfo(
7962                            info.serviceInfo.packageName, info.serviceInfo.splitName,
7963                            info.serviceInfo.applicationInfo.versionCode, null /*failureIntent*/);
7964                    // make sure this resolver is the default
7965                    installerInfo.isDefault = true;
7966                    installerInfo.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART
7967                            | IntentFilter.MATCH_ADJUSTMENT_NORMAL;
7968                    // add a non-generic filter
7969                    installerInfo.filter = new IntentFilter();
7970                    // load resources from the correct package
7971                    installerInfo.resolvePackageName = info.getComponentInfo().packageName;
7972                    resolveInfos.set(i, installerInfo);
7973                }
7974                continue;
7975            }
7976            // allow services that have been explicitly exposed to ephemeral apps
7977            if (!isEphemeralApp
7978                    && ((info.serviceInfo.flags & ServiceInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0)) {
7979                continue;
7980            }
7981            resolveInfos.remove(i);
7982        }
7983        return resolveInfos;
7984    }
7985
7986    @Override
7987    public @NonNull ParceledListSlice<ResolveInfo> queryIntentContentProviders(Intent intent,
7988            String resolvedType, int flags, int userId) {
7989        return new ParceledListSlice<>(
7990                queryIntentContentProvidersInternal(intent, resolvedType, flags, userId));
7991    }
7992
7993    private @NonNull List<ResolveInfo> queryIntentContentProvidersInternal(
7994            Intent intent, String resolvedType, int flags, int userId) {
7995        if (!sUserManager.exists(userId)) return Collections.emptyList();
7996        final int callingUid = Binder.getCallingUid();
7997        final String instantAppPkgName = getInstantAppPackageName(callingUid);
7998        flags = updateFlagsForResolve(flags, userId, intent, callingUid,
7999                false /*includeInstantApps*/);
8000        ComponentName comp = intent.getComponent();
8001        if (comp == null) {
8002            if (intent.getSelector() != null) {
8003                intent = intent.getSelector();
8004                comp = intent.getComponent();
8005            }
8006        }
8007        if (comp != null) {
8008            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
8009            final ProviderInfo pi = getProviderInfo(comp, flags, userId);
8010            if (pi != null) {
8011                // When specifying an explicit component, we prevent the provider from being
8012                // used when either 1) the provider is in an instant application and the
8013                // caller is not the same instant application or 2) the calling package is an
8014                // instant application and the provider is not visible to instant applications.
8015                final boolean matchInstantApp =
8016                        (flags & PackageManager.MATCH_INSTANT) != 0;
8017                final boolean matchVisibleToInstantAppOnly =
8018                        (flags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
8019                final boolean isCallerInstantApp =
8020                        instantAppPkgName != null;
8021                final boolean isTargetSameInstantApp =
8022                        comp.getPackageName().equals(instantAppPkgName);
8023                final boolean isTargetInstantApp =
8024                        (pi.applicationInfo.privateFlags
8025                                & ApplicationInfo.PRIVATE_FLAG_INSTANT) != 0;
8026                final boolean isTargetHiddenFromInstantApp =
8027                        (pi.flags & ProviderInfo.FLAG_VISIBLE_TO_INSTANT_APP) == 0;
8028                final boolean blockResolution =
8029                        !isTargetSameInstantApp
8030                        && ((!matchInstantApp && !isCallerInstantApp && isTargetInstantApp)
8031                                || (matchVisibleToInstantAppOnly && isCallerInstantApp
8032                                        && isTargetHiddenFromInstantApp));
8033                if (!blockResolution) {
8034                    final ResolveInfo ri = new ResolveInfo();
8035                    ri.providerInfo = pi;
8036                    list.add(ri);
8037                }
8038            }
8039            return list;
8040        }
8041
8042        // reader
8043        synchronized (mPackages) {
8044            String pkgName = intent.getPackage();
8045            if (pkgName == null) {
8046                return applyPostContentProviderResolutionFilter(
8047                        mProviders.queryIntent(intent, resolvedType, flags, userId),
8048                        instantAppPkgName);
8049            }
8050            final PackageParser.Package pkg = mPackages.get(pkgName);
8051            if (pkg != null) {
8052                return applyPostContentProviderResolutionFilter(
8053                        mProviders.queryIntentForPackage(
8054                        intent, resolvedType, flags, pkg.providers, userId),
8055                        instantAppPkgName);
8056            }
8057            return Collections.emptyList();
8058        }
8059    }
8060
8061    private List<ResolveInfo> applyPostContentProviderResolutionFilter(
8062            List<ResolveInfo> resolveInfos, String instantAppPkgName) {
8063        // TODO: When adding on-demand split support for non-instant applications, remove
8064        // this check and always apply post filtering
8065        if (instantAppPkgName == null) {
8066            return resolveInfos;
8067        }
8068        for (int i = resolveInfos.size() - 1; i >= 0; i--) {
8069            final ResolveInfo info = resolveInfos.get(i);
8070            final boolean isEphemeralApp = info.providerInfo.applicationInfo.isInstantApp();
8071            // allow providers that are defined in the provided package
8072            if (isEphemeralApp && instantAppPkgName.equals(info.providerInfo.packageName)) {
8073                if (info.providerInfo.splitName != null
8074                        && !ArrayUtils.contains(info.providerInfo.applicationInfo.splitNames,
8075                                info.providerInfo.splitName)) {
8076                    // requested provider is defined in a split that hasn't been installed yet.
8077                    // add the installer to the resolve list
8078                    if (DEBUG_EPHEMERAL) {
8079                        Slog.v(TAG, "Adding ephemeral installer to the ResolveInfo list");
8080                    }
8081                    final ResolveInfo installerInfo = new ResolveInfo(mInstantAppInstallerInfo);
8082                    installerInfo.auxiliaryInfo = new AuxiliaryResolveInfo(
8083                            info.providerInfo.packageName, info.providerInfo.splitName,
8084                            info.providerInfo.applicationInfo.versionCode, null /*failureIntent*/);
8085                    // make sure this resolver is the default
8086                    installerInfo.isDefault = true;
8087                    installerInfo.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART
8088                            | IntentFilter.MATCH_ADJUSTMENT_NORMAL;
8089                    // add a non-generic filter
8090                    installerInfo.filter = new IntentFilter();
8091                    // load resources from the correct package
8092                    installerInfo.resolvePackageName = info.getComponentInfo().packageName;
8093                    resolveInfos.set(i, installerInfo);
8094                }
8095                continue;
8096            }
8097            // allow providers that have been explicitly exposed to instant applications
8098            if (!isEphemeralApp
8099                    && ((info.providerInfo.flags & ProviderInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0)) {
8100                continue;
8101            }
8102            resolveInfos.remove(i);
8103        }
8104        return resolveInfos;
8105    }
8106
8107    @Override
8108    public ParceledListSlice<PackageInfo> getInstalledPackages(int flags, int userId) {
8109        final int callingUid = Binder.getCallingUid();
8110        if (getInstantAppPackageName(callingUid) != null) {
8111            return ParceledListSlice.emptyList();
8112        }
8113        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
8114        flags = updateFlagsForPackage(flags, userId, null);
8115        final boolean listUninstalled = (flags & MATCH_KNOWN_PACKAGES) != 0;
8116        enforceCrossUserPermission(callingUid, userId,
8117                true /* requireFullPermission */, false /* checkShell */,
8118                "get installed packages");
8119
8120        // writer
8121        synchronized (mPackages) {
8122            ArrayList<PackageInfo> list;
8123            if (listUninstalled) {
8124                list = new ArrayList<>(mSettings.mPackages.size());
8125                for (PackageSetting ps : mSettings.mPackages.values()) {
8126                    if (filterSharedLibPackageLPr(ps, callingUid, userId, flags)) {
8127                        continue;
8128                    }
8129                    if (filterAppAccessLPr(ps, callingUid, userId)) {
8130                        return null;
8131                    }
8132                    final PackageInfo pi = generatePackageInfo(ps, flags, userId);
8133                    if (pi != null) {
8134                        list.add(pi);
8135                    }
8136                }
8137            } else {
8138                list = new ArrayList<>(mPackages.size());
8139                for (PackageParser.Package p : mPackages.values()) {
8140                    final PackageSetting ps = (PackageSetting) p.mExtras;
8141                    if (filterSharedLibPackageLPr(ps, callingUid, userId, flags)) {
8142                        continue;
8143                    }
8144                    if (filterAppAccessLPr(ps, callingUid, userId)) {
8145                        return null;
8146                    }
8147                    final PackageInfo pi = generatePackageInfo((PackageSetting)
8148                            p.mExtras, flags, userId);
8149                    if (pi != null) {
8150                        list.add(pi);
8151                    }
8152                }
8153            }
8154
8155            return new ParceledListSlice<>(list);
8156        }
8157    }
8158
8159    private void addPackageHoldingPermissions(ArrayList<PackageInfo> list, PackageSetting ps,
8160            String[] permissions, boolean[] tmp, int flags, int userId) {
8161        int numMatch = 0;
8162        final PermissionsState permissionsState = ps.getPermissionsState();
8163        for (int i=0; i<permissions.length; i++) {
8164            final String permission = permissions[i];
8165            if (permissionsState.hasPermission(permission, userId)) {
8166                tmp[i] = true;
8167                numMatch++;
8168            } else {
8169                tmp[i] = false;
8170            }
8171        }
8172        if (numMatch == 0) {
8173            return;
8174        }
8175        final PackageInfo pi = generatePackageInfo(ps, flags, userId);
8176
8177        // The above might return null in cases of uninstalled apps or install-state
8178        // skew across users/profiles.
8179        if (pi != null) {
8180            if ((flags&PackageManager.GET_PERMISSIONS) == 0) {
8181                if (numMatch == permissions.length) {
8182                    pi.requestedPermissions = permissions;
8183                } else {
8184                    pi.requestedPermissions = new String[numMatch];
8185                    numMatch = 0;
8186                    for (int i=0; i<permissions.length; i++) {
8187                        if (tmp[i]) {
8188                            pi.requestedPermissions[numMatch] = permissions[i];
8189                            numMatch++;
8190                        }
8191                    }
8192                }
8193            }
8194            list.add(pi);
8195        }
8196    }
8197
8198    @Override
8199    public ParceledListSlice<PackageInfo> getPackagesHoldingPermissions(
8200            String[] permissions, int flags, int userId) {
8201        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
8202        flags = updateFlagsForPackage(flags, userId, permissions);
8203        enforceCrossUserPermission(Binder.getCallingUid(), userId,
8204                true /* requireFullPermission */, false /* checkShell */,
8205                "get packages holding permissions");
8206        final boolean listUninstalled = (flags & MATCH_KNOWN_PACKAGES) != 0;
8207
8208        // writer
8209        synchronized (mPackages) {
8210            ArrayList<PackageInfo> list = new ArrayList<PackageInfo>();
8211            boolean[] tmpBools = new boolean[permissions.length];
8212            if (listUninstalled) {
8213                for (PackageSetting ps : mSettings.mPackages.values()) {
8214                    addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags,
8215                            userId);
8216                }
8217            } else {
8218                for (PackageParser.Package pkg : mPackages.values()) {
8219                    PackageSetting ps = (PackageSetting)pkg.mExtras;
8220                    if (ps != null) {
8221                        addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags,
8222                                userId);
8223                    }
8224                }
8225            }
8226
8227            return new ParceledListSlice<PackageInfo>(list);
8228        }
8229    }
8230
8231    @Override
8232    public ParceledListSlice<ApplicationInfo> getInstalledApplications(int flags, int userId) {
8233        final int callingUid = Binder.getCallingUid();
8234        if (getInstantAppPackageName(callingUid) != null) {
8235            return ParceledListSlice.emptyList();
8236        }
8237        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
8238        flags = updateFlagsForApplication(flags, userId, null);
8239        final boolean listUninstalled = (flags & MATCH_KNOWN_PACKAGES) != 0;
8240
8241        // writer
8242        synchronized (mPackages) {
8243            ArrayList<ApplicationInfo> list;
8244            if (listUninstalled) {
8245                list = new ArrayList<>(mSettings.mPackages.size());
8246                for (PackageSetting ps : mSettings.mPackages.values()) {
8247                    ApplicationInfo ai;
8248                    int effectiveFlags = flags;
8249                    if (ps.isSystem()) {
8250                        effectiveFlags |= PackageManager.MATCH_ANY_USER;
8251                    }
8252                    if (ps.pkg != null) {
8253                        if (filterSharedLibPackageLPr(ps, callingUid, userId, flags)) {
8254                            continue;
8255                        }
8256                        if (filterAppAccessLPr(ps, callingUid, userId)) {
8257                            return null;
8258                        }
8259                        ai = PackageParser.generateApplicationInfo(ps.pkg, effectiveFlags,
8260                                ps.readUserState(userId), userId);
8261                        if (ai != null) {
8262                            ai.packageName = resolveExternalPackageNameLPr(ps.pkg);
8263                        }
8264                    } else {
8265                        // Shared lib filtering done in generateApplicationInfoFromSettingsLPw
8266                        // and already converts to externally visible package name
8267                        ai = generateApplicationInfoFromSettingsLPw(ps.name,
8268                                callingUid, effectiveFlags, userId);
8269                    }
8270                    if (ai != null) {
8271                        list.add(ai);
8272                    }
8273                }
8274            } else {
8275                list = new ArrayList<>(mPackages.size());
8276                for (PackageParser.Package p : mPackages.values()) {
8277                    if (p.mExtras != null) {
8278                        PackageSetting ps = (PackageSetting) p.mExtras;
8279                        if (filterSharedLibPackageLPr(ps, Binder.getCallingUid(), userId, flags)) {
8280                            continue;
8281                        }
8282                        if (filterAppAccessLPr(ps, callingUid, userId)) {
8283                            return null;
8284                        }
8285                        ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags,
8286                                ps.readUserState(userId), userId);
8287                        if (ai != null) {
8288                            ai.packageName = resolveExternalPackageNameLPr(p);
8289                            list.add(ai);
8290                        }
8291                    }
8292                }
8293            }
8294
8295            return new ParceledListSlice<>(list);
8296        }
8297    }
8298
8299    @Override
8300    public ParceledListSlice<InstantAppInfo> getInstantApps(int userId) {
8301        if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) {
8302            return null;
8303        }
8304        mContext.enforceCallingOrSelfPermission(Manifest.permission.ACCESS_INSTANT_APPS,
8305                "getEphemeralApplications");
8306        enforceCrossUserPermission(Binder.getCallingUid(), userId,
8307                true /* requireFullPermission */, false /* checkShell */,
8308                "getEphemeralApplications");
8309        synchronized (mPackages) {
8310            List<InstantAppInfo> instantApps = mInstantAppRegistry
8311                    .getInstantAppsLPr(userId);
8312            if (instantApps != null) {
8313                return new ParceledListSlice<>(instantApps);
8314            }
8315        }
8316        return null;
8317    }
8318
8319    @Override
8320    public boolean isInstantApp(String packageName, int userId) {
8321        enforceCrossUserPermission(Binder.getCallingUid(), userId,
8322                true /* requireFullPermission */, false /* checkShell */,
8323                "isInstantApp");
8324        if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) {
8325            return false;
8326        }
8327        int callingUid = Binder.getCallingUid();
8328        if (Process.isIsolated(callingUid)) {
8329            callingUid = mIsolatedOwners.get(callingUid);
8330        }
8331
8332        synchronized (mPackages) {
8333            final PackageSetting ps = mSettings.mPackages.get(packageName);
8334            PackageParser.Package pkg = mPackages.get(packageName);
8335            final boolean returnAllowed =
8336                    ps != null
8337                    && (isCallerSameApp(packageName, callingUid)
8338                            || canViewInstantApps(callingUid, userId)
8339                            || mInstantAppRegistry.isInstantAccessGranted(
8340                                    userId, UserHandle.getAppId(callingUid), ps.appId));
8341            if (returnAllowed) {
8342                return ps.getInstantApp(userId);
8343            }
8344        }
8345        return false;
8346    }
8347
8348    @Override
8349    public byte[] getInstantAppCookie(String packageName, int userId) {
8350        if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) {
8351            return null;
8352        }
8353
8354        enforceCrossUserPermission(Binder.getCallingUid(), userId,
8355                true /* requireFullPermission */, false /* checkShell */,
8356                "getInstantAppCookie");
8357        if (!isCallerSameApp(packageName, Binder.getCallingUid())) {
8358            return null;
8359        }
8360        synchronized (mPackages) {
8361            return mInstantAppRegistry.getInstantAppCookieLPw(
8362                    packageName, userId);
8363        }
8364    }
8365
8366    @Override
8367    public boolean setInstantAppCookie(String packageName, byte[] cookie, int userId) {
8368        if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) {
8369            return true;
8370        }
8371
8372        enforceCrossUserPermission(Binder.getCallingUid(), userId,
8373                true /* requireFullPermission */, true /* checkShell */,
8374                "setInstantAppCookie");
8375        if (!isCallerSameApp(packageName, Binder.getCallingUid())) {
8376            return false;
8377        }
8378        synchronized (mPackages) {
8379            return mInstantAppRegistry.setInstantAppCookieLPw(
8380                    packageName, cookie, userId);
8381        }
8382    }
8383
8384    @Override
8385    public Bitmap getInstantAppIcon(String packageName, int userId) {
8386        if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) {
8387            return null;
8388        }
8389
8390        mContext.enforceCallingOrSelfPermission(Manifest.permission.ACCESS_INSTANT_APPS,
8391                "getInstantAppIcon");
8392
8393        enforceCrossUserPermission(Binder.getCallingUid(), userId,
8394                true /* requireFullPermission */, false /* checkShell */,
8395                "getInstantAppIcon");
8396
8397        synchronized (mPackages) {
8398            return mInstantAppRegistry.getInstantAppIconLPw(
8399                    packageName, userId);
8400        }
8401    }
8402
8403    private boolean isCallerSameApp(String packageName, int uid) {
8404        PackageParser.Package pkg = mPackages.get(packageName);
8405        return pkg != null
8406                && UserHandle.getAppId(uid) == pkg.applicationInfo.uid;
8407    }
8408
8409    @Override
8410    public @NonNull ParceledListSlice<ApplicationInfo> getPersistentApplications(int flags) {
8411        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
8412            return ParceledListSlice.emptyList();
8413        }
8414        return new ParceledListSlice<>(getPersistentApplicationsInternal(flags));
8415    }
8416
8417    private @NonNull List<ApplicationInfo> getPersistentApplicationsInternal(int flags) {
8418        final ArrayList<ApplicationInfo> finalList = new ArrayList<ApplicationInfo>();
8419
8420        // reader
8421        synchronized (mPackages) {
8422            final Iterator<PackageParser.Package> i = mPackages.values().iterator();
8423            final int userId = UserHandle.getCallingUserId();
8424            while (i.hasNext()) {
8425                final PackageParser.Package p = i.next();
8426                if (p.applicationInfo == null) continue;
8427
8428                final boolean matchesUnaware = ((flags & MATCH_DIRECT_BOOT_UNAWARE) != 0)
8429                        && !p.applicationInfo.isDirectBootAware();
8430                final boolean matchesAware = ((flags & MATCH_DIRECT_BOOT_AWARE) != 0)
8431                        && p.applicationInfo.isDirectBootAware();
8432
8433                if ((p.applicationInfo.flags & ApplicationInfo.FLAG_PERSISTENT) != 0
8434                        && (!mSafeMode || isSystemApp(p))
8435                        && (matchesUnaware || matchesAware)) {
8436                    PackageSetting ps = mSettings.mPackages.get(p.packageName);
8437                    if (ps != null) {
8438                        ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags,
8439                                ps.readUserState(userId), userId);
8440                        if (ai != null) {
8441                            finalList.add(ai);
8442                        }
8443                    }
8444                }
8445            }
8446        }
8447
8448        return finalList;
8449    }
8450
8451    @Override
8452    public ProviderInfo resolveContentProvider(String name, int flags, int userId) {
8453        if (!sUserManager.exists(userId)) return null;
8454        flags = updateFlagsForComponent(flags, userId, name);
8455        final String instantAppPkgName = getInstantAppPackageName(Binder.getCallingUid());
8456        // reader
8457        synchronized (mPackages) {
8458            final PackageParser.Provider provider = mProvidersByAuthority.get(name);
8459            PackageSetting ps = provider != null
8460                    ? mSettings.mPackages.get(provider.owner.packageName)
8461                    : null;
8462            if (ps != null) {
8463                final boolean isInstantApp = ps.getInstantApp(userId);
8464                // normal application; filter out instant application provider
8465                if (instantAppPkgName == null && isInstantApp) {
8466                    return null;
8467                }
8468                // instant application; filter out other instant applications
8469                if (instantAppPkgName != null
8470                        && isInstantApp
8471                        && !provider.owner.packageName.equals(instantAppPkgName)) {
8472                    return null;
8473                }
8474                // instant application; filter out non-exposed provider
8475                if (instantAppPkgName != null
8476                        && !isInstantApp
8477                        && (provider.info.flags & ProviderInfo.FLAG_VISIBLE_TO_INSTANT_APP) == 0) {
8478                    return null;
8479                }
8480                // provider not enabled
8481                if (!mSettings.isEnabledAndMatchLPr(provider.info, flags, userId)) {
8482                    return null;
8483                }
8484                return PackageParser.generateProviderInfo(
8485                        provider, flags, ps.readUserState(userId), userId);
8486            }
8487            return null;
8488        }
8489    }
8490
8491    /**
8492     * @deprecated
8493     */
8494    @Deprecated
8495    public void querySyncProviders(List<String> outNames, List<ProviderInfo> outInfo) {
8496        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
8497            return;
8498        }
8499        // reader
8500        synchronized (mPackages) {
8501            final Iterator<Map.Entry<String, PackageParser.Provider>> i = mProvidersByAuthority
8502                    .entrySet().iterator();
8503            final int userId = UserHandle.getCallingUserId();
8504            while (i.hasNext()) {
8505                Map.Entry<String, PackageParser.Provider> entry = i.next();
8506                PackageParser.Provider p = entry.getValue();
8507                PackageSetting ps = mSettings.mPackages.get(p.owner.packageName);
8508
8509                if (ps != null && p.syncable
8510                        && (!mSafeMode || (p.info.applicationInfo.flags
8511                                &ApplicationInfo.FLAG_SYSTEM) != 0)) {
8512                    ProviderInfo info = PackageParser.generateProviderInfo(p, 0,
8513                            ps.readUserState(userId), userId);
8514                    if (info != null) {
8515                        outNames.add(entry.getKey());
8516                        outInfo.add(info);
8517                    }
8518                }
8519            }
8520        }
8521    }
8522
8523    @Override
8524    public @NonNull ParceledListSlice<ProviderInfo> queryContentProviders(String processName,
8525            int uid, int flags, String metaDataKey) {
8526        final int callingUid = Binder.getCallingUid();
8527        final int userId = processName != null ? UserHandle.getUserId(uid)
8528                : UserHandle.getCallingUserId();
8529        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
8530        flags = updateFlagsForComponent(flags, userId, processName);
8531        ArrayList<ProviderInfo> finalList = null;
8532        // reader
8533        synchronized (mPackages) {
8534            final Iterator<PackageParser.Provider> i = mProviders.mProviders.values().iterator();
8535            while (i.hasNext()) {
8536                final PackageParser.Provider p = i.next();
8537                PackageSetting ps = mSettings.mPackages.get(p.owner.packageName);
8538                if (ps != null && p.info.authority != null
8539                        && (processName == null
8540                                || (p.info.processName.equals(processName)
8541                                        && UserHandle.isSameApp(p.info.applicationInfo.uid, uid)))
8542                        && mSettings.isEnabledAndMatchLPr(p.info, flags, userId)) {
8543
8544                    // See PM.queryContentProviders()'s javadoc for why we have the metaData
8545                    // parameter.
8546                    if (metaDataKey != null
8547                            && (p.metaData == null || !p.metaData.containsKey(metaDataKey))) {
8548                        continue;
8549                    }
8550                    final ComponentName component =
8551                            new ComponentName(p.info.packageName, p.info.name);
8552                    if (filterAppAccessLPr(ps, callingUid, component, TYPE_PROVIDER, userId)) {
8553                        continue;
8554                    }
8555                    if (finalList == null) {
8556                        finalList = new ArrayList<ProviderInfo>(3);
8557                    }
8558                    ProviderInfo info = PackageParser.generateProviderInfo(p, flags,
8559                            ps.readUserState(userId), userId);
8560                    if (info != null) {
8561                        finalList.add(info);
8562                    }
8563                }
8564            }
8565        }
8566
8567        if (finalList != null) {
8568            Collections.sort(finalList, mProviderInitOrderSorter);
8569            return new ParceledListSlice<ProviderInfo>(finalList);
8570        }
8571
8572        return ParceledListSlice.emptyList();
8573    }
8574
8575    @Override
8576    public InstrumentationInfo getInstrumentationInfo(ComponentName component, int flags) {
8577        // reader
8578        synchronized (mPackages) {
8579            final int callingUid = Binder.getCallingUid();
8580            final int callingUserId = UserHandle.getUserId(callingUid);
8581            final PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
8582            if (ps == null) return null;
8583            if (filterAppAccessLPr(ps, callingUid, component, TYPE_UNKNOWN, callingUserId)) {
8584                return null;
8585            }
8586            final PackageParser.Instrumentation i = mInstrumentation.get(component);
8587            return PackageParser.generateInstrumentationInfo(i, flags);
8588        }
8589    }
8590
8591    @Override
8592    public @NonNull ParceledListSlice<InstrumentationInfo> queryInstrumentation(
8593            String targetPackage, int flags) {
8594        final int callingUid = Binder.getCallingUid();
8595        final int callingUserId = UserHandle.getUserId(callingUid);
8596        final PackageSetting ps = mSettings.mPackages.get(targetPackage);
8597        if (filterAppAccessLPr(ps, callingUid, callingUserId)) {
8598            return ParceledListSlice.emptyList();
8599        }
8600        return new ParceledListSlice<>(queryInstrumentationInternal(targetPackage, flags));
8601    }
8602
8603    private @NonNull List<InstrumentationInfo> queryInstrumentationInternal(String targetPackage,
8604            int flags) {
8605        ArrayList<InstrumentationInfo> finalList = new ArrayList<InstrumentationInfo>();
8606
8607        // reader
8608        synchronized (mPackages) {
8609            final Iterator<PackageParser.Instrumentation> i = mInstrumentation.values().iterator();
8610            while (i.hasNext()) {
8611                final PackageParser.Instrumentation p = i.next();
8612                if (targetPackage == null
8613                        || targetPackage.equals(p.info.targetPackage)) {
8614                    InstrumentationInfo ii = PackageParser.generateInstrumentationInfo(p,
8615                            flags);
8616                    if (ii != null) {
8617                        finalList.add(ii);
8618                    }
8619                }
8620            }
8621        }
8622
8623        return finalList;
8624    }
8625
8626    private void scanDirTracedLI(File dir, final int parseFlags, int scanFlags, long currentTime) {
8627        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanDir [" + dir.getAbsolutePath() + "]");
8628        try {
8629            scanDirLI(dir, parseFlags, scanFlags, currentTime);
8630        } finally {
8631            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
8632        }
8633    }
8634
8635    private void scanDirLI(File dir, int parseFlags, int scanFlags, long currentTime) {
8636        final File[] files = dir.listFiles();
8637        if (ArrayUtils.isEmpty(files)) {
8638            Log.d(TAG, "No files in app dir " + dir);
8639            return;
8640        }
8641
8642        if (DEBUG_PACKAGE_SCANNING) {
8643            Log.d(TAG, "Scanning app dir " + dir + " scanFlags=" + scanFlags
8644                    + " flags=0x" + Integer.toHexString(parseFlags));
8645        }
8646        ParallelPackageParser parallelPackageParser = new ParallelPackageParser(
8647                mSeparateProcesses, mOnlyCore, mMetrics, mCacheDir,
8648                mParallelPackageParserCallback);
8649
8650        // Submit files for parsing in parallel
8651        int fileCount = 0;
8652        for (File file : files) {
8653            final boolean isPackage = (isApkFile(file) || file.isDirectory())
8654                    && !PackageInstallerService.isStageName(file.getName());
8655            if (!isPackage) {
8656                // Ignore entries which are not packages
8657                continue;
8658            }
8659            parallelPackageParser.submit(file, parseFlags);
8660            fileCount++;
8661        }
8662
8663        // Process results one by one
8664        for (; fileCount > 0; fileCount--) {
8665            ParallelPackageParser.ParseResult parseResult = parallelPackageParser.take();
8666            Throwable throwable = parseResult.throwable;
8667            int errorCode = PackageManager.INSTALL_SUCCEEDED;
8668
8669            if (throwable == null) {
8670                // Static shared libraries have synthetic package names
8671                if (parseResult.pkg.applicationInfo.isStaticSharedLibrary()) {
8672                    renameStaticSharedLibraryPackage(parseResult.pkg);
8673                }
8674                try {
8675                    if (errorCode == PackageManager.INSTALL_SUCCEEDED) {
8676                        scanPackageLI(parseResult.pkg, parseResult.scanFile, parseFlags, scanFlags,
8677                                currentTime, null);
8678                    }
8679                } catch (PackageManagerException e) {
8680                    errorCode = e.error;
8681                    Slog.w(TAG, "Failed to scan " + parseResult.scanFile + ": " + e.getMessage());
8682                }
8683            } else if (throwable instanceof PackageParser.PackageParserException) {
8684                PackageParser.PackageParserException e = (PackageParser.PackageParserException)
8685                        throwable;
8686                errorCode = e.error;
8687                Slog.w(TAG, "Failed to parse " + parseResult.scanFile + ": " + e.getMessage());
8688            } else {
8689                throw new IllegalStateException("Unexpected exception occurred while parsing "
8690                        + parseResult.scanFile, throwable);
8691            }
8692
8693            // Delete invalid userdata apps
8694            if ((parseFlags & PackageParser.PARSE_IS_SYSTEM) == 0 &&
8695                    errorCode == PackageManager.INSTALL_FAILED_INVALID_APK) {
8696                logCriticalInfo(Log.WARN,
8697                        "Deleting invalid package at " + parseResult.scanFile);
8698                removeCodePathLI(parseResult.scanFile);
8699            }
8700        }
8701        parallelPackageParser.close();
8702    }
8703
8704    private static File getSettingsProblemFile() {
8705        File dataDir = Environment.getDataDirectory();
8706        File systemDir = new File(dataDir, "system");
8707        File fname = new File(systemDir, "uiderrors.txt");
8708        return fname;
8709    }
8710
8711    static void reportSettingsProblem(int priority, String msg) {
8712        logCriticalInfo(priority, msg);
8713    }
8714
8715    public static void logCriticalInfo(int priority, String msg) {
8716        Slog.println(priority, TAG, msg);
8717        EventLogTags.writePmCriticalInfo(msg);
8718        try {
8719            File fname = getSettingsProblemFile();
8720            FileOutputStream out = new FileOutputStream(fname, true);
8721            PrintWriter pw = new FastPrintWriter(out);
8722            SimpleDateFormat formatter = new SimpleDateFormat();
8723            String dateString = formatter.format(new Date(System.currentTimeMillis()));
8724            pw.println(dateString + ": " + msg);
8725            pw.close();
8726            FileUtils.setPermissions(
8727                    fname.toString(),
8728                    FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IROTH,
8729                    -1, -1);
8730        } catch (java.io.IOException e) {
8731        }
8732    }
8733
8734    private long getLastModifiedTime(PackageParser.Package pkg, File srcFile) {
8735        if (srcFile.isDirectory()) {
8736            final File baseFile = new File(pkg.baseCodePath);
8737            long maxModifiedTime = baseFile.lastModified();
8738            if (pkg.splitCodePaths != null) {
8739                for (int i = pkg.splitCodePaths.length - 1; i >=0; --i) {
8740                    final File splitFile = new File(pkg.splitCodePaths[i]);
8741                    maxModifiedTime = Math.max(maxModifiedTime, splitFile.lastModified());
8742                }
8743            }
8744            return maxModifiedTime;
8745        }
8746        return srcFile.lastModified();
8747    }
8748
8749    private void collectCertificatesLI(PackageSetting ps, PackageParser.Package pkg, File srcFile,
8750            final int policyFlags) throws PackageManagerException {
8751        // When upgrading from pre-N MR1, verify the package time stamp using the package
8752        // directory and not the APK file.
8753        final long lastModifiedTime = mIsPreNMR1Upgrade
8754                ? new File(pkg.codePath).lastModified() : getLastModifiedTime(pkg, srcFile);
8755        if (ps != null
8756                && ps.codePath.equals(srcFile)
8757                && ps.timeStamp == lastModifiedTime
8758                && !isCompatSignatureUpdateNeeded(pkg)
8759                && !isRecoverSignatureUpdateNeeded(pkg)) {
8760            long mSigningKeySetId = ps.keySetData.getProperSigningKeySet();
8761            KeySetManagerService ksms = mSettings.mKeySetManagerService;
8762            ArraySet<PublicKey> signingKs;
8763            synchronized (mPackages) {
8764                signingKs = ksms.getPublicKeysFromKeySetLPr(mSigningKeySetId);
8765            }
8766            if (ps.signatures.mSignatures != null
8767                    && ps.signatures.mSignatures.length != 0
8768                    && signingKs != null) {
8769                // Optimization: reuse the existing cached certificates
8770                // if the package appears to be unchanged.
8771                pkg.mSignatures = ps.signatures.mSignatures;
8772                pkg.mSigningKeys = signingKs;
8773                return;
8774            }
8775
8776            Slog.w(TAG, "PackageSetting for " + ps.name
8777                    + " is missing signatures.  Collecting certs again to recover them.");
8778        } else {
8779            Slog.i(TAG, srcFile.toString() + " changed; collecting certs");
8780        }
8781
8782        try {
8783            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "collectCertificates");
8784            PackageParser.collectCertificates(pkg, policyFlags);
8785        } catch (PackageParserException e) {
8786            throw PackageManagerException.from(e);
8787        } finally {
8788            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
8789        }
8790    }
8791
8792    /**
8793     *  Traces a package scan.
8794     *  @see #scanPackageLI(File, int, int, long, UserHandle)
8795     */
8796    private PackageParser.Package scanPackageTracedLI(File scanFile, final int parseFlags,
8797            int scanFlags, long currentTime, UserHandle user) throws PackageManagerException {
8798        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage [" + scanFile.toString() + "]");
8799        try {
8800            return scanPackageLI(scanFile, parseFlags, scanFlags, currentTime, user);
8801        } finally {
8802            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
8803        }
8804    }
8805
8806    /**
8807     *  Scans a package and returns the newly parsed package.
8808     *  Returns {@code null} in case of errors and the error code is stored in mLastScanError
8809     */
8810    private PackageParser.Package scanPackageLI(File scanFile, int parseFlags, int scanFlags,
8811            long currentTime, UserHandle user) throws PackageManagerException {
8812        if (DEBUG_INSTALL) Slog.d(TAG, "Parsing: " + scanFile);
8813        PackageParser pp = new PackageParser();
8814        pp.setSeparateProcesses(mSeparateProcesses);
8815        pp.setOnlyCoreApps(mOnlyCore);
8816        pp.setDisplayMetrics(mMetrics);
8817        pp.setCallback(mPackageParserCallback);
8818
8819        if ((scanFlags & SCAN_TRUSTED_OVERLAY) != 0) {
8820            parseFlags |= PackageParser.PARSE_TRUSTED_OVERLAY;
8821        }
8822
8823        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "parsePackage");
8824        final PackageParser.Package pkg;
8825        try {
8826            pkg = pp.parsePackage(scanFile, parseFlags);
8827        } catch (PackageParserException e) {
8828            throw PackageManagerException.from(e);
8829        } finally {
8830            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
8831        }
8832
8833        // Static shared libraries have synthetic package names
8834        if (pkg.applicationInfo.isStaticSharedLibrary()) {
8835            renameStaticSharedLibraryPackage(pkg);
8836        }
8837
8838        return scanPackageLI(pkg, scanFile, parseFlags, scanFlags, currentTime, user);
8839    }
8840
8841    /**
8842     *  Scans a package and returns the newly parsed package.
8843     *  @throws PackageManagerException on a parse error.
8844     */
8845    private PackageParser.Package scanPackageLI(PackageParser.Package pkg, File scanFile,
8846            final int policyFlags, int scanFlags, long currentTime, @Nullable UserHandle user)
8847            throws PackageManagerException {
8848        // If the package has children and this is the first dive in the function
8849        // we scan the package with the SCAN_CHECK_ONLY flag set to see whether all
8850        // packages (parent and children) would be successfully scanned before the
8851        // actual scan since scanning mutates internal state and we want to atomically
8852        // install the package and its children.
8853        if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
8854            if (pkg.childPackages != null && pkg.childPackages.size() > 0) {
8855                scanFlags |= SCAN_CHECK_ONLY;
8856            }
8857        } else {
8858            scanFlags &= ~SCAN_CHECK_ONLY;
8859        }
8860
8861        // Scan the parent
8862        PackageParser.Package scannedPkg = scanPackageInternalLI(pkg, scanFile, policyFlags,
8863                scanFlags, currentTime, user);
8864
8865        // Scan the children
8866        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
8867        for (int i = 0; i < childCount; i++) {
8868            PackageParser.Package childPackage = pkg.childPackages.get(i);
8869            scanPackageInternalLI(childPackage, scanFile, policyFlags, scanFlags,
8870                    currentTime, user);
8871        }
8872
8873
8874        if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
8875            return scanPackageLI(pkg, scanFile, policyFlags, scanFlags, currentTime, user);
8876        }
8877
8878        return scannedPkg;
8879    }
8880
8881    /**
8882     *  Scans a package and returns the newly parsed package.
8883     *  @throws PackageManagerException on a parse error.
8884     */
8885    private PackageParser.Package scanPackageInternalLI(PackageParser.Package pkg, File scanFile,
8886            int policyFlags, int scanFlags, long currentTime, @Nullable UserHandle user)
8887            throws PackageManagerException {
8888        PackageSetting ps = null;
8889        PackageSetting updatedPkg;
8890        // reader
8891        synchronized (mPackages) {
8892            // Look to see if we already know about this package.
8893            String oldName = mSettings.getRenamedPackageLPr(pkg.packageName);
8894            if (pkg.mOriginalPackages != null && pkg.mOriginalPackages.contains(oldName)) {
8895                // This package has been renamed to its original name.  Let's
8896                // use that.
8897                ps = mSettings.getPackageLPr(oldName);
8898            }
8899            // If there was no original package, see one for the real package name.
8900            if (ps == null) {
8901                ps = mSettings.getPackageLPr(pkg.packageName);
8902            }
8903            // Check to see if this package could be hiding/updating a system
8904            // package.  Must look for it either under the original or real
8905            // package name depending on our state.
8906            updatedPkg = mSettings.getDisabledSystemPkgLPr(ps != null ? ps.name : pkg.packageName);
8907            if (DEBUG_INSTALL && updatedPkg != null) Slog.d(TAG, "updatedPkg = " + updatedPkg);
8908
8909            // If this is a package we don't know about on the system partition, we
8910            // may need to remove disabled child packages on the system partition
8911            // or may need to not add child packages if the parent apk is updated
8912            // on the data partition and no longer defines this child package.
8913            if ((policyFlags & PackageParser.PARSE_IS_SYSTEM) != 0) {
8914                // If this is a parent package for an updated system app and this system
8915                // app got an OTA update which no longer defines some of the child packages
8916                // we have to prune them from the disabled system packages.
8917                PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(pkg.packageName);
8918                if (disabledPs != null) {
8919                    final int scannedChildCount = (pkg.childPackages != null)
8920                            ? pkg.childPackages.size() : 0;
8921                    final int disabledChildCount = disabledPs.childPackageNames != null
8922                            ? disabledPs.childPackageNames.size() : 0;
8923                    for (int i = 0; i < disabledChildCount; i++) {
8924                        String disabledChildPackageName = disabledPs.childPackageNames.get(i);
8925                        boolean disabledPackageAvailable = false;
8926                        for (int j = 0; j < scannedChildCount; j++) {
8927                            PackageParser.Package childPkg = pkg.childPackages.get(j);
8928                            if (childPkg.packageName.equals(disabledChildPackageName)) {
8929                                disabledPackageAvailable = true;
8930                                break;
8931                            }
8932                         }
8933                         if (!disabledPackageAvailable) {
8934                             mSettings.removeDisabledSystemPackageLPw(disabledChildPackageName);
8935                         }
8936                    }
8937                }
8938            }
8939        }
8940
8941        final boolean isUpdatedPkg = updatedPkg != null;
8942        final boolean isUpdatedSystemPkg = isUpdatedPkg
8943                && (policyFlags & PackageParser.PARSE_IS_SYSTEM) != 0;
8944        boolean isUpdatedPkgBetter = false;
8945        // First check if this is a system package that may involve an update
8946        if (isUpdatedSystemPkg) {
8947            // If new package is not located in "/system/priv-app" (e.g. due to an OTA),
8948            // it needs to drop FLAG_PRIVILEGED.
8949            if (locationIsPrivileged(scanFile)) {
8950                updatedPkg.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
8951            } else {
8952                updatedPkg.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
8953            }
8954
8955            if (ps != null && !ps.codePath.equals(scanFile)) {
8956                // The path has changed from what was last scanned...  check the
8957                // version of the new path against what we have stored to determine
8958                // what to do.
8959                if (DEBUG_INSTALL) Slog.d(TAG, "Path changing from " + ps.codePath);
8960                if (pkg.mVersionCode <= ps.versionCode) {
8961                    // The system package has been updated and the code path does not match
8962                    // Ignore entry. Skip it.
8963                    if (DEBUG_INSTALL) Slog.i(TAG, "Package " + ps.name + " at " + scanFile
8964                            + " ignored: updated version " + ps.versionCode
8965                            + " better than this " + pkg.mVersionCode);
8966                    if (!updatedPkg.codePath.equals(scanFile)) {
8967                        Slog.w(PackageManagerService.TAG, "Code path for hidden system pkg "
8968                                + ps.name + " changing from " + updatedPkg.codePathString
8969                                + " to " + scanFile);
8970                        updatedPkg.codePath = scanFile;
8971                        updatedPkg.codePathString = scanFile.toString();
8972                        updatedPkg.resourcePath = scanFile;
8973                        updatedPkg.resourcePathString = scanFile.toString();
8974                    }
8975                    updatedPkg.pkg = pkg;
8976                    updatedPkg.versionCode = pkg.mVersionCode;
8977
8978                    // Update the disabled system child packages to point to the package too.
8979                    final int childCount = updatedPkg.childPackageNames != null
8980                            ? updatedPkg.childPackageNames.size() : 0;
8981                    for (int i = 0; i < childCount; i++) {
8982                        String childPackageName = updatedPkg.childPackageNames.get(i);
8983                        PackageSetting updatedChildPkg = mSettings.getDisabledSystemPkgLPr(
8984                                childPackageName);
8985                        if (updatedChildPkg != null) {
8986                            updatedChildPkg.pkg = pkg;
8987                            updatedChildPkg.versionCode = pkg.mVersionCode;
8988                        }
8989                    }
8990                } else {
8991                    // The current app on the system partition is better than
8992                    // what we have updated to on the data partition; switch
8993                    // back to the system partition version.
8994                    // At this point, its safely assumed that package installation for
8995                    // apps in system partition will go through. If not there won't be a working
8996                    // version of the app
8997                    // writer
8998                    synchronized (mPackages) {
8999                        // Just remove the loaded entries from package lists.
9000                        mPackages.remove(ps.name);
9001                    }
9002
9003                    logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile
9004                            + " reverting from " + ps.codePathString
9005                            + ": new version " + pkg.mVersionCode
9006                            + " better than installed " + ps.versionCode);
9007
9008                    InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
9009                            ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
9010                    synchronized (mInstallLock) {
9011                        args.cleanUpResourcesLI();
9012                    }
9013                    synchronized (mPackages) {
9014                        mSettings.enableSystemPackageLPw(ps.name);
9015                    }
9016                    isUpdatedPkgBetter = true;
9017                }
9018            }
9019        }
9020
9021        String resourcePath = null;
9022        String baseResourcePath = null;
9023        if ((policyFlags & PackageParser.PARSE_FORWARD_LOCK) != 0 && !isUpdatedPkgBetter) {
9024            if (ps != null && ps.resourcePathString != null) {
9025                resourcePath = ps.resourcePathString;
9026                baseResourcePath = ps.resourcePathString;
9027            } else {
9028                // Should not happen at all. Just log an error.
9029                Slog.e(TAG, "Resource path not set for package " + pkg.packageName);
9030            }
9031        } else {
9032            resourcePath = pkg.codePath;
9033            baseResourcePath = pkg.baseCodePath;
9034        }
9035
9036        // Set application objects path explicitly.
9037        pkg.setApplicationVolumeUuid(pkg.volumeUuid);
9038        pkg.setApplicationInfoCodePath(pkg.codePath);
9039        pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
9040        pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
9041        pkg.setApplicationInfoResourcePath(resourcePath);
9042        pkg.setApplicationInfoBaseResourcePath(baseResourcePath);
9043        pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
9044
9045        // throw an exception if we have an update to a system application, but, it's not more
9046        // recent than the package we've already scanned
9047        if (isUpdatedSystemPkg && !isUpdatedPkgBetter) {
9048            throw new PackageManagerException(Log.WARN, "Package " + ps.name + " at "
9049                    + scanFile + " ignored: updated version " + ps.versionCode
9050                    + " better than this " + pkg.mVersionCode);
9051        }
9052
9053        if (isUpdatedPkg) {
9054            // An updated system app will not have the PARSE_IS_SYSTEM flag set
9055            // initially
9056            policyFlags |= PackageParser.PARSE_IS_SYSTEM;
9057
9058            // An updated privileged app will not have the PARSE_IS_PRIVILEGED
9059            // flag set initially
9060            if ((updatedPkg.pkgPrivateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0) {
9061                policyFlags |= PackageParser.PARSE_IS_PRIVILEGED;
9062            }
9063        }
9064
9065        // Verify certificates against what was last scanned
9066        collectCertificatesLI(ps, pkg, scanFile, policyFlags);
9067
9068        /*
9069         * A new system app appeared, but we already had a non-system one of the
9070         * same name installed earlier.
9071         */
9072        boolean shouldHideSystemApp = false;
9073        if (!isUpdatedPkg && ps != null
9074                && (policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0 && !isSystemApp(ps)) {
9075            /*
9076             * Check to make sure the signatures match first. If they don't,
9077             * wipe the installed application and its data.
9078             */
9079            if (compareSignatures(ps.signatures.mSignatures, pkg.mSignatures)
9080                    != PackageManager.SIGNATURE_MATCH) {
9081                logCriticalInfo(Log.WARN, "Package " + ps.name + " appeared on system, but"
9082                        + " signatures don't match existing userdata copy; removing");
9083                try (PackageFreezer freezer = freezePackage(pkg.packageName,
9084                        "scanPackageInternalLI")) {
9085                    deletePackageLIF(pkg.packageName, null, true, null, 0, null, false, null);
9086                }
9087                ps = null;
9088            } else {
9089                /*
9090                 * If the newly-added system app is an older version than the
9091                 * already installed version, hide it. It will be scanned later
9092                 * and re-added like an update.
9093                 */
9094                if (pkg.mVersionCode <= ps.versionCode) {
9095                    shouldHideSystemApp = true;
9096                    logCriticalInfo(Log.INFO, "Package " + ps.name + " appeared at " + scanFile
9097                            + " but new version " + pkg.mVersionCode + " better than installed "
9098                            + ps.versionCode + "; hiding system");
9099                } else {
9100                    /*
9101                     * The newly found system app is a newer version that the
9102                     * one previously installed. Simply remove the
9103                     * already-installed application and replace it with our own
9104                     * while keeping the application data.
9105                     */
9106                    logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile
9107                            + " reverting from " + ps.codePathString + ": new version "
9108                            + pkg.mVersionCode + " better than installed " + ps.versionCode);
9109                    InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
9110                            ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
9111                    synchronized (mInstallLock) {
9112                        args.cleanUpResourcesLI();
9113                    }
9114                }
9115            }
9116        }
9117
9118        // The apk is forward locked (not public) if its code and resources
9119        // are kept in different files. (except for app in either system or
9120        // vendor path).
9121        // TODO grab this value from PackageSettings
9122        if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
9123            if (ps != null && !ps.codePath.equals(ps.resourcePath)) {
9124                policyFlags |= PackageParser.PARSE_FORWARD_LOCK;
9125            }
9126        }
9127
9128        final int userId = ((user == null) ? 0 : user.getIdentifier());
9129        if (ps != null && ps.getInstantApp(userId)) {
9130            scanFlags |= SCAN_AS_INSTANT_APP;
9131        }
9132
9133        // Note that we invoke the following method only if we are about to unpack an application
9134        PackageParser.Package scannedPkg = scanPackageLI(pkg, policyFlags, scanFlags
9135                | SCAN_UPDATE_SIGNATURE, currentTime, user);
9136
9137        /*
9138         * If the system app should be overridden by a previously installed
9139         * data, hide the system app now and let the /data/app scan pick it up
9140         * again.
9141         */
9142        if (shouldHideSystemApp) {
9143            synchronized (mPackages) {
9144                mSettings.disableSystemPackageLPw(pkg.packageName, true);
9145            }
9146        }
9147
9148        return scannedPkg;
9149    }
9150
9151    private void renameStaticSharedLibraryPackage(PackageParser.Package pkg) {
9152        // Derive the new package synthetic package name
9153        pkg.setPackageName(pkg.packageName + STATIC_SHARED_LIB_DELIMITER
9154                + pkg.staticSharedLibVersion);
9155    }
9156
9157    private static String fixProcessName(String defProcessName,
9158            String processName) {
9159        if (processName == null) {
9160            return defProcessName;
9161        }
9162        return processName;
9163    }
9164
9165    private void verifySignaturesLP(PackageSetting pkgSetting, PackageParser.Package pkg)
9166            throws PackageManagerException {
9167        if (pkgSetting.signatures.mSignatures != null) {
9168            // Already existing package. Make sure signatures match
9169            boolean match = compareSignatures(pkgSetting.signatures.mSignatures, pkg.mSignatures)
9170                    == PackageManager.SIGNATURE_MATCH;
9171            if (!match) {
9172                match = compareSignaturesCompat(pkgSetting.signatures, pkg)
9173                        == PackageManager.SIGNATURE_MATCH;
9174            }
9175            if (!match) {
9176                match = compareSignaturesRecover(pkgSetting.signatures, pkg)
9177                        == PackageManager.SIGNATURE_MATCH;
9178            }
9179            if (!match) {
9180                throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package "
9181                        + pkg.packageName + " signatures do not match the "
9182                        + "previously installed version; ignoring!");
9183            }
9184        }
9185
9186        // Check for shared user signatures
9187        if (pkgSetting.sharedUser != null && pkgSetting.sharedUser.signatures.mSignatures != null) {
9188            // Already existing package. Make sure signatures match
9189            boolean match = compareSignatures(pkgSetting.sharedUser.signatures.mSignatures,
9190                    pkg.mSignatures) == PackageManager.SIGNATURE_MATCH;
9191            if (!match) {
9192                match = compareSignaturesCompat(pkgSetting.sharedUser.signatures, pkg)
9193                        == PackageManager.SIGNATURE_MATCH;
9194            }
9195            if (!match) {
9196                match = compareSignaturesRecover(pkgSetting.sharedUser.signatures, pkg)
9197                        == PackageManager.SIGNATURE_MATCH;
9198            }
9199            if (!match) {
9200                throw new PackageManagerException(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE,
9201                        "Package " + pkg.packageName
9202                        + " has no signatures that match those in shared user "
9203                        + pkgSetting.sharedUser.name + "; ignoring!");
9204            }
9205        }
9206    }
9207
9208    /**
9209     * Enforces that only the system UID or root's UID can call a method exposed
9210     * via Binder.
9211     *
9212     * @param message used as message if SecurityException is thrown
9213     * @throws SecurityException if the caller is not system or root
9214     */
9215    private static final void enforceSystemOrRoot(String message) {
9216        final int uid = Binder.getCallingUid();
9217        if (uid != Process.SYSTEM_UID && uid != Process.ROOT_UID) {
9218            throw new SecurityException(message);
9219        }
9220    }
9221
9222    @Override
9223    public void performFstrimIfNeeded() {
9224        enforceSystemOrRoot("Only the system can request fstrim");
9225
9226        // Before everything else, see whether we need to fstrim.
9227        try {
9228            IStorageManager sm = PackageHelper.getStorageManager();
9229            if (sm != null) {
9230                boolean doTrim = false;
9231                final long interval = android.provider.Settings.Global.getLong(
9232                        mContext.getContentResolver(),
9233                        android.provider.Settings.Global.FSTRIM_MANDATORY_INTERVAL,
9234                        DEFAULT_MANDATORY_FSTRIM_INTERVAL);
9235                if (interval > 0) {
9236                    final long timeSinceLast = System.currentTimeMillis() - sm.lastMaintenance();
9237                    if (timeSinceLast > interval) {
9238                        doTrim = true;
9239                        Slog.w(TAG, "No disk maintenance in " + timeSinceLast
9240                                + "; running immediately");
9241                    }
9242                }
9243                if (doTrim) {
9244                    final boolean dexOptDialogShown;
9245                    synchronized (mPackages) {
9246                        dexOptDialogShown = mDexOptDialogShown;
9247                    }
9248                    if (!isFirstBoot() && dexOptDialogShown) {
9249                        try {
9250                            ActivityManager.getService().showBootMessage(
9251                                    mContext.getResources().getString(
9252                                            R.string.android_upgrading_fstrim), true);
9253                        } catch (RemoteException e) {
9254                        }
9255                    }
9256                    sm.runMaintenance();
9257                }
9258            } else {
9259                Slog.e(TAG, "storageManager service unavailable!");
9260            }
9261        } catch (RemoteException e) {
9262            // Can't happen; StorageManagerService is local
9263        }
9264    }
9265
9266    @Override
9267    public void updatePackagesIfNeeded() {
9268        enforceSystemOrRoot("Only the system can request package update");
9269
9270        // We need to re-extract after an OTA.
9271        boolean causeUpgrade = isUpgrade();
9272
9273        // First boot or factory reset.
9274        // Note: we also handle devices that are upgrading to N right now as if it is their
9275        //       first boot, as they do not have profile data.
9276        boolean causeFirstBoot = isFirstBoot() || mIsPreNUpgrade;
9277
9278        // We need to re-extract after a pruned cache, as AoT-ed files will be out of date.
9279        boolean causePrunedCache = VMRuntime.didPruneDalvikCache();
9280
9281        if (!causeUpgrade && !causeFirstBoot && !causePrunedCache) {
9282            return;
9283        }
9284
9285        List<PackageParser.Package> pkgs;
9286        synchronized (mPackages) {
9287            pkgs = PackageManagerServiceUtils.getPackagesForDexopt(mPackages.values(), this);
9288        }
9289
9290        final long startTime = System.nanoTime();
9291        final int[] stats = performDexOptUpgrade(pkgs, mIsPreNUpgrade /* showDialog */,
9292                    getCompilerFilterForReason(causeFirstBoot ? REASON_FIRST_BOOT : REASON_BOOT),
9293                    false /* bootComplete */);
9294
9295        final int elapsedTimeSeconds =
9296                (int) TimeUnit.NANOSECONDS.toSeconds(System.nanoTime() - startTime);
9297
9298        MetricsLogger.histogram(mContext, "opt_dialog_num_dexopted", stats[0]);
9299        MetricsLogger.histogram(mContext, "opt_dialog_num_skipped", stats[1]);
9300        MetricsLogger.histogram(mContext, "opt_dialog_num_failed", stats[2]);
9301        MetricsLogger.histogram(mContext, "opt_dialog_num_total", getOptimizablePackages().size());
9302        MetricsLogger.histogram(mContext, "opt_dialog_time_s", elapsedTimeSeconds);
9303    }
9304
9305    /*
9306     * Return the prebuilt profile path given a package base code path.
9307     */
9308    private static String getPrebuildProfilePath(PackageParser.Package pkg) {
9309        return pkg.baseCodePath + ".prof";
9310    }
9311
9312    /**
9313     * Performs dexopt on the set of packages in {@code packages} and returns an int array
9314     * containing statistics about the invocation. The array consists of three elements,
9315     * which are (in order) {@code numberOfPackagesOptimized}, {@code numberOfPackagesSkipped}
9316     * and {@code numberOfPackagesFailed}.
9317     */
9318    private int[] performDexOptUpgrade(List<PackageParser.Package> pkgs, boolean showDialog,
9319            String compilerFilter, boolean bootComplete) {
9320
9321        int numberOfPackagesVisited = 0;
9322        int numberOfPackagesOptimized = 0;
9323        int numberOfPackagesSkipped = 0;
9324        int numberOfPackagesFailed = 0;
9325        final int numberOfPackagesToDexopt = pkgs.size();
9326
9327        for (PackageParser.Package pkg : pkgs) {
9328            numberOfPackagesVisited++;
9329
9330            if ((isFirstBoot() || isUpgrade()) && isSystemApp(pkg)) {
9331                // Copy over initial preopt profiles since we won't get any JIT samples for methods
9332                // that are already compiled.
9333                File profileFile = new File(getPrebuildProfilePath(pkg));
9334                // Copy profile if it exists.
9335                if (profileFile.exists()) {
9336                    try {
9337                        // We could also do this lazily before calling dexopt in
9338                        // PackageDexOptimizer to prevent this happening on first boot. The issue
9339                        // is that we don't have a good way to say "do this only once".
9340                        if (!mInstaller.copySystemProfile(profileFile.getAbsolutePath(),
9341                                pkg.applicationInfo.uid, pkg.packageName)) {
9342                            Log.e(TAG, "Installer failed to copy system profile!");
9343                        }
9344                    } catch (Exception e) {
9345                        Log.e(TAG, "Failed to copy profile " + profileFile.getAbsolutePath() + " ",
9346                                e);
9347                    }
9348                }
9349            }
9350
9351            if (!PackageDexOptimizer.canOptimizePackage(pkg)) {
9352                if (DEBUG_DEXOPT) {
9353                    Log.i(TAG, "Skipping update of of non-optimizable app " + pkg.packageName);
9354                }
9355                numberOfPackagesSkipped++;
9356                continue;
9357            }
9358
9359            if (DEBUG_DEXOPT) {
9360                Log.i(TAG, "Updating app " + numberOfPackagesVisited + " of " +
9361                        numberOfPackagesToDexopt + ": " + pkg.packageName);
9362            }
9363
9364            if (showDialog) {
9365                try {
9366                    ActivityManager.getService().showBootMessage(
9367                            mContext.getResources().getString(R.string.android_upgrading_apk,
9368                                    numberOfPackagesVisited, numberOfPackagesToDexopt), true);
9369                } catch (RemoteException e) {
9370                }
9371                synchronized (mPackages) {
9372                    mDexOptDialogShown = true;
9373                }
9374            }
9375
9376            // If the OTA updates a system app which was previously preopted to a non-preopted state
9377            // the app might end up being verified at runtime. That's because by default the apps
9378            // are verify-profile but for preopted apps there's no profile.
9379            // Do a hacky check to ensure that if we have no profiles (a reasonable indication
9380            // that before the OTA the app was preopted) the app gets compiled with a non-profile
9381            // filter (by default 'quicken').
9382            // Note that at this stage unused apps are already filtered.
9383            if (isSystemApp(pkg) &&
9384                    DexFile.isProfileGuidedCompilerFilter(compilerFilter) &&
9385                    !Environment.getReferenceProfile(pkg.packageName).exists()) {
9386                compilerFilter = getNonProfileGuidedCompilerFilter(compilerFilter);
9387            }
9388
9389            // checkProfiles is false to avoid merging profiles during boot which
9390            // might interfere with background compilation (b/28612421).
9391            // Unfortunately this will also means that "pm.dexopt.boot=speed-profile" will
9392            // behave differently than "pm.dexopt.bg-dexopt=speed-profile" but that's a
9393            // trade-off worth doing to save boot time work.
9394            int dexOptStatus = performDexOptTraced(pkg.packageName,
9395                    false /* checkProfiles */,
9396                    compilerFilter,
9397                    false /* force */,
9398                    bootComplete);
9399            switch (dexOptStatus) {
9400                case PackageDexOptimizer.DEX_OPT_PERFORMED:
9401                    numberOfPackagesOptimized++;
9402                    break;
9403                case PackageDexOptimizer.DEX_OPT_SKIPPED:
9404                    numberOfPackagesSkipped++;
9405                    break;
9406                case PackageDexOptimizer.DEX_OPT_FAILED:
9407                    numberOfPackagesFailed++;
9408                    break;
9409                default:
9410                    Log.e(TAG, "Unexpected dexopt return code " + dexOptStatus);
9411                    break;
9412            }
9413        }
9414
9415        return new int[] { numberOfPackagesOptimized, numberOfPackagesSkipped,
9416                numberOfPackagesFailed };
9417    }
9418
9419    @Override
9420    public void notifyPackageUse(String packageName, int reason) {
9421        synchronized (mPackages) {
9422            final int callingUid = Binder.getCallingUid();
9423            final int callingUserId = UserHandle.getUserId(callingUid);
9424            if (getInstantAppPackageName(callingUid) != null) {
9425                if (!isCallerSameApp(packageName, callingUid)) {
9426                    return;
9427                }
9428            } else {
9429                if (isInstantApp(packageName, callingUserId)) {
9430                    return;
9431                }
9432            }
9433            final PackageParser.Package p = mPackages.get(packageName);
9434            if (p == null) {
9435                return;
9436            }
9437            p.mLastPackageUsageTimeInMills[reason] = System.currentTimeMillis();
9438        }
9439    }
9440
9441    @Override
9442    public void notifyDexLoad(String loadingPackageName, List<String> dexPaths, String loaderIsa) {
9443        int userId = UserHandle.getCallingUserId();
9444        ApplicationInfo ai = getApplicationInfo(loadingPackageName, /*flags*/ 0, userId);
9445        if (ai == null) {
9446            Slog.w(TAG, "Loading a package that does not exist for the calling user. package="
9447                + loadingPackageName + ", user=" + userId);
9448            return;
9449        }
9450        mDexManager.notifyDexLoad(ai, dexPaths, loaderIsa, userId);
9451    }
9452
9453    @Override
9454    public void registerDexModule(String packageName, String dexModulePath, boolean isSharedModule,
9455            IDexModuleRegisterCallback callback) {
9456        int userId = UserHandle.getCallingUserId();
9457        ApplicationInfo ai = getApplicationInfo(packageName, /*flags*/ 0, userId);
9458        DexManager.RegisterDexModuleResult result;
9459        if (ai == null) {
9460            Slog.w(TAG, "Registering a dex module for a package that does not exist for the" +
9461                     " calling user. package=" + packageName + ", user=" + userId);
9462            result = new DexManager.RegisterDexModuleResult(false, "Package not installed");
9463        } else {
9464            result = mDexManager.registerDexModule(ai, dexModulePath, isSharedModule, userId);
9465        }
9466
9467        if (callback != null) {
9468            mHandler.post(() -> {
9469                try {
9470                    callback.onDexModuleRegistered(dexModulePath, result.success, result.message);
9471                } catch (RemoteException e) {
9472                    Slog.w(TAG, "Failed to callback after module registration " + dexModulePath, e);
9473                }
9474            });
9475        }
9476    }
9477
9478    @Override
9479    public boolean performDexOpt(String packageName,
9480            boolean checkProfiles, int compileReason, boolean force, boolean bootComplete) {
9481        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
9482            return false;
9483        } else if (isInstantApp(packageName, UserHandle.getCallingUserId())) {
9484            return false;
9485        }
9486        int dexoptStatus = performDexOptWithStatus(
9487              packageName, checkProfiles, compileReason, force, bootComplete);
9488        return dexoptStatus != PackageDexOptimizer.DEX_OPT_FAILED;
9489    }
9490
9491    /**
9492     * Perform dexopt on the given package and return one of following result:
9493     *  {@link PackageDexOptimizer#DEX_OPT_SKIPPED}
9494     *  {@link PackageDexOptimizer#DEX_OPT_PERFORMED}
9495     *  {@link PackageDexOptimizer#DEX_OPT_FAILED}
9496     */
9497    /* package */ int performDexOptWithStatus(String packageName,
9498            boolean checkProfiles, int compileReason, boolean force, boolean bootComplete) {
9499        return performDexOptTraced(packageName, checkProfiles,
9500                getCompilerFilterForReason(compileReason), force, bootComplete);
9501    }
9502
9503    @Override
9504    public boolean performDexOptMode(String packageName,
9505            boolean checkProfiles, String targetCompilerFilter, boolean force,
9506            boolean bootComplete) {
9507        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
9508            return false;
9509        } else if (isInstantApp(packageName, UserHandle.getCallingUserId())) {
9510            return false;
9511        }
9512        int dexOptStatus = performDexOptTraced(packageName, checkProfiles,
9513                targetCompilerFilter, force, bootComplete);
9514        return dexOptStatus != PackageDexOptimizer.DEX_OPT_FAILED;
9515    }
9516
9517    private int performDexOptTraced(String packageName,
9518                boolean checkProfiles, String targetCompilerFilter, boolean force,
9519                boolean bootComplete) {
9520        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt");
9521        try {
9522            return performDexOptInternal(packageName, checkProfiles,
9523                    targetCompilerFilter, force, bootComplete);
9524        } finally {
9525            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
9526        }
9527    }
9528
9529    // Run dexopt on a given package. Returns true if dexopt did not fail, i.e.
9530    // if the package can now be considered up to date for the given filter.
9531    private int performDexOptInternal(String packageName,
9532                boolean checkProfiles, String targetCompilerFilter, boolean force,
9533                boolean bootComplete) {
9534        PackageParser.Package p;
9535        synchronized (mPackages) {
9536            p = mPackages.get(packageName);
9537            if (p == null) {
9538                // Package could not be found. Report failure.
9539                return PackageDexOptimizer.DEX_OPT_FAILED;
9540            }
9541            mPackageUsage.maybeWriteAsync(mPackages);
9542            mCompilerStats.maybeWriteAsync();
9543        }
9544        long callingId = Binder.clearCallingIdentity();
9545        try {
9546            synchronized (mInstallLock) {
9547                return performDexOptInternalWithDependenciesLI(p, checkProfiles,
9548                        targetCompilerFilter, force, bootComplete);
9549            }
9550        } finally {
9551            Binder.restoreCallingIdentity(callingId);
9552        }
9553    }
9554
9555    public ArraySet<String> getOptimizablePackages() {
9556        ArraySet<String> pkgs = new ArraySet<String>();
9557        synchronized (mPackages) {
9558            for (PackageParser.Package p : mPackages.values()) {
9559                if (PackageDexOptimizer.canOptimizePackage(p)) {
9560                    pkgs.add(p.packageName);
9561                }
9562            }
9563        }
9564        return pkgs;
9565    }
9566
9567    private int performDexOptInternalWithDependenciesLI(PackageParser.Package p,
9568            boolean checkProfiles, String targetCompilerFilter,
9569            boolean force, boolean bootComplete) {
9570        // Select the dex optimizer based on the force parameter.
9571        // Note: The force option is rarely used (cmdline input for testing, mostly), so it's OK to
9572        //       allocate an object here.
9573        PackageDexOptimizer pdo = force
9574                ? new PackageDexOptimizer.ForcedUpdatePackageDexOptimizer(mPackageDexOptimizer)
9575                : mPackageDexOptimizer;
9576
9577        // Dexopt all dependencies first. Note: we ignore the return value and march on
9578        // on errors.
9579        // Note that we are going to call performDexOpt on those libraries as many times as
9580        // they are referenced in packages. When we do a batch of performDexOpt (for example
9581        // at boot, or background job), the passed 'targetCompilerFilter' stays the same,
9582        // and the first package that uses the library will dexopt it. The
9583        // others will see that the compiled code for the library is up to date.
9584        Collection<PackageParser.Package> deps = findSharedNonSystemLibraries(p);
9585        final String[] instructionSets = getAppDexInstructionSets(p.applicationInfo);
9586        if (!deps.isEmpty()) {
9587            for (PackageParser.Package depPackage : deps) {
9588                // TODO: Analyze and investigate if we (should) profile libraries.
9589                pdo.performDexOpt(depPackage, null /* sharedLibraries */, instructionSets,
9590                        false /* checkProfiles */,
9591                        targetCompilerFilter,
9592                        getOrCreateCompilerPackageStats(depPackage),
9593                        true /* isUsedByOtherApps */,
9594                        bootComplete);
9595            }
9596        }
9597        return pdo.performDexOpt(p, p.usesLibraryFiles, instructionSets, checkProfiles,
9598                targetCompilerFilter, getOrCreateCompilerPackageStats(p),
9599                mDexManager.isUsedByOtherApps(p.packageName), bootComplete);
9600    }
9601
9602    // Performs dexopt on the used secondary dex files belonging to the given package.
9603    // Returns true if all dex files were process successfully (which could mean either dexopt or
9604    // skip). Returns false if any of the files caused errors.
9605    @Override
9606    public boolean performDexOptSecondary(String packageName, String compilerFilter,
9607            boolean force) {
9608        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
9609            return false;
9610        } else if (isInstantApp(packageName, UserHandle.getCallingUserId())) {
9611            return false;
9612        }
9613        mDexManager.reconcileSecondaryDexFiles(packageName);
9614        return mDexManager.dexoptSecondaryDex(packageName, compilerFilter, force);
9615    }
9616
9617    public boolean performDexOptSecondary(String packageName, int compileReason,
9618            boolean force) {
9619        return mDexManager.dexoptSecondaryDex(packageName, compileReason, force);
9620    }
9621
9622    /**
9623     * Reconcile the information we have about the secondary dex files belonging to
9624     * {@code packagName} and the actual dex files. For all dex files that were
9625     * deleted, update the internal records and delete the generated oat files.
9626     */
9627    @Override
9628    public void reconcileSecondaryDexFiles(String packageName) {
9629        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
9630            return;
9631        } else if (isInstantApp(packageName, UserHandle.getCallingUserId())) {
9632            return;
9633        }
9634        mDexManager.reconcileSecondaryDexFiles(packageName);
9635    }
9636
9637    // TODO(calin): this is only needed for BackgroundDexOptService. Find a cleaner way to inject
9638    // a reference there.
9639    /*package*/ DexManager getDexManager() {
9640        return mDexManager;
9641    }
9642
9643    /**
9644     * Execute the background dexopt job immediately.
9645     */
9646    @Override
9647    public boolean runBackgroundDexoptJob() {
9648        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
9649            return false;
9650        }
9651        return BackgroundDexOptService.runIdleOptimizationsNow(this, mContext);
9652    }
9653
9654    List<PackageParser.Package> findSharedNonSystemLibraries(PackageParser.Package p) {
9655        if (p.usesLibraries != null || p.usesOptionalLibraries != null
9656                || p.usesStaticLibraries != null) {
9657            ArrayList<PackageParser.Package> retValue = new ArrayList<>();
9658            Set<String> collectedNames = new HashSet<>();
9659            findSharedNonSystemLibrariesRecursive(p, retValue, collectedNames);
9660
9661            retValue.remove(p);
9662
9663            return retValue;
9664        } else {
9665            return Collections.emptyList();
9666        }
9667    }
9668
9669    private void findSharedNonSystemLibrariesRecursive(PackageParser.Package p,
9670            ArrayList<PackageParser.Package> collected, Set<String> collectedNames) {
9671        if (!collectedNames.contains(p.packageName)) {
9672            collectedNames.add(p.packageName);
9673            collected.add(p);
9674
9675            if (p.usesLibraries != null) {
9676                findSharedNonSystemLibrariesRecursive(p.usesLibraries,
9677                        null, collected, collectedNames);
9678            }
9679            if (p.usesOptionalLibraries != null) {
9680                findSharedNonSystemLibrariesRecursive(p.usesOptionalLibraries,
9681                        null, collected, collectedNames);
9682            }
9683            if (p.usesStaticLibraries != null) {
9684                findSharedNonSystemLibrariesRecursive(p.usesStaticLibraries,
9685                        p.usesStaticLibrariesVersions, collected, collectedNames);
9686            }
9687        }
9688    }
9689
9690    private void findSharedNonSystemLibrariesRecursive(ArrayList<String> libs, int[] versions,
9691            ArrayList<PackageParser.Package> collected, Set<String> collectedNames) {
9692        final int libNameCount = libs.size();
9693        for (int i = 0; i < libNameCount; i++) {
9694            String libName = libs.get(i);
9695            int version = (versions != null && versions.length == libNameCount)
9696                    ? versions[i] : PackageManager.VERSION_CODE_HIGHEST;
9697            PackageParser.Package libPkg = findSharedNonSystemLibrary(libName, version);
9698            if (libPkg != null) {
9699                findSharedNonSystemLibrariesRecursive(libPkg, collected, collectedNames);
9700            }
9701        }
9702    }
9703
9704    private PackageParser.Package findSharedNonSystemLibrary(String name, int version) {
9705        synchronized (mPackages) {
9706            SharedLibraryEntry libEntry = getSharedLibraryEntryLPr(name, version);
9707            if (libEntry != null) {
9708                return mPackages.get(libEntry.apk);
9709            }
9710            return null;
9711        }
9712    }
9713
9714    private SharedLibraryEntry getSharedLibraryEntryLPr(String name, int version) {
9715        SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(name);
9716        if (versionedLib == null) {
9717            return null;
9718        }
9719        return versionedLib.get(version);
9720    }
9721
9722    private SharedLibraryEntry getLatestSharedLibraVersionLPr(PackageParser.Package pkg) {
9723        SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(
9724                pkg.staticSharedLibName);
9725        if (versionedLib == null) {
9726            return null;
9727        }
9728        int previousLibVersion = -1;
9729        final int versionCount = versionedLib.size();
9730        for (int i = 0; i < versionCount; i++) {
9731            final int libVersion = versionedLib.keyAt(i);
9732            if (libVersion < pkg.staticSharedLibVersion) {
9733                previousLibVersion = Math.max(previousLibVersion, libVersion);
9734            }
9735        }
9736        if (previousLibVersion >= 0) {
9737            return versionedLib.get(previousLibVersion);
9738        }
9739        return null;
9740    }
9741
9742    public void shutdown() {
9743        mPackageUsage.writeNow(mPackages);
9744        mCompilerStats.writeNow();
9745    }
9746
9747    @Override
9748    public void dumpProfiles(String packageName) {
9749        PackageParser.Package pkg;
9750        synchronized (mPackages) {
9751            pkg = mPackages.get(packageName);
9752            if (pkg == null) {
9753                throw new IllegalArgumentException("Unknown package: " + packageName);
9754            }
9755        }
9756        /* Only the shell, root, or the app user should be able to dump profiles. */
9757        int callingUid = Binder.getCallingUid();
9758        if (callingUid != Process.SHELL_UID &&
9759            callingUid != Process.ROOT_UID &&
9760            callingUid != pkg.applicationInfo.uid) {
9761            throw new SecurityException("dumpProfiles");
9762        }
9763
9764        synchronized (mInstallLock) {
9765            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dump profiles");
9766            final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid);
9767            try {
9768                List<String> allCodePaths = pkg.getAllCodePathsExcludingResourceOnly();
9769                String codePaths = TextUtils.join(";", allCodePaths);
9770                mInstaller.dumpProfiles(sharedGid, packageName, codePaths);
9771            } catch (InstallerException e) {
9772                Slog.w(TAG, "Failed to dump profiles", e);
9773            }
9774            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
9775        }
9776    }
9777
9778    @Override
9779    public void forceDexOpt(String packageName) {
9780        enforceSystemOrRoot("forceDexOpt");
9781
9782        PackageParser.Package pkg;
9783        synchronized (mPackages) {
9784            pkg = mPackages.get(packageName);
9785            if (pkg == null) {
9786                throw new IllegalArgumentException("Unknown package: " + packageName);
9787            }
9788        }
9789
9790        synchronized (mInstallLock) {
9791            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt");
9792
9793            // Whoever is calling forceDexOpt wants a compiled package.
9794            // Don't use profiles since that may cause compilation to be skipped.
9795            final int res = performDexOptInternalWithDependenciesLI(pkg,
9796                    false /* checkProfiles */, getDefaultCompilerFilter(),
9797                    true /* force */,
9798                    true /* bootComplete */);
9799
9800            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
9801            if (res != PackageDexOptimizer.DEX_OPT_PERFORMED) {
9802                throw new IllegalStateException("Failed to dexopt: " + res);
9803            }
9804        }
9805    }
9806
9807    private boolean verifyPackageUpdateLPr(PackageSetting oldPkg, PackageParser.Package newPkg) {
9808        if ((oldPkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) {
9809            Slog.w(TAG, "Unable to update from " + oldPkg.name
9810                    + " to " + newPkg.packageName
9811                    + ": old package not in system partition");
9812            return false;
9813        } else if (mPackages.get(oldPkg.name) != null) {
9814            Slog.w(TAG, "Unable to update from " + oldPkg.name
9815                    + " to " + newPkg.packageName
9816                    + ": old package still exists");
9817            return false;
9818        }
9819        return true;
9820    }
9821
9822    void removeCodePathLI(File codePath) {
9823        if (codePath.isDirectory()) {
9824            try {
9825                mInstaller.rmPackageDir(codePath.getAbsolutePath());
9826            } catch (InstallerException e) {
9827                Slog.w(TAG, "Failed to remove code path", e);
9828            }
9829        } else {
9830            codePath.delete();
9831        }
9832    }
9833
9834    private int[] resolveUserIds(int userId) {
9835        return (userId == UserHandle.USER_ALL) ? sUserManager.getUserIds() : new int[] { userId };
9836    }
9837
9838    private void clearAppDataLIF(PackageParser.Package pkg, int userId, int flags) {
9839        if (pkg == null) {
9840            Slog.wtf(TAG, "Package was null!", new Throwable());
9841            return;
9842        }
9843        clearAppDataLeafLIF(pkg, userId, flags);
9844        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
9845        for (int i = 0; i < childCount; i++) {
9846            clearAppDataLeafLIF(pkg.childPackages.get(i), userId, flags);
9847        }
9848    }
9849
9850    private void clearAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) {
9851        final PackageSetting ps;
9852        synchronized (mPackages) {
9853            ps = mSettings.mPackages.get(pkg.packageName);
9854        }
9855        for (int realUserId : resolveUserIds(userId)) {
9856            final long ceDataInode = (ps != null) ? ps.getCeDataInode(realUserId) : 0;
9857            try {
9858                mInstaller.clearAppData(pkg.volumeUuid, pkg.packageName, realUserId, flags,
9859                        ceDataInode);
9860            } catch (InstallerException e) {
9861                Slog.w(TAG, String.valueOf(e));
9862            }
9863        }
9864    }
9865
9866    private void destroyAppDataLIF(PackageParser.Package pkg, int userId, int flags) {
9867        if (pkg == null) {
9868            Slog.wtf(TAG, "Package was null!", new Throwable());
9869            return;
9870        }
9871        destroyAppDataLeafLIF(pkg, userId, flags);
9872        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
9873        for (int i = 0; i < childCount; i++) {
9874            destroyAppDataLeafLIF(pkg.childPackages.get(i), userId, flags);
9875        }
9876    }
9877
9878    private void destroyAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) {
9879        final PackageSetting ps;
9880        synchronized (mPackages) {
9881            ps = mSettings.mPackages.get(pkg.packageName);
9882        }
9883        for (int realUserId : resolveUserIds(userId)) {
9884            final long ceDataInode = (ps != null) ? ps.getCeDataInode(realUserId) : 0;
9885            try {
9886                mInstaller.destroyAppData(pkg.volumeUuid, pkg.packageName, realUserId, flags,
9887                        ceDataInode);
9888            } catch (InstallerException e) {
9889                Slog.w(TAG, String.valueOf(e));
9890            }
9891            mDexManager.notifyPackageDataDestroyed(pkg.packageName, userId);
9892        }
9893    }
9894
9895    private void destroyAppProfilesLIF(PackageParser.Package pkg, int userId) {
9896        if (pkg == null) {
9897            Slog.wtf(TAG, "Package was null!", new Throwable());
9898            return;
9899        }
9900        destroyAppProfilesLeafLIF(pkg);
9901        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
9902        for (int i = 0; i < childCount; i++) {
9903            destroyAppProfilesLeafLIF(pkg.childPackages.get(i));
9904        }
9905    }
9906
9907    private void destroyAppProfilesLeafLIF(PackageParser.Package pkg) {
9908        try {
9909            mInstaller.destroyAppProfiles(pkg.packageName);
9910        } catch (InstallerException e) {
9911            Slog.w(TAG, String.valueOf(e));
9912        }
9913    }
9914
9915    private void clearAppProfilesLIF(PackageParser.Package pkg, int userId) {
9916        if (pkg == null) {
9917            Slog.wtf(TAG, "Package was null!", new Throwable());
9918            return;
9919        }
9920        clearAppProfilesLeafLIF(pkg);
9921        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
9922        for (int i = 0; i < childCount; i++) {
9923            clearAppProfilesLeafLIF(pkg.childPackages.get(i));
9924        }
9925    }
9926
9927    private void clearAppProfilesLeafLIF(PackageParser.Package pkg) {
9928        try {
9929            mInstaller.clearAppProfiles(pkg.packageName);
9930        } catch (InstallerException e) {
9931            Slog.w(TAG, String.valueOf(e));
9932        }
9933    }
9934
9935    private void setInstallAndUpdateTime(PackageParser.Package pkg, long firstInstallTime,
9936            long lastUpdateTime) {
9937        // Set parent install/update time
9938        PackageSetting ps = (PackageSetting) pkg.mExtras;
9939        if (ps != null) {
9940            ps.firstInstallTime = firstInstallTime;
9941            ps.lastUpdateTime = lastUpdateTime;
9942        }
9943        // Set children install/update time
9944        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
9945        for (int i = 0; i < childCount; i++) {
9946            PackageParser.Package childPkg = pkg.childPackages.get(i);
9947            ps = (PackageSetting) childPkg.mExtras;
9948            if (ps != null) {
9949                ps.firstInstallTime = firstInstallTime;
9950                ps.lastUpdateTime = lastUpdateTime;
9951            }
9952        }
9953    }
9954
9955    private void addSharedLibraryLPr(ArraySet<String> usesLibraryFiles, SharedLibraryEntry file,
9956            PackageParser.Package changingLib) {
9957        if (file.path != null) {
9958            usesLibraryFiles.add(file.path);
9959            return;
9960        }
9961        PackageParser.Package p = mPackages.get(file.apk);
9962        if (changingLib != null && changingLib.packageName.equals(file.apk)) {
9963            // If we are doing this while in the middle of updating a library apk,
9964            // then we need to make sure to use that new apk for determining the
9965            // dependencies here.  (We haven't yet finished committing the new apk
9966            // to the package manager state.)
9967            if (p == null || p.packageName.equals(changingLib.packageName)) {
9968                p = changingLib;
9969            }
9970        }
9971        if (p != null) {
9972            usesLibraryFiles.addAll(p.getAllCodePaths());
9973            if (p.usesLibraryFiles != null) {
9974                Collections.addAll(usesLibraryFiles, p.usesLibraryFiles);
9975            }
9976        }
9977    }
9978
9979    private void updateSharedLibrariesLPr(PackageParser.Package pkg,
9980            PackageParser.Package changingLib) throws PackageManagerException {
9981        if (pkg == null) {
9982            return;
9983        }
9984        ArraySet<String> usesLibraryFiles = null;
9985        if (pkg.usesLibraries != null) {
9986            usesLibraryFiles = addSharedLibrariesLPw(pkg.usesLibraries,
9987                    null, null, pkg.packageName, changingLib, true, null);
9988        }
9989        if (pkg.usesStaticLibraries != null) {
9990            usesLibraryFiles = addSharedLibrariesLPw(pkg.usesStaticLibraries,
9991                    pkg.usesStaticLibrariesVersions, pkg.usesStaticLibrariesCertDigests,
9992                    pkg.packageName, changingLib, true, usesLibraryFiles);
9993        }
9994        if (pkg.usesOptionalLibraries != null) {
9995            usesLibraryFiles = addSharedLibrariesLPw(pkg.usesOptionalLibraries,
9996                    null, null, pkg.packageName, changingLib, false, usesLibraryFiles);
9997        }
9998        if (!ArrayUtils.isEmpty(usesLibraryFiles)) {
9999            pkg.usesLibraryFiles = usesLibraryFiles.toArray(new String[usesLibraryFiles.size()]);
10000        } else {
10001            pkg.usesLibraryFiles = null;
10002        }
10003    }
10004
10005    private ArraySet<String> addSharedLibrariesLPw(@NonNull List<String> requestedLibraries,
10006            @Nullable int[] requiredVersions, @Nullable String[] requiredCertDigests,
10007            @NonNull String packageName, @Nullable PackageParser.Package changingLib,
10008            boolean required, @Nullable ArraySet<String> outUsedLibraries)
10009            throws PackageManagerException {
10010        final int libCount = requestedLibraries.size();
10011        for (int i = 0; i < libCount; i++) {
10012            final String libName = requestedLibraries.get(i);
10013            final int libVersion = requiredVersions != null ? requiredVersions[i]
10014                    : SharedLibraryInfo.VERSION_UNDEFINED;
10015            final SharedLibraryEntry libEntry = getSharedLibraryEntryLPr(libName, libVersion);
10016            if (libEntry == null) {
10017                if (required) {
10018                    throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY,
10019                            "Package " + packageName + " requires unavailable shared library "
10020                                    + libName + "; failing!");
10021                } else if (DEBUG_SHARED_LIBRARIES) {
10022                    Slog.i(TAG, "Package " + packageName
10023                            + " desires unavailable shared library "
10024                            + libName + "; ignoring!");
10025                }
10026            } else {
10027                if (requiredVersions != null && requiredCertDigests != null) {
10028                    if (libEntry.info.getVersion() != requiredVersions[i]) {
10029                        throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY,
10030                            "Package " + packageName + " requires unavailable static shared"
10031                                    + " library " + libName + " version "
10032                                    + libEntry.info.getVersion() + "; failing!");
10033                    }
10034
10035                    PackageParser.Package libPkg = mPackages.get(libEntry.apk);
10036                    if (libPkg == null) {
10037                        throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY,
10038                                "Package " + packageName + " requires unavailable static shared"
10039                                        + " library; failing!");
10040                    }
10041
10042                    String expectedCertDigest = requiredCertDigests[i];
10043                    String libCertDigest = PackageUtils.computeCertSha256Digest(
10044                                libPkg.mSignatures[0]);
10045                    if (!libCertDigest.equalsIgnoreCase(expectedCertDigest)) {
10046                        throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY,
10047                                "Package " + packageName + " requires differently signed" +
10048                                        " static shared library; failing!");
10049                    }
10050                }
10051
10052                if (outUsedLibraries == null) {
10053                    outUsedLibraries = new ArraySet<>();
10054                }
10055                addSharedLibraryLPr(outUsedLibraries, libEntry, changingLib);
10056            }
10057        }
10058        return outUsedLibraries;
10059    }
10060
10061    private static boolean hasString(List<String> list, List<String> which) {
10062        if (list == null) {
10063            return false;
10064        }
10065        for (int i=list.size()-1; i>=0; i--) {
10066            for (int j=which.size()-1; j>=0; j--) {
10067                if (which.get(j).equals(list.get(i))) {
10068                    return true;
10069                }
10070            }
10071        }
10072        return false;
10073    }
10074
10075    private ArrayList<PackageParser.Package> updateAllSharedLibrariesLPw(
10076            PackageParser.Package changingPkg) {
10077        ArrayList<PackageParser.Package> res = null;
10078        for (PackageParser.Package pkg : mPackages.values()) {
10079            if (changingPkg != null
10080                    && !hasString(pkg.usesLibraries, changingPkg.libraryNames)
10081                    && !hasString(pkg.usesOptionalLibraries, changingPkg.libraryNames)
10082                    && !ArrayUtils.contains(pkg.usesStaticLibraries,
10083                            changingPkg.staticSharedLibName)) {
10084                return null;
10085            }
10086            if (res == null) {
10087                res = new ArrayList<>();
10088            }
10089            res.add(pkg);
10090            try {
10091                updateSharedLibrariesLPr(pkg, changingPkg);
10092            } catch (PackageManagerException e) {
10093                // If a system app update or an app and a required lib missing we
10094                // delete the package and for updated system apps keep the data as
10095                // it is better for the user to reinstall than to be in an limbo
10096                // state. Also libs disappearing under an app should never happen
10097                // - just in case.
10098                if (!pkg.isSystemApp() || pkg.isUpdatedSystemApp()) {
10099                    final int flags = pkg.isUpdatedSystemApp()
10100                            ? PackageManager.DELETE_KEEP_DATA : 0;
10101                    deletePackageLIF(pkg.packageName, null, true, sUserManager.getUserIds(),
10102                            flags , null, true, null);
10103                }
10104                Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
10105            }
10106        }
10107        return res;
10108    }
10109
10110    /**
10111     * Derive the value of the {@code cpuAbiOverride} based on the provided
10112     * value and an optional stored value from the package settings.
10113     */
10114    private static String deriveAbiOverride(String abiOverride, PackageSetting settings) {
10115        String cpuAbiOverride = null;
10116
10117        if (NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(abiOverride)) {
10118            cpuAbiOverride = null;
10119        } else if (abiOverride != null) {
10120            cpuAbiOverride = abiOverride;
10121        } else if (settings != null) {
10122            cpuAbiOverride = settings.cpuAbiOverrideString;
10123        }
10124
10125        return cpuAbiOverride;
10126    }
10127
10128    private PackageParser.Package scanPackageTracedLI(PackageParser.Package pkg,
10129            final int policyFlags, int scanFlags, long currentTime, @Nullable UserHandle user)
10130                    throws PackageManagerException {
10131        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage");
10132        // If the package has children and this is the first dive in the function
10133        // we recursively scan the package with the SCAN_CHECK_ONLY flag set to see
10134        // whether all packages (parent and children) would be successfully scanned
10135        // before the actual scan since scanning mutates internal state and we want
10136        // to atomically install the package and its children.
10137        if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
10138            if (pkg.childPackages != null && pkg.childPackages.size() > 0) {
10139                scanFlags |= SCAN_CHECK_ONLY;
10140            }
10141        } else {
10142            scanFlags &= ~SCAN_CHECK_ONLY;
10143        }
10144
10145        final PackageParser.Package scannedPkg;
10146        try {
10147            // Scan the parent
10148            scannedPkg = scanPackageLI(pkg, policyFlags, scanFlags, currentTime, user);
10149            // Scan the children
10150            final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
10151            for (int i = 0; i < childCount; i++) {
10152                PackageParser.Package childPkg = pkg.childPackages.get(i);
10153                scanPackageLI(childPkg, policyFlags,
10154                        scanFlags, currentTime, user);
10155            }
10156        } finally {
10157            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
10158        }
10159
10160        if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
10161            return scanPackageTracedLI(pkg, policyFlags, scanFlags, currentTime, user);
10162        }
10163
10164        return scannedPkg;
10165    }
10166
10167    private PackageParser.Package scanPackageLI(PackageParser.Package pkg, final int policyFlags,
10168            int scanFlags, long currentTime, @Nullable UserHandle user)
10169                    throws PackageManagerException {
10170        boolean success = false;
10171        try {
10172            final PackageParser.Package res = scanPackageDirtyLI(pkg, policyFlags, scanFlags,
10173                    currentTime, user);
10174            success = true;
10175            return res;
10176        } finally {
10177            if (!success && (scanFlags & SCAN_DELETE_DATA_ON_FAILURES) != 0) {
10178                // DELETE_DATA_ON_FAILURES is only used by frozen paths
10179                destroyAppDataLIF(pkg, UserHandle.USER_ALL,
10180                        StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
10181                destroyAppProfilesLIF(pkg, UserHandle.USER_ALL);
10182            }
10183        }
10184    }
10185
10186    /**
10187     * Returns {@code true} if the given file contains code. Otherwise {@code false}.
10188     */
10189    private static boolean apkHasCode(String fileName) {
10190        StrictJarFile jarFile = null;
10191        try {
10192            jarFile = new StrictJarFile(fileName,
10193                    false /*verify*/, false /*signatureSchemeRollbackProtectionsEnforced*/);
10194            return jarFile.findEntry("classes.dex") != null;
10195        } catch (IOException ignore) {
10196        } finally {
10197            try {
10198                if (jarFile != null) {
10199                    jarFile.close();
10200                }
10201            } catch (IOException ignore) {}
10202        }
10203        return false;
10204    }
10205
10206    /**
10207     * Enforces code policy for the package. This ensures that if an APK has
10208     * declared hasCode="true" in its manifest that the APK actually contains
10209     * code.
10210     *
10211     * @throws PackageManagerException If bytecode could not be found when it should exist
10212     */
10213    private static void assertCodePolicy(PackageParser.Package pkg)
10214            throws PackageManagerException {
10215        final boolean shouldHaveCode =
10216                (pkg.applicationInfo.flags & ApplicationInfo.FLAG_HAS_CODE) != 0;
10217        if (shouldHaveCode && !apkHasCode(pkg.baseCodePath)) {
10218            throw new PackageManagerException(INSTALL_FAILED_INVALID_APK,
10219                    "Package " + pkg.baseCodePath + " code is missing");
10220        }
10221
10222        if (!ArrayUtils.isEmpty(pkg.splitCodePaths)) {
10223            for (int i = 0; i < pkg.splitCodePaths.length; i++) {
10224                final boolean splitShouldHaveCode =
10225                        (pkg.splitFlags[i] & ApplicationInfo.FLAG_HAS_CODE) != 0;
10226                if (splitShouldHaveCode && !apkHasCode(pkg.splitCodePaths[i])) {
10227                    throw new PackageManagerException(INSTALL_FAILED_INVALID_APK,
10228                            "Package " + pkg.splitCodePaths[i] + " code is missing");
10229                }
10230            }
10231        }
10232    }
10233
10234    private PackageParser.Package scanPackageDirtyLI(PackageParser.Package pkg,
10235            final int policyFlags, final int scanFlags, long currentTime, @Nullable UserHandle user)
10236                    throws PackageManagerException {
10237        if (DEBUG_PACKAGE_SCANNING) {
10238            if ((policyFlags & PackageParser.PARSE_CHATTY) != 0)
10239                Log.d(TAG, "Scanning package " + pkg.packageName);
10240        }
10241
10242        applyPolicy(pkg, policyFlags);
10243
10244        assertPackageIsValid(pkg, policyFlags, scanFlags);
10245
10246        // Initialize package source and resource directories
10247        final File scanFile = new File(pkg.codePath);
10248        final File destCodeFile = new File(pkg.applicationInfo.getCodePath());
10249        final File destResourceFile = new File(pkg.applicationInfo.getResourcePath());
10250
10251        SharedUserSetting suid = null;
10252        PackageSetting pkgSetting = null;
10253
10254        // Getting the package setting may have a side-effect, so if we
10255        // are only checking if scan would succeed, stash a copy of the
10256        // old setting to restore at the end.
10257        PackageSetting nonMutatedPs = null;
10258
10259        // We keep references to the derived CPU Abis from settings in oder to reuse
10260        // them in the case where we're not upgrading or booting for the first time.
10261        String primaryCpuAbiFromSettings = null;
10262        String secondaryCpuAbiFromSettings = null;
10263
10264        // writer
10265        synchronized (mPackages) {
10266            if (pkg.mSharedUserId != null) {
10267                // SIDE EFFECTS; may potentially allocate a new shared user
10268                suid = mSettings.getSharedUserLPw(
10269                        pkg.mSharedUserId, 0 /*pkgFlags*/, 0 /*pkgPrivateFlags*/, true /*create*/);
10270                if (DEBUG_PACKAGE_SCANNING) {
10271                    if ((policyFlags & PackageParser.PARSE_CHATTY) != 0)
10272                        Log.d(TAG, "Shared UserID " + pkg.mSharedUserId + " (uid=" + suid.userId
10273                                + "): packages=" + suid.packages);
10274                }
10275            }
10276
10277            // Check if we are renaming from an original package name.
10278            PackageSetting origPackage = null;
10279            String realName = null;
10280            if (pkg.mOriginalPackages != null) {
10281                // This package may need to be renamed to a previously
10282                // installed name.  Let's check on that...
10283                final String renamed = mSettings.getRenamedPackageLPr(pkg.mRealPackage);
10284                if (pkg.mOriginalPackages.contains(renamed)) {
10285                    // This package had originally been installed as the
10286                    // original name, and we have already taken care of
10287                    // transitioning to the new one.  Just update the new
10288                    // one to continue using the old name.
10289                    realName = pkg.mRealPackage;
10290                    if (!pkg.packageName.equals(renamed)) {
10291                        // Callers into this function may have already taken
10292                        // care of renaming the package; only do it here if
10293                        // it is not already done.
10294                        pkg.setPackageName(renamed);
10295                    }
10296                } else {
10297                    for (int i=pkg.mOriginalPackages.size()-1; i>=0; i--) {
10298                        if ((origPackage = mSettings.getPackageLPr(
10299                                pkg.mOriginalPackages.get(i))) != null) {
10300                            // We do have the package already installed under its
10301                            // original name...  should we use it?
10302                            if (!verifyPackageUpdateLPr(origPackage, pkg)) {
10303                                // New package is not compatible with original.
10304                                origPackage = null;
10305                                continue;
10306                            } else if (origPackage.sharedUser != null) {
10307                                // Make sure uid is compatible between packages.
10308                                if (!origPackage.sharedUser.name.equals(pkg.mSharedUserId)) {
10309                                    Slog.w(TAG, "Unable to migrate data from " + origPackage.name
10310                                            + " to " + pkg.packageName + ": old uid "
10311                                            + origPackage.sharedUser.name
10312                                            + " differs from " + pkg.mSharedUserId);
10313                                    origPackage = null;
10314                                    continue;
10315                                }
10316                                // TODO: Add case when shared user id is added [b/28144775]
10317                            } else {
10318                                if (DEBUG_UPGRADE) Log.v(TAG, "Renaming new package "
10319                                        + pkg.packageName + " to old name " + origPackage.name);
10320                            }
10321                            break;
10322                        }
10323                    }
10324                }
10325            }
10326
10327            if (mTransferedPackages.contains(pkg.packageName)) {
10328                Slog.w(TAG, "Package " + pkg.packageName
10329                        + " was transferred to another, but its .apk remains");
10330            }
10331
10332            // See comments in nonMutatedPs declaration
10333            if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
10334                PackageSetting foundPs = mSettings.getPackageLPr(pkg.packageName);
10335                if (foundPs != null) {
10336                    nonMutatedPs = new PackageSetting(foundPs);
10337                }
10338            }
10339
10340            if ((scanFlags & SCAN_FIRST_BOOT_OR_UPGRADE) == 0) {
10341                PackageSetting foundPs = mSettings.getPackageLPr(pkg.packageName);
10342                if (foundPs != null) {
10343                    primaryCpuAbiFromSettings = foundPs.primaryCpuAbiString;
10344                    secondaryCpuAbiFromSettings = foundPs.secondaryCpuAbiString;
10345                }
10346            }
10347
10348            pkgSetting = mSettings.getPackageLPr(pkg.packageName);
10349            if (pkgSetting != null && pkgSetting.sharedUser != suid) {
10350                PackageManagerService.reportSettingsProblem(Log.WARN,
10351                        "Package " + pkg.packageName + " shared user changed from "
10352                                + (pkgSetting.sharedUser != null
10353                                        ? pkgSetting.sharedUser.name : "<nothing>")
10354                                + " to "
10355                                + (suid != null ? suid.name : "<nothing>")
10356                                + "; replacing with new");
10357                pkgSetting = null;
10358            }
10359            final PackageSetting oldPkgSetting =
10360                    pkgSetting == null ? null : new PackageSetting(pkgSetting);
10361            final PackageSetting disabledPkgSetting =
10362                    mSettings.getDisabledSystemPkgLPr(pkg.packageName);
10363
10364            String[] usesStaticLibraries = null;
10365            if (pkg.usesStaticLibraries != null) {
10366                usesStaticLibraries = new String[pkg.usesStaticLibraries.size()];
10367                pkg.usesStaticLibraries.toArray(usesStaticLibraries);
10368            }
10369
10370            if (pkgSetting == null) {
10371                final String parentPackageName = (pkg.parentPackage != null)
10372                        ? pkg.parentPackage.packageName : null;
10373                final boolean instantApp = (scanFlags & SCAN_AS_INSTANT_APP) != 0;
10374                // REMOVE SharedUserSetting from method; update in a separate call
10375                pkgSetting = Settings.createNewSetting(pkg.packageName, origPackage,
10376                        disabledPkgSetting, realName, suid, destCodeFile, destResourceFile,
10377                        pkg.applicationInfo.nativeLibraryRootDir, pkg.applicationInfo.primaryCpuAbi,
10378                        pkg.applicationInfo.secondaryCpuAbi, pkg.mVersionCode,
10379                        pkg.applicationInfo.flags, pkg.applicationInfo.privateFlags, user,
10380                        true /*allowInstall*/, instantApp, parentPackageName,
10381                        pkg.getChildPackageNames(), UserManagerService.getInstance(),
10382                        usesStaticLibraries, pkg.usesStaticLibrariesVersions);
10383                // SIDE EFFECTS; updates system state; move elsewhere
10384                if (origPackage != null) {
10385                    mSettings.addRenamedPackageLPw(pkg.packageName, origPackage.name);
10386                }
10387                mSettings.addUserToSettingLPw(pkgSetting);
10388            } else {
10389                // REMOVE SharedUserSetting from method; update in a separate call.
10390                //
10391                // TODO(narayan): This update is bogus. nativeLibraryDir & primaryCpuAbi,
10392                // secondaryCpuAbi are not known at this point so we always update them
10393                // to null here, only to reset them at a later point.
10394                Settings.updatePackageSetting(pkgSetting, disabledPkgSetting, suid, destCodeFile,
10395                        pkg.applicationInfo.nativeLibraryDir, pkg.applicationInfo.primaryCpuAbi,
10396                        pkg.applicationInfo.secondaryCpuAbi, pkg.applicationInfo.flags,
10397                        pkg.applicationInfo.privateFlags, pkg.getChildPackageNames(),
10398                        UserManagerService.getInstance(), usesStaticLibraries,
10399                        pkg.usesStaticLibrariesVersions);
10400            }
10401            // SIDE EFFECTS; persists system state to files on disk; move elsewhere
10402            mSettings.writeUserRestrictionsLPw(pkgSetting, oldPkgSetting);
10403
10404            // SIDE EFFECTS; modifies system state; move elsewhere
10405            if (pkgSetting.origPackage != null) {
10406                // If we are first transitioning from an original package,
10407                // fix up the new package's name now.  We need to do this after
10408                // looking up the package under its new name, so getPackageLP
10409                // can take care of fiddling things correctly.
10410                pkg.setPackageName(origPackage.name);
10411
10412                // File a report about this.
10413                String msg = "New package " + pkgSetting.realName
10414                        + " renamed to replace old package " + pkgSetting.name;
10415                reportSettingsProblem(Log.WARN, msg);
10416
10417                // Make a note of it.
10418                if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
10419                    mTransferedPackages.add(origPackage.name);
10420                }
10421
10422                // No longer need to retain this.
10423                pkgSetting.origPackage = null;
10424            }
10425
10426            // SIDE EFFECTS; modifies system state; move elsewhere
10427            if ((scanFlags & SCAN_CHECK_ONLY) == 0 && realName != null) {
10428                // Make a note of it.
10429                mTransferedPackages.add(pkg.packageName);
10430            }
10431
10432            if (mSettings.isDisabledSystemPackageLPr(pkg.packageName)) {
10433                pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
10434            }
10435
10436            if ((scanFlags & SCAN_BOOTING) == 0
10437                    && (policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
10438                // Check all shared libraries and map to their actual file path.
10439                // We only do this here for apps not on a system dir, because those
10440                // are the only ones that can fail an install due to this.  We
10441                // will take care of the system apps by updating all of their
10442                // library paths after the scan is done. Also during the initial
10443                // scan don't update any libs as we do this wholesale after all
10444                // apps are scanned to avoid dependency based scanning.
10445                updateSharedLibrariesLPr(pkg, null);
10446            }
10447
10448            if (mFoundPolicyFile) {
10449                SELinuxMMAC.assignSeInfoValue(pkg);
10450            }
10451            pkg.applicationInfo.uid = pkgSetting.appId;
10452            pkg.mExtras = pkgSetting;
10453
10454
10455            // Static shared libs have same package with different versions where
10456            // we internally use a synthetic package name to allow multiple versions
10457            // of the same package, therefore we need to compare signatures against
10458            // the package setting for the latest library version.
10459            PackageSetting signatureCheckPs = pkgSetting;
10460            if (pkg.applicationInfo.isStaticSharedLibrary()) {
10461                SharedLibraryEntry libraryEntry = getLatestSharedLibraVersionLPr(pkg);
10462                if (libraryEntry != null) {
10463                    signatureCheckPs = mSettings.getPackageLPr(libraryEntry.apk);
10464                }
10465            }
10466
10467            if (shouldCheckUpgradeKeySetLP(signatureCheckPs, scanFlags)) {
10468                if (checkUpgradeKeySetLP(signatureCheckPs, pkg)) {
10469                    // We just determined the app is signed correctly, so bring
10470                    // over the latest parsed certs.
10471                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
10472                } else {
10473                    if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
10474                        throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
10475                                "Package " + pkg.packageName + " upgrade keys do not match the "
10476                                + "previously installed version");
10477                    } else {
10478                        pkgSetting.signatures.mSignatures = pkg.mSignatures;
10479                        String msg = "System package " + pkg.packageName
10480                                + " signature changed; retaining data.";
10481                        reportSettingsProblem(Log.WARN, msg);
10482                    }
10483                }
10484            } else {
10485                try {
10486                    // SIDE EFFECTS; compareSignaturesCompat() changes KeysetManagerService
10487                    verifySignaturesLP(signatureCheckPs, pkg);
10488                    // We just determined the app is signed correctly, so bring
10489                    // over the latest parsed certs.
10490                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
10491                } catch (PackageManagerException e) {
10492                    if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
10493                        throw e;
10494                    }
10495                    // The signature has changed, but this package is in the system
10496                    // image...  let's recover!
10497                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
10498                    // However...  if this package is part of a shared user, but it
10499                    // doesn't match the signature of the shared user, let's fail.
10500                    // What this means is that you can't change the signatures
10501                    // associated with an overall shared user, which doesn't seem all
10502                    // that unreasonable.
10503                    if (signatureCheckPs.sharedUser != null) {
10504                        if (compareSignatures(signatureCheckPs.sharedUser.signatures.mSignatures,
10505                                pkg.mSignatures) != PackageManager.SIGNATURE_MATCH) {
10506                            throw new PackageManagerException(
10507                                    INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES,
10508                                    "Signature mismatch for shared user: "
10509                                            + pkgSetting.sharedUser);
10510                        }
10511                    }
10512                    // File a report about this.
10513                    String msg = "System package " + pkg.packageName
10514                            + " signature changed; retaining data.";
10515                    reportSettingsProblem(Log.WARN, msg);
10516                }
10517            }
10518
10519            if ((scanFlags & SCAN_CHECK_ONLY) == 0 && pkg.mAdoptPermissions != null) {
10520                // This package wants to adopt ownership of permissions from
10521                // another package.
10522                for (int i = pkg.mAdoptPermissions.size() - 1; i >= 0; i--) {
10523                    final String origName = pkg.mAdoptPermissions.get(i);
10524                    final PackageSetting orig = mSettings.getPackageLPr(origName);
10525                    if (orig != null) {
10526                        if (verifyPackageUpdateLPr(orig, pkg)) {
10527                            Slog.i(TAG, "Adopting permissions from " + origName + " to "
10528                                    + pkg.packageName);
10529                            // SIDE EFFECTS; updates permissions system state; move elsewhere
10530                            mSettings.transferPermissionsLPw(origName, pkg.packageName);
10531                        }
10532                    }
10533                }
10534            }
10535        }
10536
10537        pkg.applicationInfo.processName = fixProcessName(
10538                pkg.applicationInfo.packageName,
10539                pkg.applicationInfo.processName);
10540
10541        if (pkg != mPlatformPackage) {
10542            // Get all of our default paths setup
10543            pkg.applicationInfo.initForUser(UserHandle.USER_SYSTEM);
10544        }
10545
10546        final String cpuAbiOverride = deriveAbiOverride(pkg.cpuAbiOverride, pkgSetting);
10547
10548        if ((scanFlags & SCAN_NEW_INSTALL) == 0) {
10549            if ((scanFlags & SCAN_FIRST_BOOT_OR_UPGRADE) != 0) {
10550                Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "derivePackageAbi");
10551                final boolean extractNativeLibs = !pkg.isLibrary();
10552                derivePackageAbi(pkg, scanFile, cpuAbiOverride, extractNativeLibs,
10553                        mAppLib32InstallDir);
10554                Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
10555
10556                // Some system apps still use directory structure for native libraries
10557                // in which case we might end up not detecting abi solely based on apk
10558                // structure. Try to detect abi based on directory structure.
10559                if (isSystemApp(pkg) && !pkg.isUpdatedSystemApp() &&
10560                        pkg.applicationInfo.primaryCpuAbi == null) {
10561                    setBundledAppAbisAndRoots(pkg, pkgSetting);
10562                    setNativeLibraryPaths(pkg, mAppLib32InstallDir);
10563                }
10564            } else {
10565                // This is not a first boot or an upgrade, don't bother deriving the
10566                // ABI during the scan. Instead, trust the value that was stored in the
10567                // package setting.
10568                pkg.applicationInfo.primaryCpuAbi = primaryCpuAbiFromSettings;
10569                pkg.applicationInfo.secondaryCpuAbi = secondaryCpuAbiFromSettings;
10570
10571                setNativeLibraryPaths(pkg, mAppLib32InstallDir);
10572
10573                if (DEBUG_ABI_SELECTION) {
10574                    Slog.i(TAG, "Using ABIS and native lib paths from settings : " +
10575                        pkg.packageName + " " + pkg.applicationInfo.primaryCpuAbi + ", " +
10576                        pkg.applicationInfo.secondaryCpuAbi);
10577                }
10578            }
10579        } else {
10580            if ((scanFlags & SCAN_MOVE) != 0) {
10581                // We haven't run dex-opt for this move (since we've moved the compiled output too)
10582                // but we already have this packages package info in the PackageSetting. We just
10583                // use that and derive the native library path based on the new codepath.
10584                pkg.applicationInfo.primaryCpuAbi = pkgSetting.primaryCpuAbiString;
10585                pkg.applicationInfo.secondaryCpuAbi = pkgSetting.secondaryCpuAbiString;
10586            }
10587
10588            // Set native library paths again. For moves, the path will be updated based on the
10589            // ABIs we've determined above. For non-moves, the path will be updated based on the
10590            // ABIs we determined during compilation, but the path will depend on the final
10591            // package path (after the rename away from the stage path).
10592            setNativeLibraryPaths(pkg, mAppLib32InstallDir);
10593        }
10594
10595        // This is a special case for the "system" package, where the ABI is
10596        // dictated by the zygote configuration (and init.rc). We should keep track
10597        // of this ABI so that we can deal with "normal" applications that run under
10598        // the same UID correctly.
10599        if (mPlatformPackage == pkg) {
10600            pkg.applicationInfo.primaryCpuAbi = VMRuntime.getRuntime().is64Bit() ?
10601                    Build.SUPPORTED_64_BIT_ABIS[0] : Build.SUPPORTED_32_BIT_ABIS[0];
10602        }
10603
10604        // If there's a mismatch between the abi-override in the package setting
10605        // and the abiOverride specified for the install. Warn about this because we
10606        // would've already compiled the app without taking the package setting into
10607        // account.
10608        if ((scanFlags & SCAN_NO_DEX) == 0 && (scanFlags & SCAN_NEW_INSTALL) != 0) {
10609            if (cpuAbiOverride == null && pkgSetting.cpuAbiOverrideString != null) {
10610                Slog.w(TAG, "Ignoring persisted ABI override " + cpuAbiOverride +
10611                        " for package " + pkg.packageName);
10612            }
10613        }
10614
10615        pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi;
10616        pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi;
10617        pkgSetting.cpuAbiOverrideString = cpuAbiOverride;
10618
10619        // Copy the derived override back to the parsed package, so that we can
10620        // update the package settings accordingly.
10621        pkg.cpuAbiOverride = cpuAbiOverride;
10622
10623        if (DEBUG_ABI_SELECTION) {
10624            Slog.d(TAG, "Resolved nativeLibraryRoot for " + pkg.applicationInfo.packageName
10625                    + " to root=" + pkg.applicationInfo.nativeLibraryRootDir + ", isa="
10626                    + pkg.applicationInfo.nativeLibraryRootRequiresIsa);
10627        }
10628
10629        // Push the derived path down into PackageSettings so we know what to
10630        // clean up at uninstall time.
10631        pkgSetting.legacyNativeLibraryPathString = pkg.applicationInfo.nativeLibraryRootDir;
10632
10633        if (DEBUG_ABI_SELECTION) {
10634            Log.d(TAG, "Abis for package[" + pkg.packageName + "] are" +
10635                    " primary=" + pkg.applicationInfo.primaryCpuAbi +
10636                    " secondary=" + pkg.applicationInfo.secondaryCpuAbi);
10637        }
10638
10639        // SIDE EFFECTS; removes DEX files from disk; move elsewhere
10640        if ((scanFlags & SCAN_BOOTING) == 0 && pkgSetting.sharedUser != null) {
10641            // We don't do this here during boot because we can do it all
10642            // at once after scanning all existing packages.
10643            //
10644            // We also do this *before* we perform dexopt on this package, so that
10645            // we can avoid redundant dexopts, and also to make sure we've got the
10646            // code and package path correct.
10647            adjustCpuAbisForSharedUserLPw(pkgSetting.sharedUser.packages, pkg);
10648        }
10649
10650        if (mFactoryTest && pkg.requestedPermissions.contains(
10651                android.Manifest.permission.FACTORY_TEST)) {
10652            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_FACTORY_TEST;
10653        }
10654
10655        if (isSystemApp(pkg)) {
10656            pkgSetting.isOrphaned = true;
10657        }
10658
10659        // Take care of first install / last update times.
10660        final long scanFileTime = getLastModifiedTime(pkg, scanFile);
10661        if (currentTime != 0) {
10662            if (pkgSetting.firstInstallTime == 0) {
10663                pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = currentTime;
10664            } else if ((scanFlags & SCAN_UPDATE_TIME) != 0) {
10665                pkgSetting.lastUpdateTime = currentTime;
10666            }
10667        } else if (pkgSetting.firstInstallTime == 0) {
10668            // We need *something*.  Take time time stamp of the file.
10669            pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = scanFileTime;
10670        } else if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0) {
10671            if (scanFileTime != pkgSetting.timeStamp) {
10672                // A package on the system image has changed; consider this
10673                // to be an update.
10674                pkgSetting.lastUpdateTime = scanFileTime;
10675            }
10676        }
10677        pkgSetting.setTimeStamp(scanFileTime);
10678
10679        if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
10680            if (nonMutatedPs != null) {
10681                synchronized (mPackages) {
10682                    mSettings.mPackages.put(nonMutatedPs.name, nonMutatedPs);
10683                }
10684            }
10685        } else {
10686            final int userId = user == null ? 0 : user.getIdentifier();
10687            // Modify state for the given package setting
10688            commitPackageSettings(pkg, pkgSetting, user, scanFlags,
10689                    (policyFlags & PackageParser.PARSE_CHATTY) != 0 /*chatty*/);
10690            if (pkgSetting.getInstantApp(userId)) {
10691                mInstantAppRegistry.addInstantAppLPw(userId, pkgSetting.appId);
10692            }
10693        }
10694        return pkg;
10695    }
10696
10697    /**
10698     * Applies policy to the parsed package based upon the given policy flags.
10699     * Ensures the package is in a good state.
10700     * <p>
10701     * Implementation detail: This method must NOT have any side effect. It would
10702     * ideally be static, but, it requires locks to read system state.
10703     */
10704    private void applyPolicy(PackageParser.Package pkg, int policyFlags) {
10705        if ((policyFlags&PackageParser.PARSE_IS_SYSTEM) != 0) {
10706            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_SYSTEM;
10707            if (pkg.applicationInfo.isDirectBootAware()) {
10708                // we're direct boot aware; set for all components
10709                for (PackageParser.Service s : pkg.services) {
10710                    s.info.encryptionAware = s.info.directBootAware = true;
10711                }
10712                for (PackageParser.Provider p : pkg.providers) {
10713                    p.info.encryptionAware = p.info.directBootAware = true;
10714                }
10715                for (PackageParser.Activity a : pkg.activities) {
10716                    a.info.encryptionAware = a.info.directBootAware = true;
10717                }
10718                for (PackageParser.Activity r : pkg.receivers) {
10719                    r.info.encryptionAware = r.info.directBootAware = true;
10720                }
10721            }
10722        } else {
10723            // Only allow system apps to be flagged as core apps.
10724            pkg.coreApp = false;
10725            // clear flags not applicable to regular apps
10726            pkg.applicationInfo.privateFlags &=
10727                    ~ApplicationInfo.PRIVATE_FLAG_DEFAULT_TO_DEVICE_PROTECTED_STORAGE;
10728            pkg.applicationInfo.privateFlags &=
10729                    ~ApplicationInfo.PRIVATE_FLAG_DIRECT_BOOT_AWARE;
10730        }
10731        pkg.mTrustedOverlay = (policyFlags&PackageParser.PARSE_TRUSTED_OVERLAY) != 0;
10732
10733        if ((policyFlags&PackageParser.PARSE_IS_PRIVILEGED) != 0) {
10734            pkg.applicationInfo.privateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
10735        }
10736
10737        if (!isSystemApp(pkg)) {
10738            // Only system apps can use these features.
10739            pkg.mOriginalPackages = null;
10740            pkg.mRealPackage = null;
10741            pkg.mAdoptPermissions = null;
10742        }
10743    }
10744
10745    /**
10746     * Asserts the parsed package is valid according to the given policy. If the
10747     * package is invalid, for whatever reason, throws {@link PackageManagerException}.
10748     * <p>
10749     * Implementation detail: This method must NOT have any side effects. It would
10750     * ideally be static, but, it requires locks to read system state.
10751     *
10752     * @throws PackageManagerException If the package fails any of the validation checks
10753     */
10754    private void assertPackageIsValid(PackageParser.Package pkg, int policyFlags, int scanFlags)
10755            throws PackageManagerException {
10756        if ((policyFlags & PackageParser.PARSE_ENFORCE_CODE) != 0) {
10757            assertCodePolicy(pkg);
10758        }
10759
10760        if (pkg.applicationInfo.getCodePath() == null ||
10761                pkg.applicationInfo.getResourcePath() == null) {
10762            // Bail out. The resource and code paths haven't been set.
10763            throw new PackageManagerException(INSTALL_FAILED_INVALID_APK,
10764                    "Code and resource paths haven't been set correctly");
10765        }
10766
10767        // Make sure we're not adding any bogus keyset info
10768        KeySetManagerService ksms = mSettings.mKeySetManagerService;
10769        ksms.assertScannedPackageValid(pkg);
10770
10771        synchronized (mPackages) {
10772            // The special "android" package can only be defined once
10773            if (pkg.packageName.equals("android")) {
10774                if (mAndroidApplication != null) {
10775                    Slog.w(TAG, "*************************************************");
10776                    Slog.w(TAG, "Core android package being redefined.  Skipping.");
10777                    Slog.w(TAG, " codePath=" + pkg.codePath);
10778                    Slog.w(TAG, "*************************************************");
10779                    throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE,
10780                            "Core android package being redefined.  Skipping.");
10781                }
10782            }
10783
10784            // A package name must be unique; don't allow duplicates
10785            if (mPackages.containsKey(pkg.packageName)) {
10786                throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE,
10787                        "Application package " + pkg.packageName
10788                        + " already installed.  Skipping duplicate.");
10789            }
10790
10791            if (pkg.applicationInfo.isStaticSharedLibrary()) {
10792                // Static libs have a synthetic package name containing the version
10793                // but we still want the base name to be unique.
10794                if (mPackages.containsKey(pkg.manifestPackageName)) {
10795                    throw new PackageManagerException(
10796                            "Duplicate static shared lib provider package");
10797                }
10798
10799                // Static shared libraries should have at least O target SDK
10800                if (pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.O) {
10801                    throw new PackageManagerException(
10802                            "Packages declaring static-shared libs must target O SDK or higher");
10803                }
10804
10805                // Package declaring static a shared lib cannot be instant apps
10806                if ((scanFlags & SCAN_AS_INSTANT_APP) != 0) {
10807                    throw new PackageManagerException(
10808                            "Packages declaring static-shared libs cannot be instant apps");
10809                }
10810
10811                // Package declaring static a shared lib cannot be renamed since the package
10812                // name is synthetic and apps can't code around package manager internals.
10813                if (!ArrayUtils.isEmpty(pkg.mOriginalPackages)) {
10814                    throw new PackageManagerException(
10815                            "Packages declaring static-shared libs cannot be renamed");
10816                }
10817
10818                // Package declaring static a shared lib cannot declare child packages
10819                if (!ArrayUtils.isEmpty(pkg.childPackages)) {
10820                    throw new PackageManagerException(
10821                            "Packages declaring static-shared libs cannot have child packages");
10822                }
10823
10824                // Package declaring static a shared lib cannot declare dynamic libs
10825                if (!ArrayUtils.isEmpty(pkg.libraryNames)) {
10826                    throw new PackageManagerException(
10827                            "Packages declaring static-shared libs cannot declare dynamic libs");
10828                }
10829
10830                // Package declaring static a shared lib cannot declare shared users
10831                if (pkg.mSharedUserId != null) {
10832                    throw new PackageManagerException(
10833                            "Packages declaring static-shared libs cannot declare shared users");
10834                }
10835
10836                // Static shared libs cannot declare activities
10837                if (!pkg.activities.isEmpty()) {
10838                    throw new PackageManagerException(
10839                            "Static shared libs cannot declare activities");
10840                }
10841
10842                // Static shared libs cannot declare services
10843                if (!pkg.services.isEmpty()) {
10844                    throw new PackageManagerException(
10845                            "Static shared libs cannot declare services");
10846                }
10847
10848                // Static shared libs cannot declare providers
10849                if (!pkg.providers.isEmpty()) {
10850                    throw new PackageManagerException(
10851                            "Static shared libs cannot declare content providers");
10852                }
10853
10854                // Static shared libs cannot declare receivers
10855                if (!pkg.receivers.isEmpty()) {
10856                    throw new PackageManagerException(
10857                            "Static shared libs cannot declare broadcast receivers");
10858                }
10859
10860                // Static shared libs cannot declare permission groups
10861                if (!pkg.permissionGroups.isEmpty()) {
10862                    throw new PackageManagerException(
10863                            "Static shared libs cannot declare permission groups");
10864                }
10865
10866                // Static shared libs cannot declare permissions
10867                if (!pkg.permissions.isEmpty()) {
10868                    throw new PackageManagerException(
10869                            "Static shared libs cannot declare permissions");
10870                }
10871
10872                // Static shared libs cannot declare protected broadcasts
10873                if (pkg.protectedBroadcasts != null) {
10874                    throw new PackageManagerException(
10875                            "Static shared libs cannot declare protected broadcasts");
10876                }
10877
10878                // Static shared libs cannot be overlay targets
10879                if (pkg.mOverlayTarget != null) {
10880                    throw new PackageManagerException(
10881                            "Static shared libs cannot be overlay targets");
10882                }
10883
10884                // The version codes must be ordered as lib versions
10885                int minVersionCode = Integer.MIN_VALUE;
10886                int maxVersionCode = Integer.MAX_VALUE;
10887
10888                SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(
10889                        pkg.staticSharedLibName);
10890                if (versionedLib != null) {
10891                    final int versionCount = versionedLib.size();
10892                    for (int i = 0; i < versionCount; i++) {
10893                        SharedLibraryInfo libInfo = versionedLib.valueAt(i).info;
10894                        final int libVersionCode = libInfo.getDeclaringPackage()
10895                                .getVersionCode();
10896                        if (libInfo.getVersion() <  pkg.staticSharedLibVersion) {
10897                            minVersionCode = Math.max(minVersionCode, libVersionCode + 1);
10898                        } else if (libInfo.getVersion() >  pkg.staticSharedLibVersion) {
10899                            maxVersionCode = Math.min(maxVersionCode, libVersionCode - 1);
10900                        } else {
10901                            minVersionCode = maxVersionCode = libVersionCode;
10902                            break;
10903                        }
10904                    }
10905                }
10906                if (pkg.mVersionCode < minVersionCode || pkg.mVersionCode > maxVersionCode) {
10907                    throw new PackageManagerException("Static shared"
10908                            + " lib version codes must be ordered as lib versions");
10909                }
10910            }
10911
10912            // Only privileged apps and updated privileged apps can add child packages.
10913            if (pkg.childPackages != null && !pkg.childPackages.isEmpty()) {
10914                if ((policyFlags & PARSE_IS_PRIVILEGED) == 0) {
10915                    throw new PackageManagerException("Only privileged apps can add child "
10916                            + "packages. Ignoring package " + pkg.packageName);
10917                }
10918                final int childCount = pkg.childPackages.size();
10919                for (int i = 0; i < childCount; i++) {
10920                    PackageParser.Package childPkg = pkg.childPackages.get(i);
10921                    if (mSettings.hasOtherDisabledSystemPkgWithChildLPr(pkg.packageName,
10922                            childPkg.packageName)) {
10923                        throw new PackageManagerException("Can't override child of "
10924                                + "another disabled app. Ignoring package " + pkg.packageName);
10925                    }
10926                }
10927            }
10928
10929            // If we're only installing presumed-existing packages, require that the
10930            // scanned APK is both already known and at the path previously established
10931            // for it.  Previously unknown packages we pick up normally, but if we have an
10932            // a priori expectation about this package's install presence, enforce it.
10933            // With a singular exception for new system packages. When an OTA contains
10934            // a new system package, we allow the codepath to change from a system location
10935            // to the user-installed location. If we don't allow this change, any newer,
10936            // user-installed version of the application will be ignored.
10937            if ((scanFlags & SCAN_REQUIRE_KNOWN) != 0) {
10938                if (mExpectingBetter.containsKey(pkg.packageName)) {
10939                    logCriticalInfo(Log.WARN,
10940                            "Relax SCAN_REQUIRE_KNOWN requirement for package " + pkg.packageName);
10941                } else {
10942                    PackageSetting known = mSettings.getPackageLPr(pkg.packageName);
10943                    if (known != null) {
10944                        if (DEBUG_PACKAGE_SCANNING) {
10945                            Log.d(TAG, "Examining " + pkg.codePath
10946                                    + " and requiring known paths " + known.codePathString
10947                                    + " & " + known.resourcePathString);
10948                        }
10949                        if (!pkg.applicationInfo.getCodePath().equals(known.codePathString)
10950                                || !pkg.applicationInfo.getResourcePath().equals(
10951                                        known.resourcePathString)) {
10952                            throw new PackageManagerException(INSTALL_FAILED_PACKAGE_CHANGED,
10953                                    "Application package " + pkg.packageName
10954                                    + " found at " + pkg.applicationInfo.getCodePath()
10955                                    + " but expected at " + known.codePathString
10956                                    + "; ignoring.");
10957                        }
10958                    }
10959                }
10960            }
10961
10962            // Verify that this new package doesn't have any content providers
10963            // that conflict with existing packages.  Only do this if the
10964            // package isn't already installed, since we don't want to break
10965            // things that are installed.
10966            if ((scanFlags & SCAN_NEW_INSTALL) != 0) {
10967                final int N = pkg.providers.size();
10968                int i;
10969                for (i=0; i<N; i++) {
10970                    PackageParser.Provider p = pkg.providers.get(i);
10971                    if (p.info.authority != null) {
10972                        String names[] = p.info.authority.split(";");
10973                        for (int j = 0; j < names.length; j++) {
10974                            if (mProvidersByAuthority.containsKey(names[j])) {
10975                                PackageParser.Provider other = mProvidersByAuthority.get(names[j]);
10976                                final String otherPackageName =
10977                                        ((other != null && other.getComponentName() != null) ?
10978                                                other.getComponentName().getPackageName() : "?");
10979                                throw new PackageManagerException(
10980                                        INSTALL_FAILED_CONFLICTING_PROVIDER,
10981                                        "Can't install because provider name " + names[j]
10982                                                + " (in package " + pkg.applicationInfo.packageName
10983                                                + ") is already used by " + otherPackageName);
10984                            }
10985                        }
10986                    }
10987                }
10988            }
10989        }
10990    }
10991
10992    private boolean addSharedLibraryLPw(String path, String apk, String name, int version,
10993            int type, String declaringPackageName, int declaringVersionCode) {
10994        SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(name);
10995        if (versionedLib == null) {
10996            versionedLib = new SparseArray<>();
10997            mSharedLibraries.put(name, versionedLib);
10998            if (type == SharedLibraryInfo.TYPE_STATIC) {
10999                mStaticLibsByDeclaringPackage.put(declaringPackageName, versionedLib);
11000            }
11001        } else if (versionedLib.indexOfKey(version) >= 0) {
11002            return false;
11003        }
11004        SharedLibraryEntry libEntry = new SharedLibraryEntry(path, apk, name,
11005                version, type, declaringPackageName, declaringVersionCode);
11006        versionedLib.put(version, libEntry);
11007        return true;
11008    }
11009
11010    private boolean removeSharedLibraryLPw(String name, int version) {
11011        SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(name);
11012        if (versionedLib == null) {
11013            return false;
11014        }
11015        final int libIdx = versionedLib.indexOfKey(version);
11016        if (libIdx < 0) {
11017            return false;
11018        }
11019        SharedLibraryEntry libEntry = versionedLib.valueAt(libIdx);
11020        versionedLib.remove(version);
11021        if (versionedLib.size() <= 0) {
11022            mSharedLibraries.remove(name);
11023            if (libEntry.info.getType() == SharedLibraryInfo.TYPE_STATIC) {
11024                mStaticLibsByDeclaringPackage.remove(libEntry.info.getDeclaringPackage()
11025                        .getPackageName());
11026            }
11027        }
11028        return true;
11029    }
11030
11031    /**
11032     * Adds a scanned package to the system. When this method is finished, the package will
11033     * be available for query, resolution, etc...
11034     */
11035    private void commitPackageSettings(PackageParser.Package pkg, PackageSetting pkgSetting,
11036            UserHandle user, int scanFlags, boolean chatty) throws PackageManagerException {
11037        final String pkgName = pkg.packageName;
11038        if (mCustomResolverComponentName != null &&
11039                mCustomResolverComponentName.getPackageName().equals(pkg.packageName)) {
11040            setUpCustomResolverActivity(pkg);
11041        }
11042
11043        if (pkg.packageName.equals("android")) {
11044            synchronized (mPackages) {
11045                if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
11046                    // Set up information for our fall-back user intent resolution activity.
11047                    mPlatformPackage = pkg;
11048                    pkg.mVersionCode = mSdkVersion;
11049                    mAndroidApplication = pkg.applicationInfo;
11050                    if (!mResolverReplaced) {
11051                        mResolveActivity.applicationInfo = mAndroidApplication;
11052                        mResolveActivity.name = ResolverActivity.class.getName();
11053                        mResolveActivity.packageName = mAndroidApplication.packageName;
11054                        mResolveActivity.processName = "system:ui";
11055                        mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
11056                        mResolveActivity.documentLaunchMode = ActivityInfo.DOCUMENT_LAUNCH_NEVER;
11057                        mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS;
11058                        mResolveActivity.theme = R.style.Theme_Material_Dialog_Alert;
11059                        mResolveActivity.exported = true;
11060                        mResolveActivity.enabled = true;
11061                        mResolveActivity.resizeMode = ActivityInfo.RESIZE_MODE_RESIZEABLE;
11062                        mResolveActivity.configChanges = ActivityInfo.CONFIG_SCREEN_SIZE
11063                                | ActivityInfo.CONFIG_SMALLEST_SCREEN_SIZE
11064                                | ActivityInfo.CONFIG_SCREEN_LAYOUT
11065                                | ActivityInfo.CONFIG_ORIENTATION
11066                                | ActivityInfo.CONFIG_KEYBOARD
11067                                | ActivityInfo.CONFIG_KEYBOARD_HIDDEN;
11068                        mResolveInfo.activityInfo = mResolveActivity;
11069                        mResolveInfo.priority = 0;
11070                        mResolveInfo.preferredOrder = 0;
11071                        mResolveInfo.match = 0;
11072                        mResolveComponentName = new ComponentName(
11073                                mAndroidApplication.packageName, mResolveActivity.name);
11074                    }
11075                }
11076            }
11077        }
11078
11079        ArrayList<PackageParser.Package> clientLibPkgs = null;
11080        // writer
11081        synchronized (mPackages) {
11082            boolean hasStaticSharedLibs = false;
11083
11084            // Any app can add new static shared libraries
11085            if (pkg.staticSharedLibName != null) {
11086                // Static shared libs don't allow renaming as they have synthetic package
11087                // names to allow install of multiple versions, so use name from manifest.
11088                if (addSharedLibraryLPw(null, pkg.packageName, pkg.staticSharedLibName,
11089                        pkg.staticSharedLibVersion, SharedLibraryInfo.TYPE_STATIC,
11090                        pkg.manifestPackageName, pkg.mVersionCode)) {
11091                    hasStaticSharedLibs = true;
11092                } else {
11093                    Slog.w(TAG, "Package " + pkg.packageName + " library "
11094                                + pkg.staticSharedLibName + " already exists; skipping");
11095                }
11096                // Static shared libs cannot be updated once installed since they
11097                // use synthetic package name which includes the version code, so
11098                // not need to update other packages's shared lib dependencies.
11099            }
11100
11101            if (!hasStaticSharedLibs
11102                    && (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
11103                // Only system apps can add new dynamic shared libraries.
11104                if (pkg.libraryNames != null) {
11105                    for (int i = 0; i < pkg.libraryNames.size(); i++) {
11106                        String name = pkg.libraryNames.get(i);
11107                        boolean allowed = false;
11108                        if (pkg.isUpdatedSystemApp()) {
11109                            // New library entries can only be added through the
11110                            // system image.  This is important to get rid of a lot
11111                            // of nasty edge cases: for example if we allowed a non-
11112                            // system update of the app to add a library, then uninstalling
11113                            // the update would make the library go away, and assumptions
11114                            // we made such as through app install filtering would now
11115                            // have allowed apps on the device which aren't compatible
11116                            // with it.  Better to just have the restriction here, be
11117                            // conservative, and create many fewer cases that can negatively
11118                            // impact the user experience.
11119                            final PackageSetting sysPs = mSettings
11120                                    .getDisabledSystemPkgLPr(pkg.packageName);
11121                            if (sysPs.pkg != null && sysPs.pkg.libraryNames != null) {
11122                                for (int j = 0; j < sysPs.pkg.libraryNames.size(); j++) {
11123                                    if (name.equals(sysPs.pkg.libraryNames.get(j))) {
11124                                        allowed = true;
11125                                        break;
11126                                    }
11127                                }
11128                            }
11129                        } else {
11130                            allowed = true;
11131                        }
11132                        if (allowed) {
11133                            if (!addSharedLibraryLPw(null, pkg.packageName, name,
11134                                    SharedLibraryInfo.VERSION_UNDEFINED,
11135                                    SharedLibraryInfo.TYPE_DYNAMIC,
11136                                    pkg.packageName, pkg.mVersionCode)) {
11137                                Slog.w(TAG, "Package " + pkg.packageName + " library "
11138                                        + name + " already exists; skipping");
11139                            }
11140                        } else {
11141                            Slog.w(TAG, "Package " + pkg.packageName + " declares lib "
11142                                    + name + " that is not declared on system image; skipping");
11143                        }
11144                    }
11145
11146                    if ((scanFlags & SCAN_BOOTING) == 0) {
11147                        // If we are not booting, we need to update any applications
11148                        // that are clients of our shared library.  If we are booting,
11149                        // this will all be done once the scan is complete.
11150                        clientLibPkgs = updateAllSharedLibrariesLPw(pkg);
11151                    }
11152                }
11153            }
11154        }
11155
11156        if ((scanFlags & SCAN_BOOTING) != 0) {
11157            // No apps can run during boot scan, so they don't need to be frozen
11158        } else if ((scanFlags & SCAN_DONT_KILL_APP) != 0) {
11159            // Caller asked to not kill app, so it's probably not frozen
11160        } else if ((scanFlags & SCAN_IGNORE_FROZEN) != 0) {
11161            // Caller asked us to ignore frozen check for some reason; they
11162            // probably didn't know the package name
11163        } else {
11164            // We're doing major surgery on this package, so it better be frozen
11165            // right now to keep it from launching
11166            checkPackageFrozen(pkgName);
11167        }
11168
11169        // Also need to kill any apps that are dependent on the library.
11170        if (clientLibPkgs != null) {
11171            for (int i=0; i<clientLibPkgs.size(); i++) {
11172                PackageParser.Package clientPkg = clientLibPkgs.get(i);
11173                killApplication(clientPkg.applicationInfo.packageName,
11174                        clientPkg.applicationInfo.uid, "update lib");
11175            }
11176        }
11177
11178        // writer
11179        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings");
11180
11181        synchronized (mPackages) {
11182            // We don't expect installation to fail beyond this point
11183
11184            // Add the new setting to mSettings
11185            mSettings.insertPackageSettingLPw(pkgSetting, pkg);
11186            // Add the new setting to mPackages
11187            mPackages.put(pkg.applicationInfo.packageName, pkg);
11188            // Make sure we don't accidentally delete its data.
11189            final Iterator<PackageCleanItem> iter = mSettings.mPackagesToBeCleaned.iterator();
11190            while (iter.hasNext()) {
11191                PackageCleanItem item = iter.next();
11192                if (pkgName.equals(item.packageName)) {
11193                    iter.remove();
11194                }
11195            }
11196
11197            // Add the package's KeySets to the global KeySetManagerService
11198            KeySetManagerService ksms = mSettings.mKeySetManagerService;
11199            ksms.addScannedPackageLPw(pkg);
11200
11201            int N = pkg.providers.size();
11202            StringBuilder r = null;
11203            int i;
11204            for (i=0; i<N; i++) {
11205                PackageParser.Provider p = pkg.providers.get(i);
11206                p.info.processName = fixProcessName(pkg.applicationInfo.processName,
11207                        p.info.processName);
11208                mProviders.addProvider(p);
11209                p.syncable = p.info.isSyncable;
11210                if (p.info.authority != null) {
11211                    String names[] = p.info.authority.split(";");
11212                    p.info.authority = null;
11213                    for (int j = 0; j < names.length; j++) {
11214                        if (j == 1 && p.syncable) {
11215                            // We only want the first authority for a provider to possibly be
11216                            // syncable, so if we already added this provider using a different
11217                            // authority clear the syncable flag. We copy the provider before
11218                            // changing it because the mProviders object contains a reference
11219                            // to a provider that we don't want to change.
11220                            // Only do this for the second authority since the resulting provider
11221                            // object can be the same for all future authorities for this provider.
11222                            p = new PackageParser.Provider(p);
11223                            p.syncable = false;
11224                        }
11225                        if (!mProvidersByAuthority.containsKey(names[j])) {
11226                            mProvidersByAuthority.put(names[j], p);
11227                            if (p.info.authority == null) {
11228                                p.info.authority = names[j];
11229                            } else {
11230                                p.info.authority = p.info.authority + ";" + names[j];
11231                            }
11232                            if (DEBUG_PACKAGE_SCANNING) {
11233                                if (chatty)
11234                                    Log.d(TAG, "Registered content provider: " + names[j]
11235                                            + ", className = " + p.info.name + ", isSyncable = "
11236                                            + p.info.isSyncable);
11237                            }
11238                        } else {
11239                            PackageParser.Provider other = mProvidersByAuthority.get(names[j]);
11240                            Slog.w(TAG, "Skipping provider name " + names[j] +
11241                                    " (in package " + pkg.applicationInfo.packageName +
11242                                    "): name already used by "
11243                                    + ((other != null && other.getComponentName() != null)
11244                                            ? other.getComponentName().getPackageName() : "?"));
11245                        }
11246                    }
11247                }
11248                if (chatty) {
11249                    if (r == null) {
11250                        r = new StringBuilder(256);
11251                    } else {
11252                        r.append(' ');
11253                    }
11254                    r.append(p.info.name);
11255                }
11256            }
11257            if (r != null) {
11258                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Providers: " + r);
11259            }
11260
11261            N = pkg.services.size();
11262            r = null;
11263            for (i=0; i<N; i++) {
11264                PackageParser.Service s = pkg.services.get(i);
11265                s.info.processName = fixProcessName(pkg.applicationInfo.processName,
11266                        s.info.processName);
11267                mServices.addService(s);
11268                if (chatty) {
11269                    if (r == null) {
11270                        r = new StringBuilder(256);
11271                    } else {
11272                        r.append(' ');
11273                    }
11274                    r.append(s.info.name);
11275                }
11276            }
11277            if (r != null) {
11278                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Services: " + r);
11279            }
11280
11281            N = pkg.receivers.size();
11282            r = null;
11283            for (i=0; i<N; i++) {
11284                PackageParser.Activity a = pkg.receivers.get(i);
11285                a.info.processName = fixProcessName(pkg.applicationInfo.processName,
11286                        a.info.processName);
11287                mReceivers.addActivity(a, "receiver");
11288                if (chatty) {
11289                    if (r == null) {
11290                        r = new StringBuilder(256);
11291                    } else {
11292                        r.append(' ');
11293                    }
11294                    r.append(a.info.name);
11295                }
11296            }
11297            if (r != null) {
11298                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Receivers: " + r);
11299            }
11300
11301            N = pkg.activities.size();
11302            r = null;
11303            for (i=0; i<N; i++) {
11304                PackageParser.Activity a = pkg.activities.get(i);
11305                a.info.processName = fixProcessName(pkg.applicationInfo.processName,
11306                        a.info.processName);
11307                mActivities.addActivity(a, "activity");
11308                if (chatty) {
11309                    if (r == null) {
11310                        r = new StringBuilder(256);
11311                    } else {
11312                        r.append(' ');
11313                    }
11314                    r.append(a.info.name);
11315                }
11316            }
11317            if (r != null) {
11318                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Activities: " + r);
11319            }
11320
11321            N = pkg.permissionGroups.size();
11322            r = null;
11323            for (i=0; i<N; i++) {
11324                PackageParser.PermissionGroup pg = pkg.permissionGroups.get(i);
11325                PackageParser.PermissionGroup cur = mPermissionGroups.get(pg.info.name);
11326                final String curPackageName = cur == null ? null : cur.info.packageName;
11327                // Dont allow ephemeral apps to define new permission groups.
11328                if ((scanFlags & SCAN_AS_INSTANT_APP) != 0) {
11329                    Slog.w(TAG, "Permission group " + pg.info.name + " from package "
11330                            + pg.info.packageName
11331                            + " ignored: instant apps cannot define new permission groups.");
11332                    continue;
11333                }
11334                final boolean isPackageUpdate = pg.info.packageName.equals(curPackageName);
11335                if (cur == null || isPackageUpdate) {
11336                    mPermissionGroups.put(pg.info.name, pg);
11337                    if (chatty) {
11338                        if (r == null) {
11339                            r = new StringBuilder(256);
11340                        } else {
11341                            r.append(' ');
11342                        }
11343                        if (isPackageUpdate) {
11344                            r.append("UPD:");
11345                        }
11346                        r.append(pg.info.name);
11347                    }
11348                } else {
11349                    Slog.w(TAG, "Permission group " + pg.info.name + " from package "
11350                            + pg.info.packageName + " ignored: original from "
11351                            + cur.info.packageName);
11352                    if (chatty) {
11353                        if (r == null) {
11354                            r = new StringBuilder(256);
11355                        } else {
11356                            r.append(' ');
11357                        }
11358                        r.append("DUP:");
11359                        r.append(pg.info.name);
11360                    }
11361                }
11362            }
11363            if (r != null) {
11364                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Permission Groups: " + r);
11365            }
11366
11367            N = pkg.permissions.size();
11368            r = null;
11369            for (i=0; i<N; i++) {
11370                PackageParser.Permission p = pkg.permissions.get(i);
11371
11372                // Dont allow ephemeral apps to define new permissions.
11373                if ((scanFlags & SCAN_AS_INSTANT_APP) != 0) {
11374                    Slog.w(TAG, "Permission " + p.info.name + " from package "
11375                            + p.info.packageName
11376                            + " ignored: instant apps cannot define new permissions.");
11377                    continue;
11378                }
11379
11380                // Assume by default that we did not install this permission into the system.
11381                p.info.flags &= ~PermissionInfo.FLAG_INSTALLED;
11382
11383                // Now that permission groups have a special meaning, we ignore permission
11384                // groups for legacy apps to prevent unexpected behavior. In particular,
11385                // permissions for one app being granted to someone just because they happen
11386                // to be in a group defined by another app (before this had no implications).
11387                if (pkg.applicationInfo.targetSdkVersion > Build.VERSION_CODES.LOLLIPOP_MR1) {
11388                    p.group = mPermissionGroups.get(p.info.group);
11389                    // Warn for a permission in an unknown group.
11390                    if (DEBUG_PERMISSIONS && p.info.group != null && p.group == null) {
11391                        Slog.i(TAG, "Permission " + p.info.name + " from package "
11392                                + p.info.packageName + " in an unknown group " + p.info.group);
11393                    }
11394                }
11395
11396                ArrayMap<String, BasePermission> permissionMap =
11397                        p.tree ? mSettings.mPermissionTrees
11398                                : mSettings.mPermissions;
11399                BasePermission bp = permissionMap.get(p.info.name);
11400
11401                // Allow system apps to redefine non-system permissions
11402                if (bp != null && !Objects.equals(bp.sourcePackage, p.info.packageName)) {
11403                    final boolean currentOwnerIsSystem = (bp.perm != null
11404                            && isSystemApp(bp.perm.owner));
11405                    if (isSystemApp(p.owner)) {
11406                        if (bp.type == BasePermission.TYPE_BUILTIN && bp.perm == null) {
11407                            // It's a built-in permission and no owner, take ownership now
11408                            bp.packageSetting = pkgSetting;
11409                            bp.perm = p;
11410                            bp.uid = pkg.applicationInfo.uid;
11411                            bp.sourcePackage = p.info.packageName;
11412                            p.info.flags |= PermissionInfo.FLAG_INSTALLED;
11413                        } else if (!currentOwnerIsSystem) {
11414                            String msg = "New decl " + p.owner + " of permission  "
11415                                    + p.info.name + " is system; overriding " + bp.sourcePackage;
11416                            reportSettingsProblem(Log.WARN, msg);
11417                            bp = null;
11418                        }
11419                    }
11420                }
11421
11422                if (bp == null) {
11423                    bp = new BasePermission(p.info.name, p.info.packageName,
11424                            BasePermission.TYPE_NORMAL);
11425                    permissionMap.put(p.info.name, bp);
11426                }
11427
11428                if (bp.perm == null) {
11429                    if (bp.sourcePackage == null
11430                            || bp.sourcePackage.equals(p.info.packageName)) {
11431                        BasePermission tree = findPermissionTreeLP(p.info.name);
11432                        if (tree == null
11433                                || tree.sourcePackage.equals(p.info.packageName)) {
11434                            bp.packageSetting = pkgSetting;
11435                            bp.perm = p;
11436                            bp.uid = pkg.applicationInfo.uid;
11437                            bp.sourcePackage = p.info.packageName;
11438                            p.info.flags |= PermissionInfo.FLAG_INSTALLED;
11439                            if (chatty) {
11440                                if (r == null) {
11441                                    r = new StringBuilder(256);
11442                                } else {
11443                                    r.append(' ');
11444                                }
11445                                r.append(p.info.name);
11446                            }
11447                        } else {
11448                            Slog.w(TAG, "Permission " + p.info.name + " from package "
11449                                    + p.info.packageName + " ignored: base tree "
11450                                    + tree.name + " is from package "
11451                                    + tree.sourcePackage);
11452                        }
11453                    } else {
11454                        Slog.w(TAG, "Permission " + p.info.name + " from package "
11455                                + p.info.packageName + " ignored: original from "
11456                                + bp.sourcePackage);
11457                    }
11458                } else if (chatty) {
11459                    if (r == null) {
11460                        r = new StringBuilder(256);
11461                    } else {
11462                        r.append(' ');
11463                    }
11464                    r.append("DUP:");
11465                    r.append(p.info.name);
11466                }
11467                if (bp.perm == p) {
11468                    bp.protectionLevel = p.info.protectionLevel;
11469                }
11470            }
11471
11472            if (r != null) {
11473                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Permissions: " + r);
11474            }
11475
11476            N = pkg.instrumentation.size();
11477            r = null;
11478            for (i=0; i<N; i++) {
11479                PackageParser.Instrumentation a = pkg.instrumentation.get(i);
11480                a.info.packageName = pkg.applicationInfo.packageName;
11481                a.info.sourceDir = pkg.applicationInfo.sourceDir;
11482                a.info.publicSourceDir = pkg.applicationInfo.publicSourceDir;
11483                a.info.splitNames = pkg.splitNames;
11484                a.info.splitSourceDirs = pkg.applicationInfo.splitSourceDirs;
11485                a.info.splitPublicSourceDirs = pkg.applicationInfo.splitPublicSourceDirs;
11486                a.info.splitDependencies = pkg.applicationInfo.splitDependencies;
11487                a.info.dataDir = pkg.applicationInfo.dataDir;
11488                a.info.deviceProtectedDataDir = pkg.applicationInfo.deviceProtectedDataDir;
11489                a.info.credentialProtectedDataDir = pkg.applicationInfo.credentialProtectedDataDir;
11490                a.info.nativeLibraryDir = pkg.applicationInfo.nativeLibraryDir;
11491                a.info.secondaryNativeLibraryDir = pkg.applicationInfo.secondaryNativeLibraryDir;
11492                mInstrumentation.put(a.getComponentName(), a);
11493                if (chatty) {
11494                    if (r == null) {
11495                        r = new StringBuilder(256);
11496                    } else {
11497                        r.append(' ');
11498                    }
11499                    r.append(a.info.name);
11500                }
11501            }
11502            if (r != null) {
11503                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Instrumentation: " + r);
11504            }
11505
11506            if (pkg.protectedBroadcasts != null) {
11507                N = pkg.protectedBroadcasts.size();
11508                for (i=0; i<N; i++) {
11509                    mProtectedBroadcasts.add(pkg.protectedBroadcasts.get(i));
11510                }
11511            }
11512        }
11513
11514        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
11515    }
11516
11517    /**
11518     * Derive the ABI of a non-system package located at {@code scanFile}. This information
11519     * is derived purely on the basis of the contents of {@code scanFile} and
11520     * {@code cpuAbiOverride}.
11521     *
11522     * If {@code extractLibs} is true, native libraries are extracted from the app if required.
11523     */
11524    private static void derivePackageAbi(PackageParser.Package pkg, File scanFile,
11525                                 String cpuAbiOverride, boolean extractLibs,
11526                                 File appLib32InstallDir)
11527            throws PackageManagerException {
11528        // Give ourselves some initial paths; we'll come back for another
11529        // pass once we've determined ABI below.
11530        setNativeLibraryPaths(pkg, appLib32InstallDir);
11531
11532        // We would never need to extract libs for forward-locked and external packages,
11533        // since the container service will do it for us. We shouldn't attempt to
11534        // extract libs from system app when it was not updated.
11535        if (pkg.isForwardLocked() || pkg.applicationInfo.isExternalAsec() ||
11536                (isSystemApp(pkg) && !pkg.isUpdatedSystemApp())) {
11537            extractLibs = false;
11538        }
11539
11540        final String nativeLibraryRootStr = pkg.applicationInfo.nativeLibraryRootDir;
11541        final boolean useIsaSpecificSubdirs = pkg.applicationInfo.nativeLibraryRootRequiresIsa;
11542
11543        NativeLibraryHelper.Handle handle = null;
11544        try {
11545            handle = NativeLibraryHelper.Handle.create(pkg);
11546            // TODO(multiArch): This can be null for apps that didn't go through the
11547            // usual installation process. We can calculate it again, like we
11548            // do during install time.
11549            //
11550            // TODO(multiArch): Why do we need to rescan ASEC apps again ? It seems totally
11551            // unnecessary.
11552            final File nativeLibraryRoot = new File(nativeLibraryRootStr);
11553
11554            // Null out the abis so that they can be recalculated.
11555            pkg.applicationInfo.primaryCpuAbi = null;
11556            pkg.applicationInfo.secondaryCpuAbi = null;
11557            if (isMultiArch(pkg.applicationInfo)) {
11558                // Warn if we've set an abiOverride for multi-lib packages..
11559                // By definition, we need to copy both 32 and 64 bit libraries for
11560                // such packages.
11561                if (pkg.cpuAbiOverride != null
11562                        && !NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(pkg.cpuAbiOverride)) {
11563                    Slog.w(TAG, "Ignoring abiOverride for multi arch application.");
11564                }
11565
11566                int abi32 = PackageManager.NO_NATIVE_LIBRARIES;
11567                int abi64 = PackageManager.NO_NATIVE_LIBRARIES;
11568                if (Build.SUPPORTED_32_BIT_ABIS.length > 0) {
11569                    if (extractLibs) {
11570                        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyNativeBinaries");
11571                        abi32 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
11572                                nativeLibraryRoot, Build.SUPPORTED_32_BIT_ABIS,
11573                                useIsaSpecificSubdirs);
11574                    } else {
11575                        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "findSupportedAbi");
11576                        abi32 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_32_BIT_ABIS);
11577                    }
11578                    Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
11579                }
11580
11581                // Shared library native code should be in the APK zip aligned
11582                if (abi32 >= 0 && pkg.isLibrary() && extractLibs) {
11583                    throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR,
11584                            "Shared library native lib extraction not supported");
11585                }
11586
11587                maybeThrowExceptionForMultiArchCopy(
11588                        "Error unpackaging 32 bit native libs for multiarch app.", abi32);
11589
11590                if (Build.SUPPORTED_64_BIT_ABIS.length > 0) {
11591                    if (extractLibs) {
11592                        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyNativeBinaries");
11593                        abi64 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
11594                                nativeLibraryRoot, Build.SUPPORTED_64_BIT_ABIS,
11595                                useIsaSpecificSubdirs);
11596                    } else {
11597                        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "findSupportedAbi");
11598                        abi64 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_64_BIT_ABIS);
11599                    }
11600                    Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
11601                }
11602
11603                maybeThrowExceptionForMultiArchCopy(
11604                        "Error unpackaging 64 bit native libs for multiarch app.", abi64);
11605
11606                if (abi64 >= 0) {
11607                    // Shared library native libs should be in the APK zip aligned
11608                    if (extractLibs && pkg.isLibrary()) {
11609                        throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR,
11610                                "Shared library native lib extraction not supported");
11611                    }
11612                    pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[abi64];
11613                }
11614
11615                if (abi32 >= 0) {
11616                    final String abi = Build.SUPPORTED_32_BIT_ABIS[abi32];
11617                    if (abi64 >= 0) {
11618                        if (pkg.use32bitAbi) {
11619                            pkg.applicationInfo.secondaryCpuAbi = pkg.applicationInfo.primaryCpuAbi;
11620                            pkg.applicationInfo.primaryCpuAbi = abi;
11621                        } else {
11622                            pkg.applicationInfo.secondaryCpuAbi = abi;
11623                        }
11624                    } else {
11625                        pkg.applicationInfo.primaryCpuAbi = abi;
11626                    }
11627                }
11628            } else {
11629                String[] abiList = (cpuAbiOverride != null) ?
11630                        new String[] { cpuAbiOverride } : Build.SUPPORTED_ABIS;
11631
11632                // Enable gross and lame hacks for apps that are built with old
11633                // SDK tools. We must scan their APKs for renderscript bitcode and
11634                // not launch them if it's present. Don't bother checking on devices
11635                // that don't have 64 bit support.
11636                boolean needsRenderScriptOverride = false;
11637                if (Build.SUPPORTED_64_BIT_ABIS.length > 0 && cpuAbiOverride == null &&
11638                        NativeLibraryHelper.hasRenderscriptBitcode(handle)) {
11639                    abiList = Build.SUPPORTED_32_BIT_ABIS;
11640                    needsRenderScriptOverride = true;
11641                }
11642
11643                final int copyRet;
11644                if (extractLibs) {
11645                    Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyNativeBinaries");
11646                    copyRet = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
11647                            nativeLibraryRoot, abiList, useIsaSpecificSubdirs);
11648                } else {
11649                    Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "findSupportedAbi");
11650                    copyRet = NativeLibraryHelper.findSupportedAbi(handle, abiList);
11651                }
11652                Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
11653
11654                if (copyRet < 0 && copyRet != PackageManager.NO_NATIVE_LIBRARIES) {
11655                    throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR,
11656                            "Error unpackaging native libs for app, errorCode=" + copyRet);
11657                }
11658
11659                if (copyRet >= 0) {
11660                    // Shared libraries that have native libs must be multi-architecture
11661                    if (pkg.isLibrary()) {
11662                        throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR,
11663                                "Shared library with native libs must be multiarch");
11664                    }
11665                    pkg.applicationInfo.primaryCpuAbi = abiList[copyRet];
11666                } else if (copyRet == PackageManager.NO_NATIVE_LIBRARIES && cpuAbiOverride != null) {
11667                    pkg.applicationInfo.primaryCpuAbi = cpuAbiOverride;
11668                } else if (needsRenderScriptOverride) {
11669                    pkg.applicationInfo.primaryCpuAbi = abiList[0];
11670                }
11671            }
11672        } catch (IOException ioe) {
11673            Slog.e(TAG, "Unable to get canonical file " + ioe.toString());
11674        } finally {
11675            IoUtils.closeQuietly(handle);
11676        }
11677
11678        // Now that we've calculated the ABIs and determined if it's an internal app,
11679        // we will go ahead and populate the nativeLibraryPath.
11680        setNativeLibraryPaths(pkg, appLib32InstallDir);
11681    }
11682
11683    /**
11684     * Adjusts ABIs for a set of packages belonging to a shared user so that they all match.
11685     * i.e, so that all packages can be run inside a single process if required.
11686     *
11687     * Optionally, callers can pass in a parsed package via {@code newPackage} in which case
11688     * this function will either try and make the ABI for all packages in {@code packagesForUser}
11689     * match {@code scannedPackage} or will update the ABI of {@code scannedPackage} to match
11690     * the ABI selected for {@code packagesForUser}. This variant is used when installing or
11691     * updating a package that belongs to a shared user.
11692     *
11693     * NOTE: We currently only match for the primary CPU abi string. Matching the secondary
11694     * adds unnecessary complexity.
11695     */
11696    private void adjustCpuAbisForSharedUserLPw(Set<PackageSetting> packagesForUser,
11697            PackageParser.Package scannedPackage) {
11698        String requiredInstructionSet = null;
11699        if (scannedPackage != null && scannedPackage.applicationInfo.primaryCpuAbi != null) {
11700            requiredInstructionSet = VMRuntime.getInstructionSet(
11701                     scannedPackage.applicationInfo.primaryCpuAbi);
11702        }
11703
11704        PackageSetting requirer = null;
11705        for (PackageSetting ps : packagesForUser) {
11706            // If packagesForUser contains scannedPackage, we skip it. This will happen
11707            // when scannedPackage is an update of an existing package. Without this check,
11708            // we will never be able to change the ABI of any package belonging to a shared
11709            // user, even if it's compatible with other packages.
11710            if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) {
11711                if (ps.primaryCpuAbiString == null) {
11712                    continue;
11713                }
11714
11715                final String instructionSet = VMRuntime.getInstructionSet(ps.primaryCpuAbiString);
11716                if (requiredInstructionSet != null && !instructionSet.equals(requiredInstructionSet)) {
11717                    // We have a mismatch between instruction sets (say arm vs arm64) warn about
11718                    // this but there's not much we can do.
11719                    String errorMessage = "Instruction set mismatch, "
11720                            + ((requirer == null) ? "[caller]" : requirer)
11721                            + " requires " + requiredInstructionSet + " whereas " + ps
11722                            + " requires " + instructionSet;
11723                    Slog.w(TAG, errorMessage);
11724                }
11725
11726                if (requiredInstructionSet == null) {
11727                    requiredInstructionSet = instructionSet;
11728                    requirer = ps;
11729                }
11730            }
11731        }
11732
11733        if (requiredInstructionSet != null) {
11734            String adjustedAbi;
11735            if (requirer != null) {
11736                // requirer != null implies that either scannedPackage was null or that scannedPackage
11737                // did not require an ABI, in which case we have to adjust scannedPackage to match
11738                // the ABI of the set (which is the same as requirer's ABI)
11739                adjustedAbi = requirer.primaryCpuAbiString;
11740                if (scannedPackage != null) {
11741                    scannedPackage.applicationInfo.primaryCpuAbi = adjustedAbi;
11742                }
11743            } else {
11744                // requirer == null implies that we're updating all ABIs in the set to
11745                // match scannedPackage.
11746                adjustedAbi =  scannedPackage.applicationInfo.primaryCpuAbi;
11747            }
11748
11749            for (PackageSetting ps : packagesForUser) {
11750                if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) {
11751                    if (ps.primaryCpuAbiString != null) {
11752                        continue;
11753                    }
11754
11755                    ps.primaryCpuAbiString = adjustedAbi;
11756                    if (ps.pkg != null && ps.pkg.applicationInfo != null &&
11757                            !TextUtils.equals(adjustedAbi, ps.pkg.applicationInfo.primaryCpuAbi)) {
11758                        ps.pkg.applicationInfo.primaryCpuAbi = adjustedAbi;
11759                        if (DEBUG_ABI_SELECTION) {
11760                            Slog.i(TAG, "Adjusting ABI for " + ps.name + " to " + adjustedAbi
11761                                    + " (requirer="
11762                                    + (requirer != null ? requirer.pkg : "null")
11763                                    + ", scannedPackage="
11764                                    + (scannedPackage != null ? scannedPackage : "null")
11765                                    + ")");
11766                        }
11767                        try {
11768                            mInstaller.rmdex(ps.codePathString,
11769                                    getDexCodeInstructionSet(getPreferredInstructionSet()));
11770                        } catch (InstallerException ignored) {
11771                        }
11772                    }
11773                }
11774            }
11775        }
11776    }
11777
11778    private void setUpCustomResolverActivity(PackageParser.Package pkg) {
11779        synchronized (mPackages) {
11780            mResolverReplaced = true;
11781            // Set up information for custom user intent resolution activity.
11782            mResolveActivity.applicationInfo = pkg.applicationInfo;
11783            mResolveActivity.name = mCustomResolverComponentName.getClassName();
11784            mResolveActivity.packageName = pkg.applicationInfo.packageName;
11785            mResolveActivity.processName = pkg.applicationInfo.packageName;
11786            mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
11787            mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS |
11788                    ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS;
11789            mResolveActivity.theme = 0;
11790            mResolveActivity.exported = true;
11791            mResolveActivity.enabled = true;
11792            mResolveInfo.activityInfo = mResolveActivity;
11793            mResolveInfo.priority = 0;
11794            mResolveInfo.preferredOrder = 0;
11795            mResolveInfo.match = 0;
11796            mResolveComponentName = mCustomResolverComponentName;
11797            Slog.i(TAG, "Replacing default ResolverActivity with custom activity: " +
11798                    mResolveComponentName);
11799        }
11800    }
11801
11802    private void setUpInstantAppInstallerActivityLP(ActivityInfo installerActivity) {
11803        if (installerActivity == null) {
11804            if (DEBUG_EPHEMERAL) {
11805                Slog.d(TAG, "Clear ephemeral installer activity");
11806            }
11807            mInstantAppInstallerActivity = null;
11808            return;
11809        }
11810
11811        if (DEBUG_EPHEMERAL) {
11812            Slog.d(TAG, "Set ephemeral installer activity: "
11813                    + installerActivity.getComponentName());
11814        }
11815        // Set up information for ephemeral installer activity
11816        mInstantAppInstallerActivity = installerActivity;
11817        mInstantAppInstallerActivity.flags |= ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS
11818                | ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS;
11819        mInstantAppInstallerActivity.exported = true;
11820        mInstantAppInstallerActivity.enabled = true;
11821        mInstantAppInstallerInfo.activityInfo = mInstantAppInstallerActivity;
11822        mInstantAppInstallerInfo.priority = 0;
11823        mInstantAppInstallerInfo.preferredOrder = 1;
11824        mInstantAppInstallerInfo.isDefault = true;
11825        mInstantAppInstallerInfo.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART
11826                | IntentFilter.MATCH_ADJUSTMENT_NORMAL;
11827    }
11828
11829    private static String calculateBundledApkRoot(final String codePathString) {
11830        final File codePath = new File(codePathString);
11831        final File codeRoot;
11832        if (FileUtils.contains(Environment.getRootDirectory(), codePath)) {
11833            codeRoot = Environment.getRootDirectory();
11834        } else if (FileUtils.contains(Environment.getOemDirectory(), codePath)) {
11835            codeRoot = Environment.getOemDirectory();
11836        } else if (FileUtils.contains(Environment.getVendorDirectory(), codePath)) {
11837            codeRoot = Environment.getVendorDirectory();
11838        } else {
11839            // Unrecognized code path; take its top real segment as the apk root:
11840            // e.g. /something/app/blah.apk => /something
11841            try {
11842                File f = codePath.getCanonicalFile();
11843                File parent = f.getParentFile();    // non-null because codePath is a file
11844                File tmp;
11845                while ((tmp = parent.getParentFile()) != null) {
11846                    f = parent;
11847                    parent = tmp;
11848                }
11849                codeRoot = f;
11850                Slog.w(TAG, "Unrecognized code path "
11851                        + codePath + " - using " + codeRoot);
11852            } catch (IOException e) {
11853                // Can't canonicalize the code path -- shenanigans?
11854                Slog.w(TAG, "Can't canonicalize code path " + codePath);
11855                return Environment.getRootDirectory().getPath();
11856            }
11857        }
11858        return codeRoot.getPath();
11859    }
11860
11861    /**
11862     * Derive and set the location of native libraries for the given package,
11863     * which varies depending on where and how the package was installed.
11864     */
11865    private static void setNativeLibraryPaths(PackageParser.Package pkg, File appLib32InstallDir) {
11866        final ApplicationInfo info = pkg.applicationInfo;
11867        final String codePath = pkg.codePath;
11868        final File codeFile = new File(codePath);
11869        final boolean bundledApp = info.isSystemApp() && !info.isUpdatedSystemApp();
11870        final boolean asecApp = info.isForwardLocked() || info.isExternalAsec();
11871
11872        info.nativeLibraryRootDir = null;
11873        info.nativeLibraryRootRequiresIsa = false;
11874        info.nativeLibraryDir = null;
11875        info.secondaryNativeLibraryDir = null;
11876
11877        if (isApkFile(codeFile)) {
11878            // Monolithic install
11879            if (bundledApp) {
11880                // If "/system/lib64/apkname" exists, assume that is the per-package
11881                // native library directory to use; otherwise use "/system/lib/apkname".
11882                final String apkRoot = calculateBundledApkRoot(info.sourceDir);
11883                final boolean is64Bit = VMRuntime.is64BitInstructionSet(
11884                        getPrimaryInstructionSet(info));
11885
11886                // This is a bundled system app so choose the path based on the ABI.
11887                // if it's a 64 bit abi, use lib64 otherwise use lib32. Note that this
11888                // is just the default path.
11889                final String apkName = deriveCodePathName(codePath);
11890                final String libDir = is64Bit ? LIB64_DIR_NAME : LIB_DIR_NAME;
11891                info.nativeLibraryRootDir = Environment.buildPath(new File(apkRoot), libDir,
11892                        apkName).getAbsolutePath();
11893
11894                if (info.secondaryCpuAbi != null) {
11895                    final String secondaryLibDir = is64Bit ? LIB_DIR_NAME : LIB64_DIR_NAME;
11896                    info.secondaryNativeLibraryDir = Environment.buildPath(new File(apkRoot),
11897                            secondaryLibDir, apkName).getAbsolutePath();
11898                }
11899            } else if (asecApp) {
11900                info.nativeLibraryRootDir = new File(codeFile.getParentFile(), LIB_DIR_NAME)
11901                        .getAbsolutePath();
11902            } else {
11903                final String apkName = deriveCodePathName(codePath);
11904                info.nativeLibraryRootDir = new File(appLib32InstallDir, apkName)
11905                        .getAbsolutePath();
11906            }
11907
11908            info.nativeLibraryRootRequiresIsa = false;
11909            info.nativeLibraryDir = info.nativeLibraryRootDir;
11910        } else {
11911            // Cluster install
11912            info.nativeLibraryRootDir = new File(codeFile, LIB_DIR_NAME).getAbsolutePath();
11913            info.nativeLibraryRootRequiresIsa = true;
11914
11915            info.nativeLibraryDir = new File(info.nativeLibraryRootDir,
11916                    getPrimaryInstructionSet(info)).getAbsolutePath();
11917
11918            if (info.secondaryCpuAbi != null) {
11919                info.secondaryNativeLibraryDir = new File(info.nativeLibraryRootDir,
11920                        VMRuntime.getInstructionSet(info.secondaryCpuAbi)).getAbsolutePath();
11921            }
11922        }
11923    }
11924
11925    /**
11926     * Calculate the abis and roots for a bundled app. These can uniquely
11927     * be determined from the contents of the system partition, i.e whether
11928     * it contains 64 or 32 bit shared libraries etc. We do not validate any
11929     * of this information, and instead assume that the system was built
11930     * sensibly.
11931     */
11932    private static void setBundledAppAbisAndRoots(PackageParser.Package pkg,
11933                                           PackageSetting pkgSetting) {
11934        final String apkName = deriveCodePathName(pkg.applicationInfo.getCodePath());
11935
11936        // If "/system/lib64/apkname" exists, assume that is the per-package
11937        // native library directory to use; otherwise use "/system/lib/apkname".
11938        final String apkRoot = calculateBundledApkRoot(pkg.applicationInfo.sourceDir);
11939        setBundledAppAbi(pkg, apkRoot, apkName);
11940        // pkgSetting might be null during rescan following uninstall of updates
11941        // to a bundled app, so accommodate that possibility.  The settings in
11942        // that case will be established later from the parsed package.
11943        //
11944        // If the settings aren't null, sync them up with what we've just derived.
11945        // note that apkRoot isn't stored in the package settings.
11946        if (pkgSetting != null) {
11947            pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi;
11948            pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi;
11949        }
11950    }
11951
11952    /**
11953     * Deduces the ABI of a bundled app and sets the relevant fields on the
11954     * parsed pkg object.
11955     *
11956     * @param apkRoot the root of the installed apk, something like {@code /system} or {@code /oem}
11957     *        under which system libraries are installed.
11958     * @param apkName the name of the installed package.
11959     */
11960    private static void setBundledAppAbi(PackageParser.Package pkg, String apkRoot, String apkName) {
11961        final File codeFile = new File(pkg.codePath);
11962
11963        final boolean has64BitLibs;
11964        final boolean has32BitLibs;
11965        if (isApkFile(codeFile)) {
11966            // Monolithic install
11967            has64BitLibs = (new File(apkRoot, new File(LIB64_DIR_NAME, apkName).getPath())).exists();
11968            has32BitLibs = (new File(apkRoot, new File(LIB_DIR_NAME, apkName).getPath())).exists();
11969        } else {
11970            // Cluster install
11971            final File rootDir = new File(codeFile, LIB_DIR_NAME);
11972            if (!ArrayUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS)
11973                    && !TextUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS[0])) {
11974                final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_64_BIT_ABIS[0]);
11975                has64BitLibs = (new File(rootDir, isa)).exists();
11976            } else {
11977                has64BitLibs = false;
11978            }
11979            if (!ArrayUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS)
11980                    && !TextUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS[0])) {
11981                final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_32_BIT_ABIS[0]);
11982                has32BitLibs = (new File(rootDir, isa)).exists();
11983            } else {
11984                has32BitLibs = false;
11985            }
11986        }
11987
11988        if (has64BitLibs && !has32BitLibs) {
11989            // The package has 64 bit libs, but not 32 bit libs. Its primary
11990            // ABI should be 64 bit. We can safely assume here that the bundled
11991            // native libraries correspond to the most preferred ABI in the list.
11992
11993            pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
11994            pkg.applicationInfo.secondaryCpuAbi = null;
11995        } else if (has32BitLibs && !has64BitLibs) {
11996            // The package has 32 bit libs but not 64 bit libs. Its primary
11997            // ABI should be 32 bit.
11998
11999            pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
12000            pkg.applicationInfo.secondaryCpuAbi = null;
12001        } else if (has32BitLibs && has64BitLibs) {
12002            // The application has both 64 and 32 bit bundled libraries. We check
12003            // here that the app declares multiArch support, and warn if it doesn't.
12004            //
12005            // We will be lenient here and record both ABIs. The primary will be the
12006            // ABI that's higher on the list, i.e, a device that's configured to prefer
12007            // 64 bit apps will see a 64 bit primary ABI,
12008
12009            if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_MULTIARCH) == 0) {
12010                Slog.e(TAG, "Package " + pkg + " has multiple bundled libs, but is not multiarch.");
12011            }
12012
12013            if (VMRuntime.is64BitInstructionSet(getPreferredInstructionSet())) {
12014                pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
12015                pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
12016            } else {
12017                pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
12018                pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
12019            }
12020        } else {
12021            pkg.applicationInfo.primaryCpuAbi = null;
12022            pkg.applicationInfo.secondaryCpuAbi = null;
12023        }
12024    }
12025
12026    private void killApplication(String pkgName, int appId, String reason) {
12027        killApplication(pkgName, appId, UserHandle.USER_ALL, reason);
12028    }
12029
12030    private void killApplication(String pkgName, int appId, int userId, String reason) {
12031        // Request the ActivityManager to kill the process(only for existing packages)
12032        // so that we do not end up in a confused state while the user is still using the older
12033        // version of the application while the new one gets installed.
12034        final long token = Binder.clearCallingIdentity();
12035        try {
12036            IActivityManager am = ActivityManager.getService();
12037            if (am != null) {
12038                try {
12039                    am.killApplication(pkgName, appId, userId, reason);
12040                } catch (RemoteException e) {
12041                }
12042            }
12043        } finally {
12044            Binder.restoreCallingIdentity(token);
12045        }
12046    }
12047
12048    private void removePackageLI(PackageParser.Package pkg, boolean chatty) {
12049        // Remove the parent package setting
12050        PackageSetting ps = (PackageSetting) pkg.mExtras;
12051        if (ps != null) {
12052            removePackageLI(ps, chatty);
12053        }
12054        // Remove the child package setting
12055        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
12056        for (int i = 0; i < childCount; i++) {
12057            PackageParser.Package childPkg = pkg.childPackages.get(i);
12058            ps = (PackageSetting) childPkg.mExtras;
12059            if (ps != null) {
12060                removePackageLI(ps, chatty);
12061            }
12062        }
12063    }
12064
12065    void removePackageLI(PackageSetting ps, boolean chatty) {
12066        if (DEBUG_INSTALL) {
12067            if (chatty)
12068                Log.d(TAG, "Removing package " + ps.name);
12069        }
12070
12071        // writer
12072        synchronized (mPackages) {
12073            mPackages.remove(ps.name);
12074            final PackageParser.Package pkg = ps.pkg;
12075            if (pkg != null) {
12076                cleanPackageDataStructuresLILPw(pkg, chatty);
12077            }
12078        }
12079    }
12080
12081    void removeInstalledPackageLI(PackageParser.Package pkg, boolean chatty) {
12082        if (DEBUG_INSTALL) {
12083            if (chatty)
12084                Log.d(TAG, "Removing package " + pkg.applicationInfo.packageName);
12085        }
12086
12087        // writer
12088        synchronized (mPackages) {
12089            // Remove the parent package
12090            mPackages.remove(pkg.applicationInfo.packageName);
12091            cleanPackageDataStructuresLILPw(pkg, chatty);
12092
12093            // Remove the child packages
12094            final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
12095            for (int i = 0; i < childCount; i++) {
12096                PackageParser.Package childPkg = pkg.childPackages.get(i);
12097                mPackages.remove(childPkg.applicationInfo.packageName);
12098                cleanPackageDataStructuresLILPw(childPkg, chatty);
12099            }
12100        }
12101    }
12102
12103    void cleanPackageDataStructuresLILPw(PackageParser.Package pkg, boolean chatty) {
12104        int N = pkg.providers.size();
12105        StringBuilder r = null;
12106        int i;
12107        for (i=0; i<N; i++) {
12108            PackageParser.Provider p = pkg.providers.get(i);
12109            mProviders.removeProvider(p);
12110            if (p.info.authority == null) {
12111
12112                /* There was another ContentProvider with this authority when
12113                 * this app was installed so this authority is null,
12114                 * Ignore it as we don't have to unregister the provider.
12115                 */
12116                continue;
12117            }
12118            String names[] = p.info.authority.split(";");
12119            for (int j = 0; j < names.length; j++) {
12120                if (mProvidersByAuthority.get(names[j]) == p) {
12121                    mProvidersByAuthority.remove(names[j]);
12122                    if (DEBUG_REMOVE) {
12123                        if (chatty)
12124                            Log.d(TAG, "Unregistered content provider: " + names[j]
12125                                    + ", className = " + p.info.name + ", isSyncable = "
12126                                    + p.info.isSyncable);
12127                    }
12128                }
12129            }
12130            if (DEBUG_REMOVE && chatty) {
12131                if (r == null) {
12132                    r = new StringBuilder(256);
12133                } else {
12134                    r.append(' ');
12135                }
12136                r.append(p.info.name);
12137            }
12138        }
12139        if (r != null) {
12140            if (DEBUG_REMOVE) Log.d(TAG, "  Providers: " + r);
12141        }
12142
12143        N = pkg.services.size();
12144        r = null;
12145        for (i=0; i<N; i++) {
12146            PackageParser.Service s = pkg.services.get(i);
12147            mServices.removeService(s);
12148            if (chatty) {
12149                if (r == null) {
12150                    r = new StringBuilder(256);
12151                } else {
12152                    r.append(' ');
12153                }
12154                r.append(s.info.name);
12155            }
12156        }
12157        if (r != null) {
12158            if (DEBUG_REMOVE) Log.d(TAG, "  Services: " + r);
12159        }
12160
12161        N = pkg.receivers.size();
12162        r = null;
12163        for (i=0; i<N; i++) {
12164            PackageParser.Activity a = pkg.receivers.get(i);
12165            mReceivers.removeActivity(a, "receiver");
12166            if (DEBUG_REMOVE && chatty) {
12167                if (r == null) {
12168                    r = new StringBuilder(256);
12169                } else {
12170                    r.append(' ');
12171                }
12172                r.append(a.info.name);
12173            }
12174        }
12175        if (r != null) {
12176            if (DEBUG_REMOVE) Log.d(TAG, "  Receivers: " + r);
12177        }
12178
12179        N = pkg.activities.size();
12180        r = null;
12181        for (i=0; i<N; i++) {
12182            PackageParser.Activity a = pkg.activities.get(i);
12183            mActivities.removeActivity(a, "activity");
12184            if (DEBUG_REMOVE && chatty) {
12185                if (r == null) {
12186                    r = new StringBuilder(256);
12187                } else {
12188                    r.append(' ');
12189                }
12190                r.append(a.info.name);
12191            }
12192        }
12193        if (r != null) {
12194            if (DEBUG_REMOVE) Log.d(TAG, "  Activities: " + r);
12195        }
12196
12197        N = pkg.permissions.size();
12198        r = null;
12199        for (i=0; i<N; i++) {
12200            PackageParser.Permission p = pkg.permissions.get(i);
12201            BasePermission bp = mSettings.mPermissions.get(p.info.name);
12202            if (bp == null) {
12203                bp = mSettings.mPermissionTrees.get(p.info.name);
12204            }
12205            if (bp != null && bp.perm == p) {
12206                bp.perm = null;
12207                if (DEBUG_REMOVE && chatty) {
12208                    if (r == null) {
12209                        r = new StringBuilder(256);
12210                    } else {
12211                        r.append(' ');
12212                    }
12213                    r.append(p.info.name);
12214                }
12215            }
12216            if ((p.info.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
12217                ArraySet<String> appOpPkgs = mAppOpPermissionPackages.get(p.info.name);
12218                if (appOpPkgs != null) {
12219                    appOpPkgs.remove(pkg.packageName);
12220                }
12221            }
12222        }
12223        if (r != null) {
12224            if (DEBUG_REMOVE) Log.d(TAG, "  Permissions: " + r);
12225        }
12226
12227        N = pkg.requestedPermissions.size();
12228        r = null;
12229        for (i=0; i<N; i++) {
12230            String perm = pkg.requestedPermissions.get(i);
12231            BasePermission bp = mSettings.mPermissions.get(perm);
12232            if (bp != null && (bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
12233                ArraySet<String> appOpPkgs = mAppOpPermissionPackages.get(perm);
12234                if (appOpPkgs != null) {
12235                    appOpPkgs.remove(pkg.packageName);
12236                    if (appOpPkgs.isEmpty()) {
12237                        mAppOpPermissionPackages.remove(perm);
12238                    }
12239                }
12240            }
12241        }
12242        if (r != null) {
12243            if (DEBUG_REMOVE) Log.d(TAG, "  Permissions: " + r);
12244        }
12245
12246        N = pkg.instrumentation.size();
12247        r = null;
12248        for (i=0; i<N; i++) {
12249            PackageParser.Instrumentation a = pkg.instrumentation.get(i);
12250            mInstrumentation.remove(a.getComponentName());
12251            if (DEBUG_REMOVE && chatty) {
12252                if (r == null) {
12253                    r = new StringBuilder(256);
12254                } else {
12255                    r.append(' ');
12256                }
12257                r.append(a.info.name);
12258            }
12259        }
12260        if (r != null) {
12261            if (DEBUG_REMOVE) Log.d(TAG, "  Instrumentation: " + r);
12262        }
12263
12264        r = null;
12265        if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) {
12266            // Only system apps can hold shared libraries.
12267            if (pkg.libraryNames != null) {
12268                for (i = 0; i < pkg.libraryNames.size(); i++) {
12269                    String name = pkg.libraryNames.get(i);
12270                    if (removeSharedLibraryLPw(name, 0)) {
12271                        if (DEBUG_REMOVE && chatty) {
12272                            if (r == null) {
12273                                r = new StringBuilder(256);
12274                            } else {
12275                                r.append(' ');
12276                            }
12277                            r.append(name);
12278                        }
12279                    }
12280                }
12281            }
12282        }
12283
12284        r = null;
12285
12286        // Any package can hold static shared libraries.
12287        if (pkg.staticSharedLibName != null) {
12288            if (removeSharedLibraryLPw(pkg.staticSharedLibName, pkg.staticSharedLibVersion)) {
12289                if (DEBUG_REMOVE && chatty) {
12290                    if (r == null) {
12291                        r = new StringBuilder(256);
12292                    } else {
12293                        r.append(' ');
12294                    }
12295                    r.append(pkg.staticSharedLibName);
12296                }
12297            }
12298        }
12299
12300        if (r != null) {
12301            if (DEBUG_REMOVE) Log.d(TAG, "  Libraries: " + r);
12302        }
12303    }
12304
12305    private static boolean hasPermission(PackageParser.Package pkgInfo, String perm) {
12306        for (int i=pkgInfo.permissions.size()-1; i>=0; i--) {
12307            if (pkgInfo.permissions.get(i).info.name.equals(perm)) {
12308                return true;
12309            }
12310        }
12311        return false;
12312    }
12313
12314    static final int UPDATE_PERMISSIONS_ALL = 1<<0;
12315    static final int UPDATE_PERMISSIONS_REPLACE_PKG = 1<<1;
12316    static final int UPDATE_PERMISSIONS_REPLACE_ALL = 1<<2;
12317
12318    private void updatePermissionsLPw(PackageParser.Package pkg, int flags) {
12319        // Update the parent permissions
12320        updatePermissionsLPw(pkg.packageName, pkg, flags);
12321        // Update the child permissions
12322        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
12323        for (int i = 0; i < childCount; i++) {
12324            PackageParser.Package childPkg = pkg.childPackages.get(i);
12325            updatePermissionsLPw(childPkg.packageName, childPkg, flags);
12326        }
12327    }
12328
12329    private void updatePermissionsLPw(String changingPkg, PackageParser.Package pkgInfo,
12330            int flags) {
12331        final String volumeUuid = (pkgInfo != null) ? getVolumeUuidForPackage(pkgInfo) : null;
12332        updatePermissionsLPw(changingPkg, pkgInfo, volumeUuid, flags);
12333    }
12334
12335    private void updatePermissionsLPw(String changingPkg,
12336            PackageParser.Package pkgInfo, String replaceVolumeUuid, int flags) {
12337        // Make sure there are no dangling permission trees.
12338        Iterator<BasePermission> it = mSettings.mPermissionTrees.values().iterator();
12339        while (it.hasNext()) {
12340            final BasePermission bp = it.next();
12341            if (bp.packageSetting == null) {
12342                // We may not yet have parsed the package, so just see if
12343                // we still know about its settings.
12344                bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage);
12345            }
12346            if (bp.packageSetting == null) {
12347                Slog.w(TAG, "Removing dangling permission tree: " + bp.name
12348                        + " from package " + bp.sourcePackage);
12349                it.remove();
12350            } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) {
12351                if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) {
12352                    Slog.i(TAG, "Removing old permission tree: " + bp.name
12353                            + " from package " + bp.sourcePackage);
12354                    flags |= UPDATE_PERMISSIONS_ALL;
12355                    it.remove();
12356                }
12357            }
12358        }
12359
12360        // Make sure all dynamic permissions have been assigned to a package,
12361        // and make sure there are no dangling permissions.
12362        it = mSettings.mPermissions.values().iterator();
12363        while (it.hasNext()) {
12364            final BasePermission bp = it.next();
12365            if (bp.type == BasePermission.TYPE_DYNAMIC) {
12366                if (DEBUG_SETTINGS) Log.v(TAG, "Dynamic permission: name="
12367                        + bp.name + " pkg=" + bp.sourcePackage
12368                        + " info=" + bp.pendingInfo);
12369                if (bp.packageSetting == null && bp.pendingInfo != null) {
12370                    final BasePermission tree = findPermissionTreeLP(bp.name);
12371                    if (tree != null && tree.perm != null) {
12372                        bp.packageSetting = tree.packageSetting;
12373                        bp.perm = new PackageParser.Permission(tree.perm.owner,
12374                                new PermissionInfo(bp.pendingInfo));
12375                        bp.perm.info.packageName = tree.perm.info.packageName;
12376                        bp.perm.info.name = bp.name;
12377                        bp.uid = tree.uid;
12378                    }
12379                }
12380            }
12381            if (bp.packageSetting == null) {
12382                // We may not yet have parsed the package, so just see if
12383                // we still know about its settings.
12384                bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage);
12385            }
12386            if (bp.packageSetting == null) {
12387                Slog.w(TAG, "Removing dangling permission: " + bp.name
12388                        + " from package " + bp.sourcePackage);
12389                it.remove();
12390            } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) {
12391                if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) {
12392                    Slog.i(TAG, "Removing old permission: " + bp.name
12393                            + " from package " + bp.sourcePackage);
12394                    flags |= UPDATE_PERMISSIONS_ALL;
12395                    it.remove();
12396                }
12397            }
12398        }
12399
12400        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "grantPermissions");
12401        // Now update the permissions for all packages, in particular
12402        // replace the granted permissions of the system packages.
12403        if ((flags&UPDATE_PERMISSIONS_ALL) != 0) {
12404            for (PackageParser.Package pkg : mPackages.values()) {
12405                if (pkg != pkgInfo) {
12406                    // Only replace for packages on requested volume
12407                    final String volumeUuid = getVolumeUuidForPackage(pkg);
12408                    final boolean replace = ((flags & UPDATE_PERMISSIONS_REPLACE_ALL) != 0)
12409                            && Objects.equals(replaceVolumeUuid, volumeUuid);
12410                    grantPermissionsLPw(pkg, replace, changingPkg);
12411                }
12412            }
12413        }
12414
12415        if (pkgInfo != null) {
12416            // Only replace for packages on requested volume
12417            final String volumeUuid = getVolumeUuidForPackage(pkgInfo);
12418            final boolean replace = ((flags & UPDATE_PERMISSIONS_REPLACE_PKG) != 0)
12419                    && Objects.equals(replaceVolumeUuid, volumeUuid);
12420            grantPermissionsLPw(pkgInfo, replace, changingPkg);
12421        }
12422        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
12423    }
12424
12425    private void grantPermissionsLPw(PackageParser.Package pkg, boolean replace,
12426            String packageOfInterest) {
12427        // IMPORTANT: There are two types of permissions: install and runtime.
12428        // Install time permissions are granted when the app is installed to
12429        // all device users and users added in the future. Runtime permissions
12430        // are granted at runtime explicitly to specific users. Normal and signature
12431        // protected permissions are install time permissions. Dangerous permissions
12432        // are install permissions if the app's target SDK is Lollipop MR1 or older,
12433        // otherwise they are runtime permissions. This function does not manage
12434        // runtime permissions except for the case an app targeting Lollipop MR1
12435        // being upgraded to target a newer SDK, in which case dangerous permissions
12436        // are transformed from install time to runtime ones.
12437
12438        final PackageSetting ps = (PackageSetting) pkg.mExtras;
12439        if (ps == null) {
12440            return;
12441        }
12442
12443        PermissionsState permissionsState = ps.getPermissionsState();
12444        PermissionsState origPermissions = permissionsState;
12445
12446        final int[] currentUserIds = UserManagerService.getInstance().getUserIds();
12447
12448        boolean runtimePermissionsRevoked = false;
12449        int[] changedRuntimePermissionUserIds = EMPTY_INT_ARRAY;
12450
12451        boolean changedInstallPermission = false;
12452
12453        if (replace) {
12454            ps.installPermissionsFixed = false;
12455            if (!ps.isSharedUser()) {
12456                origPermissions = new PermissionsState(permissionsState);
12457                permissionsState.reset();
12458            } else {
12459                // We need to know only about runtime permission changes since the
12460                // calling code always writes the install permissions state but
12461                // the runtime ones are written only if changed. The only cases of
12462                // changed runtime permissions here are promotion of an install to
12463                // runtime and revocation of a runtime from a shared user.
12464                changedRuntimePermissionUserIds = revokeUnusedSharedUserPermissionsLPw(
12465                        ps.sharedUser, UserManagerService.getInstance().getUserIds());
12466                if (!ArrayUtils.isEmpty(changedRuntimePermissionUserIds)) {
12467                    runtimePermissionsRevoked = true;
12468                }
12469            }
12470        }
12471
12472        permissionsState.setGlobalGids(mGlobalGids);
12473
12474        final int N = pkg.requestedPermissions.size();
12475        for (int i=0; i<N; i++) {
12476            final String name = pkg.requestedPermissions.get(i);
12477            final BasePermission bp = mSettings.mPermissions.get(name);
12478            final boolean appSupportsRuntimePermissions = pkg.applicationInfo.targetSdkVersion
12479                    >= Build.VERSION_CODES.M;
12480
12481            if (DEBUG_INSTALL) {
12482                Log.i(TAG, "Package " + pkg.packageName + " checking " + name + ": " + bp);
12483            }
12484
12485            if (bp == null || bp.packageSetting == null) {
12486                if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) {
12487                    if (DEBUG_PERMISSIONS) {
12488                        Slog.i(TAG, "Unknown permission " + name
12489                                + " in package " + pkg.packageName);
12490                    }
12491                }
12492                continue;
12493            }
12494
12495
12496            // Limit ephemeral apps to ephemeral allowed permissions.
12497            if (pkg.applicationInfo.isInstantApp() && !bp.isInstant()) {
12498                if (DEBUG_PERMISSIONS) {
12499                    Log.i(TAG, "Denying non-ephemeral permission " + bp.name + " for package "
12500                            + pkg.packageName);
12501                }
12502                continue;
12503            }
12504
12505            if (bp.isRuntimeOnly() && !appSupportsRuntimePermissions) {
12506                if (DEBUG_PERMISSIONS) {
12507                    Log.i(TAG, "Denying runtime-only permission " + bp.name + " for package "
12508                            + pkg.packageName);
12509                }
12510                continue;
12511            }
12512
12513            final String perm = bp.name;
12514            boolean allowedSig = false;
12515            int grant = GRANT_DENIED;
12516
12517            // Keep track of app op permissions.
12518            if ((bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
12519                ArraySet<String> pkgs = mAppOpPermissionPackages.get(bp.name);
12520                if (pkgs == null) {
12521                    pkgs = new ArraySet<>();
12522                    mAppOpPermissionPackages.put(bp.name, pkgs);
12523                }
12524                pkgs.add(pkg.packageName);
12525            }
12526
12527            final int level = bp.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE;
12528            switch (level) {
12529                case PermissionInfo.PROTECTION_NORMAL: {
12530                    // For all apps normal permissions are install time ones.
12531                    grant = GRANT_INSTALL;
12532                } break;
12533
12534                case PermissionInfo.PROTECTION_DANGEROUS: {
12535                    // If a permission review is required for legacy apps we represent
12536                    // their permissions as always granted runtime ones since we need
12537                    // to keep the review required permission flag per user while an
12538                    // install permission's state is shared across all users.
12539                    if (!appSupportsRuntimePermissions && !mPermissionReviewRequired) {
12540                        // For legacy apps dangerous permissions are install time ones.
12541                        grant = GRANT_INSTALL;
12542                    } else if (origPermissions.hasInstallPermission(bp.name)) {
12543                        // For legacy apps that became modern, install becomes runtime.
12544                        grant = GRANT_UPGRADE;
12545                    } else if (mPromoteSystemApps
12546                            && isSystemApp(ps)
12547                            && mExistingSystemPackages.contains(ps.name)) {
12548                        // For legacy system apps, install becomes runtime.
12549                        // We cannot check hasInstallPermission() for system apps since those
12550                        // permissions were granted implicitly and not persisted pre-M.
12551                        grant = GRANT_UPGRADE;
12552                    } else {
12553                        // For modern apps keep runtime permissions unchanged.
12554                        grant = GRANT_RUNTIME;
12555                    }
12556                } break;
12557
12558                case PermissionInfo.PROTECTION_SIGNATURE: {
12559                    // For all apps signature permissions are install time ones.
12560                    allowedSig = grantSignaturePermission(perm, pkg, bp, origPermissions);
12561                    if (allowedSig) {
12562                        grant = GRANT_INSTALL;
12563                    }
12564                } break;
12565            }
12566
12567            if (DEBUG_PERMISSIONS) {
12568                Slog.i(TAG, "Granting permission " + perm + " to package " + pkg.packageName);
12569            }
12570
12571            if (grant != GRANT_DENIED) {
12572                if (!isSystemApp(ps) && ps.installPermissionsFixed) {
12573                    // If this is an existing, non-system package, then
12574                    // we can't add any new permissions to it.
12575                    if (!allowedSig && !origPermissions.hasInstallPermission(perm)) {
12576                        // Except...  if this is a permission that was added
12577                        // to the platform (note: need to only do this when
12578                        // updating the platform).
12579                        if (!isNewPlatformPermissionForPackage(perm, pkg)) {
12580                            grant = GRANT_DENIED;
12581                        }
12582                    }
12583                }
12584
12585                switch (grant) {
12586                    case GRANT_INSTALL: {
12587                        // Revoke this as runtime permission to handle the case of
12588                        // a runtime permission being downgraded to an install one.
12589                        // Also in permission review mode we keep dangerous permissions
12590                        // for legacy apps
12591                        for (int userId : UserManagerService.getInstance().getUserIds()) {
12592                            if (origPermissions.getRuntimePermissionState(
12593                                    bp.name, userId) != null) {
12594                                // Revoke the runtime permission and clear the flags.
12595                                origPermissions.revokeRuntimePermission(bp, userId);
12596                                origPermissions.updatePermissionFlags(bp, userId,
12597                                      PackageManager.MASK_PERMISSION_FLAGS, 0);
12598                                // If we revoked a permission permission, we have to write.
12599                                changedRuntimePermissionUserIds = ArrayUtils.appendInt(
12600                                        changedRuntimePermissionUserIds, userId);
12601                            }
12602                        }
12603                        // Grant an install permission.
12604                        if (permissionsState.grantInstallPermission(bp) !=
12605                                PermissionsState.PERMISSION_OPERATION_FAILURE) {
12606                            changedInstallPermission = true;
12607                        }
12608                    } break;
12609
12610                    case GRANT_RUNTIME: {
12611                        // Grant previously granted runtime permissions.
12612                        for (int userId : UserManagerService.getInstance().getUserIds()) {
12613                            PermissionState permissionState = origPermissions
12614                                    .getRuntimePermissionState(bp.name, userId);
12615                            int flags = permissionState != null
12616                                    ? permissionState.getFlags() : 0;
12617                            if (origPermissions.hasRuntimePermission(bp.name, userId)) {
12618                                // Don't propagate the permission in a permission review mode if
12619                                // the former was revoked, i.e. marked to not propagate on upgrade.
12620                                // Note that in a permission review mode install permissions are
12621                                // represented as constantly granted runtime ones since we need to
12622                                // keep a per user state associated with the permission. Also the
12623                                // revoke on upgrade flag is no longer applicable and is reset.
12624                                final boolean revokeOnUpgrade = (flags & PackageManager
12625                                        .FLAG_PERMISSION_REVOKE_ON_UPGRADE) != 0;
12626                                if (revokeOnUpgrade) {
12627                                    flags &= ~PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE;
12628                                    // Since we changed the flags, we have to write.
12629                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
12630                                            changedRuntimePermissionUserIds, userId);
12631                                }
12632                                if (!mPermissionReviewRequired || !revokeOnUpgrade) {
12633                                    if (permissionsState.grantRuntimePermission(bp, userId) ==
12634                                            PermissionsState.PERMISSION_OPERATION_FAILURE) {
12635                                        // If we cannot put the permission as it was,
12636                                        // we have to write.
12637                                        changedRuntimePermissionUserIds = ArrayUtils.appendInt(
12638                                                changedRuntimePermissionUserIds, userId);
12639                                    }
12640                                }
12641
12642                                // If the app supports runtime permissions no need for a review.
12643                                if (mPermissionReviewRequired
12644                                        && appSupportsRuntimePermissions
12645                                        && (flags & PackageManager
12646                                                .FLAG_PERMISSION_REVIEW_REQUIRED) != 0) {
12647                                    flags &= ~PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED;
12648                                    // Since we changed the flags, we have to write.
12649                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
12650                                            changedRuntimePermissionUserIds, userId);
12651                                }
12652                            } else if (mPermissionReviewRequired
12653                                    && !appSupportsRuntimePermissions) {
12654                                // For legacy apps that need a permission review, every new
12655                                // runtime permission is granted but it is pending a review.
12656                                // We also need to review only platform defined runtime
12657                                // permissions as these are the only ones the platform knows
12658                                // how to disable the API to simulate revocation as legacy
12659                                // apps don't expect to run with revoked permissions.
12660                                if (PLATFORM_PACKAGE_NAME.equals(bp.sourcePackage)) {
12661                                    if ((flags & FLAG_PERMISSION_REVIEW_REQUIRED) == 0) {
12662                                        flags |= FLAG_PERMISSION_REVIEW_REQUIRED;
12663                                        // We changed the flags, hence have to write.
12664                                        changedRuntimePermissionUserIds = ArrayUtils.appendInt(
12665                                                changedRuntimePermissionUserIds, userId);
12666                                    }
12667                                }
12668                                if (permissionsState.grantRuntimePermission(bp, userId)
12669                                        != PermissionsState.PERMISSION_OPERATION_FAILURE) {
12670                                    // We changed the permission, hence have to write.
12671                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
12672                                            changedRuntimePermissionUserIds, userId);
12673                                }
12674                            }
12675                            // Propagate the permission flags.
12676                            permissionsState.updatePermissionFlags(bp, userId, flags, flags);
12677                        }
12678                    } break;
12679
12680                    case GRANT_UPGRADE: {
12681                        // Grant runtime permissions for a previously held install permission.
12682                        PermissionState permissionState = origPermissions
12683                                .getInstallPermissionState(bp.name);
12684                        final int flags = permissionState != null ? permissionState.getFlags() : 0;
12685
12686                        if (origPermissions.revokeInstallPermission(bp)
12687                                != PermissionsState.PERMISSION_OPERATION_FAILURE) {
12688                            // We will be transferring the permission flags, so clear them.
12689                            origPermissions.updatePermissionFlags(bp, UserHandle.USER_ALL,
12690                                    PackageManager.MASK_PERMISSION_FLAGS, 0);
12691                            changedInstallPermission = true;
12692                        }
12693
12694                        // If the permission is not to be promoted to runtime we ignore it and
12695                        // also its other flags as they are not applicable to install permissions.
12696                        if ((flags & PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE) == 0) {
12697                            for (int userId : currentUserIds) {
12698                                if (permissionsState.grantRuntimePermission(bp, userId) !=
12699                                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
12700                                    // Transfer the permission flags.
12701                                    permissionsState.updatePermissionFlags(bp, userId,
12702                                            flags, flags);
12703                                    // If we granted the permission, we have to write.
12704                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
12705                                            changedRuntimePermissionUserIds, userId);
12706                                }
12707                            }
12708                        }
12709                    } break;
12710
12711                    default: {
12712                        if (packageOfInterest == null
12713                                || packageOfInterest.equals(pkg.packageName)) {
12714                            if (DEBUG_PERMISSIONS) {
12715                                Slog.i(TAG, "Not granting permission " + perm
12716                                        + " to package " + pkg.packageName
12717                                        + " because it was previously installed without");
12718                            }
12719                        }
12720                    } break;
12721                }
12722            } else {
12723                if (permissionsState.revokeInstallPermission(bp) !=
12724                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
12725                    // Also drop the permission flags.
12726                    permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL,
12727                            PackageManager.MASK_PERMISSION_FLAGS, 0);
12728                    changedInstallPermission = true;
12729                    Slog.i(TAG, "Un-granting permission " + perm
12730                            + " from package " + pkg.packageName
12731                            + " (protectionLevel=" + bp.protectionLevel
12732                            + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
12733                            + ")");
12734                } else if ((bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) == 0) {
12735                    // Don't print warning for app op permissions, since it is fine for them
12736                    // not to be granted, there is a UI for the user to decide.
12737                    if (DEBUG_PERMISSIONS
12738                            && (packageOfInterest == null
12739                                    || packageOfInterest.equals(pkg.packageName))) {
12740                        Slog.i(TAG, "Not granting permission " + perm
12741                                + " to package " + pkg.packageName
12742                                + " (protectionLevel=" + bp.protectionLevel
12743                                + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
12744                                + ")");
12745                    }
12746                }
12747            }
12748        }
12749
12750        if ((changedInstallPermission || replace) && !ps.installPermissionsFixed &&
12751                !isSystemApp(ps) || isUpdatedSystemApp(ps)){
12752            // This is the first that we have heard about this package, so the
12753            // permissions we have now selected are fixed until explicitly
12754            // changed.
12755            ps.installPermissionsFixed = true;
12756        }
12757
12758        // Persist the runtime permissions state for users with changes. If permissions
12759        // were revoked because no app in the shared user declares them we have to
12760        // write synchronously to avoid losing runtime permissions state.
12761        for (int userId : changedRuntimePermissionUserIds) {
12762            mSettings.writeRuntimePermissionsForUserLPr(userId, runtimePermissionsRevoked);
12763        }
12764    }
12765
12766    private boolean isNewPlatformPermissionForPackage(String perm, PackageParser.Package pkg) {
12767        boolean allowed = false;
12768        final int NP = PackageParser.NEW_PERMISSIONS.length;
12769        for (int ip=0; ip<NP; ip++) {
12770            final PackageParser.NewPermissionInfo npi
12771                    = PackageParser.NEW_PERMISSIONS[ip];
12772            if (npi.name.equals(perm)
12773                    && pkg.applicationInfo.targetSdkVersion < npi.sdkVersion) {
12774                allowed = true;
12775                Log.i(TAG, "Auto-granting " + perm + " to old pkg "
12776                        + pkg.packageName);
12777                break;
12778            }
12779        }
12780        return allowed;
12781    }
12782
12783    private boolean grantSignaturePermission(String perm, PackageParser.Package pkg,
12784            BasePermission bp, PermissionsState origPermissions) {
12785        boolean privilegedPermission = (bp.protectionLevel
12786                & PermissionInfo.PROTECTION_FLAG_PRIVILEGED) != 0;
12787        boolean privappPermissionsDisable =
12788                RoSystemProperties.CONTROL_PRIVAPP_PERMISSIONS_DISABLE;
12789        boolean platformPermission = PLATFORM_PACKAGE_NAME.equals(bp.sourcePackage);
12790        boolean platformPackage = PLATFORM_PACKAGE_NAME.equals(pkg.packageName);
12791        if (!privappPermissionsDisable && privilegedPermission && pkg.isPrivilegedApp()
12792                && !platformPackage && platformPermission) {
12793            ArraySet<String> wlPermissions = SystemConfig.getInstance()
12794                    .getPrivAppPermissions(pkg.packageName);
12795            boolean whitelisted = wlPermissions != null && wlPermissions.contains(perm);
12796            if (!whitelisted) {
12797                Slog.w(TAG, "Privileged permission " + perm + " for package "
12798                        + pkg.packageName + " - not in privapp-permissions whitelist");
12799                // Only report violations for apps on system image
12800                if (!mSystemReady && !pkg.isUpdatedSystemApp()) {
12801                    if (mPrivappPermissionsViolations == null) {
12802                        mPrivappPermissionsViolations = new ArraySet<>();
12803                    }
12804                    mPrivappPermissionsViolations.add(pkg.packageName + ": " + perm);
12805                }
12806                if (RoSystemProperties.CONTROL_PRIVAPP_PERMISSIONS_ENFORCE) {
12807                    return false;
12808                }
12809            }
12810        }
12811        boolean allowed = (compareSignatures(
12812                bp.packageSetting.signatures.mSignatures, pkg.mSignatures)
12813                        == PackageManager.SIGNATURE_MATCH)
12814                || (compareSignatures(mPlatformPackage.mSignatures, pkg.mSignatures)
12815                        == PackageManager.SIGNATURE_MATCH);
12816        if (!allowed && privilegedPermission) {
12817            if (isSystemApp(pkg)) {
12818                // For updated system applications, a system permission
12819                // is granted only if it had been defined by the original application.
12820                if (pkg.isUpdatedSystemApp()) {
12821                    final PackageSetting sysPs = mSettings
12822                            .getDisabledSystemPkgLPr(pkg.packageName);
12823                    if (sysPs != null && sysPs.getPermissionsState().hasInstallPermission(perm)) {
12824                        // If the original was granted this permission, we take
12825                        // that grant decision as read and propagate it to the
12826                        // update.
12827                        if (sysPs.isPrivileged()) {
12828                            allowed = true;
12829                        }
12830                    } else {
12831                        // The system apk may have been updated with an older
12832                        // version of the one on the data partition, but which
12833                        // granted a new system permission that it didn't have
12834                        // before.  In this case we do want to allow the app to
12835                        // now get the new permission if the ancestral apk is
12836                        // privileged to get it.
12837                        if (sysPs != null && sysPs.pkg != null && sysPs.isPrivileged()) {
12838                            for (int j = 0; j < sysPs.pkg.requestedPermissions.size(); j++) {
12839                                if (perm.equals(sysPs.pkg.requestedPermissions.get(j))) {
12840                                    allowed = true;
12841                                    break;
12842                                }
12843                            }
12844                        }
12845                        // Also if a privileged parent package on the system image or any of
12846                        // its children requested a privileged permission, the updated child
12847                        // packages can also get the permission.
12848                        if (pkg.parentPackage != null) {
12849                            final PackageSetting disabledSysParentPs = mSettings
12850                                    .getDisabledSystemPkgLPr(pkg.parentPackage.packageName);
12851                            if (disabledSysParentPs != null && disabledSysParentPs.pkg != null
12852                                    && disabledSysParentPs.isPrivileged()) {
12853                                if (isPackageRequestingPermission(disabledSysParentPs.pkg, perm)) {
12854                                    allowed = true;
12855                                } else if (disabledSysParentPs.pkg.childPackages != null) {
12856                                    final int count = disabledSysParentPs.pkg.childPackages.size();
12857                                    for (int i = 0; i < count; i++) {
12858                                        PackageParser.Package disabledSysChildPkg =
12859                                                disabledSysParentPs.pkg.childPackages.get(i);
12860                                        if (isPackageRequestingPermission(disabledSysChildPkg,
12861                                                perm)) {
12862                                            allowed = true;
12863                                            break;
12864                                        }
12865                                    }
12866                                }
12867                            }
12868                        }
12869                    }
12870                } else {
12871                    allowed = isPrivilegedApp(pkg);
12872                }
12873            }
12874        }
12875        if (!allowed) {
12876            if (!allowed && (bp.protectionLevel
12877                    & PermissionInfo.PROTECTION_FLAG_PRE23) != 0
12878                    && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) {
12879                // If this was a previously normal/dangerous permission that got moved
12880                // to a system permission as part of the runtime permission redesign, then
12881                // we still want to blindly grant it to old apps.
12882                allowed = true;
12883            }
12884            if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_INSTALLER) != 0
12885                    && pkg.packageName.equals(mRequiredInstallerPackage)) {
12886                // If this permission is to be granted to the system installer and
12887                // this app is an installer, then it gets the permission.
12888                allowed = true;
12889            }
12890            if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_VERIFIER) != 0
12891                    && pkg.packageName.equals(mRequiredVerifierPackage)) {
12892                // If this permission is to be granted to the system verifier and
12893                // this app is a verifier, then it gets the permission.
12894                allowed = true;
12895            }
12896            if (!allowed && (bp.protectionLevel
12897                    & PermissionInfo.PROTECTION_FLAG_PREINSTALLED) != 0
12898                    && isSystemApp(pkg)) {
12899                // Any pre-installed system app is allowed to get this permission.
12900                allowed = true;
12901            }
12902            if (!allowed && (bp.protectionLevel
12903                    & PermissionInfo.PROTECTION_FLAG_DEVELOPMENT) != 0) {
12904                // For development permissions, a development permission
12905                // is granted only if it was already granted.
12906                allowed = origPermissions.hasInstallPermission(perm);
12907            }
12908            if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_SETUP) != 0
12909                    && pkg.packageName.equals(mSetupWizardPackage)) {
12910                // If this permission is to be granted to the system setup wizard and
12911                // this app is a setup wizard, then it gets the permission.
12912                allowed = true;
12913            }
12914        }
12915        return allowed;
12916    }
12917
12918    private boolean isPackageRequestingPermission(PackageParser.Package pkg, String permission) {
12919        final int permCount = pkg.requestedPermissions.size();
12920        for (int j = 0; j < permCount; j++) {
12921            String requestedPermission = pkg.requestedPermissions.get(j);
12922            if (permission.equals(requestedPermission)) {
12923                return true;
12924            }
12925        }
12926        return false;
12927    }
12928
12929    final class ActivityIntentResolver
12930            extends IntentResolver<PackageParser.ActivityIntentInfo, ResolveInfo> {
12931        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
12932                boolean defaultOnly, int userId) {
12933            if (!sUserManager.exists(userId)) return null;
12934            mFlags = (defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0);
12935            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
12936        }
12937
12938        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
12939                int userId) {
12940            if (!sUserManager.exists(userId)) return null;
12941            mFlags = flags;
12942            return super.queryIntent(intent, resolvedType,
12943                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0,
12944                    userId);
12945        }
12946
12947        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
12948                int flags, ArrayList<PackageParser.Activity> packageActivities, int userId) {
12949            if (!sUserManager.exists(userId)) return null;
12950            if (packageActivities == null) {
12951                return null;
12952            }
12953            mFlags = flags;
12954            final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0;
12955            final int N = packageActivities.size();
12956            ArrayList<PackageParser.ActivityIntentInfo[]> listCut =
12957                new ArrayList<PackageParser.ActivityIntentInfo[]>(N);
12958
12959            ArrayList<PackageParser.ActivityIntentInfo> intentFilters;
12960            for (int i = 0; i < N; ++i) {
12961                intentFilters = packageActivities.get(i).intents;
12962                if (intentFilters != null && intentFilters.size() > 0) {
12963                    PackageParser.ActivityIntentInfo[] array =
12964                            new PackageParser.ActivityIntentInfo[intentFilters.size()];
12965                    intentFilters.toArray(array);
12966                    listCut.add(array);
12967                }
12968            }
12969            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
12970        }
12971
12972        /**
12973         * Finds a privileged activity that matches the specified activity names.
12974         */
12975        private PackageParser.Activity findMatchingActivity(
12976                List<PackageParser.Activity> activityList, ActivityInfo activityInfo) {
12977            for (PackageParser.Activity sysActivity : activityList) {
12978                if (sysActivity.info.name.equals(activityInfo.name)) {
12979                    return sysActivity;
12980                }
12981                if (sysActivity.info.name.equals(activityInfo.targetActivity)) {
12982                    return sysActivity;
12983                }
12984                if (sysActivity.info.targetActivity != null) {
12985                    if (sysActivity.info.targetActivity.equals(activityInfo.name)) {
12986                        return sysActivity;
12987                    }
12988                    if (sysActivity.info.targetActivity.equals(activityInfo.targetActivity)) {
12989                        return sysActivity;
12990                    }
12991                }
12992            }
12993            return null;
12994        }
12995
12996        public class IterGenerator<E> {
12997            public Iterator<E> generate(ActivityIntentInfo info) {
12998                return null;
12999            }
13000        }
13001
13002        public class ActionIterGenerator extends IterGenerator<String> {
13003            @Override
13004            public Iterator<String> generate(ActivityIntentInfo info) {
13005                return info.actionsIterator();
13006            }
13007        }
13008
13009        public class CategoriesIterGenerator extends IterGenerator<String> {
13010            @Override
13011            public Iterator<String> generate(ActivityIntentInfo info) {
13012                return info.categoriesIterator();
13013            }
13014        }
13015
13016        public class SchemesIterGenerator extends IterGenerator<String> {
13017            @Override
13018            public Iterator<String> generate(ActivityIntentInfo info) {
13019                return info.schemesIterator();
13020            }
13021        }
13022
13023        public class AuthoritiesIterGenerator extends IterGenerator<IntentFilter.AuthorityEntry> {
13024            @Override
13025            public Iterator<IntentFilter.AuthorityEntry> generate(ActivityIntentInfo info) {
13026                return info.authoritiesIterator();
13027            }
13028        }
13029
13030        /**
13031         * <em>WARNING</em> for performance reasons, the passed in intentList WILL BE
13032         * MODIFIED. Do not pass in a list that should not be changed.
13033         */
13034        private <T> void getIntentListSubset(List<ActivityIntentInfo> intentList,
13035                IterGenerator<T> generator, Iterator<T> searchIterator) {
13036            // loop through the set of actions; every one must be found in the intent filter
13037            while (searchIterator.hasNext()) {
13038                // we must have at least one filter in the list to consider a match
13039                if (intentList.size() == 0) {
13040                    break;
13041                }
13042
13043                final T searchAction = searchIterator.next();
13044
13045                // loop through the set of intent filters
13046                final Iterator<ActivityIntentInfo> intentIter = intentList.iterator();
13047                while (intentIter.hasNext()) {
13048                    final ActivityIntentInfo intentInfo = intentIter.next();
13049                    boolean selectionFound = false;
13050
13051                    // loop through the intent filter's selection criteria; at least one
13052                    // of them must match the searched criteria
13053                    final Iterator<T> intentSelectionIter = generator.generate(intentInfo);
13054                    while (intentSelectionIter != null && intentSelectionIter.hasNext()) {
13055                        final T intentSelection = intentSelectionIter.next();
13056                        if (intentSelection != null && intentSelection.equals(searchAction)) {
13057                            selectionFound = true;
13058                            break;
13059                        }
13060                    }
13061
13062                    // the selection criteria wasn't found in this filter's set; this filter
13063                    // is not a potential match
13064                    if (!selectionFound) {
13065                        intentIter.remove();
13066                    }
13067                }
13068            }
13069        }
13070
13071        private boolean isProtectedAction(ActivityIntentInfo filter) {
13072            final Iterator<String> actionsIter = filter.actionsIterator();
13073            while (actionsIter != null && actionsIter.hasNext()) {
13074                final String filterAction = actionsIter.next();
13075                if (PROTECTED_ACTIONS.contains(filterAction)) {
13076                    return true;
13077                }
13078            }
13079            return false;
13080        }
13081
13082        /**
13083         * Adjusts the priority of the given intent filter according to policy.
13084         * <p>
13085         * <ul>
13086         * <li>The priority for non privileged applications is capped to '0'</li>
13087         * <li>The priority for protected actions on privileged applications is capped to '0'</li>
13088         * <li>The priority for unbundled updates to privileged applications is capped to the
13089         *      priority defined on the system partition</li>
13090         * </ul>
13091         * <p>
13092         * <em>NOTE:</em> There is one exception. For security reasons, the setup wizard is
13093         * allowed to obtain any priority on any action.
13094         */
13095        private void adjustPriority(
13096                List<PackageParser.Activity> systemActivities, ActivityIntentInfo intent) {
13097            // nothing to do; priority is fine as-is
13098            if (intent.getPriority() <= 0) {
13099                return;
13100            }
13101
13102            final ActivityInfo activityInfo = intent.activity.info;
13103            final ApplicationInfo applicationInfo = activityInfo.applicationInfo;
13104
13105            final boolean privilegedApp =
13106                    ((applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0);
13107            if (!privilegedApp) {
13108                // non-privileged applications can never define a priority >0
13109                if (DEBUG_FILTERS) {
13110                    Slog.i(TAG, "Non-privileged app; cap priority to 0;"
13111                            + " package: " + applicationInfo.packageName
13112                            + " activity: " + intent.activity.className
13113                            + " origPrio: " + intent.getPriority());
13114                }
13115                intent.setPriority(0);
13116                return;
13117            }
13118
13119            if (systemActivities == null) {
13120                // the system package is not disabled; we're parsing the system partition
13121                if (isProtectedAction(intent)) {
13122                    if (mDeferProtectedFilters) {
13123                        // We can't deal with these just yet. No component should ever obtain a
13124                        // >0 priority for a protected actions, with ONE exception -- the setup
13125                        // wizard. The setup wizard, however, cannot be known until we're able to
13126                        // query it for the category CATEGORY_SETUP_WIZARD. Which we can't do
13127                        // until all intent filters have been processed. Chicken, meet egg.
13128                        // Let the filter temporarily have a high priority and rectify the
13129                        // priorities after all system packages have been scanned.
13130                        mProtectedFilters.add(intent);
13131                        if (DEBUG_FILTERS) {
13132                            Slog.i(TAG, "Protected action; save for later;"
13133                                    + " package: " + applicationInfo.packageName
13134                                    + " activity: " + intent.activity.className
13135                                    + " origPrio: " + intent.getPriority());
13136                        }
13137                        return;
13138                    } else {
13139                        if (DEBUG_FILTERS && mSetupWizardPackage == null) {
13140                            Slog.i(TAG, "No setup wizard;"
13141                                + " All protected intents capped to priority 0");
13142                        }
13143                        if (intent.activity.info.packageName.equals(mSetupWizardPackage)) {
13144                            if (DEBUG_FILTERS) {
13145                                Slog.i(TAG, "Found setup wizard;"
13146                                    + " allow priority " + intent.getPriority() + ";"
13147                                    + " package: " + intent.activity.info.packageName
13148                                    + " activity: " + intent.activity.className
13149                                    + " priority: " + intent.getPriority());
13150                            }
13151                            // setup wizard gets whatever it wants
13152                            return;
13153                        }
13154                        if (DEBUG_FILTERS) {
13155                            Slog.i(TAG, "Protected action; cap priority to 0;"
13156                                    + " package: " + intent.activity.info.packageName
13157                                    + " activity: " + intent.activity.className
13158                                    + " origPrio: " + intent.getPriority());
13159                        }
13160                        intent.setPriority(0);
13161                        return;
13162                    }
13163                }
13164                // privileged apps on the system image get whatever priority they request
13165                return;
13166            }
13167
13168            // privileged app unbundled update ... try to find the same activity
13169            final PackageParser.Activity foundActivity =
13170                    findMatchingActivity(systemActivities, activityInfo);
13171            if (foundActivity == null) {
13172                // this is a new activity; it cannot obtain >0 priority
13173                if (DEBUG_FILTERS) {
13174                    Slog.i(TAG, "New activity; cap priority to 0;"
13175                            + " package: " + applicationInfo.packageName
13176                            + " activity: " + intent.activity.className
13177                            + " origPrio: " + intent.getPriority());
13178                }
13179                intent.setPriority(0);
13180                return;
13181            }
13182
13183            // found activity, now check for filter equivalence
13184
13185            // a shallow copy is enough; we modify the list, not its contents
13186            final List<ActivityIntentInfo> intentListCopy =
13187                    new ArrayList<>(foundActivity.intents);
13188            final List<ActivityIntentInfo> foundFilters = findFilters(intent);
13189
13190            // find matching action subsets
13191            final Iterator<String> actionsIterator = intent.actionsIterator();
13192            if (actionsIterator != null) {
13193                getIntentListSubset(
13194                        intentListCopy, new ActionIterGenerator(), actionsIterator);
13195                if (intentListCopy.size() == 0) {
13196                    // no more intents to match; we're not equivalent
13197                    if (DEBUG_FILTERS) {
13198                        Slog.i(TAG, "Mismatched action; cap priority to 0;"
13199                                + " package: " + applicationInfo.packageName
13200                                + " activity: " + intent.activity.className
13201                                + " origPrio: " + intent.getPriority());
13202                    }
13203                    intent.setPriority(0);
13204                    return;
13205                }
13206            }
13207
13208            // find matching category subsets
13209            final Iterator<String> categoriesIterator = intent.categoriesIterator();
13210            if (categoriesIterator != null) {
13211                getIntentListSubset(intentListCopy, new CategoriesIterGenerator(),
13212                        categoriesIterator);
13213                if (intentListCopy.size() == 0) {
13214                    // no more intents to match; we're not equivalent
13215                    if (DEBUG_FILTERS) {
13216                        Slog.i(TAG, "Mismatched category; cap priority to 0;"
13217                                + " package: " + applicationInfo.packageName
13218                                + " activity: " + intent.activity.className
13219                                + " origPrio: " + intent.getPriority());
13220                    }
13221                    intent.setPriority(0);
13222                    return;
13223                }
13224            }
13225
13226            // find matching schemes subsets
13227            final Iterator<String> schemesIterator = intent.schemesIterator();
13228            if (schemesIterator != null) {
13229                getIntentListSubset(intentListCopy, new SchemesIterGenerator(),
13230                        schemesIterator);
13231                if (intentListCopy.size() == 0) {
13232                    // no more intents to match; we're not equivalent
13233                    if (DEBUG_FILTERS) {
13234                        Slog.i(TAG, "Mismatched scheme; cap priority to 0;"
13235                                + " package: " + applicationInfo.packageName
13236                                + " activity: " + intent.activity.className
13237                                + " origPrio: " + intent.getPriority());
13238                    }
13239                    intent.setPriority(0);
13240                    return;
13241                }
13242            }
13243
13244            // find matching authorities subsets
13245            final Iterator<IntentFilter.AuthorityEntry>
13246                    authoritiesIterator = intent.authoritiesIterator();
13247            if (authoritiesIterator != null) {
13248                getIntentListSubset(intentListCopy,
13249                        new AuthoritiesIterGenerator(),
13250                        authoritiesIterator);
13251                if (intentListCopy.size() == 0) {
13252                    // no more intents to match; we're not equivalent
13253                    if (DEBUG_FILTERS) {
13254                        Slog.i(TAG, "Mismatched authority; cap priority to 0;"
13255                                + " package: " + applicationInfo.packageName
13256                                + " activity: " + intent.activity.className
13257                                + " origPrio: " + intent.getPriority());
13258                    }
13259                    intent.setPriority(0);
13260                    return;
13261                }
13262            }
13263
13264            // we found matching filter(s); app gets the max priority of all intents
13265            int cappedPriority = 0;
13266            for (int i = intentListCopy.size() - 1; i >= 0; --i) {
13267                cappedPriority = Math.max(cappedPriority, intentListCopy.get(i).getPriority());
13268            }
13269            if (intent.getPriority() > cappedPriority) {
13270                if (DEBUG_FILTERS) {
13271                    Slog.i(TAG, "Found matching filter(s);"
13272                            + " cap priority to " + cappedPriority + ";"
13273                            + " package: " + applicationInfo.packageName
13274                            + " activity: " + intent.activity.className
13275                            + " origPrio: " + intent.getPriority());
13276                }
13277                intent.setPriority(cappedPriority);
13278                return;
13279            }
13280            // all this for nothing; the requested priority was <= what was on the system
13281        }
13282
13283        public final void addActivity(PackageParser.Activity a, String type) {
13284            mActivities.put(a.getComponentName(), a);
13285            if (DEBUG_SHOW_INFO)
13286                Log.v(
13287                TAG, "  " + type + " " +
13288                (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":");
13289            if (DEBUG_SHOW_INFO)
13290                Log.v(TAG, "    Class=" + a.info.name);
13291            final int NI = a.intents.size();
13292            for (int j=0; j<NI; j++) {
13293                PackageParser.ActivityIntentInfo intent = a.intents.get(j);
13294                if ("activity".equals(type)) {
13295                    final PackageSetting ps =
13296                            mSettings.getDisabledSystemPkgLPr(intent.activity.info.packageName);
13297                    final List<PackageParser.Activity> systemActivities =
13298                            ps != null && ps.pkg != null ? ps.pkg.activities : null;
13299                    adjustPriority(systemActivities, intent);
13300                }
13301                if (DEBUG_SHOW_INFO) {
13302                    Log.v(TAG, "    IntentFilter:");
13303                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
13304                }
13305                if (!intent.debugCheck()) {
13306                    Log.w(TAG, "==> For Activity " + a.info.name);
13307                }
13308                addFilter(intent);
13309            }
13310        }
13311
13312        public final void removeActivity(PackageParser.Activity a, String type) {
13313            mActivities.remove(a.getComponentName());
13314            if (DEBUG_SHOW_INFO) {
13315                Log.v(TAG, "  " + type + " "
13316                        + (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel
13317                                : a.info.name) + ":");
13318                Log.v(TAG, "    Class=" + a.info.name);
13319            }
13320            final int NI = a.intents.size();
13321            for (int j=0; j<NI; j++) {
13322                PackageParser.ActivityIntentInfo intent = a.intents.get(j);
13323                if (DEBUG_SHOW_INFO) {
13324                    Log.v(TAG, "    IntentFilter:");
13325                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
13326                }
13327                removeFilter(intent);
13328            }
13329        }
13330
13331        @Override
13332        protected boolean allowFilterResult(
13333                PackageParser.ActivityIntentInfo filter, List<ResolveInfo> dest) {
13334            ActivityInfo filterAi = filter.activity.info;
13335            for (int i=dest.size()-1; i>=0; i--) {
13336                ActivityInfo destAi = dest.get(i).activityInfo;
13337                if (destAi.name == filterAi.name
13338                        && destAi.packageName == filterAi.packageName) {
13339                    return false;
13340                }
13341            }
13342            return true;
13343        }
13344
13345        @Override
13346        protected ActivityIntentInfo[] newArray(int size) {
13347            return new ActivityIntentInfo[size];
13348        }
13349
13350        @Override
13351        protected boolean isFilterStopped(PackageParser.ActivityIntentInfo filter, int userId) {
13352            if (!sUserManager.exists(userId)) return true;
13353            PackageParser.Package p = filter.activity.owner;
13354            if (p != null) {
13355                PackageSetting ps = (PackageSetting)p.mExtras;
13356                if (ps != null) {
13357                    // System apps are never considered stopped for purposes of
13358                    // filtering, because there may be no way for the user to
13359                    // actually re-launch them.
13360                    return (ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0
13361                            && ps.getStopped(userId);
13362                }
13363            }
13364            return false;
13365        }
13366
13367        @Override
13368        protected boolean isPackageForFilter(String packageName,
13369                PackageParser.ActivityIntentInfo info) {
13370            return packageName.equals(info.activity.owner.packageName);
13371        }
13372
13373        @Override
13374        protected ResolveInfo newResult(PackageParser.ActivityIntentInfo info,
13375                int match, int userId) {
13376            if (!sUserManager.exists(userId)) return null;
13377            if (!mSettings.isEnabledAndMatchLPr(info.activity.info, mFlags, userId)) {
13378                return null;
13379            }
13380            final PackageParser.Activity activity = info.activity;
13381            PackageSetting ps = (PackageSetting) activity.owner.mExtras;
13382            if (ps == null) {
13383                return null;
13384            }
13385            final PackageUserState userState = ps.readUserState(userId);
13386            ActivityInfo ai =
13387                    PackageParser.generateActivityInfo(activity, mFlags, userState, userId);
13388            if (ai == null) {
13389                return null;
13390            }
13391            final boolean matchExplicitlyVisibleOnly =
13392                    (mFlags & PackageManager.MATCH_EXPLICITLY_VISIBLE_ONLY) != 0;
13393            final boolean matchVisibleToInstantApp =
13394                    (mFlags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
13395            final boolean componentVisible =
13396                    matchVisibleToInstantApp
13397                    && info.isVisibleToInstantApp()
13398                    && (!matchExplicitlyVisibleOnly || info.isExplicitlyVisibleToInstantApp());
13399            final boolean matchInstantApp = (mFlags & PackageManager.MATCH_INSTANT) != 0;
13400            // throw out filters that aren't visible to ephemeral apps
13401            if (matchVisibleToInstantApp && !(componentVisible || userState.instantApp)) {
13402                return null;
13403            }
13404            // throw out instant app filters if we're not explicitly requesting them
13405            if (!matchInstantApp && userState.instantApp) {
13406                return null;
13407            }
13408            // throw out instant app filters if updates are available; will trigger
13409            // instant app resolution
13410            if (userState.instantApp && ps.isUpdateAvailable()) {
13411                return null;
13412            }
13413            final ResolveInfo res = new ResolveInfo();
13414            res.activityInfo = ai;
13415            if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
13416                res.filter = info;
13417            }
13418            if (info != null) {
13419                res.handleAllWebDataURI = info.handleAllWebDataURI();
13420            }
13421            res.priority = info.getPriority();
13422            res.preferredOrder = activity.owner.mPreferredOrder;
13423            //System.out.println("Result: " + res.activityInfo.className +
13424            //                   " = " + res.priority);
13425            res.match = match;
13426            res.isDefault = info.hasDefault;
13427            res.labelRes = info.labelRes;
13428            res.nonLocalizedLabel = info.nonLocalizedLabel;
13429            if (userNeedsBadging(userId)) {
13430                res.noResourceId = true;
13431            } else {
13432                res.icon = info.icon;
13433            }
13434            res.iconResourceId = info.icon;
13435            res.system = res.activityInfo.applicationInfo.isSystemApp();
13436            res.isInstantAppAvailable = userState.instantApp;
13437            return res;
13438        }
13439
13440        @Override
13441        protected void sortResults(List<ResolveInfo> results) {
13442            Collections.sort(results, mResolvePrioritySorter);
13443        }
13444
13445        @Override
13446        protected void dumpFilter(PrintWriter out, String prefix,
13447                PackageParser.ActivityIntentInfo filter) {
13448            out.print(prefix); out.print(
13449                    Integer.toHexString(System.identityHashCode(filter.activity)));
13450                    out.print(' ');
13451                    filter.activity.printComponentShortName(out);
13452                    out.print(" filter ");
13453                    out.println(Integer.toHexString(System.identityHashCode(filter)));
13454        }
13455
13456        @Override
13457        protected Object filterToLabel(PackageParser.ActivityIntentInfo filter) {
13458            return filter.activity;
13459        }
13460
13461        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
13462            PackageParser.Activity activity = (PackageParser.Activity)label;
13463            out.print(prefix); out.print(
13464                    Integer.toHexString(System.identityHashCode(activity)));
13465                    out.print(' ');
13466                    activity.printComponentShortName(out);
13467            if (count > 1) {
13468                out.print(" ("); out.print(count); out.print(" filters)");
13469            }
13470            out.println();
13471        }
13472
13473        // Keys are String (activity class name), values are Activity.
13474        private final ArrayMap<ComponentName, PackageParser.Activity> mActivities
13475                = new ArrayMap<ComponentName, PackageParser.Activity>();
13476        private int mFlags;
13477    }
13478
13479    private final class ServiceIntentResolver
13480            extends IntentResolver<PackageParser.ServiceIntentInfo, ResolveInfo> {
13481        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
13482                boolean defaultOnly, int userId) {
13483            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
13484            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
13485        }
13486
13487        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
13488                int userId) {
13489            if (!sUserManager.exists(userId)) return null;
13490            mFlags = flags;
13491            return super.queryIntent(intent, resolvedType,
13492                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0,
13493                    userId);
13494        }
13495
13496        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
13497                int flags, ArrayList<PackageParser.Service> packageServices, int userId) {
13498            if (!sUserManager.exists(userId)) return null;
13499            if (packageServices == null) {
13500                return null;
13501            }
13502            mFlags = flags;
13503            final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0;
13504            final int N = packageServices.size();
13505            ArrayList<PackageParser.ServiceIntentInfo[]> listCut =
13506                new ArrayList<PackageParser.ServiceIntentInfo[]>(N);
13507
13508            ArrayList<PackageParser.ServiceIntentInfo> intentFilters;
13509            for (int i = 0; i < N; ++i) {
13510                intentFilters = packageServices.get(i).intents;
13511                if (intentFilters != null && intentFilters.size() > 0) {
13512                    PackageParser.ServiceIntentInfo[] array =
13513                            new PackageParser.ServiceIntentInfo[intentFilters.size()];
13514                    intentFilters.toArray(array);
13515                    listCut.add(array);
13516                }
13517            }
13518            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
13519        }
13520
13521        public final void addService(PackageParser.Service s) {
13522            mServices.put(s.getComponentName(), s);
13523            if (DEBUG_SHOW_INFO) {
13524                Log.v(TAG, "  "
13525                        + (s.info.nonLocalizedLabel != null
13526                        ? s.info.nonLocalizedLabel : s.info.name) + ":");
13527                Log.v(TAG, "    Class=" + s.info.name);
13528            }
13529            final int NI = s.intents.size();
13530            int j;
13531            for (j=0; j<NI; j++) {
13532                PackageParser.ServiceIntentInfo intent = s.intents.get(j);
13533                if (DEBUG_SHOW_INFO) {
13534                    Log.v(TAG, "    IntentFilter:");
13535                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
13536                }
13537                if (!intent.debugCheck()) {
13538                    Log.w(TAG, "==> For Service " + s.info.name);
13539                }
13540                addFilter(intent);
13541            }
13542        }
13543
13544        public final void removeService(PackageParser.Service s) {
13545            mServices.remove(s.getComponentName());
13546            if (DEBUG_SHOW_INFO) {
13547                Log.v(TAG, "  " + (s.info.nonLocalizedLabel != null
13548                        ? s.info.nonLocalizedLabel : s.info.name) + ":");
13549                Log.v(TAG, "    Class=" + s.info.name);
13550            }
13551            final int NI = s.intents.size();
13552            int j;
13553            for (j=0; j<NI; j++) {
13554                PackageParser.ServiceIntentInfo intent = s.intents.get(j);
13555                if (DEBUG_SHOW_INFO) {
13556                    Log.v(TAG, "    IntentFilter:");
13557                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
13558                }
13559                removeFilter(intent);
13560            }
13561        }
13562
13563        @Override
13564        protected boolean allowFilterResult(
13565                PackageParser.ServiceIntentInfo filter, List<ResolveInfo> dest) {
13566            ServiceInfo filterSi = filter.service.info;
13567            for (int i=dest.size()-1; i>=0; i--) {
13568                ServiceInfo destAi = dest.get(i).serviceInfo;
13569                if (destAi.name == filterSi.name
13570                        && destAi.packageName == filterSi.packageName) {
13571                    return false;
13572                }
13573            }
13574            return true;
13575        }
13576
13577        @Override
13578        protected PackageParser.ServiceIntentInfo[] newArray(int size) {
13579            return new PackageParser.ServiceIntentInfo[size];
13580        }
13581
13582        @Override
13583        protected boolean isFilterStopped(PackageParser.ServiceIntentInfo filter, int userId) {
13584            if (!sUserManager.exists(userId)) return true;
13585            PackageParser.Package p = filter.service.owner;
13586            if (p != null) {
13587                PackageSetting ps = (PackageSetting)p.mExtras;
13588                if (ps != null) {
13589                    // System apps are never considered stopped for purposes of
13590                    // filtering, because there may be no way for the user to
13591                    // actually re-launch them.
13592                    return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0
13593                            && ps.getStopped(userId);
13594                }
13595            }
13596            return false;
13597        }
13598
13599        @Override
13600        protected boolean isPackageForFilter(String packageName,
13601                PackageParser.ServiceIntentInfo info) {
13602            return packageName.equals(info.service.owner.packageName);
13603        }
13604
13605        @Override
13606        protected ResolveInfo newResult(PackageParser.ServiceIntentInfo filter,
13607                int match, int userId) {
13608            if (!sUserManager.exists(userId)) return null;
13609            final PackageParser.ServiceIntentInfo info = (PackageParser.ServiceIntentInfo)filter;
13610            if (!mSettings.isEnabledAndMatchLPr(info.service.info, mFlags, userId)) {
13611                return null;
13612            }
13613            final PackageParser.Service service = info.service;
13614            PackageSetting ps = (PackageSetting) service.owner.mExtras;
13615            if (ps == null) {
13616                return null;
13617            }
13618            final PackageUserState userState = ps.readUserState(userId);
13619            ServiceInfo si = PackageParser.generateServiceInfo(service, mFlags,
13620                    userState, userId);
13621            if (si == null) {
13622                return null;
13623            }
13624            final boolean matchVisibleToInstantApp =
13625                    (mFlags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
13626            final boolean isInstantApp = (mFlags & PackageManager.MATCH_INSTANT) != 0;
13627            // throw out filters that aren't visible to ephemeral apps
13628            if (matchVisibleToInstantApp
13629                    && !(info.isVisibleToInstantApp() || userState.instantApp)) {
13630                return null;
13631            }
13632            // throw out ephemeral filters if we're not explicitly requesting them
13633            if (!isInstantApp && userState.instantApp) {
13634                return null;
13635            }
13636            // throw out instant app filters if updates are available; will trigger
13637            // instant app resolution
13638            if (userState.instantApp && ps.isUpdateAvailable()) {
13639                return null;
13640            }
13641            final ResolveInfo res = new ResolveInfo();
13642            res.serviceInfo = si;
13643            if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
13644                res.filter = filter;
13645            }
13646            res.priority = info.getPriority();
13647            res.preferredOrder = service.owner.mPreferredOrder;
13648            res.match = match;
13649            res.isDefault = info.hasDefault;
13650            res.labelRes = info.labelRes;
13651            res.nonLocalizedLabel = info.nonLocalizedLabel;
13652            res.icon = info.icon;
13653            res.system = res.serviceInfo.applicationInfo.isSystemApp();
13654            return res;
13655        }
13656
13657        @Override
13658        protected void sortResults(List<ResolveInfo> results) {
13659            Collections.sort(results, mResolvePrioritySorter);
13660        }
13661
13662        @Override
13663        protected void dumpFilter(PrintWriter out, String prefix,
13664                PackageParser.ServiceIntentInfo filter) {
13665            out.print(prefix); out.print(
13666                    Integer.toHexString(System.identityHashCode(filter.service)));
13667                    out.print(' ');
13668                    filter.service.printComponentShortName(out);
13669                    out.print(" filter ");
13670                    out.println(Integer.toHexString(System.identityHashCode(filter)));
13671        }
13672
13673        @Override
13674        protected Object filterToLabel(PackageParser.ServiceIntentInfo filter) {
13675            return filter.service;
13676        }
13677
13678        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
13679            PackageParser.Service service = (PackageParser.Service)label;
13680            out.print(prefix); out.print(
13681                    Integer.toHexString(System.identityHashCode(service)));
13682                    out.print(' ');
13683                    service.printComponentShortName(out);
13684            if (count > 1) {
13685                out.print(" ("); out.print(count); out.print(" filters)");
13686            }
13687            out.println();
13688        }
13689
13690//        List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) {
13691//            final Iterator<ResolveInfo> i = resolveInfoList.iterator();
13692//            final List<ResolveInfo> retList = Lists.newArrayList();
13693//            while (i.hasNext()) {
13694//                final ResolveInfo resolveInfo = (ResolveInfo) i;
13695//                if (isEnabledLP(resolveInfo.serviceInfo)) {
13696//                    retList.add(resolveInfo);
13697//                }
13698//            }
13699//            return retList;
13700//        }
13701
13702        // Keys are String (activity class name), values are Activity.
13703        private final ArrayMap<ComponentName, PackageParser.Service> mServices
13704                = new ArrayMap<ComponentName, PackageParser.Service>();
13705        private int mFlags;
13706    }
13707
13708    private final class ProviderIntentResolver
13709            extends IntentResolver<PackageParser.ProviderIntentInfo, ResolveInfo> {
13710        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
13711                boolean defaultOnly, int userId) {
13712            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
13713            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
13714        }
13715
13716        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
13717                int userId) {
13718            if (!sUserManager.exists(userId))
13719                return null;
13720            mFlags = flags;
13721            return super.queryIntent(intent, resolvedType,
13722                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0,
13723                    userId);
13724        }
13725
13726        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
13727                int flags, ArrayList<PackageParser.Provider> packageProviders, int userId) {
13728            if (!sUserManager.exists(userId))
13729                return null;
13730            if (packageProviders == null) {
13731                return null;
13732            }
13733            mFlags = flags;
13734            final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0;
13735            final int N = packageProviders.size();
13736            ArrayList<PackageParser.ProviderIntentInfo[]> listCut =
13737                    new ArrayList<PackageParser.ProviderIntentInfo[]>(N);
13738
13739            ArrayList<PackageParser.ProviderIntentInfo> intentFilters;
13740            for (int i = 0; i < N; ++i) {
13741                intentFilters = packageProviders.get(i).intents;
13742                if (intentFilters != null && intentFilters.size() > 0) {
13743                    PackageParser.ProviderIntentInfo[] array =
13744                            new PackageParser.ProviderIntentInfo[intentFilters.size()];
13745                    intentFilters.toArray(array);
13746                    listCut.add(array);
13747                }
13748            }
13749            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
13750        }
13751
13752        public final void addProvider(PackageParser.Provider p) {
13753            if (mProviders.containsKey(p.getComponentName())) {
13754                Slog.w(TAG, "Provider " + p.getComponentName() + " already defined; ignoring");
13755                return;
13756            }
13757
13758            mProviders.put(p.getComponentName(), p);
13759            if (DEBUG_SHOW_INFO) {
13760                Log.v(TAG, "  "
13761                        + (p.info.nonLocalizedLabel != null
13762                                ? p.info.nonLocalizedLabel : p.info.name) + ":");
13763                Log.v(TAG, "    Class=" + p.info.name);
13764            }
13765            final int NI = p.intents.size();
13766            int j;
13767            for (j = 0; j < NI; j++) {
13768                PackageParser.ProviderIntentInfo intent = p.intents.get(j);
13769                if (DEBUG_SHOW_INFO) {
13770                    Log.v(TAG, "    IntentFilter:");
13771                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
13772                }
13773                if (!intent.debugCheck()) {
13774                    Log.w(TAG, "==> For Provider " + p.info.name);
13775                }
13776                addFilter(intent);
13777            }
13778        }
13779
13780        public final void removeProvider(PackageParser.Provider p) {
13781            mProviders.remove(p.getComponentName());
13782            if (DEBUG_SHOW_INFO) {
13783                Log.v(TAG, "  " + (p.info.nonLocalizedLabel != null
13784                        ? p.info.nonLocalizedLabel : p.info.name) + ":");
13785                Log.v(TAG, "    Class=" + p.info.name);
13786            }
13787            final int NI = p.intents.size();
13788            int j;
13789            for (j = 0; j < NI; j++) {
13790                PackageParser.ProviderIntentInfo intent = p.intents.get(j);
13791                if (DEBUG_SHOW_INFO) {
13792                    Log.v(TAG, "    IntentFilter:");
13793                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
13794                }
13795                removeFilter(intent);
13796            }
13797        }
13798
13799        @Override
13800        protected boolean allowFilterResult(
13801                PackageParser.ProviderIntentInfo filter, List<ResolveInfo> dest) {
13802            ProviderInfo filterPi = filter.provider.info;
13803            for (int i = dest.size() - 1; i >= 0; i--) {
13804                ProviderInfo destPi = dest.get(i).providerInfo;
13805                if (destPi.name == filterPi.name
13806                        && destPi.packageName == filterPi.packageName) {
13807                    return false;
13808                }
13809            }
13810            return true;
13811        }
13812
13813        @Override
13814        protected PackageParser.ProviderIntentInfo[] newArray(int size) {
13815            return new PackageParser.ProviderIntentInfo[size];
13816        }
13817
13818        @Override
13819        protected boolean isFilterStopped(PackageParser.ProviderIntentInfo filter, int userId) {
13820            if (!sUserManager.exists(userId))
13821                return true;
13822            PackageParser.Package p = filter.provider.owner;
13823            if (p != null) {
13824                PackageSetting ps = (PackageSetting) p.mExtras;
13825                if (ps != null) {
13826                    // System apps are never considered stopped for purposes of
13827                    // filtering, because there may be no way for the user to
13828                    // actually re-launch them.
13829                    return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0
13830                            && ps.getStopped(userId);
13831                }
13832            }
13833            return false;
13834        }
13835
13836        @Override
13837        protected boolean isPackageForFilter(String packageName,
13838                PackageParser.ProviderIntentInfo info) {
13839            return packageName.equals(info.provider.owner.packageName);
13840        }
13841
13842        @Override
13843        protected ResolveInfo newResult(PackageParser.ProviderIntentInfo filter,
13844                int match, int userId) {
13845            if (!sUserManager.exists(userId))
13846                return null;
13847            final PackageParser.ProviderIntentInfo info = filter;
13848            if (!mSettings.isEnabledAndMatchLPr(info.provider.info, mFlags, userId)) {
13849                return null;
13850            }
13851            final PackageParser.Provider provider = info.provider;
13852            PackageSetting ps = (PackageSetting) provider.owner.mExtras;
13853            if (ps == null) {
13854                return null;
13855            }
13856            final PackageUserState userState = ps.readUserState(userId);
13857            final boolean matchVisibleToInstantApp =
13858                    (mFlags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
13859            final boolean isInstantApp = (mFlags & PackageManager.MATCH_INSTANT) != 0;
13860            // throw out filters that aren't visible to instant applications
13861            if (matchVisibleToInstantApp
13862                    && !(info.isVisibleToInstantApp() || userState.instantApp)) {
13863                return null;
13864            }
13865            // throw out instant application filters if we're not explicitly requesting them
13866            if (!isInstantApp && userState.instantApp) {
13867                return null;
13868            }
13869            // throw out instant application filters if updates are available; will trigger
13870            // instant application resolution
13871            if (userState.instantApp && ps.isUpdateAvailable()) {
13872                return null;
13873            }
13874            ProviderInfo pi = PackageParser.generateProviderInfo(provider, mFlags,
13875                    userState, userId);
13876            if (pi == null) {
13877                return null;
13878            }
13879            final ResolveInfo res = new ResolveInfo();
13880            res.providerInfo = pi;
13881            if ((mFlags & PackageManager.GET_RESOLVED_FILTER) != 0) {
13882                res.filter = filter;
13883            }
13884            res.priority = info.getPriority();
13885            res.preferredOrder = provider.owner.mPreferredOrder;
13886            res.match = match;
13887            res.isDefault = info.hasDefault;
13888            res.labelRes = info.labelRes;
13889            res.nonLocalizedLabel = info.nonLocalizedLabel;
13890            res.icon = info.icon;
13891            res.system = res.providerInfo.applicationInfo.isSystemApp();
13892            return res;
13893        }
13894
13895        @Override
13896        protected void sortResults(List<ResolveInfo> results) {
13897            Collections.sort(results, mResolvePrioritySorter);
13898        }
13899
13900        @Override
13901        protected void dumpFilter(PrintWriter out, String prefix,
13902                PackageParser.ProviderIntentInfo filter) {
13903            out.print(prefix);
13904            out.print(
13905                    Integer.toHexString(System.identityHashCode(filter.provider)));
13906            out.print(' ');
13907            filter.provider.printComponentShortName(out);
13908            out.print(" filter ");
13909            out.println(Integer.toHexString(System.identityHashCode(filter)));
13910        }
13911
13912        @Override
13913        protected Object filterToLabel(PackageParser.ProviderIntentInfo filter) {
13914            return filter.provider;
13915        }
13916
13917        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
13918            PackageParser.Provider provider = (PackageParser.Provider)label;
13919            out.print(prefix); out.print(
13920                    Integer.toHexString(System.identityHashCode(provider)));
13921                    out.print(' ');
13922                    provider.printComponentShortName(out);
13923            if (count > 1) {
13924                out.print(" ("); out.print(count); out.print(" filters)");
13925            }
13926            out.println();
13927        }
13928
13929        private final ArrayMap<ComponentName, PackageParser.Provider> mProviders
13930                = new ArrayMap<ComponentName, PackageParser.Provider>();
13931        private int mFlags;
13932    }
13933
13934    static final class EphemeralIntentResolver
13935            extends IntentResolver<AuxiliaryResolveInfo, AuxiliaryResolveInfo> {
13936        /**
13937         * The result that has the highest defined order. Ordering applies on a
13938         * per-package basis. Mapping is from package name to Pair of order and
13939         * EphemeralResolveInfo.
13940         * <p>
13941         * NOTE: This is implemented as a field variable for convenience and efficiency.
13942         * By having a field variable, we're able to track filter ordering as soon as
13943         * a non-zero order is defined. Otherwise, multiple loops across the result set
13944         * would be needed to apply ordering. If the intent resolver becomes re-entrant,
13945         * this needs to be contained entirely within {@link #filterResults}.
13946         */
13947        final ArrayMap<String, Pair<Integer, InstantAppResolveInfo>> mOrderResult = new ArrayMap<>();
13948
13949        @Override
13950        protected AuxiliaryResolveInfo[] newArray(int size) {
13951            return new AuxiliaryResolveInfo[size];
13952        }
13953
13954        @Override
13955        protected boolean isPackageForFilter(String packageName, AuxiliaryResolveInfo responseObj) {
13956            return true;
13957        }
13958
13959        @Override
13960        protected AuxiliaryResolveInfo newResult(AuxiliaryResolveInfo responseObj, int match,
13961                int userId) {
13962            if (!sUserManager.exists(userId)) {
13963                return null;
13964            }
13965            final String packageName = responseObj.resolveInfo.getPackageName();
13966            final Integer order = responseObj.getOrder();
13967            final Pair<Integer, InstantAppResolveInfo> lastOrderResult =
13968                    mOrderResult.get(packageName);
13969            // ordering is enabled and this item's order isn't high enough
13970            if (lastOrderResult != null && lastOrderResult.first >= order) {
13971                return null;
13972            }
13973            final InstantAppResolveInfo res = responseObj.resolveInfo;
13974            if (order > 0) {
13975                // non-zero order, enable ordering
13976                mOrderResult.put(packageName, new Pair<>(order, res));
13977            }
13978            return responseObj;
13979        }
13980
13981        @Override
13982        protected void filterResults(List<AuxiliaryResolveInfo> results) {
13983            // only do work if ordering is enabled [most of the time it won't be]
13984            if (mOrderResult.size() == 0) {
13985                return;
13986            }
13987            int resultSize = results.size();
13988            for (int i = 0; i < resultSize; i++) {
13989                final InstantAppResolveInfo info = results.get(i).resolveInfo;
13990                final String packageName = info.getPackageName();
13991                final Pair<Integer, InstantAppResolveInfo> savedInfo = mOrderResult.get(packageName);
13992                if (savedInfo == null) {
13993                    // package doesn't having ordering
13994                    continue;
13995                }
13996                if (savedInfo.second == info) {
13997                    // circled back to the highest ordered item; remove from order list
13998                    mOrderResult.remove(savedInfo);
13999                    if (mOrderResult.size() == 0) {
14000                        // no more ordered items
14001                        break;
14002                    }
14003                    continue;
14004                }
14005                // item has a worse order, remove it from the result list
14006                results.remove(i);
14007                resultSize--;
14008                i--;
14009            }
14010        }
14011    }
14012
14013    private static final Comparator<ResolveInfo> mResolvePrioritySorter =
14014            new Comparator<ResolveInfo>() {
14015        public int compare(ResolveInfo r1, ResolveInfo r2) {
14016            int v1 = r1.priority;
14017            int v2 = r2.priority;
14018            //System.out.println("Comparing: q1=" + q1 + " q2=" + q2);
14019            if (v1 != v2) {
14020                return (v1 > v2) ? -1 : 1;
14021            }
14022            v1 = r1.preferredOrder;
14023            v2 = r2.preferredOrder;
14024            if (v1 != v2) {
14025                return (v1 > v2) ? -1 : 1;
14026            }
14027            if (r1.isDefault != r2.isDefault) {
14028                return r1.isDefault ? -1 : 1;
14029            }
14030            v1 = r1.match;
14031            v2 = r2.match;
14032            //System.out.println("Comparing: m1=" + m1 + " m2=" + m2);
14033            if (v1 != v2) {
14034                return (v1 > v2) ? -1 : 1;
14035            }
14036            if (r1.system != r2.system) {
14037                return r1.system ? -1 : 1;
14038            }
14039            if (r1.activityInfo != null) {
14040                return r1.activityInfo.packageName.compareTo(r2.activityInfo.packageName);
14041            }
14042            if (r1.serviceInfo != null) {
14043                return r1.serviceInfo.packageName.compareTo(r2.serviceInfo.packageName);
14044            }
14045            if (r1.providerInfo != null) {
14046                return r1.providerInfo.packageName.compareTo(r2.providerInfo.packageName);
14047            }
14048            return 0;
14049        }
14050    };
14051
14052    private static final Comparator<ProviderInfo> mProviderInitOrderSorter =
14053            new Comparator<ProviderInfo>() {
14054        public int compare(ProviderInfo p1, ProviderInfo p2) {
14055            final int v1 = p1.initOrder;
14056            final int v2 = p2.initOrder;
14057            return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0);
14058        }
14059    };
14060
14061    public void sendPackageBroadcast(final String action, final String pkg, final Bundle extras,
14062            final int flags, final String targetPkg, final IIntentReceiver finishedReceiver,
14063            final int[] userIds) {
14064        mHandler.post(new Runnable() {
14065            @Override
14066            public void run() {
14067                try {
14068                    final IActivityManager am = ActivityManager.getService();
14069                    if (am == null) return;
14070                    final int[] resolvedUserIds;
14071                    if (userIds == null) {
14072                        resolvedUserIds = am.getRunningUserIds();
14073                    } else {
14074                        resolvedUserIds = userIds;
14075                    }
14076                    for (int id : resolvedUserIds) {
14077                        final Intent intent = new Intent(action,
14078                                pkg != null ? Uri.fromParts(PACKAGE_SCHEME, pkg, null) : null);
14079                        if (extras != null) {
14080                            intent.putExtras(extras);
14081                        }
14082                        if (targetPkg != null) {
14083                            intent.setPackage(targetPkg);
14084                        }
14085                        // Modify the UID when posting to other users
14086                        int uid = intent.getIntExtra(Intent.EXTRA_UID, -1);
14087                        if (uid > 0 && UserHandle.getUserId(uid) != id) {
14088                            uid = UserHandle.getUid(id, UserHandle.getAppId(uid));
14089                            intent.putExtra(Intent.EXTRA_UID, uid);
14090                        }
14091                        intent.putExtra(Intent.EXTRA_USER_HANDLE, id);
14092                        intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT | flags);
14093                        if (DEBUG_BROADCASTS) {
14094                            RuntimeException here = new RuntimeException("here");
14095                            here.fillInStackTrace();
14096                            Slog.d(TAG, "Sending to user " + id + ": "
14097                                    + intent.toShortString(false, true, false, false)
14098                                    + " " + intent.getExtras(), here);
14099                        }
14100                        am.broadcastIntent(null, intent, null, finishedReceiver,
14101                                0, null, null, null, android.app.AppOpsManager.OP_NONE,
14102                                null, finishedReceiver != null, false, id);
14103                    }
14104                } catch (RemoteException ex) {
14105                }
14106            }
14107        });
14108    }
14109
14110    /**
14111     * Check if the external storage media is available. This is true if there
14112     * is a mounted external storage medium or if the external storage is
14113     * emulated.
14114     */
14115    private boolean isExternalMediaAvailable() {
14116        return mMediaMounted || Environment.isExternalStorageEmulated();
14117    }
14118
14119    @Override
14120    public PackageCleanItem nextPackageToClean(PackageCleanItem lastPackage) {
14121        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
14122            return null;
14123        }
14124        // writer
14125        synchronized (mPackages) {
14126            if (!isExternalMediaAvailable()) {
14127                // If the external storage is no longer mounted at this point,
14128                // the caller may not have been able to delete all of this
14129                // packages files and can not delete any more.  Bail.
14130                return null;
14131            }
14132            final ArrayList<PackageCleanItem> pkgs = mSettings.mPackagesToBeCleaned;
14133            if (lastPackage != null) {
14134                pkgs.remove(lastPackage);
14135            }
14136            if (pkgs.size() > 0) {
14137                return pkgs.get(0);
14138            }
14139        }
14140        return null;
14141    }
14142
14143    void schedulePackageCleaning(String packageName, int userId, boolean andCode) {
14144        final Message msg = mHandler.obtainMessage(START_CLEANING_PACKAGE,
14145                userId, andCode ? 1 : 0, packageName);
14146        if (mSystemReady) {
14147            msg.sendToTarget();
14148        } else {
14149            if (mPostSystemReadyMessages == null) {
14150                mPostSystemReadyMessages = new ArrayList<>();
14151            }
14152            mPostSystemReadyMessages.add(msg);
14153        }
14154    }
14155
14156    void startCleaningPackages() {
14157        // reader
14158        if (!isExternalMediaAvailable()) {
14159            return;
14160        }
14161        synchronized (mPackages) {
14162            if (mSettings.mPackagesToBeCleaned.isEmpty()) {
14163                return;
14164            }
14165        }
14166        Intent intent = new Intent(PackageManager.ACTION_CLEAN_EXTERNAL_STORAGE);
14167        intent.setComponent(DEFAULT_CONTAINER_COMPONENT);
14168        IActivityManager am = ActivityManager.getService();
14169        if (am != null) {
14170            int dcsUid = -1;
14171            synchronized (mPackages) {
14172                if (!mDefaultContainerWhitelisted) {
14173                    mDefaultContainerWhitelisted = true;
14174                    PackageSetting ps = mSettings.mPackages.get(DEFAULT_CONTAINER_PACKAGE);
14175                    dcsUid = UserHandle.getUid(UserHandle.USER_SYSTEM, ps.appId);
14176                }
14177            }
14178            try {
14179                if (dcsUid > 0) {
14180                    am.backgroundWhitelistUid(dcsUid);
14181                }
14182                am.startService(null, intent, null, false, mContext.getOpPackageName(),
14183                        UserHandle.USER_SYSTEM);
14184            } catch (RemoteException e) {
14185            }
14186        }
14187    }
14188
14189    @Override
14190    public void installPackageAsUser(String originPath, IPackageInstallObserver2 observer,
14191            int installFlags, String installerPackageName, int userId) {
14192        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, null);
14193
14194        final int callingUid = Binder.getCallingUid();
14195        enforceCrossUserPermission(callingUid, userId,
14196                true /* requireFullPermission */, true /* checkShell */, "installPackageAsUser");
14197
14198        if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) {
14199            try {
14200                if (observer != null) {
14201                    observer.onPackageInstalled("", INSTALL_FAILED_USER_RESTRICTED, null, null);
14202                }
14203            } catch (RemoteException re) {
14204            }
14205            return;
14206        }
14207
14208        if ((callingUid == Process.SHELL_UID) || (callingUid == Process.ROOT_UID)) {
14209            installFlags |= PackageManager.INSTALL_FROM_ADB;
14210
14211        } else {
14212            // Caller holds INSTALL_PACKAGES permission, so we're less strict
14213            // about installerPackageName.
14214
14215            installFlags &= ~PackageManager.INSTALL_FROM_ADB;
14216            installFlags &= ~PackageManager.INSTALL_ALL_USERS;
14217        }
14218
14219        UserHandle user;
14220        if ((installFlags & PackageManager.INSTALL_ALL_USERS) != 0) {
14221            user = UserHandle.ALL;
14222        } else {
14223            user = new UserHandle(userId);
14224        }
14225
14226        // Only system components can circumvent runtime permissions when installing.
14227        if ((installFlags & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0
14228                && mContext.checkCallingOrSelfPermission(Manifest.permission
14229                .INSTALL_GRANT_RUNTIME_PERMISSIONS) == PackageManager.PERMISSION_DENIED) {
14230            throw new SecurityException("You need the "
14231                    + "android.permission.INSTALL_GRANT_RUNTIME_PERMISSIONS permission "
14232                    + "to use the PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS flag");
14233        }
14234
14235        if ((installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0
14236                || (installFlags & PackageManager.INSTALL_EXTERNAL) != 0) {
14237            throw new IllegalArgumentException(
14238                    "New installs into ASEC containers no longer supported");
14239        }
14240
14241        final File originFile = new File(originPath);
14242        final OriginInfo origin = OriginInfo.fromUntrustedFile(originFile);
14243
14244        final Message msg = mHandler.obtainMessage(INIT_COPY);
14245        final VerificationInfo verificationInfo = new VerificationInfo(
14246                null /*originatingUri*/, null /*referrer*/, -1 /*originatingUid*/, callingUid);
14247        final InstallParams params = new InstallParams(origin, null /*moveInfo*/, observer,
14248                installFlags, installerPackageName, null /*volumeUuid*/, verificationInfo, user,
14249                null /*packageAbiOverride*/, null /*grantedPermissions*/,
14250                null /*certificates*/, PackageManager.INSTALL_REASON_UNKNOWN);
14251        params.setTraceMethod("installAsUser").setTraceCookie(System.identityHashCode(params));
14252        msg.obj = params;
14253
14254        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "installAsUser",
14255                System.identityHashCode(msg.obj));
14256        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
14257                System.identityHashCode(msg.obj));
14258
14259        mHandler.sendMessage(msg);
14260    }
14261
14262
14263    /**
14264     * Ensure that the install reason matches what we know about the package installer (e.g. whether
14265     * it is acting on behalf on an enterprise or the user).
14266     *
14267     * Note that the ordering of the conditionals in this method is important. The checks we perform
14268     * are as follows, in this order:
14269     *
14270     * 1) If the install is being performed by a system app, we can trust the app to have set the
14271     *    install reason correctly. Thus, we pass through the install reason unchanged, no matter
14272     *    what it is.
14273     * 2) If the install is being performed by a device or profile owner app, the install reason
14274     *    should be enterprise policy. However, we cannot be sure that the device or profile owner
14275     *    set the install reason correctly. If the app targets an older SDK version where install
14276     *    reasons did not exist yet, or if the app author simply forgot, the install reason may be
14277     *    unset or wrong. Thus, we force the install reason to be enterprise policy.
14278     * 3) In all other cases, the install is being performed by a regular app that is neither part
14279     *    of the system nor a device or profile owner. We have no reason to believe that this app is
14280     *    acting on behalf of the enterprise admin. Thus, we check whether the install reason was
14281     *    set to enterprise policy and if so, change it to unknown instead.
14282     */
14283    private int fixUpInstallReason(String installerPackageName, int installerUid,
14284            int installReason) {
14285        if (checkUidPermission(android.Manifest.permission.INSTALL_PACKAGES, installerUid)
14286                == PERMISSION_GRANTED) {
14287            // If the install is being performed by a system app, we trust that app to have set the
14288            // install reason correctly.
14289            return installReason;
14290        }
14291
14292        final IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface(
14293            ServiceManager.getService(Context.DEVICE_POLICY_SERVICE));
14294        if (dpm != null) {
14295            ComponentName owner = null;
14296            try {
14297                owner = dpm.getDeviceOwnerComponent(true /* callingUserOnly */);
14298                if (owner == null) {
14299                    owner = dpm.getProfileOwner(UserHandle.getUserId(installerUid));
14300                }
14301            } catch (RemoteException e) {
14302            }
14303            if (owner != null && owner.getPackageName().equals(installerPackageName)) {
14304                // If the install is being performed by a device or profile owner, the install
14305                // reason should be enterprise policy.
14306                return PackageManager.INSTALL_REASON_POLICY;
14307            }
14308        }
14309
14310        if (installReason == PackageManager.INSTALL_REASON_POLICY) {
14311            // If the install is being performed by a regular app (i.e. neither system app nor
14312            // device or profile owner), we have no reason to believe that the app is acting on
14313            // behalf of an enterprise. If the app set the install reason to enterprise policy,
14314            // change it to unknown instead.
14315            return PackageManager.INSTALL_REASON_UNKNOWN;
14316        }
14317
14318        // If the install is being performed by a regular app and the install reason was set to any
14319        // value but enterprise policy, leave the install reason unchanged.
14320        return installReason;
14321    }
14322
14323    void installStage(String packageName, File stagedDir, String stagedCid,
14324            IPackageInstallObserver2 observer, PackageInstaller.SessionParams sessionParams,
14325            String installerPackageName, int installerUid, UserHandle user,
14326            Certificate[][] certificates) {
14327        if (DEBUG_EPHEMERAL) {
14328            if ((sessionParams.installFlags & PackageManager.INSTALL_INSTANT_APP) != 0) {
14329                Slog.d(TAG, "Ephemeral install of " + packageName);
14330            }
14331        }
14332        final VerificationInfo verificationInfo = new VerificationInfo(
14333                sessionParams.originatingUri, sessionParams.referrerUri,
14334                sessionParams.originatingUid, installerUid);
14335
14336        final OriginInfo origin;
14337        if (stagedDir != null) {
14338            origin = OriginInfo.fromStagedFile(stagedDir);
14339        } else {
14340            origin = OriginInfo.fromStagedContainer(stagedCid);
14341        }
14342
14343        final Message msg = mHandler.obtainMessage(INIT_COPY);
14344        final int installReason = fixUpInstallReason(installerPackageName, installerUid,
14345                sessionParams.installReason);
14346        final InstallParams params = new InstallParams(origin, null, observer,
14347                sessionParams.installFlags, installerPackageName, sessionParams.volumeUuid,
14348                verificationInfo, user, sessionParams.abiOverride,
14349                sessionParams.grantedRuntimePermissions, certificates, installReason);
14350        params.setTraceMethod("installStage").setTraceCookie(System.identityHashCode(params));
14351        msg.obj = params;
14352
14353        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "installStage",
14354                System.identityHashCode(msg.obj));
14355        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
14356                System.identityHashCode(msg.obj));
14357
14358        mHandler.sendMessage(msg);
14359    }
14360
14361    private void sendPackageAddedForUser(String packageName, PackageSetting pkgSetting,
14362            int userId) {
14363        final boolean isSystem = isSystemApp(pkgSetting) || isUpdatedSystemApp(pkgSetting);
14364        sendPackageAddedForNewUsers(packageName, isSystem, pkgSetting.appId, userId);
14365
14366        // Send a session commit broadcast
14367        final PackageInstaller.SessionInfo info = new PackageInstaller.SessionInfo();
14368        info.installReason = pkgSetting.getInstallReason(userId);
14369        info.appPackageName = packageName;
14370        sendSessionCommitBroadcast(info, userId);
14371    }
14372
14373    public void sendPackageAddedForNewUsers(String packageName, boolean isSystem, int appId, int... userIds) {
14374        if (ArrayUtils.isEmpty(userIds)) {
14375            return;
14376        }
14377        Bundle extras = new Bundle(1);
14378        // Set to UID of the first user, EXTRA_UID is automatically updated in sendPackageBroadcast
14379        extras.putInt(Intent.EXTRA_UID, UserHandle.getUid(userIds[0], appId));
14380
14381        sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
14382                packageName, extras, 0, null, null, userIds);
14383        if (isSystem) {
14384            mHandler.post(() -> {
14385                        for (int userId : userIds) {
14386                            sendBootCompletedBroadcastToSystemApp(packageName, userId);
14387                        }
14388                    }
14389            );
14390        }
14391    }
14392
14393    /**
14394     * The just-installed/enabled app is bundled on the system, so presumed to be able to run
14395     * automatically without needing an explicit launch.
14396     * Send it a LOCKED_BOOT_COMPLETED/BOOT_COMPLETED if it would ordinarily have gotten ones.
14397     */
14398    private void sendBootCompletedBroadcastToSystemApp(String packageName, int userId) {
14399        // If user is not running, the app didn't miss any broadcast
14400        if (!mUserManagerInternal.isUserRunning(userId)) {
14401            return;
14402        }
14403        final IActivityManager am = ActivityManager.getService();
14404        try {
14405            // Deliver LOCKED_BOOT_COMPLETED first
14406            Intent lockedBcIntent = new Intent(Intent.ACTION_LOCKED_BOOT_COMPLETED)
14407                    .setPackage(packageName);
14408            final String[] requiredPermissions = {Manifest.permission.RECEIVE_BOOT_COMPLETED};
14409            am.broadcastIntent(null, lockedBcIntent, null, null, 0, null, null, requiredPermissions,
14410                    android.app.AppOpsManager.OP_NONE, null, false, false, userId);
14411
14412            // Deliver BOOT_COMPLETED only if user is unlocked
14413            if (mUserManagerInternal.isUserUnlockingOrUnlocked(userId)) {
14414                Intent bcIntent = new Intent(Intent.ACTION_BOOT_COMPLETED).setPackage(packageName);
14415                am.broadcastIntent(null, bcIntent, null, null, 0, null, null, requiredPermissions,
14416                        android.app.AppOpsManager.OP_NONE, null, false, false, userId);
14417            }
14418        } catch (RemoteException e) {
14419            throw e.rethrowFromSystemServer();
14420        }
14421    }
14422
14423    @Override
14424    public boolean setApplicationHiddenSettingAsUser(String packageName, boolean hidden,
14425            int userId) {
14426        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
14427        PackageSetting pkgSetting;
14428        final int callingUid = Binder.getCallingUid();
14429        enforceCrossUserPermission(callingUid, userId,
14430                true /* requireFullPermission */, true /* checkShell */,
14431                "setApplicationHiddenSetting for user " + userId);
14432
14433        if (hidden && isPackageDeviceAdmin(packageName, userId)) {
14434            Slog.w(TAG, "Not hiding package " + packageName + ": has active device admin");
14435            return false;
14436        }
14437
14438        long callingId = Binder.clearCallingIdentity();
14439        try {
14440            boolean sendAdded = false;
14441            boolean sendRemoved = false;
14442            // writer
14443            synchronized (mPackages) {
14444                pkgSetting = mSettings.mPackages.get(packageName);
14445                if (pkgSetting == null) {
14446                    return false;
14447                }
14448                if (filterAppAccessLPr(pkgSetting, callingUid, userId)) {
14449                    return false;
14450                }
14451                // Do not allow "android" is being disabled
14452                if ("android".equals(packageName)) {
14453                    Slog.w(TAG, "Cannot hide package: android");
14454                    return false;
14455                }
14456                // Cannot hide static shared libs as they are considered
14457                // a part of the using app (emulating static linking). Also
14458                // static libs are installed always on internal storage.
14459                PackageParser.Package pkg = mPackages.get(packageName);
14460                if (pkg != null && pkg.staticSharedLibName != null) {
14461                    Slog.w(TAG, "Cannot hide package: " + packageName
14462                            + " providing static shared library: "
14463                            + pkg.staticSharedLibName);
14464                    return false;
14465                }
14466                // Only allow protected packages to hide themselves.
14467                if (hidden && !UserHandle.isSameApp(callingUid, pkgSetting.appId)
14468                        && mProtectedPackages.isPackageStateProtected(userId, packageName)) {
14469                    Slog.w(TAG, "Not hiding protected package: " + packageName);
14470                    return false;
14471                }
14472
14473                if (pkgSetting.getHidden(userId) != hidden) {
14474                    pkgSetting.setHidden(hidden, userId);
14475                    mSettings.writePackageRestrictionsLPr(userId);
14476                    if (hidden) {
14477                        sendRemoved = true;
14478                    } else {
14479                        sendAdded = true;
14480                    }
14481                }
14482            }
14483            if (sendAdded) {
14484                sendPackageAddedForUser(packageName, pkgSetting, userId);
14485                return true;
14486            }
14487            if (sendRemoved) {
14488                killApplication(packageName, UserHandle.getUid(userId, pkgSetting.appId),
14489                        "hiding pkg");
14490                sendApplicationHiddenForUser(packageName, pkgSetting, userId);
14491                return true;
14492            }
14493        } finally {
14494            Binder.restoreCallingIdentity(callingId);
14495        }
14496        return false;
14497    }
14498
14499    private void sendApplicationHiddenForUser(String packageName, PackageSetting pkgSetting,
14500            int userId) {
14501        final PackageRemovedInfo info = new PackageRemovedInfo(this);
14502        info.removedPackage = packageName;
14503        info.installerPackageName = pkgSetting.installerPackageName;
14504        info.removedUsers = new int[] {userId};
14505        info.broadcastUsers = new int[] {userId};
14506        info.uid = UserHandle.getUid(userId, pkgSetting.appId);
14507        info.sendPackageRemovedBroadcasts(true /*killApp*/);
14508    }
14509
14510    private void sendPackagesSuspendedForUser(String[] pkgList, int userId, boolean suspended) {
14511        if (pkgList.length > 0) {
14512            Bundle extras = new Bundle(1);
14513            extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList);
14514
14515            sendPackageBroadcast(
14516                    suspended ? Intent.ACTION_PACKAGES_SUSPENDED
14517                            : Intent.ACTION_PACKAGES_UNSUSPENDED,
14518                    null, extras, Intent.FLAG_RECEIVER_REGISTERED_ONLY, null, null,
14519                    new int[] {userId});
14520        }
14521    }
14522
14523    /**
14524     * Returns true if application is not found or there was an error. Otherwise it returns
14525     * the hidden state of the package for the given user.
14526     */
14527    @Override
14528    public boolean getApplicationHiddenSettingAsUser(String packageName, int userId) {
14529        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
14530        final int callingUid = Binder.getCallingUid();
14531        enforceCrossUserPermission(callingUid, userId,
14532                true /* requireFullPermission */, false /* checkShell */,
14533                "getApplicationHidden for user " + userId);
14534        PackageSetting ps;
14535        long callingId = Binder.clearCallingIdentity();
14536        try {
14537            // writer
14538            synchronized (mPackages) {
14539                ps = mSettings.mPackages.get(packageName);
14540                if (ps == null) {
14541                    return true;
14542                }
14543                if (filterAppAccessLPr(ps, callingUid, userId)) {
14544                    return true;
14545                }
14546                return ps.getHidden(userId);
14547            }
14548        } finally {
14549            Binder.restoreCallingIdentity(callingId);
14550        }
14551    }
14552
14553    /**
14554     * @hide
14555     */
14556    @Override
14557    public int installExistingPackageAsUser(String packageName, int userId, int installFlags,
14558            int installReason) {
14559        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES,
14560                null);
14561        PackageSetting pkgSetting;
14562        final int callingUid = Binder.getCallingUid();
14563        enforceCrossUserPermission(callingUid, userId,
14564                true /* requireFullPermission */, true /* checkShell */,
14565                "installExistingPackage for user " + userId);
14566        if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) {
14567            return PackageManager.INSTALL_FAILED_USER_RESTRICTED;
14568        }
14569
14570        long callingId = Binder.clearCallingIdentity();
14571        try {
14572            boolean installed = false;
14573            final boolean instantApp =
14574                    (installFlags & PackageManager.INSTALL_INSTANT_APP) != 0;
14575            final boolean fullApp =
14576                    (installFlags & PackageManager.INSTALL_FULL_APP) != 0;
14577
14578            // writer
14579            synchronized (mPackages) {
14580                pkgSetting = mSettings.mPackages.get(packageName);
14581                if (pkgSetting == null) {
14582                    return PackageManager.INSTALL_FAILED_INVALID_URI;
14583                }
14584                if (!canViewInstantApps(callingUid, UserHandle.getUserId(callingUid))) {
14585                    // only allow the existing package to be used if it's installed as a full
14586                    // application for at least one user
14587                    boolean installAllowed = false;
14588                    for (int checkUserId : sUserManager.getUserIds()) {
14589                        installAllowed = !pkgSetting.getInstantApp(checkUserId);
14590                        if (installAllowed) {
14591                            break;
14592                        }
14593                    }
14594                    if (!installAllowed) {
14595                        return PackageManager.INSTALL_FAILED_INVALID_URI;
14596                    }
14597                }
14598                if (!pkgSetting.getInstalled(userId)) {
14599                    pkgSetting.setInstalled(true, userId);
14600                    pkgSetting.setHidden(false, userId);
14601                    pkgSetting.setInstallReason(installReason, userId);
14602                    mSettings.writePackageRestrictionsLPr(userId);
14603                    mSettings.writeKernelMappingLPr(pkgSetting);
14604                    installed = true;
14605                } else if (fullApp && pkgSetting.getInstantApp(userId)) {
14606                    // upgrade app from instant to full; we don't allow app downgrade
14607                    installed = true;
14608                }
14609                setInstantAppForUser(pkgSetting, userId, instantApp, fullApp);
14610            }
14611
14612            if (installed) {
14613                if (pkgSetting.pkg != null) {
14614                    synchronized (mInstallLock) {
14615                        // We don't need to freeze for a brand new install
14616                        prepareAppDataAfterInstallLIF(pkgSetting.pkg);
14617                    }
14618                }
14619                sendPackageAddedForUser(packageName, pkgSetting, userId);
14620                synchronized (mPackages) {
14621                    updateSequenceNumberLP(pkgSetting, new int[]{ userId });
14622                }
14623            }
14624        } finally {
14625            Binder.restoreCallingIdentity(callingId);
14626        }
14627
14628        return PackageManager.INSTALL_SUCCEEDED;
14629    }
14630
14631    void setInstantAppForUser(PackageSetting pkgSetting, int userId,
14632            boolean instantApp, boolean fullApp) {
14633        // no state specified; do nothing
14634        if (!instantApp && !fullApp) {
14635            return;
14636        }
14637        if (userId != UserHandle.USER_ALL) {
14638            if (instantApp && !pkgSetting.getInstantApp(userId)) {
14639                pkgSetting.setInstantApp(true /*instantApp*/, userId);
14640            } else if (fullApp && pkgSetting.getInstantApp(userId)) {
14641                pkgSetting.setInstantApp(false /*instantApp*/, userId);
14642            }
14643        } else {
14644            for (int currentUserId : sUserManager.getUserIds()) {
14645                if (instantApp && !pkgSetting.getInstantApp(currentUserId)) {
14646                    pkgSetting.setInstantApp(true /*instantApp*/, currentUserId);
14647                } else if (fullApp && pkgSetting.getInstantApp(currentUserId)) {
14648                    pkgSetting.setInstantApp(false /*instantApp*/, currentUserId);
14649                }
14650            }
14651        }
14652    }
14653
14654    boolean isUserRestricted(int userId, String restrictionKey) {
14655        Bundle restrictions = sUserManager.getUserRestrictions(userId);
14656        if (restrictions.getBoolean(restrictionKey, false)) {
14657            Log.w(TAG, "User is restricted: " + restrictionKey);
14658            return true;
14659        }
14660        return false;
14661    }
14662
14663    @Override
14664    public String[] setPackagesSuspendedAsUser(String[] packageNames, boolean suspended,
14665            int userId) {
14666        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
14667        final int callingUid = Binder.getCallingUid();
14668        enforceCrossUserPermission(callingUid, userId,
14669                true /* requireFullPermission */, true /* checkShell */,
14670                "setPackagesSuspended for user " + userId);
14671
14672        if (ArrayUtils.isEmpty(packageNames)) {
14673            return packageNames;
14674        }
14675
14676        // List of package names for whom the suspended state has changed.
14677        List<String> changedPackages = new ArrayList<>(packageNames.length);
14678        // List of package names for whom the suspended state is not set as requested in this
14679        // method.
14680        List<String> unactionedPackages = new ArrayList<>(packageNames.length);
14681        long callingId = Binder.clearCallingIdentity();
14682        try {
14683            for (int i = 0; i < packageNames.length; i++) {
14684                String packageName = packageNames[i];
14685                boolean changed = false;
14686                final int appId;
14687                synchronized (mPackages) {
14688                    final PackageSetting pkgSetting = mSettings.mPackages.get(packageName);
14689                    if (pkgSetting == null
14690                            || filterAppAccessLPr(pkgSetting, callingUid, userId)) {
14691                        Slog.w(TAG, "Could not find package setting for package \"" + packageName
14692                                + "\". Skipping suspending/un-suspending.");
14693                        unactionedPackages.add(packageName);
14694                        continue;
14695                    }
14696                    appId = pkgSetting.appId;
14697                    if (pkgSetting.getSuspended(userId) != suspended) {
14698                        if (!canSuspendPackageForUserLocked(packageName, userId)) {
14699                            unactionedPackages.add(packageName);
14700                            continue;
14701                        }
14702                        pkgSetting.setSuspended(suspended, userId);
14703                        mSettings.writePackageRestrictionsLPr(userId);
14704                        changed = true;
14705                        changedPackages.add(packageName);
14706                    }
14707                }
14708
14709                if (changed && suspended) {
14710                    killApplication(packageName, UserHandle.getUid(userId, appId),
14711                            "suspending package");
14712                }
14713            }
14714        } finally {
14715            Binder.restoreCallingIdentity(callingId);
14716        }
14717
14718        if (!changedPackages.isEmpty()) {
14719            sendPackagesSuspendedForUser(changedPackages.toArray(
14720                    new String[changedPackages.size()]), userId, suspended);
14721        }
14722
14723        return unactionedPackages.toArray(new String[unactionedPackages.size()]);
14724    }
14725
14726    @Override
14727    public boolean isPackageSuspendedForUser(String packageName, int userId) {
14728        final int callingUid = Binder.getCallingUid();
14729        enforceCrossUserPermission(callingUid, userId,
14730                true /* requireFullPermission */, false /* checkShell */,
14731                "isPackageSuspendedForUser for user " + userId);
14732        synchronized (mPackages) {
14733            final PackageSetting ps = mSettings.mPackages.get(packageName);
14734            if (ps == null || filterAppAccessLPr(ps, callingUid, userId)) {
14735                throw new IllegalArgumentException("Unknown target package: " + packageName);
14736            }
14737            return ps.getSuspended(userId);
14738        }
14739    }
14740
14741    private boolean canSuspendPackageForUserLocked(String packageName, int userId) {
14742        if (isPackageDeviceAdmin(packageName, userId)) {
14743            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
14744                    + "\": has an active device admin");
14745            return false;
14746        }
14747
14748        String activeLauncherPackageName = getActiveLauncherPackageName(userId);
14749        if (packageName.equals(activeLauncherPackageName)) {
14750            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
14751                    + "\": contains the active launcher");
14752            return false;
14753        }
14754
14755        if (packageName.equals(mRequiredInstallerPackage)) {
14756            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
14757                    + "\": required for package installation");
14758            return false;
14759        }
14760
14761        if (packageName.equals(mRequiredUninstallerPackage)) {
14762            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
14763                    + "\": required for package uninstallation");
14764            return false;
14765        }
14766
14767        if (packageName.equals(mRequiredVerifierPackage)) {
14768            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
14769                    + "\": required for package verification");
14770            return false;
14771        }
14772
14773        if (packageName.equals(getDefaultDialerPackageName(userId))) {
14774            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
14775                    + "\": is the default dialer");
14776            return false;
14777        }
14778
14779        if (mProtectedPackages.isPackageStateProtected(userId, packageName)) {
14780            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
14781                    + "\": protected package");
14782            return false;
14783        }
14784
14785        // Cannot suspend static shared libs as they are considered
14786        // a part of the using app (emulating static linking). Also
14787        // static libs are installed always on internal storage.
14788        PackageParser.Package pkg = mPackages.get(packageName);
14789        if (pkg != null && pkg.applicationInfo.isStaticSharedLibrary()) {
14790            Slog.w(TAG, "Cannot suspend package: " + packageName
14791                    + " providing static shared library: "
14792                    + pkg.staticSharedLibName);
14793            return false;
14794        }
14795
14796        return true;
14797    }
14798
14799    private String getActiveLauncherPackageName(int userId) {
14800        Intent intent = new Intent(Intent.ACTION_MAIN);
14801        intent.addCategory(Intent.CATEGORY_HOME);
14802        ResolveInfo resolveInfo = resolveIntent(
14803                intent,
14804                intent.resolveTypeIfNeeded(mContext.getContentResolver()),
14805                PackageManager.MATCH_DEFAULT_ONLY,
14806                userId);
14807
14808        return resolveInfo == null ? null : resolveInfo.activityInfo.packageName;
14809    }
14810
14811    private String getDefaultDialerPackageName(int userId) {
14812        synchronized (mPackages) {
14813            return mSettings.getDefaultDialerPackageNameLPw(userId);
14814        }
14815    }
14816
14817    @Override
14818    public void verifyPendingInstall(int id, int verificationCode) throws RemoteException {
14819        mContext.enforceCallingOrSelfPermission(
14820                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
14821                "Only package verification agents can verify applications");
14822
14823        final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED);
14824        final PackageVerificationResponse response = new PackageVerificationResponse(
14825                verificationCode, Binder.getCallingUid());
14826        msg.arg1 = id;
14827        msg.obj = response;
14828        mHandler.sendMessage(msg);
14829    }
14830
14831    @Override
14832    public void extendVerificationTimeout(int id, int verificationCodeAtTimeout,
14833            long millisecondsToDelay) {
14834        mContext.enforceCallingOrSelfPermission(
14835                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
14836                "Only package verification agents can extend verification timeouts");
14837
14838        final PackageVerificationState state = mPendingVerification.get(id);
14839        final PackageVerificationResponse response = new PackageVerificationResponse(
14840                verificationCodeAtTimeout, Binder.getCallingUid());
14841
14842        if (millisecondsToDelay > PackageManager.MAXIMUM_VERIFICATION_TIMEOUT) {
14843            millisecondsToDelay = PackageManager.MAXIMUM_VERIFICATION_TIMEOUT;
14844        }
14845        if (millisecondsToDelay < 0) {
14846            millisecondsToDelay = 0;
14847        }
14848        if ((verificationCodeAtTimeout != PackageManager.VERIFICATION_ALLOW)
14849                && (verificationCodeAtTimeout != PackageManager.VERIFICATION_REJECT)) {
14850            verificationCodeAtTimeout = PackageManager.VERIFICATION_REJECT;
14851        }
14852
14853        if ((state != null) && !state.timeoutExtended()) {
14854            state.extendTimeout();
14855
14856            final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED);
14857            msg.arg1 = id;
14858            msg.obj = response;
14859            mHandler.sendMessageDelayed(msg, millisecondsToDelay);
14860        }
14861    }
14862
14863    private void broadcastPackageVerified(int verificationId, Uri packageUri,
14864            int verificationCode, UserHandle user) {
14865        final Intent intent = new Intent(Intent.ACTION_PACKAGE_VERIFIED);
14866        intent.setDataAndType(packageUri, PACKAGE_MIME_TYPE);
14867        intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
14868        intent.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId);
14869        intent.putExtra(PackageManager.EXTRA_VERIFICATION_RESULT, verificationCode);
14870
14871        mContext.sendBroadcastAsUser(intent, user,
14872                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT);
14873    }
14874
14875    private ComponentName matchComponentForVerifier(String packageName,
14876            List<ResolveInfo> receivers) {
14877        ActivityInfo targetReceiver = null;
14878
14879        final int NR = receivers.size();
14880        for (int i = 0; i < NR; i++) {
14881            final ResolveInfo info = receivers.get(i);
14882            if (info.activityInfo == null) {
14883                continue;
14884            }
14885
14886            if (packageName.equals(info.activityInfo.packageName)) {
14887                targetReceiver = info.activityInfo;
14888                break;
14889            }
14890        }
14891
14892        if (targetReceiver == null) {
14893            return null;
14894        }
14895
14896        return new ComponentName(targetReceiver.packageName, targetReceiver.name);
14897    }
14898
14899    private List<ComponentName> matchVerifiers(PackageInfoLite pkgInfo,
14900            List<ResolveInfo> receivers, final PackageVerificationState verificationState) {
14901        if (pkgInfo.verifiers.length == 0) {
14902            return null;
14903        }
14904
14905        final int N = pkgInfo.verifiers.length;
14906        final List<ComponentName> sufficientVerifiers = new ArrayList<ComponentName>(N + 1);
14907        for (int i = 0; i < N; i++) {
14908            final VerifierInfo verifierInfo = pkgInfo.verifiers[i];
14909
14910            final ComponentName comp = matchComponentForVerifier(verifierInfo.packageName,
14911                    receivers);
14912            if (comp == null) {
14913                continue;
14914            }
14915
14916            final int verifierUid = getUidForVerifier(verifierInfo);
14917            if (verifierUid == -1) {
14918                continue;
14919            }
14920
14921            if (DEBUG_VERIFY) {
14922                Slog.d(TAG, "Added sufficient verifier " + verifierInfo.packageName
14923                        + " with the correct signature");
14924            }
14925            sufficientVerifiers.add(comp);
14926            verificationState.addSufficientVerifier(verifierUid);
14927        }
14928
14929        return sufficientVerifiers;
14930    }
14931
14932    private int getUidForVerifier(VerifierInfo verifierInfo) {
14933        synchronized (mPackages) {
14934            final PackageParser.Package pkg = mPackages.get(verifierInfo.packageName);
14935            if (pkg == null) {
14936                return -1;
14937            } else if (pkg.mSignatures.length != 1) {
14938                Slog.i(TAG, "Verifier package " + verifierInfo.packageName
14939                        + " has more than one signature; ignoring");
14940                return -1;
14941            }
14942
14943            /*
14944             * If the public key of the package's signature does not match
14945             * our expected public key, then this is a different package and
14946             * we should skip.
14947             */
14948
14949            final byte[] expectedPublicKey;
14950            try {
14951                final Signature verifierSig = pkg.mSignatures[0];
14952                final PublicKey publicKey = verifierSig.getPublicKey();
14953                expectedPublicKey = publicKey.getEncoded();
14954            } catch (CertificateException e) {
14955                return -1;
14956            }
14957
14958            final byte[] actualPublicKey = verifierInfo.publicKey.getEncoded();
14959
14960            if (!Arrays.equals(actualPublicKey, expectedPublicKey)) {
14961                Slog.i(TAG, "Verifier package " + verifierInfo.packageName
14962                        + " does not have the expected public key; ignoring");
14963                return -1;
14964            }
14965
14966            return pkg.applicationInfo.uid;
14967        }
14968    }
14969
14970    @Override
14971    public void finishPackageInstall(int token, boolean didLaunch) {
14972        enforceSystemOrRoot("Only the system is allowed to finish installs");
14973
14974        if (DEBUG_INSTALL) {
14975            Slog.v(TAG, "BM finishing package install for " + token);
14976        }
14977        Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "restore", token);
14978
14979        final Message msg = mHandler.obtainMessage(POST_INSTALL, token, didLaunch ? 1 : 0);
14980        mHandler.sendMessage(msg);
14981    }
14982
14983    /**
14984     * Get the verification agent timeout.  Used for both the APK verifier and the
14985     * intent filter verifier.
14986     *
14987     * @return verification timeout in milliseconds
14988     */
14989    private long getVerificationTimeout() {
14990        return android.provider.Settings.Global.getLong(mContext.getContentResolver(),
14991                android.provider.Settings.Global.PACKAGE_VERIFIER_TIMEOUT,
14992                DEFAULT_VERIFICATION_TIMEOUT);
14993    }
14994
14995    /**
14996     * Get the default verification agent response code.
14997     *
14998     * @return default verification response code
14999     */
15000    private int getDefaultVerificationResponse(UserHandle user) {
15001        if (sUserManager.hasUserRestriction(UserManager.ENSURE_VERIFY_APPS, user.getIdentifier())) {
15002            return PackageManager.VERIFICATION_REJECT;
15003        }
15004        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
15005                android.provider.Settings.Global.PACKAGE_VERIFIER_DEFAULT_RESPONSE,
15006                DEFAULT_VERIFICATION_RESPONSE);
15007    }
15008
15009    /**
15010     * Check whether or not package verification has been enabled.
15011     *
15012     * @return true if verification should be performed
15013     */
15014    private boolean isVerificationEnabled(int userId, int installFlags, int installerUid) {
15015        if (!DEFAULT_VERIFY_ENABLE) {
15016            return false;
15017        }
15018
15019        boolean ensureVerifyAppsEnabled = isUserRestricted(userId, UserManager.ENSURE_VERIFY_APPS);
15020
15021        // Check if installing from ADB
15022        if ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0) {
15023            // Do not run verification in a test harness environment
15024            if (ActivityManager.isRunningInTestHarness()) {
15025                return false;
15026            }
15027            if (ensureVerifyAppsEnabled) {
15028                return true;
15029            }
15030            // Check if the developer does not want package verification for ADB installs
15031            if (android.provider.Settings.Global.getInt(mContext.getContentResolver(),
15032                    android.provider.Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB, 1) == 0) {
15033                return false;
15034            }
15035        } else {
15036            // only when not installed from ADB, skip verification for instant apps when
15037            // the installer and verifier are the same.
15038            if ((installFlags & PackageManager.INSTALL_INSTANT_APP) != 0) {
15039                if (mInstantAppInstallerActivity != null
15040                        && mInstantAppInstallerActivity.packageName.equals(
15041                                mRequiredVerifierPackage)) {
15042                    try {
15043                        mContext.getSystemService(AppOpsManager.class)
15044                                .checkPackage(installerUid, mRequiredVerifierPackage);
15045                        if (DEBUG_VERIFY) {
15046                            Slog.i(TAG, "disable verification for instant app");
15047                        }
15048                        return false;
15049                    } catch (SecurityException ignore) { }
15050                }
15051            }
15052        }
15053
15054        if (ensureVerifyAppsEnabled) {
15055            return true;
15056        }
15057
15058        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
15059                android.provider.Settings.Global.PACKAGE_VERIFIER_ENABLE, 1) == 1;
15060    }
15061
15062    @Override
15063    public void verifyIntentFilter(int id, int verificationCode, List<String> failedDomains)
15064            throws RemoteException {
15065        mContext.enforceCallingOrSelfPermission(
15066                Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT,
15067                "Only intentfilter verification agents can verify applications");
15068
15069        final Message msg = mHandler.obtainMessage(INTENT_FILTER_VERIFIED);
15070        final IntentFilterVerificationResponse response = new IntentFilterVerificationResponse(
15071                Binder.getCallingUid(), verificationCode, failedDomains);
15072        msg.arg1 = id;
15073        msg.obj = response;
15074        mHandler.sendMessage(msg);
15075    }
15076
15077    @Override
15078    public int getIntentVerificationStatus(String packageName, int userId) {
15079        final int callingUid = Binder.getCallingUid();
15080        if (getInstantAppPackageName(callingUid) != null) {
15081            return INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED;
15082        }
15083        synchronized (mPackages) {
15084            final PackageSetting ps = mSettings.mPackages.get(packageName);
15085            if (ps == null
15086                    || filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
15087                return INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED;
15088            }
15089            return mSettings.getIntentFilterVerificationStatusLPr(packageName, userId);
15090        }
15091    }
15092
15093    @Override
15094    public boolean updateIntentVerificationStatus(String packageName, int status, int userId) {
15095        mContext.enforceCallingOrSelfPermission(
15096                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
15097
15098        boolean result = false;
15099        synchronized (mPackages) {
15100            final PackageSetting ps = mSettings.mPackages.get(packageName);
15101            if (filterAppAccessLPr(ps, Binder.getCallingUid(), UserHandle.getCallingUserId())) {
15102                return false;
15103            }
15104            result = mSettings.updateIntentFilterVerificationStatusLPw(packageName, status, userId);
15105        }
15106        if (result) {
15107            scheduleWritePackageRestrictionsLocked(userId);
15108        }
15109        return result;
15110    }
15111
15112    @Override
15113    public @NonNull ParceledListSlice<IntentFilterVerificationInfo> getIntentFilterVerifications(
15114            String packageName) {
15115        final int callingUid = Binder.getCallingUid();
15116        if (getInstantAppPackageName(callingUid) != null) {
15117            return ParceledListSlice.emptyList();
15118        }
15119        synchronized (mPackages) {
15120            final PackageSetting ps = mSettings.mPackages.get(packageName);
15121            if (filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
15122                return ParceledListSlice.emptyList();
15123            }
15124            return new ParceledListSlice<>(mSettings.getIntentFilterVerificationsLPr(packageName));
15125        }
15126    }
15127
15128    @Override
15129    public @NonNull ParceledListSlice<IntentFilter> getAllIntentFilters(String packageName) {
15130        if (TextUtils.isEmpty(packageName)) {
15131            return ParceledListSlice.emptyList();
15132        }
15133        final int callingUid = Binder.getCallingUid();
15134        final int callingUserId = UserHandle.getUserId(callingUid);
15135        synchronized (mPackages) {
15136            PackageParser.Package pkg = mPackages.get(packageName);
15137            if (pkg == null || pkg.activities == null) {
15138                return ParceledListSlice.emptyList();
15139            }
15140            if (pkg.mExtras == null) {
15141                return ParceledListSlice.emptyList();
15142            }
15143            final PackageSetting ps = (PackageSetting) pkg.mExtras;
15144            if (filterAppAccessLPr(ps, callingUid, callingUserId)) {
15145                return ParceledListSlice.emptyList();
15146            }
15147            final int count = pkg.activities.size();
15148            ArrayList<IntentFilter> result = new ArrayList<>();
15149            for (int n=0; n<count; n++) {
15150                PackageParser.Activity activity = pkg.activities.get(n);
15151                if (activity.intents != null && activity.intents.size() > 0) {
15152                    result.addAll(activity.intents);
15153                }
15154            }
15155            return new ParceledListSlice<>(result);
15156        }
15157    }
15158
15159    @Override
15160    public boolean setDefaultBrowserPackageName(String packageName, int userId) {
15161        mContext.enforceCallingOrSelfPermission(
15162                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
15163
15164        synchronized (mPackages) {
15165            boolean result = mSettings.setDefaultBrowserPackageNameLPw(packageName, userId);
15166            if (packageName != null) {
15167                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultBrowserLPr(
15168                        packageName, userId);
15169            }
15170            return result;
15171        }
15172    }
15173
15174    @Override
15175    public String getDefaultBrowserPackageName(int userId) {
15176        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
15177            return null;
15178        }
15179        synchronized (mPackages) {
15180            return mSettings.getDefaultBrowserPackageNameLPw(userId);
15181        }
15182    }
15183
15184    /**
15185     * Get the "allow unknown sources" setting.
15186     *
15187     * @return the current "allow unknown sources" setting
15188     */
15189    private int getUnknownSourcesSettings() {
15190        return android.provider.Settings.Secure.getInt(mContext.getContentResolver(),
15191                android.provider.Settings.Secure.INSTALL_NON_MARKET_APPS,
15192                -1);
15193    }
15194
15195    @Override
15196    public void setInstallerPackageName(String targetPackage, String installerPackageName) {
15197        final int callingUid = Binder.getCallingUid();
15198        if (getInstantAppPackageName(callingUid) != null) {
15199            return;
15200        }
15201        // writer
15202        synchronized (mPackages) {
15203            PackageSetting targetPackageSetting = mSettings.mPackages.get(targetPackage);
15204            if (targetPackageSetting == null
15205                    || filterAppAccessLPr(
15206                            targetPackageSetting, callingUid, UserHandle.getUserId(callingUid))) {
15207                throw new IllegalArgumentException("Unknown target package: " + targetPackage);
15208            }
15209
15210            PackageSetting installerPackageSetting;
15211            if (installerPackageName != null) {
15212                installerPackageSetting = mSettings.mPackages.get(installerPackageName);
15213                if (installerPackageSetting == null) {
15214                    throw new IllegalArgumentException("Unknown installer package: "
15215                            + installerPackageName);
15216                }
15217            } else {
15218                installerPackageSetting = null;
15219            }
15220
15221            Signature[] callerSignature;
15222            Object obj = mSettings.getUserIdLPr(callingUid);
15223            if (obj != null) {
15224                if (obj instanceof SharedUserSetting) {
15225                    callerSignature = ((SharedUserSetting)obj).signatures.mSignatures;
15226                } else if (obj instanceof PackageSetting) {
15227                    callerSignature = ((PackageSetting)obj).signatures.mSignatures;
15228                } else {
15229                    throw new SecurityException("Bad object " + obj + " for uid " + callingUid);
15230                }
15231            } else {
15232                throw new SecurityException("Unknown calling UID: " + callingUid);
15233            }
15234
15235            // Verify: can't set installerPackageName to a package that is
15236            // not signed with the same cert as the caller.
15237            if (installerPackageSetting != null) {
15238                if (compareSignatures(callerSignature,
15239                        installerPackageSetting.signatures.mSignatures)
15240                        != PackageManager.SIGNATURE_MATCH) {
15241                    throw new SecurityException(
15242                            "Caller does not have same cert as new installer package "
15243                            + installerPackageName);
15244                }
15245            }
15246
15247            // Verify: if target already has an installer package, it must
15248            // be signed with the same cert as the caller.
15249            if (targetPackageSetting.installerPackageName != null) {
15250                PackageSetting setting = mSettings.mPackages.get(
15251                        targetPackageSetting.installerPackageName);
15252                // If the currently set package isn't valid, then it's always
15253                // okay to change it.
15254                if (setting != null) {
15255                    if (compareSignatures(callerSignature,
15256                            setting.signatures.mSignatures)
15257                            != PackageManager.SIGNATURE_MATCH) {
15258                        throw new SecurityException(
15259                                "Caller does not have same cert as old installer package "
15260                                + targetPackageSetting.installerPackageName);
15261                    }
15262                }
15263            }
15264
15265            // Okay!
15266            targetPackageSetting.installerPackageName = installerPackageName;
15267            if (installerPackageName != null) {
15268                mSettings.mInstallerPackages.add(installerPackageName);
15269            }
15270            scheduleWriteSettingsLocked();
15271        }
15272    }
15273
15274    @Override
15275    public void setApplicationCategoryHint(String packageName, int categoryHint,
15276            String callerPackageName) {
15277        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
15278            throw new SecurityException("Instant applications don't have access to this method");
15279        }
15280        mContext.getSystemService(AppOpsManager.class).checkPackage(Binder.getCallingUid(),
15281                callerPackageName);
15282        synchronized (mPackages) {
15283            PackageSetting ps = mSettings.mPackages.get(packageName);
15284            if (ps == null) {
15285                throw new IllegalArgumentException("Unknown target package " + packageName);
15286            }
15287            if (filterAppAccessLPr(ps, Binder.getCallingUid(), UserHandle.getCallingUserId())) {
15288                throw new IllegalArgumentException("Unknown target package " + packageName);
15289            }
15290            if (!Objects.equals(callerPackageName, ps.installerPackageName)) {
15291                throw new IllegalArgumentException("Calling package " + callerPackageName
15292                        + " is not installer for " + packageName);
15293            }
15294
15295            if (ps.categoryHint != categoryHint) {
15296                ps.categoryHint = categoryHint;
15297                scheduleWriteSettingsLocked();
15298            }
15299        }
15300    }
15301
15302    private void processPendingInstall(final InstallArgs args, final int currentStatus) {
15303        // Queue up an async operation since the package installation may take a little while.
15304        mHandler.post(new Runnable() {
15305            public void run() {
15306                mHandler.removeCallbacks(this);
15307                 // Result object to be returned
15308                PackageInstalledInfo res = new PackageInstalledInfo();
15309                res.setReturnCode(currentStatus);
15310                res.uid = -1;
15311                res.pkg = null;
15312                res.removedInfo = null;
15313                if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
15314                    args.doPreInstall(res.returnCode);
15315                    synchronized (mInstallLock) {
15316                        installPackageTracedLI(args, res);
15317                    }
15318                    args.doPostInstall(res.returnCode, res.uid);
15319                }
15320
15321                // A restore should be performed at this point if (a) the install
15322                // succeeded, (b) the operation is not an update, and (c) the new
15323                // package has not opted out of backup participation.
15324                final boolean update = res.removedInfo != null
15325                        && res.removedInfo.removedPackage != null;
15326                final int flags = (res.pkg == null) ? 0 : res.pkg.applicationInfo.flags;
15327                boolean doRestore = !update
15328                        && ((flags & ApplicationInfo.FLAG_ALLOW_BACKUP) != 0);
15329
15330                // Set up the post-install work request bookkeeping.  This will be used
15331                // and cleaned up by the post-install event handling regardless of whether
15332                // there's a restore pass performed.  Token values are >= 1.
15333                int token;
15334                if (mNextInstallToken < 0) mNextInstallToken = 1;
15335                token = mNextInstallToken++;
15336
15337                PostInstallData data = new PostInstallData(args, res);
15338                mRunningInstalls.put(token, data);
15339                if (DEBUG_INSTALL) Log.v(TAG, "+ starting restore round-trip " + token);
15340
15341                if (res.returnCode == PackageManager.INSTALL_SUCCEEDED && doRestore) {
15342                    // Pass responsibility to the Backup Manager.  It will perform a
15343                    // restore if appropriate, then pass responsibility back to the
15344                    // Package Manager to run the post-install observer callbacks
15345                    // and broadcasts.
15346                    IBackupManager bm = IBackupManager.Stub.asInterface(
15347                            ServiceManager.getService(Context.BACKUP_SERVICE));
15348                    if (bm != null) {
15349                        if (DEBUG_INSTALL) Log.v(TAG, "token " + token
15350                                + " to BM for possible restore");
15351                        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "restore", token);
15352                        try {
15353                            // TODO: http://b/22388012
15354                            if (bm.isBackupServiceActive(UserHandle.USER_SYSTEM)) {
15355                                bm.restoreAtInstall(res.pkg.applicationInfo.packageName, token);
15356                            } else {
15357                                doRestore = false;
15358                            }
15359                        } catch (RemoteException e) {
15360                            // can't happen; the backup manager is local
15361                        } catch (Exception e) {
15362                            Slog.e(TAG, "Exception trying to enqueue restore", e);
15363                            doRestore = false;
15364                        }
15365                    } else {
15366                        Slog.e(TAG, "Backup Manager not found!");
15367                        doRestore = false;
15368                    }
15369                }
15370
15371                if (!doRestore) {
15372                    // No restore possible, or the Backup Manager was mysteriously not
15373                    // available -- just fire the post-install work request directly.
15374                    if (DEBUG_INSTALL) Log.v(TAG, "No restore - queue post-install for " + token);
15375
15376                    Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "postInstall", token);
15377
15378                    Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0);
15379                    mHandler.sendMessage(msg);
15380                }
15381            }
15382        });
15383    }
15384
15385    /**
15386     * Callback from PackageSettings whenever an app is first transitioned out of the
15387     * 'stopped' state.  Normally we just issue the broadcast, but we can't do that if
15388     * the app was "launched" for a restoreAtInstall operation.  Therefore we check
15389     * here whether the app is the target of an ongoing install, and only send the
15390     * broadcast immediately if it is not in that state.  If it *is* undergoing a restore,
15391     * the first-launch broadcast will be sent implicitly on that basis in POST_INSTALL
15392     * handling.
15393     */
15394    void notifyFirstLaunch(final String pkgName, final String installerPackage, final int userId) {
15395        // Serialize this with the rest of the install-process message chain.  In the
15396        // restore-at-install case, this Runnable will necessarily run before the
15397        // POST_INSTALL message is processed, so the contents of mRunningInstalls
15398        // are coherent.  In the non-restore case, the app has already completed install
15399        // and been launched through some other means, so it is not in a problematic
15400        // state for observers to see the FIRST_LAUNCH signal.
15401        mHandler.post(new Runnable() {
15402            @Override
15403            public void run() {
15404                for (int i = 0; i < mRunningInstalls.size(); i++) {
15405                    final PostInstallData data = mRunningInstalls.valueAt(i);
15406                    if (data.res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
15407                        continue;
15408                    }
15409                    if (pkgName.equals(data.res.pkg.applicationInfo.packageName)) {
15410                        // right package; but is it for the right user?
15411                        for (int uIndex = 0; uIndex < data.res.newUsers.length; uIndex++) {
15412                            if (userId == data.res.newUsers[uIndex]) {
15413                                if (DEBUG_BACKUP) {
15414                                    Slog.i(TAG, "Package " + pkgName
15415                                            + " being restored so deferring FIRST_LAUNCH");
15416                                }
15417                                return;
15418                            }
15419                        }
15420                    }
15421                }
15422                // didn't find it, so not being restored
15423                if (DEBUG_BACKUP) {
15424                    Slog.i(TAG, "Package " + pkgName + " sending normal FIRST_LAUNCH");
15425                }
15426                sendFirstLaunchBroadcast(pkgName, installerPackage, new int[] {userId});
15427            }
15428        });
15429    }
15430
15431    private void sendFirstLaunchBroadcast(String pkgName, String installerPkg, int[] userIds) {
15432        sendPackageBroadcast(Intent.ACTION_PACKAGE_FIRST_LAUNCH, pkgName, null, 0,
15433                installerPkg, null, userIds);
15434    }
15435
15436    private abstract class HandlerParams {
15437        private static final int MAX_RETRIES = 4;
15438
15439        /**
15440         * Number of times startCopy() has been attempted and had a non-fatal
15441         * error.
15442         */
15443        private int mRetries = 0;
15444
15445        /** User handle for the user requesting the information or installation. */
15446        private final UserHandle mUser;
15447        String traceMethod;
15448        int traceCookie;
15449
15450        HandlerParams(UserHandle user) {
15451            mUser = user;
15452        }
15453
15454        UserHandle getUser() {
15455            return mUser;
15456        }
15457
15458        HandlerParams setTraceMethod(String traceMethod) {
15459            this.traceMethod = traceMethod;
15460            return this;
15461        }
15462
15463        HandlerParams setTraceCookie(int traceCookie) {
15464            this.traceCookie = traceCookie;
15465            return this;
15466        }
15467
15468        final boolean startCopy() {
15469            boolean res;
15470            try {
15471                if (DEBUG_INSTALL) Slog.i(TAG, "startCopy " + mUser + ": " + this);
15472
15473                if (++mRetries > MAX_RETRIES) {
15474                    Slog.w(TAG, "Failed to invoke remote methods on default container service. Giving up");
15475                    mHandler.sendEmptyMessage(MCS_GIVE_UP);
15476                    handleServiceError();
15477                    return false;
15478                } else {
15479                    handleStartCopy();
15480                    res = true;
15481                }
15482            } catch (RemoteException e) {
15483                if (DEBUG_INSTALL) Slog.i(TAG, "Posting install MCS_RECONNECT");
15484                mHandler.sendEmptyMessage(MCS_RECONNECT);
15485                res = false;
15486            }
15487            handleReturnCode();
15488            return res;
15489        }
15490
15491        final void serviceError() {
15492            if (DEBUG_INSTALL) Slog.i(TAG, "serviceError");
15493            handleServiceError();
15494            handleReturnCode();
15495        }
15496
15497        abstract void handleStartCopy() throws RemoteException;
15498        abstract void handleServiceError();
15499        abstract void handleReturnCode();
15500    }
15501
15502    private static void clearDirectory(IMediaContainerService mcs, File[] paths) {
15503        for (File path : paths) {
15504            try {
15505                mcs.clearDirectory(path.getAbsolutePath());
15506            } catch (RemoteException e) {
15507            }
15508        }
15509    }
15510
15511    static class OriginInfo {
15512        /**
15513         * Location where install is coming from, before it has been
15514         * copied/renamed into place. This could be a single monolithic APK
15515         * file, or a cluster directory. This location may be untrusted.
15516         */
15517        final File file;
15518        final String cid;
15519
15520        /**
15521         * Flag indicating that {@link #file} or {@link #cid} has already been
15522         * staged, meaning downstream users don't need to defensively copy the
15523         * contents.
15524         */
15525        final boolean staged;
15526
15527        /**
15528         * Flag indicating that {@link #file} or {@link #cid} is an already
15529         * installed app that is being moved.
15530         */
15531        final boolean existing;
15532
15533        final String resolvedPath;
15534        final File resolvedFile;
15535
15536        static OriginInfo fromNothing() {
15537            return new OriginInfo(null, null, false, false);
15538        }
15539
15540        static OriginInfo fromUntrustedFile(File file) {
15541            return new OriginInfo(file, null, false, false);
15542        }
15543
15544        static OriginInfo fromExistingFile(File file) {
15545            return new OriginInfo(file, null, false, true);
15546        }
15547
15548        static OriginInfo fromStagedFile(File file) {
15549            return new OriginInfo(file, null, true, false);
15550        }
15551
15552        static OriginInfo fromStagedContainer(String cid) {
15553            return new OriginInfo(null, cid, true, false);
15554        }
15555
15556        private OriginInfo(File file, String cid, boolean staged, boolean existing) {
15557            this.file = file;
15558            this.cid = cid;
15559            this.staged = staged;
15560            this.existing = existing;
15561
15562            if (cid != null) {
15563                resolvedPath = PackageHelper.getSdDir(cid);
15564                resolvedFile = new File(resolvedPath);
15565            } else if (file != null) {
15566                resolvedPath = file.getAbsolutePath();
15567                resolvedFile = file;
15568            } else {
15569                resolvedPath = null;
15570                resolvedFile = null;
15571            }
15572        }
15573    }
15574
15575    static class MoveInfo {
15576        final int moveId;
15577        final String fromUuid;
15578        final String toUuid;
15579        final String packageName;
15580        final String dataAppName;
15581        final int appId;
15582        final String seinfo;
15583        final int targetSdkVersion;
15584
15585        public MoveInfo(int moveId, String fromUuid, String toUuid, String packageName,
15586                String dataAppName, int appId, String seinfo, int targetSdkVersion) {
15587            this.moveId = moveId;
15588            this.fromUuid = fromUuid;
15589            this.toUuid = toUuid;
15590            this.packageName = packageName;
15591            this.dataAppName = dataAppName;
15592            this.appId = appId;
15593            this.seinfo = seinfo;
15594            this.targetSdkVersion = targetSdkVersion;
15595        }
15596    }
15597
15598    static class VerificationInfo {
15599        /** A constant used to indicate that a uid value is not present. */
15600        public static final int NO_UID = -1;
15601
15602        /** URI referencing where the package was downloaded from. */
15603        final Uri originatingUri;
15604
15605        /** HTTP referrer URI associated with the originatingURI. */
15606        final Uri referrer;
15607
15608        /** UID of the application that the install request originated from. */
15609        final int originatingUid;
15610
15611        /** UID of application requesting the install */
15612        final int installerUid;
15613
15614        VerificationInfo(Uri originatingUri, Uri referrer, int originatingUid, int installerUid) {
15615            this.originatingUri = originatingUri;
15616            this.referrer = referrer;
15617            this.originatingUid = originatingUid;
15618            this.installerUid = installerUid;
15619        }
15620    }
15621
15622    class InstallParams extends HandlerParams {
15623        final OriginInfo origin;
15624        final MoveInfo move;
15625        final IPackageInstallObserver2 observer;
15626        int installFlags;
15627        final String installerPackageName;
15628        final String volumeUuid;
15629        private InstallArgs mArgs;
15630        private int mRet;
15631        final String packageAbiOverride;
15632        final String[] grantedRuntimePermissions;
15633        final VerificationInfo verificationInfo;
15634        final Certificate[][] certificates;
15635        final int installReason;
15636
15637        InstallParams(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer,
15638                int installFlags, String installerPackageName, String volumeUuid,
15639                VerificationInfo verificationInfo, UserHandle user, String packageAbiOverride,
15640                String[] grantedPermissions, Certificate[][] certificates, int installReason) {
15641            super(user);
15642            this.origin = origin;
15643            this.move = move;
15644            this.observer = observer;
15645            this.installFlags = installFlags;
15646            this.installerPackageName = installerPackageName;
15647            this.volumeUuid = volumeUuid;
15648            this.verificationInfo = verificationInfo;
15649            this.packageAbiOverride = packageAbiOverride;
15650            this.grantedRuntimePermissions = grantedPermissions;
15651            this.certificates = certificates;
15652            this.installReason = installReason;
15653        }
15654
15655        @Override
15656        public String toString() {
15657            return "InstallParams{" + Integer.toHexString(System.identityHashCode(this))
15658                    + " file=" + origin.file + " cid=" + origin.cid + "}";
15659        }
15660
15661        private int installLocationPolicy(PackageInfoLite pkgLite) {
15662            String packageName = pkgLite.packageName;
15663            int installLocation = pkgLite.installLocation;
15664            boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
15665            // reader
15666            synchronized (mPackages) {
15667                // Currently installed package which the new package is attempting to replace or
15668                // null if no such package is installed.
15669                PackageParser.Package installedPkg = mPackages.get(packageName);
15670                // Package which currently owns the data which the new package will own if installed.
15671                // If an app is unstalled while keeping data (e.g., adb uninstall -k), installedPkg
15672                // will be null whereas dataOwnerPkg will contain information about the package
15673                // which was uninstalled while keeping its data.
15674                PackageParser.Package dataOwnerPkg = installedPkg;
15675                if (dataOwnerPkg  == null) {
15676                    PackageSetting ps = mSettings.mPackages.get(packageName);
15677                    if (ps != null) {
15678                        dataOwnerPkg = ps.pkg;
15679                    }
15680                }
15681
15682                if (dataOwnerPkg != null) {
15683                    // If installed, the package will get access to data left on the device by its
15684                    // predecessor. As a security measure, this is permited only if this is not a
15685                    // version downgrade or if the predecessor package is marked as debuggable and
15686                    // a downgrade is explicitly requested.
15687                    //
15688                    // On debuggable platform builds, downgrades are permitted even for
15689                    // non-debuggable packages to make testing easier. Debuggable platform builds do
15690                    // not offer security guarantees and thus it's OK to disable some security
15691                    // mechanisms to make debugging/testing easier on those builds. However, even on
15692                    // debuggable builds downgrades of packages are permitted only if requested via
15693                    // installFlags. This is because we aim to keep the behavior of debuggable
15694                    // platform builds as close as possible to the behavior of non-debuggable
15695                    // platform builds.
15696                    final boolean downgradeRequested =
15697                            (installFlags & PackageManager.INSTALL_ALLOW_DOWNGRADE) != 0;
15698                    final boolean packageDebuggable =
15699                                (dataOwnerPkg.applicationInfo.flags
15700                                        & ApplicationInfo.FLAG_DEBUGGABLE) != 0;
15701                    final boolean downgradePermitted =
15702                            (downgradeRequested) && ((Build.IS_DEBUGGABLE) || (packageDebuggable));
15703                    if (!downgradePermitted) {
15704                        try {
15705                            checkDowngrade(dataOwnerPkg, pkgLite);
15706                        } catch (PackageManagerException e) {
15707                            Slog.w(TAG, "Downgrade detected: " + e.getMessage());
15708                            return PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE;
15709                        }
15710                    }
15711                }
15712
15713                if (installedPkg != null) {
15714                    if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
15715                        // Check for updated system application.
15716                        if ((installedPkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
15717                            if (onSd) {
15718                                Slog.w(TAG, "Cannot install update to system app on sdcard");
15719                                return PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION;
15720                            }
15721                            return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
15722                        } else {
15723                            if (onSd) {
15724                                // Install flag overrides everything.
15725                                return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
15726                            }
15727                            // If current upgrade specifies particular preference
15728                            if (installLocation == PackageInfo.INSTALL_LOCATION_INTERNAL_ONLY) {
15729                                // Application explicitly specified internal.
15730                                return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
15731                            } else if (installLocation == PackageInfo.INSTALL_LOCATION_PREFER_EXTERNAL) {
15732                                // App explictly prefers external. Let policy decide
15733                            } else {
15734                                // Prefer previous location
15735                                if (isExternal(installedPkg)) {
15736                                    return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
15737                                }
15738                                return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
15739                            }
15740                        }
15741                    } else {
15742                        // Invalid install. Return error code
15743                        return PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS;
15744                    }
15745                }
15746            }
15747            // All the special cases have been taken care of.
15748            // Return result based on recommended install location.
15749            if (onSd) {
15750                return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
15751            }
15752            return pkgLite.recommendedInstallLocation;
15753        }
15754
15755        /*
15756         * Invoke remote method to get package information and install
15757         * location values. Override install location based on default
15758         * policy if needed and then create install arguments based
15759         * on the install location.
15760         */
15761        public void handleStartCopy() throws RemoteException {
15762            int ret = PackageManager.INSTALL_SUCCEEDED;
15763
15764            // If we're already staged, we've firmly committed to an install location
15765            if (origin.staged) {
15766                if (origin.file != null) {
15767                    installFlags |= PackageManager.INSTALL_INTERNAL;
15768                    installFlags &= ~PackageManager.INSTALL_EXTERNAL;
15769                } else if (origin.cid != null) {
15770                    installFlags |= PackageManager.INSTALL_EXTERNAL;
15771                    installFlags &= ~PackageManager.INSTALL_INTERNAL;
15772                } else {
15773                    throw new IllegalStateException("Invalid stage location");
15774                }
15775            }
15776
15777            final boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
15778            final boolean onInt = (installFlags & PackageManager.INSTALL_INTERNAL) != 0;
15779            final boolean ephemeral = (installFlags & PackageManager.INSTALL_INSTANT_APP) != 0;
15780            PackageInfoLite pkgLite = null;
15781
15782            if (onInt && onSd) {
15783                // Check if both bits are set.
15784                Slog.w(TAG, "Conflicting flags specified for installing on both internal and external");
15785                ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
15786            } else if (onSd && ephemeral) {
15787                Slog.w(TAG,  "Conflicting flags specified for installing ephemeral on external");
15788                ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
15789            } else {
15790                pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, installFlags,
15791                        packageAbiOverride);
15792
15793                if (DEBUG_EPHEMERAL && ephemeral) {
15794                    Slog.v(TAG, "pkgLite for install: " + pkgLite);
15795                }
15796
15797                /*
15798                 * If we have too little free space, try to free cache
15799                 * before giving up.
15800                 */
15801                if (!origin.staged && pkgLite.recommendedInstallLocation
15802                        == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) {
15803                    // TODO: focus freeing disk space on the target device
15804                    final StorageManager storage = StorageManager.from(mContext);
15805                    final long lowThreshold = storage.getStorageLowBytes(
15806                            Environment.getDataDirectory());
15807
15808                    final long sizeBytes = mContainerService.calculateInstalledSize(
15809                            origin.resolvedPath, isForwardLocked(), packageAbiOverride);
15810
15811                    try {
15812                        mInstaller.freeCache(null, sizeBytes + lowThreshold, 0, 0);
15813                        pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath,
15814                                installFlags, packageAbiOverride);
15815                    } catch (InstallerException e) {
15816                        Slog.w(TAG, "Failed to free cache", e);
15817                    }
15818
15819                    /*
15820                     * The cache free must have deleted the file we
15821                     * downloaded to install.
15822                     *
15823                     * TODO: fix the "freeCache" call to not delete
15824                     *       the file we care about.
15825                     */
15826                    if (pkgLite.recommendedInstallLocation
15827                            == PackageHelper.RECOMMEND_FAILED_INVALID_URI) {
15828                        pkgLite.recommendedInstallLocation
15829                            = PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE;
15830                    }
15831                }
15832            }
15833
15834            if (ret == PackageManager.INSTALL_SUCCEEDED) {
15835                int loc = pkgLite.recommendedInstallLocation;
15836                if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION) {
15837                    ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
15838                } else if (loc == PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS) {
15839                    ret = PackageManager.INSTALL_FAILED_ALREADY_EXISTS;
15840                } else if (loc == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) {
15841                    ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
15842                } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_APK) {
15843                    ret = PackageManager.INSTALL_FAILED_INVALID_APK;
15844                } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_URI) {
15845                    ret = PackageManager.INSTALL_FAILED_INVALID_URI;
15846                } else if (loc == PackageHelper.RECOMMEND_MEDIA_UNAVAILABLE) {
15847                    ret = PackageManager.INSTALL_FAILED_MEDIA_UNAVAILABLE;
15848                } else {
15849                    // Override with defaults if needed.
15850                    loc = installLocationPolicy(pkgLite);
15851                    if (loc == PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE) {
15852                        ret = PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE;
15853                    } else if (!onSd && !onInt) {
15854                        // Override install location with flags
15855                        if (loc == PackageHelper.RECOMMEND_INSTALL_EXTERNAL) {
15856                            // Set the flag to install on external media.
15857                            installFlags |= PackageManager.INSTALL_EXTERNAL;
15858                            installFlags &= ~PackageManager.INSTALL_INTERNAL;
15859                        } else if (loc == PackageHelper.RECOMMEND_INSTALL_EPHEMERAL) {
15860                            if (DEBUG_EPHEMERAL) {
15861                                Slog.v(TAG, "...setting INSTALL_EPHEMERAL install flag");
15862                            }
15863                            installFlags |= PackageManager.INSTALL_INSTANT_APP;
15864                            installFlags &= ~(PackageManager.INSTALL_EXTERNAL
15865                                    |PackageManager.INSTALL_INTERNAL);
15866                        } else {
15867                            // Make sure the flag for installing on external
15868                            // media is unset
15869                            installFlags |= PackageManager.INSTALL_INTERNAL;
15870                            installFlags &= ~PackageManager.INSTALL_EXTERNAL;
15871                        }
15872                    }
15873                }
15874            }
15875
15876            final InstallArgs args = createInstallArgs(this);
15877            mArgs = args;
15878
15879            if (ret == PackageManager.INSTALL_SUCCEEDED) {
15880                // TODO: http://b/22976637
15881                // Apps installed for "all" users use the device owner to verify the app
15882                UserHandle verifierUser = getUser();
15883                if (verifierUser == UserHandle.ALL) {
15884                    verifierUser = UserHandle.SYSTEM;
15885                }
15886
15887                /*
15888                 * Determine if we have any installed package verifiers. If we
15889                 * do, then we'll defer to them to verify the packages.
15890                 */
15891                final int requiredUid = mRequiredVerifierPackage == null ? -1
15892                        : getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING,
15893                                verifierUser.getIdentifier());
15894                final int installerUid =
15895                        verificationInfo == null ? -1 : verificationInfo.installerUid;
15896                if (!origin.existing && requiredUid != -1
15897                        && isVerificationEnabled(
15898                                verifierUser.getIdentifier(), installFlags, installerUid)) {
15899                    final Intent verification = new Intent(
15900                            Intent.ACTION_PACKAGE_NEEDS_VERIFICATION);
15901                    verification.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
15902                    verification.setDataAndType(Uri.fromFile(new File(origin.resolvedPath)),
15903                            PACKAGE_MIME_TYPE);
15904                    verification.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
15905
15906                    // Query all live verifiers based on current user state
15907                    final List<ResolveInfo> receivers = queryIntentReceiversInternal(verification,
15908                            PACKAGE_MIME_TYPE, 0, verifierUser.getIdentifier());
15909
15910                    if (DEBUG_VERIFY) {
15911                        Slog.d(TAG, "Found " + receivers.size() + " verifiers for intent "
15912                                + verification.toString() + " with " + pkgLite.verifiers.length
15913                                + " optional verifiers");
15914                    }
15915
15916                    final int verificationId = mPendingVerificationToken++;
15917
15918                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId);
15919
15920                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_PACKAGE,
15921                            installerPackageName);
15922
15923                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALL_FLAGS,
15924                            installFlags);
15925
15926                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_PACKAGE_NAME,
15927                            pkgLite.packageName);
15928
15929                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_VERSION_CODE,
15930                            pkgLite.versionCode);
15931
15932                    if (verificationInfo != null) {
15933                        if (verificationInfo.originatingUri != null) {
15934                            verification.putExtra(Intent.EXTRA_ORIGINATING_URI,
15935                                    verificationInfo.originatingUri);
15936                        }
15937                        if (verificationInfo.referrer != null) {
15938                            verification.putExtra(Intent.EXTRA_REFERRER,
15939                                    verificationInfo.referrer);
15940                        }
15941                        if (verificationInfo.originatingUid >= 0) {
15942                            verification.putExtra(Intent.EXTRA_ORIGINATING_UID,
15943                                    verificationInfo.originatingUid);
15944                        }
15945                        if (verificationInfo.installerUid >= 0) {
15946                            verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_UID,
15947                                    verificationInfo.installerUid);
15948                        }
15949                    }
15950
15951                    final PackageVerificationState verificationState = new PackageVerificationState(
15952                            requiredUid, args);
15953
15954                    mPendingVerification.append(verificationId, verificationState);
15955
15956                    final List<ComponentName> sufficientVerifiers = matchVerifiers(pkgLite,
15957                            receivers, verificationState);
15958
15959                    DeviceIdleController.LocalService idleController = getDeviceIdleController();
15960                    final long idleDuration = getVerificationTimeout();
15961
15962                    /*
15963                     * If any sufficient verifiers were listed in the package
15964                     * manifest, attempt to ask them.
15965                     */
15966                    if (sufficientVerifiers != null) {
15967                        final int N = sufficientVerifiers.size();
15968                        if (N == 0) {
15969                            Slog.i(TAG, "Additional verifiers required, but none installed.");
15970                            ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
15971                        } else {
15972                            for (int i = 0; i < N; i++) {
15973                                final ComponentName verifierComponent = sufficientVerifiers.get(i);
15974                                idleController.addPowerSaveTempWhitelistApp(Process.myUid(),
15975                                        verifierComponent.getPackageName(), idleDuration,
15976                                        verifierUser.getIdentifier(), false, "package verifier");
15977
15978                                final Intent sufficientIntent = new Intent(verification);
15979                                sufficientIntent.setComponent(verifierComponent);
15980                                mContext.sendBroadcastAsUser(sufficientIntent, verifierUser);
15981                            }
15982                        }
15983                    }
15984
15985                    final ComponentName requiredVerifierComponent = matchComponentForVerifier(
15986                            mRequiredVerifierPackage, receivers);
15987                    if (ret == PackageManager.INSTALL_SUCCEEDED
15988                            && mRequiredVerifierPackage != null) {
15989                        Trace.asyncTraceBegin(
15990                                TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId);
15991                        /*
15992                         * Send the intent to the required verification agent,
15993                         * but only start the verification timeout after the
15994                         * target BroadcastReceivers have run.
15995                         */
15996                        verification.setComponent(requiredVerifierComponent);
15997                        idleController.addPowerSaveTempWhitelistApp(Process.myUid(),
15998                                mRequiredVerifierPackage, idleDuration,
15999                                verifierUser.getIdentifier(), false, "package verifier");
16000                        mContext.sendOrderedBroadcastAsUser(verification, verifierUser,
16001                                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
16002                                new BroadcastReceiver() {
16003                                    @Override
16004                                    public void onReceive(Context context, Intent intent) {
16005                                        final Message msg = mHandler
16006                                                .obtainMessage(CHECK_PENDING_VERIFICATION);
16007                                        msg.arg1 = verificationId;
16008                                        mHandler.sendMessageDelayed(msg, getVerificationTimeout());
16009                                    }
16010                                }, null, 0, null, null);
16011
16012                        /*
16013                         * We don't want the copy to proceed until verification
16014                         * succeeds, so null out this field.
16015                         */
16016                        mArgs = null;
16017                    }
16018                } else {
16019                    /*
16020                     * No package verification is enabled, so immediately start
16021                     * the remote call to initiate copy using temporary file.
16022                     */
16023                    ret = args.copyApk(mContainerService, true);
16024                }
16025            }
16026
16027            mRet = ret;
16028        }
16029
16030        @Override
16031        void handleReturnCode() {
16032            // If mArgs is null, then MCS couldn't be reached. When it
16033            // reconnects, it will try again to install. At that point, this
16034            // will succeed.
16035            if (mArgs != null) {
16036                processPendingInstall(mArgs, mRet);
16037            }
16038        }
16039
16040        @Override
16041        void handleServiceError() {
16042            mArgs = createInstallArgs(this);
16043            mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
16044        }
16045
16046        public boolean isForwardLocked() {
16047            return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
16048        }
16049    }
16050
16051    /**
16052     * Used during creation of InstallArgs
16053     *
16054     * @param installFlags package installation flags
16055     * @return true if should be installed on external storage
16056     */
16057    private static boolean installOnExternalAsec(int installFlags) {
16058        if ((installFlags & PackageManager.INSTALL_INTERNAL) != 0) {
16059            return false;
16060        }
16061        if ((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) {
16062            return true;
16063        }
16064        return false;
16065    }
16066
16067    /**
16068     * Used during creation of InstallArgs
16069     *
16070     * @param installFlags package installation flags
16071     * @return true if should be installed as forward locked
16072     */
16073    private static boolean installForwardLocked(int installFlags) {
16074        return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
16075    }
16076
16077    private InstallArgs createInstallArgs(InstallParams params) {
16078        if (params.move != null) {
16079            return new MoveInstallArgs(params);
16080        } else if (installOnExternalAsec(params.installFlags) || params.isForwardLocked()) {
16081            return new AsecInstallArgs(params);
16082        } else {
16083            return new FileInstallArgs(params);
16084        }
16085    }
16086
16087    /**
16088     * Create args that describe an existing installed package. Typically used
16089     * when cleaning up old installs, or used as a move source.
16090     */
16091    private InstallArgs createInstallArgsForExisting(int installFlags, String codePath,
16092            String resourcePath, String[] instructionSets) {
16093        final boolean isInAsec;
16094        if (installOnExternalAsec(installFlags)) {
16095            /* Apps on SD card are always in ASEC containers. */
16096            isInAsec = true;
16097        } else if (installForwardLocked(installFlags)
16098                && !codePath.startsWith(mDrmAppPrivateInstallDir.getAbsolutePath())) {
16099            /*
16100             * Forward-locked apps are only in ASEC containers if they're the
16101             * new style
16102             */
16103            isInAsec = true;
16104        } else {
16105            isInAsec = false;
16106        }
16107
16108        if (isInAsec) {
16109            return new AsecInstallArgs(codePath, instructionSets,
16110                    installOnExternalAsec(installFlags), installForwardLocked(installFlags));
16111        } else {
16112            return new FileInstallArgs(codePath, resourcePath, instructionSets);
16113        }
16114    }
16115
16116    static abstract class InstallArgs {
16117        /** @see InstallParams#origin */
16118        final OriginInfo origin;
16119        /** @see InstallParams#move */
16120        final MoveInfo move;
16121
16122        final IPackageInstallObserver2 observer;
16123        // Always refers to PackageManager flags only
16124        final int installFlags;
16125        final String installerPackageName;
16126        final String volumeUuid;
16127        final UserHandle user;
16128        final String abiOverride;
16129        final String[] installGrantPermissions;
16130        /** If non-null, drop an async trace when the install completes */
16131        final String traceMethod;
16132        final int traceCookie;
16133        final Certificate[][] certificates;
16134        final int installReason;
16135
16136        // The list of instruction sets supported by this app. This is currently
16137        // only used during the rmdex() phase to clean up resources. We can get rid of this
16138        // if we move dex files under the common app path.
16139        /* nullable */ String[] instructionSets;
16140
16141        InstallArgs(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer,
16142                int installFlags, String installerPackageName, String volumeUuid,
16143                UserHandle user, String[] instructionSets,
16144                String abiOverride, String[] installGrantPermissions,
16145                String traceMethod, int traceCookie, Certificate[][] certificates,
16146                int installReason) {
16147            this.origin = origin;
16148            this.move = move;
16149            this.installFlags = installFlags;
16150            this.observer = observer;
16151            this.installerPackageName = installerPackageName;
16152            this.volumeUuid = volumeUuid;
16153            this.user = user;
16154            this.instructionSets = instructionSets;
16155            this.abiOverride = abiOverride;
16156            this.installGrantPermissions = installGrantPermissions;
16157            this.traceMethod = traceMethod;
16158            this.traceCookie = traceCookie;
16159            this.certificates = certificates;
16160            this.installReason = installReason;
16161        }
16162
16163        abstract int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException;
16164        abstract int doPreInstall(int status);
16165
16166        /**
16167         * Rename package into final resting place. All paths on the given
16168         * scanned package should be updated to reflect the rename.
16169         */
16170        abstract boolean doRename(int status, PackageParser.Package pkg, String oldCodePath);
16171        abstract int doPostInstall(int status, int uid);
16172
16173        /** @see PackageSettingBase#codePathString */
16174        abstract String getCodePath();
16175        /** @see PackageSettingBase#resourcePathString */
16176        abstract String getResourcePath();
16177
16178        // Need installer lock especially for dex file removal.
16179        abstract void cleanUpResourcesLI();
16180        abstract boolean doPostDeleteLI(boolean delete);
16181
16182        /**
16183         * Called before the source arguments are copied. This is used mostly
16184         * for MoveParams when it needs to read the source file to put it in the
16185         * destination.
16186         */
16187        int doPreCopy() {
16188            return PackageManager.INSTALL_SUCCEEDED;
16189        }
16190
16191        /**
16192         * Called after the source arguments are copied. This is used mostly for
16193         * MoveParams when it needs to read the source file to put it in the
16194         * destination.
16195         */
16196        int doPostCopy(int uid) {
16197            return PackageManager.INSTALL_SUCCEEDED;
16198        }
16199
16200        protected boolean isFwdLocked() {
16201            return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
16202        }
16203
16204        protected boolean isExternalAsec() {
16205            return (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
16206        }
16207
16208        protected boolean isEphemeral() {
16209            return (installFlags & PackageManager.INSTALL_INSTANT_APP) != 0;
16210        }
16211
16212        UserHandle getUser() {
16213            return user;
16214        }
16215    }
16216
16217    private void removeDexFiles(List<String> allCodePaths, String[] instructionSets) {
16218        if (!allCodePaths.isEmpty()) {
16219            if (instructionSets == null) {
16220                throw new IllegalStateException("instructionSet == null");
16221            }
16222            String[] dexCodeInstructionSets = getDexCodeInstructionSets(instructionSets);
16223            for (String codePath : allCodePaths) {
16224                for (String dexCodeInstructionSet : dexCodeInstructionSets) {
16225                    try {
16226                        mInstaller.rmdex(codePath, dexCodeInstructionSet);
16227                    } catch (InstallerException ignored) {
16228                    }
16229                }
16230            }
16231        }
16232    }
16233
16234    /**
16235     * Logic to handle installation of non-ASEC applications, including copying
16236     * and renaming logic.
16237     */
16238    class FileInstallArgs extends InstallArgs {
16239        private File codeFile;
16240        private File resourceFile;
16241
16242        // Example topology:
16243        // /data/app/com.example/base.apk
16244        // /data/app/com.example/split_foo.apk
16245        // /data/app/com.example/lib/arm/libfoo.so
16246        // /data/app/com.example/lib/arm64/libfoo.so
16247        // /data/app/com.example/dalvik/arm/base.apk@classes.dex
16248
16249        /** New install */
16250        FileInstallArgs(InstallParams params) {
16251            super(params.origin, params.move, params.observer, params.installFlags,
16252                    params.installerPackageName, params.volumeUuid,
16253                    params.getUser(), null /*instructionSets*/, params.packageAbiOverride,
16254                    params.grantedRuntimePermissions,
16255                    params.traceMethod, params.traceCookie, params.certificates,
16256                    params.installReason);
16257            if (isFwdLocked()) {
16258                throw new IllegalArgumentException("Forward locking only supported in ASEC");
16259            }
16260        }
16261
16262        /** Existing install */
16263        FileInstallArgs(String codePath, String resourcePath, String[] instructionSets) {
16264            super(OriginInfo.fromNothing(), null, null, 0, null, null, null, instructionSets,
16265                    null, null, null, 0, null /*certificates*/,
16266                    PackageManager.INSTALL_REASON_UNKNOWN);
16267            this.codeFile = (codePath != null) ? new File(codePath) : null;
16268            this.resourceFile = (resourcePath != null) ? new File(resourcePath) : null;
16269        }
16270
16271        int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
16272            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyApk");
16273            try {
16274                return doCopyApk(imcs, temp);
16275            } finally {
16276                Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
16277            }
16278        }
16279
16280        private int doCopyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
16281            if (origin.staged) {
16282                if (DEBUG_INSTALL) Slog.d(TAG, origin.file + " already staged; skipping copy");
16283                codeFile = origin.file;
16284                resourceFile = origin.file;
16285                return PackageManager.INSTALL_SUCCEEDED;
16286            }
16287
16288            try {
16289                final boolean isEphemeral = (installFlags & PackageManager.INSTALL_INSTANT_APP) != 0;
16290                final File tempDir =
16291                        mInstallerService.allocateStageDirLegacy(volumeUuid, isEphemeral);
16292                codeFile = tempDir;
16293                resourceFile = tempDir;
16294            } catch (IOException e) {
16295                Slog.w(TAG, "Failed to create copy file: " + e);
16296                return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
16297            }
16298
16299            final IParcelFileDescriptorFactory target = new IParcelFileDescriptorFactory.Stub() {
16300                @Override
16301                public ParcelFileDescriptor open(String name, int mode) throws RemoteException {
16302                    if (!FileUtils.isValidExtFilename(name)) {
16303                        throw new IllegalArgumentException("Invalid filename: " + name);
16304                    }
16305                    try {
16306                        final File file = new File(codeFile, name);
16307                        final FileDescriptor fd = Os.open(file.getAbsolutePath(),
16308                                O_RDWR | O_CREAT, 0644);
16309                        Os.chmod(file.getAbsolutePath(), 0644);
16310                        return new ParcelFileDescriptor(fd);
16311                    } catch (ErrnoException e) {
16312                        throw new RemoteException("Failed to open: " + e.getMessage());
16313                    }
16314                }
16315            };
16316
16317            int ret = PackageManager.INSTALL_SUCCEEDED;
16318            ret = imcs.copyPackage(origin.file.getAbsolutePath(), target);
16319            if (ret != PackageManager.INSTALL_SUCCEEDED) {
16320                Slog.e(TAG, "Failed to copy package");
16321                return ret;
16322            }
16323
16324            final File libraryRoot = new File(codeFile, LIB_DIR_NAME);
16325            NativeLibraryHelper.Handle handle = null;
16326            try {
16327                handle = NativeLibraryHelper.Handle.create(codeFile);
16328                ret = NativeLibraryHelper.copyNativeBinariesWithOverride(handle, libraryRoot,
16329                        abiOverride);
16330            } catch (IOException e) {
16331                Slog.e(TAG, "Copying native libraries failed", e);
16332                ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
16333            } finally {
16334                IoUtils.closeQuietly(handle);
16335            }
16336
16337            return ret;
16338        }
16339
16340        int doPreInstall(int status) {
16341            if (status != PackageManager.INSTALL_SUCCEEDED) {
16342                cleanUp();
16343            }
16344            return status;
16345        }
16346
16347        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
16348            if (status != PackageManager.INSTALL_SUCCEEDED) {
16349                cleanUp();
16350                return false;
16351            }
16352
16353            final File targetDir = codeFile.getParentFile();
16354            final File beforeCodeFile = codeFile;
16355            final File afterCodeFile = getNextCodePath(targetDir, pkg.packageName);
16356
16357            if (DEBUG_INSTALL) Slog.d(TAG, "Renaming " + beforeCodeFile + " to " + afterCodeFile);
16358            try {
16359                Os.rename(beforeCodeFile.getAbsolutePath(), afterCodeFile.getAbsolutePath());
16360            } catch (ErrnoException e) {
16361                Slog.w(TAG, "Failed to rename", e);
16362                return false;
16363            }
16364
16365            if (!SELinux.restoreconRecursive(afterCodeFile)) {
16366                Slog.w(TAG, "Failed to restorecon");
16367                return false;
16368            }
16369
16370            // Reflect the rename internally
16371            codeFile = afterCodeFile;
16372            resourceFile = afterCodeFile;
16373
16374            // Reflect the rename in scanned details
16375            pkg.setCodePath(afterCodeFile.getAbsolutePath());
16376            pkg.setBaseCodePath(FileUtils.rewriteAfterRename(beforeCodeFile,
16377                    afterCodeFile, pkg.baseCodePath));
16378            pkg.setSplitCodePaths(FileUtils.rewriteAfterRename(beforeCodeFile,
16379                    afterCodeFile, pkg.splitCodePaths));
16380
16381            // Reflect the rename in app info
16382            pkg.setApplicationVolumeUuid(pkg.volumeUuid);
16383            pkg.setApplicationInfoCodePath(pkg.codePath);
16384            pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
16385            pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
16386            pkg.setApplicationInfoResourcePath(pkg.codePath);
16387            pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath);
16388            pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
16389
16390            return true;
16391        }
16392
16393        int doPostInstall(int status, int uid) {
16394            if (status != PackageManager.INSTALL_SUCCEEDED) {
16395                cleanUp();
16396            }
16397            return status;
16398        }
16399
16400        @Override
16401        String getCodePath() {
16402            return (codeFile != null) ? codeFile.getAbsolutePath() : null;
16403        }
16404
16405        @Override
16406        String getResourcePath() {
16407            return (resourceFile != null) ? resourceFile.getAbsolutePath() : null;
16408        }
16409
16410        private boolean cleanUp() {
16411            if (codeFile == null || !codeFile.exists()) {
16412                return false;
16413            }
16414
16415            removeCodePathLI(codeFile);
16416
16417            if (resourceFile != null && !FileUtils.contains(codeFile, resourceFile)) {
16418                resourceFile.delete();
16419            }
16420
16421            return true;
16422        }
16423
16424        void cleanUpResourcesLI() {
16425            // Try enumerating all code paths before deleting
16426            List<String> allCodePaths = Collections.EMPTY_LIST;
16427            if (codeFile != null && codeFile.exists()) {
16428                try {
16429                    final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0);
16430                    allCodePaths = pkg.getAllCodePaths();
16431                } catch (PackageParserException e) {
16432                    // Ignored; we tried our best
16433                }
16434            }
16435
16436            cleanUp();
16437            removeDexFiles(allCodePaths, instructionSets);
16438        }
16439
16440        boolean doPostDeleteLI(boolean delete) {
16441            // XXX err, shouldn't we respect the delete flag?
16442            cleanUpResourcesLI();
16443            return true;
16444        }
16445    }
16446
16447    private boolean isAsecExternal(String cid) {
16448        final String asecPath = PackageHelper.getSdFilesystem(cid);
16449        return !asecPath.startsWith(mAsecInternalPath);
16450    }
16451
16452    private static void maybeThrowExceptionForMultiArchCopy(String message, int copyRet) throws
16453            PackageManagerException {
16454        if (copyRet < 0) {
16455            if (copyRet != PackageManager.NO_NATIVE_LIBRARIES &&
16456                    copyRet != PackageManager.INSTALL_FAILED_NO_MATCHING_ABIS) {
16457                throw new PackageManagerException(copyRet, message);
16458            }
16459        }
16460    }
16461
16462    /**
16463     * Extract the StorageManagerService "container ID" from the full code path of an
16464     * .apk.
16465     */
16466    static String cidFromCodePath(String fullCodePath) {
16467        int eidx = fullCodePath.lastIndexOf("/");
16468        String subStr1 = fullCodePath.substring(0, eidx);
16469        int sidx = subStr1.lastIndexOf("/");
16470        return subStr1.substring(sidx+1, eidx);
16471    }
16472
16473    /**
16474     * Logic to handle installation of ASEC applications, including copying and
16475     * renaming logic.
16476     */
16477    class AsecInstallArgs extends InstallArgs {
16478        static final String RES_FILE_NAME = "pkg.apk";
16479        static final String PUBLIC_RES_FILE_NAME = "res.zip";
16480
16481        String cid;
16482        String packagePath;
16483        String resourcePath;
16484
16485        /** New install */
16486        AsecInstallArgs(InstallParams params) {
16487            super(params.origin, params.move, params.observer, params.installFlags,
16488                    params.installerPackageName, params.volumeUuid,
16489                    params.getUser(), null /* instruction sets */, params.packageAbiOverride,
16490                    params.grantedRuntimePermissions,
16491                    params.traceMethod, params.traceCookie, params.certificates,
16492                    params.installReason);
16493        }
16494
16495        /** Existing install */
16496        AsecInstallArgs(String fullCodePath, String[] instructionSets,
16497                        boolean isExternal, boolean isForwardLocked) {
16498            super(OriginInfo.fromNothing(), null, null, (isExternal ? INSTALL_EXTERNAL : 0)
16499                    | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null,
16500                    instructionSets, null, null, null, 0, null /*certificates*/,
16501                    PackageManager.INSTALL_REASON_UNKNOWN);
16502            // Hackily pretend we're still looking at a full code path
16503            if (!fullCodePath.endsWith(RES_FILE_NAME)) {
16504                fullCodePath = new File(fullCodePath, RES_FILE_NAME).getAbsolutePath();
16505            }
16506
16507            // Extract cid from fullCodePath
16508            int eidx = fullCodePath.lastIndexOf("/");
16509            String subStr1 = fullCodePath.substring(0, eidx);
16510            int sidx = subStr1.lastIndexOf("/");
16511            cid = subStr1.substring(sidx+1, eidx);
16512            setMountPath(subStr1);
16513        }
16514
16515        AsecInstallArgs(String cid, String[] instructionSets, boolean isForwardLocked) {
16516            super(OriginInfo.fromNothing(), null, null, (isAsecExternal(cid) ? INSTALL_EXTERNAL : 0)
16517                    | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null,
16518                    instructionSets, null, null, null, 0, null /*certificates*/,
16519                    PackageManager.INSTALL_REASON_UNKNOWN);
16520            this.cid = cid;
16521            setMountPath(PackageHelper.getSdDir(cid));
16522        }
16523
16524        void createCopyFile() {
16525            cid = mInstallerService.allocateExternalStageCidLegacy();
16526        }
16527
16528        int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
16529            if (origin.staged && origin.cid != null) {
16530                if (DEBUG_INSTALL) Slog.d(TAG, origin.cid + " already staged; skipping copy");
16531                cid = origin.cid;
16532                setMountPath(PackageHelper.getSdDir(cid));
16533                return PackageManager.INSTALL_SUCCEEDED;
16534            }
16535
16536            if (temp) {
16537                createCopyFile();
16538            } else {
16539                /*
16540                 * Pre-emptively destroy the container since it's destroyed if
16541                 * copying fails due to it existing anyway.
16542                 */
16543                PackageHelper.destroySdDir(cid);
16544            }
16545
16546            final String newMountPath = imcs.copyPackageToContainer(
16547                    origin.file.getAbsolutePath(), cid, getEncryptKey(), isExternalAsec(),
16548                    isFwdLocked(), deriveAbiOverride(abiOverride, null /* settings */));
16549
16550            if (newMountPath != null) {
16551                setMountPath(newMountPath);
16552                return PackageManager.INSTALL_SUCCEEDED;
16553            } else {
16554                return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
16555            }
16556        }
16557
16558        @Override
16559        String getCodePath() {
16560            return packagePath;
16561        }
16562
16563        @Override
16564        String getResourcePath() {
16565            return resourcePath;
16566        }
16567
16568        int doPreInstall(int status) {
16569            if (status != PackageManager.INSTALL_SUCCEEDED) {
16570                // Destroy container
16571                PackageHelper.destroySdDir(cid);
16572            } else {
16573                boolean mounted = PackageHelper.isContainerMounted(cid);
16574                if (!mounted) {
16575                    String newMountPath = PackageHelper.mountSdDir(cid, getEncryptKey(),
16576                            Process.SYSTEM_UID);
16577                    if (newMountPath != null) {
16578                        setMountPath(newMountPath);
16579                    } else {
16580                        return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
16581                    }
16582                }
16583            }
16584            return status;
16585        }
16586
16587        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
16588            String newCacheId = getNextCodePath(oldCodePath, pkg.packageName, "/" + RES_FILE_NAME);
16589            String newMountPath = null;
16590            if (PackageHelper.isContainerMounted(cid)) {
16591                // Unmount the container
16592                if (!PackageHelper.unMountSdDir(cid)) {
16593                    Slog.i(TAG, "Failed to unmount " + cid + " before renaming");
16594                    return false;
16595                }
16596            }
16597            if (!PackageHelper.renameSdDir(cid, newCacheId)) {
16598                Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId +
16599                        " which might be stale. Will try to clean up.");
16600                // Clean up the stale container and proceed to recreate.
16601                if (!PackageHelper.destroySdDir(newCacheId)) {
16602                    Slog.e(TAG, "Very strange. Cannot clean up stale container " + newCacheId);
16603                    return false;
16604                }
16605                // Successfully cleaned up stale container. Try to rename again.
16606                if (!PackageHelper.renameSdDir(cid, newCacheId)) {
16607                    Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId
16608                            + " inspite of cleaning it up.");
16609                    return false;
16610                }
16611            }
16612            if (!PackageHelper.isContainerMounted(newCacheId)) {
16613                Slog.w(TAG, "Mounting container " + newCacheId);
16614                newMountPath = PackageHelper.mountSdDir(newCacheId,
16615                        getEncryptKey(), Process.SYSTEM_UID);
16616            } else {
16617                newMountPath = PackageHelper.getSdDir(newCacheId);
16618            }
16619            if (newMountPath == null) {
16620                Slog.w(TAG, "Failed to get cache path for  " + newCacheId);
16621                return false;
16622            }
16623            Log.i(TAG, "Succesfully renamed " + cid +
16624                    " to " + newCacheId +
16625                    " at new path: " + newMountPath);
16626            cid = newCacheId;
16627
16628            final File beforeCodeFile = new File(packagePath);
16629            setMountPath(newMountPath);
16630            final File afterCodeFile = new File(packagePath);
16631
16632            // Reflect the rename in scanned details
16633            pkg.setCodePath(afterCodeFile.getAbsolutePath());
16634            pkg.setBaseCodePath(FileUtils.rewriteAfterRename(beforeCodeFile,
16635                    afterCodeFile, pkg.baseCodePath));
16636            pkg.setSplitCodePaths(FileUtils.rewriteAfterRename(beforeCodeFile,
16637                    afterCodeFile, pkg.splitCodePaths));
16638
16639            // Reflect the rename in app info
16640            pkg.setApplicationVolumeUuid(pkg.volumeUuid);
16641            pkg.setApplicationInfoCodePath(pkg.codePath);
16642            pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
16643            pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
16644            pkg.setApplicationInfoResourcePath(pkg.codePath);
16645            pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath);
16646            pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
16647
16648            return true;
16649        }
16650
16651        private void setMountPath(String mountPath) {
16652            final File mountFile = new File(mountPath);
16653
16654            final File monolithicFile = new File(mountFile, RES_FILE_NAME);
16655            if (monolithicFile.exists()) {
16656                packagePath = monolithicFile.getAbsolutePath();
16657                if (isFwdLocked()) {
16658                    resourcePath = new File(mountFile, PUBLIC_RES_FILE_NAME).getAbsolutePath();
16659                } else {
16660                    resourcePath = packagePath;
16661                }
16662            } else {
16663                packagePath = mountFile.getAbsolutePath();
16664                resourcePath = packagePath;
16665            }
16666        }
16667
16668        int doPostInstall(int status, int uid) {
16669            if (status != PackageManager.INSTALL_SUCCEEDED) {
16670                cleanUp();
16671            } else {
16672                final int groupOwner;
16673                final String protectedFile;
16674                if (isFwdLocked()) {
16675                    groupOwner = UserHandle.getSharedAppGid(uid);
16676                    protectedFile = RES_FILE_NAME;
16677                } else {
16678                    groupOwner = -1;
16679                    protectedFile = null;
16680                }
16681
16682                if (uid < Process.FIRST_APPLICATION_UID
16683                        || !PackageHelper.fixSdPermissions(cid, groupOwner, protectedFile)) {
16684                    Slog.e(TAG, "Failed to finalize " + cid);
16685                    PackageHelper.destroySdDir(cid);
16686                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
16687                }
16688
16689                boolean mounted = PackageHelper.isContainerMounted(cid);
16690                if (!mounted) {
16691                    PackageHelper.mountSdDir(cid, getEncryptKey(), Process.myUid());
16692                }
16693            }
16694            return status;
16695        }
16696
16697        private void cleanUp() {
16698            if (DEBUG_SD_INSTALL) Slog.i(TAG, "cleanUp");
16699
16700            // Destroy secure container
16701            PackageHelper.destroySdDir(cid);
16702        }
16703
16704        private List<String> getAllCodePaths() {
16705            final File codeFile = new File(getCodePath());
16706            if (codeFile != null && codeFile.exists()) {
16707                try {
16708                    final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0);
16709                    return pkg.getAllCodePaths();
16710                } catch (PackageParserException e) {
16711                    // Ignored; we tried our best
16712                }
16713            }
16714            return Collections.EMPTY_LIST;
16715        }
16716
16717        void cleanUpResourcesLI() {
16718            // Enumerate all code paths before deleting
16719            cleanUpResourcesLI(getAllCodePaths());
16720        }
16721
16722        private void cleanUpResourcesLI(List<String> allCodePaths) {
16723            cleanUp();
16724            removeDexFiles(allCodePaths, instructionSets);
16725        }
16726
16727        String getPackageName() {
16728            return getAsecPackageName(cid);
16729        }
16730
16731        boolean doPostDeleteLI(boolean delete) {
16732            if (DEBUG_SD_INSTALL) Slog.i(TAG, "doPostDeleteLI() del=" + delete);
16733            final List<String> allCodePaths = getAllCodePaths();
16734            boolean mounted = PackageHelper.isContainerMounted(cid);
16735            if (mounted) {
16736                // Unmount first
16737                if (PackageHelper.unMountSdDir(cid)) {
16738                    mounted = false;
16739                }
16740            }
16741            if (!mounted && delete) {
16742                cleanUpResourcesLI(allCodePaths);
16743            }
16744            return !mounted;
16745        }
16746
16747        @Override
16748        int doPreCopy() {
16749            if (isFwdLocked()) {
16750                if (!PackageHelper.fixSdPermissions(cid, getPackageUid(DEFAULT_CONTAINER_PACKAGE,
16751                        MATCH_SYSTEM_ONLY, UserHandle.USER_SYSTEM), RES_FILE_NAME)) {
16752                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
16753                }
16754            }
16755
16756            return PackageManager.INSTALL_SUCCEEDED;
16757        }
16758
16759        @Override
16760        int doPostCopy(int uid) {
16761            if (isFwdLocked()) {
16762                if (uid < Process.FIRST_APPLICATION_UID
16763                        || !PackageHelper.fixSdPermissions(cid, UserHandle.getSharedAppGid(uid),
16764                                RES_FILE_NAME)) {
16765                    Slog.e(TAG, "Failed to finalize " + cid);
16766                    PackageHelper.destroySdDir(cid);
16767                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
16768                }
16769            }
16770
16771            return PackageManager.INSTALL_SUCCEEDED;
16772        }
16773    }
16774
16775    /**
16776     * Logic to handle movement of existing installed applications.
16777     */
16778    class MoveInstallArgs extends InstallArgs {
16779        private File codeFile;
16780        private File resourceFile;
16781
16782        /** New install */
16783        MoveInstallArgs(InstallParams params) {
16784            super(params.origin, params.move, params.observer, params.installFlags,
16785                    params.installerPackageName, params.volumeUuid,
16786                    params.getUser(), null /* instruction sets */, params.packageAbiOverride,
16787                    params.grantedRuntimePermissions,
16788                    params.traceMethod, params.traceCookie, params.certificates,
16789                    params.installReason);
16790        }
16791
16792        int copyApk(IMediaContainerService imcs, boolean temp) {
16793            if (DEBUG_INSTALL) Slog.d(TAG, "Moving " + move.packageName + " from "
16794                    + move.fromUuid + " to " + move.toUuid);
16795            synchronized (mInstaller) {
16796                try {
16797                    mInstaller.moveCompleteApp(move.fromUuid, move.toUuid, move.packageName,
16798                            move.dataAppName, move.appId, move.seinfo, move.targetSdkVersion);
16799                } catch (InstallerException e) {
16800                    Slog.w(TAG, "Failed to move app", e);
16801                    return PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
16802                }
16803            }
16804
16805            codeFile = new File(Environment.getDataAppDirectory(move.toUuid), move.dataAppName);
16806            resourceFile = codeFile;
16807            if (DEBUG_INSTALL) Slog.d(TAG, "codeFile after move is " + codeFile);
16808
16809            return PackageManager.INSTALL_SUCCEEDED;
16810        }
16811
16812        int doPreInstall(int status) {
16813            if (status != PackageManager.INSTALL_SUCCEEDED) {
16814                cleanUp(move.toUuid);
16815            }
16816            return status;
16817        }
16818
16819        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
16820            if (status != PackageManager.INSTALL_SUCCEEDED) {
16821                cleanUp(move.toUuid);
16822                return false;
16823            }
16824
16825            // Reflect the move in app info
16826            pkg.setApplicationVolumeUuid(pkg.volumeUuid);
16827            pkg.setApplicationInfoCodePath(pkg.codePath);
16828            pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
16829            pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
16830            pkg.setApplicationInfoResourcePath(pkg.codePath);
16831            pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath);
16832            pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
16833
16834            return true;
16835        }
16836
16837        int doPostInstall(int status, int uid) {
16838            if (status == PackageManager.INSTALL_SUCCEEDED) {
16839                cleanUp(move.fromUuid);
16840            } else {
16841                cleanUp(move.toUuid);
16842            }
16843            return status;
16844        }
16845
16846        @Override
16847        String getCodePath() {
16848            return (codeFile != null) ? codeFile.getAbsolutePath() : null;
16849        }
16850
16851        @Override
16852        String getResourcePath() {
16853            return (resourceFile != null) ? resourceFile.getAbsolutePath() : null;
16854        }
16855
16856        private boolean cleanUp(String volumeUuid) {
16857            final File codeFile = new File(Environment.getDataAppDirectory(volumeUuid),
16858                    move.dataAppName);
16859            Slog.d(TAG, "Cleaning up " + move.packageName + " on " + volumeUuid);
16860            final int[] userIds = sUserManager.getUserIds();
16861            synchronized (mInstallLock) {
16862                // Clean up both app data and code
16863                // All package moves are frozen until finished
16864                for (int userId : userIds) {
16865                    try {
16866                        mInstaller.destroyAppData(volumeUuid, move.packageName, userId,
16867                                StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE, 0);
16868                    } catch (InstallerException e) {
16869                        Slog.w(TAG, String.valueOf(e));
16870                    }
16871                }
16872                removeCodePathLI(codeFile);
16873            }
16874            return true;
16875        }
16876
16877        void cleanUpResourcesLI() {
16878            throw new UnsupportedOperationException();
16879        }
16880
16881        boolean doPostDeleteLI(boolean delete) {
16882            throw new UnsupportedOperationException();
16883        }
16884    }
16885
16886    static String getAsecPackageName(String packageCid) {
16887        int idx = packageCid.lastIndexOf("-");
16888        if (idx == -1) {
16889            return packageCid;
16890        }
16891        return packageCid.substring(0, idx);
16892    }
16893
16894    // Utility method used to create code paths based on package name and available index.
16895    private static String getNextCodePath(String oldCodePath, String prefix, String suffix) {
16896        String idxStr = "";
16897        int idx = 1;
16898        // Fall back to default value of idx=1 if prefix is not
16899        // part of oldCodePath
16900        if (oldCodePath != null) {
16901            String subStr = oldCodePath;
16902            // Drop the suffix right away
16903            if (suffix != null && subStr.endsWith(suffix)) {
16904                subStr = subStr.substring(0, subStr.length() - suffix.length());
16905            }
16906            // If oldCodePath already contains prefix find out the
16907            // ending index to either increment or decrement.
16908            int sidx = subStr.lastIndexOf(prefix);
16909            if (sidx != -1) {
16910                subStr = subStr.substring(sidx + prefix.length());
16911                if (subStr != null) {
16912                    if (subStr.startsWith(INSTALL_PACKAGE_SUFFIX)) {
16913                        subStr = subStr.substring(INSTALL_PACKAGE_SUFFIX.length());
16914                    }
16915                    try {
16916                        idx = Integer.parseInt(subStr);
16917                        if (idx <= 1) {
16918                            idx++;
16919                        } else {
16920                            idx--;
16921                        }
16922                    } catch(NumberFormatException e) {
16923                    }
16924                }
16925            }
16926        }
16927        idxStr = INSTALL_PACKAGE_SUFFIX + Integer.toString(idx);
16928        return prefix + idxStr;
16929    }
16930
16931    private File getNextCodePath(File targetDir, String packageName) {
16932        File result;
16933        SecureRandom random = new SecureRandom();
16934        byte[] bytes = new byte[16];
16935        do {
16936            random.nextBytes(bytes);
16937            String suffix = Base64.encodeToString(bytes, Base64.URL_SAFE | Base64.NO_WRAP);
16938            result = new File(targetDir, packageName + "-" + suffix);
16939        } while (result.exists());
16940        return result;
16941    }
16942
16943    // Utility method that returns the relative package path with respect
16944    // to the installation directory. Like say for /data/data/com.test-1.apk
16945    // string com.test-1 is returned.
16946    static String deriveCodePathName(String codePath) {
16947        if (codePath == null) {
16948            return null;
16949        }
16950        final File codeFile = new File(codePath);
16951        final String name = codeFile.getName();
16952        if (codeFile.isDirectory()) {
16953            return name;
16954        } else if (name.endsWith(".apk") || name.endsWith(".tmp")) {
16955            final int lastDot = name.lastIndexOf('.');
16956            return name.substring(0, lastDot);
16957        } else {
16958            Slog.w(TAG, "Odd, " + codePath + " doesn't look like an APK");
16959            return null;
16960        }
16961    }
16962
16963    static class PackageInstalledInfo {
16964        String name;
16965        int uid;
16966        // The set of users that originally had this package installed.
16967        int[] origUsers;
16968        // The set of users that now have this package installed.
16969        int[] newUsers;
16970        PackageParser.Package pkg;
16971        int returnCode;
16972        String returnMsg;
16973        PackageRemovedInfo removedInfo;
16974        ArrayMap<String, PackageInstalledInfo> addedChildPackages;
16975
16976        public void setError(int code, String msg) {
16977            setReturnCode(code);
16978            setReturnMessage(msg);
16979            Slog.w(TAG, msg);
16980        }
16981
16982        public void setError(String msg, PackageParserException e) {
16983            setReturnCode(e.error);
16984            setReturnMessage(ExceptionUtils.getCompleteMessage(msg, e));
16985            Slog.w(TAG, msg, e);
16986        }
16987
16988        public void setError(String msg, PackageManagerException e) {
16989            returnCode = e.error;
16990            setReturnMessage(ExceptionUtils.getCompleteMessage(msg, e));
16991            Slog.w(TAG, msg, e);
16992        }
16993
16994        public void setReturnCode(int returnCode) {
16995            this.returnCode = returnCode;
16996            final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0;
16997            for (int i = 0; i < childCount; i++) {
16998                addedChildPackages.valueAt(i).returnCode = returnCode;
16999            }
17000        }
17001
17002        private void setReturnMessage(String returnMsg) {
17003            this.returnMsg = returnMsg;
17004            final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0;
17005            for (int i = 0; i < childCount; i++) {
17006                addedChildPackages.valueAt(i).returnMsg = returnMsg;
17007            }
17008        }
17009
17010        // In some error cases we want to convey more info back to the observer
17011        String origPackage;
17012        String origPermission;
17013    }
17014
17015    /*
17016     * Install a non-existing package.
17017     */
17018    private void installNewPackageLIF(PackageParser.Package pkg, final int policyFlags,
17019            int scanFlags, UserHandle user, String installerPackageName, String volumeUuid,
17020            PackageInstalledInfo res, int installReason) {
17021        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installNewPackage");
17022
17023        // Remember this for later, in case we need to rollback this install
17024        String pkgName = pkg.packageName;
17025
17026        if (DEBUG_INSTALL) Slog.d(TAG, "installNewPackageLI: " + pkg);
17027
17028        synchronized(mPackages) {
17029            final String renamedPackage = mSettings.getRenamedPackageLPr(pkgName);
17030            if (renamedPackage != null) {
17031                // A package with the same name is already installed, though
17032                // it has been renamed to an older name.  The package we
17033                // are trying to install should be installed as an update to
17034                // the existing one, but that has not been requested, so bail.
17035                res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName
17036                        + " without first uninstalling package running as "
17037                        + renamedPackage);
17038                return;
17039            }
17040            if (mPackages.containsKey(pkgName)) {
17041                // Don't allow installation over an existing package with the same name.
17042                res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName
17043                        + " without first uninstalling.");
17044                return;
17045            }
17046        }
17047
17048        try {
17049            PackageParser.Package newPackage = scanPackageTracedLI(pkg, policyFlags, scanFlags,
17050                    System.currentTimeMillis(), user);
17051
17052            updateSettingsLI(newPackage, installerPackageName, null, res, user, installReason);
17053
17054            if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
17055                prepareAppDataAfterInstallLIF(newPackage);
17056
17057            } else {
17058                // Remove package from internal structures, but keep around any
17059                // data that might have already existed
17060                deletePackageLIF(pkgName, UserHandle.ALL, false, null,
17061                        PackageManager.DELETE_KEEP_DATA, res.removedInfo, true, null);
17062            }
17063        } catch (PackageManagerException e) {
17064            res.setError("Package couldn't be installed in " + pkg.codePath, e);
17065        }
17066
17067        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
17068    }
17069
17070    private boolean shouldCheckUpgradeKeySetLP(PackageSetting oldPs, int scanFlags) {
17071        // Can't rotate keys during boot or if sharedUser.
17072        if (oldPs == null || (scanFlags&SCAN_INITIAL) != 0 || oldPs.sharedUser != null
17073                || !oldPs.keySetData.isUsingUpgradeKeySets()) {
17074            return false;
17075        }
17076        // app is using upgradeKeySets; make sure all are valid
17077        KeySetManagerService ksms = mSettings.mKeySetManagerService;
17078        long[] upgradeKeySets = oldPs.keySetData.getUpgradeKeySets();
17079        for (int i = 0; i < upgradeKeySets.length; i++) {
17080            if (!ksms.isIdValidKeySetId(upgradeKeySets[i])) {
17081                Slog.wtf(TAG, "Package "
17082                         + (oldPs.name != null ? oldPs.name : "<null>")
17083                         + " contains upgrade-key-set reference to unknown key-set: "
17084                         + upgradeKeySets[i]
17085                         + " reverting to signatures check.");
17086                return false;
17087            }
17088        }
17089        return true;
17090    }
17091
17092    private boolean checkUpgradeKeySetLP(PackageSetting oldPS, PackageParser.Package newPkg) {
17093        // Upgrade keysets are being used.  Determine if new package has a superset of the
17094        // required keys.
17095        long[] upgradeKeySets = oldPS.keySetData.getUpgradeKeySets();
17096        KeySetManagerService ksms = mSettings.mKeySetManagerService;
17097        for (int i = 0; i < upgradeKeySets.length; i++) {
17098            Set<PublicKey> upgradeSet = ksms.getPublicKeysFromKeySetLPr(upgradeKeySets[i]);
17099            if (upgradeSet != null && newPkg.mSigningKeys.containsAll(upgradeSet)) {
17100                return true;
17101            }
17102        }
17103        return false;
17104    }
17105
17106    private static void updateDigest(MessageDigest digest, File file) throws IOException {
17107        try (DigestInputStream digestStream =
17108                new DigestInputStream(new FileInputStream(file), digest)) {
17109            while (digestStream.read() != -1) {} // nothing to do; just plow through the file
17110        }
17111    }
17112
17113    private void replacePackageLIF(PackageParser.Package pkg, final int policyFlags, int scanFlags,
17114            UserHandle user, String installerPackageName, PackageInstalledInfo res,
17115            int installReason) {
17116        final boolean isInstantApp = (scanFlags & SCAN_AS_INSTANT_APP) != 0;
17117
17118        final PackageParser.Package oldPackage;
17119        final PackageSetting ps;
17120        final String pkgName = pkg.packageName;
17121        final int[] allUsers;
17122        final int[] installedUsers;
17123
17124        synchronized(mPackages) {
17125            oldPackage = mPackages.get(pkgName);
17126            if (DEBUG_INSTALL) Slog.d(TAG, "replacePackageLI: new=" + pkg + ", old=" + oldPackage);
17127
17128            // don't allow upgrade to target a release SDK from a pre-release SDK
17129            final boolean oldTargetsPreRelease = oldPackage.applicationInfo.targetSdkVersion
17130                    == android.os.Build.VERSION_CODES.CUR_DEVELOPMENT;
17131            final boolean newTargetsPreRelease = pkg.applicationInfo.targetSdkVersion
17132                    == android.os.Build.VERSION_CODES.CUR_DEVELOPMENT;
17133            if (oldTargetsPreRelease
17134                    && !newTargetsPreRelease
17135                    && ((policyFlags & PackageParser.PARSE_FORCE_SDK) == 0)) {
17136                Slog.w(TAG, "Can't install package targeting released sdk");
17137                res.setReturnCode(PackageManager.INSTALL_FAILED_UPDATE_INCOMPATIBLE);
17138                return;
17139            }
17140
17141            ps = mSettings.mPackages.get(pkgName);
17142
17143            // verify signatures are valid
17144            if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) {
17145                if (!checkUpgradeKeySetLP(ps, pkg)) {
17146                    res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
17147                            "New package not signed by keys specified by upgrade-keysets: "
17148                                    + pkgName);
17149                    return;
17150                }
17151            } else {
17152                // default to original signature matching
17153                if (compareSignatures(oldPackage.mSignatures, pkg.mSignatures)
17154                        != PackageManager.SIGNATURE_MATCH) {
17155                    res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
17156                            "New package has a different signature: " + pkgName);
17157                    return;
17158                }
17159            }
17160
17161            // don't allow a system upgrade unless the upgrade hash matches
17162            if (oldPackage.restrictUpdateHash != null && oldPackage.isSystemApp()) {
17163                byte[] digestBytes = null;
17164                try {
17165                    final MessageDigest digest = MessageDigest.getInstance("SHA-512");
17166                    updateDigest(digest, new File(pkg.baseCodePath));
17167                    if (!ArrayUtils.isEmpty(pkg.splitCodePaths)) {
17168                        for (String path : pkg.splitCodePaths) {
17169                            updateDigest(digest, new File(path));
17170                        }
17171                    }
17172                    digestBytes = digest.digest();
17173                } catch (NoSuchAlgorithmException | IOException e) {
17174                    res.setError(INSTALL_FAILED_INVALID_APK,
17175                            "Could not compute hash: " + pkgName);
17176                    return;
17177                }
17178                if (!Arrays.equals(oldPackage.restrictUpdateHash, digestBytes)) {
17179                    res.setError(INSTALL_FAILED_INVALID_APK,
17180                            "New package fails restrict-update check: " + pkgName);
17181                    return;
17182                }
17183                // retain upgrade restriction
17184                pkg.restrictUpdateHash = oldPackage.restrictUpdateHash;
17185            }
17186
17187            // Check for shared user id changes
17188            String invalidPackageName =
17189                    getParentOrChildPackageChangedSharedUser(oldPackage, pkg);
17190            if (invalidPackageName != null) {
17191                res.setError(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE,
17192                        "Package " + invalidPackageName + " tried to change user "
17193                                + oldPackage.mSharedUserId);
17194                return;
17195            }
17196
17197            // In case of rollback, remember per-user/profile install state
17198            allUsers = sUserManager.getUserIds();
17199            installedUsers = ps.queryInstalledUsers(allUsers, true);
17200
17201            // don't allow an upgrade from full to ephemeral
17202            if (isInstantApp) {
17203                if (user == null || user.getIdentifier() == UserHandle.USER_ALL) {
17204                    for (int currentUser : allUsers) {
17205                        if (!ps.getInstantApp(currentUser)) {
17206                            // can't downgrade from full to instant
17207                            Slog.w(TAG, "Can't replace full app with instant app: " + pkgName
17208                                    + " for user: " + currentUser);
17209                            res.setReturnCode(PackageManager.INSTALL_FAILED_INSTANT_APP_INVALID);
17210                            return;
17211                        }
17212                    }
17213                } else if (!ps.getInstantApp(user.getIdentifier())) {
17214                    // can't downgrade from full to instant
17215                    Slog.w(TAG, "Can't replace full app with instant app: " + pkgName
17216                            + " for user: " + user.getIdentifier());
17217                    res.setReturnCode(PackageManager.INSTALL_FAILED_INSTANT_APP_INVALID);
17218                    return;
17219                }
17220            }
17221        }
17222
17223        // Update what is removed
17224        res.removedInfo = new PackageRemovedInfo(this);
17225        res.removedInfo.uid = oldPackage.applicationInfo.uid;
17226        res.removedInfo.removedPackage = oldPackage.packageName;
17227        res.removedInfo.installerPackageName = ps.installerPackageName;
17228        res.removedInfo.isStaticSharedLib = pkg.staticSharedLibName != null;
17229        res.removedInfo.isUpdate = true;
17230        res.removedInfo.origUsers = installedUsers;
17231        res.removedInfo.installReasons = new SparseArray<>(installedUsers.length);
17232        for (int i = 0; i < installedUsers.length; i++) {
17233            final int userId = installedUsers[i];
17234            res.removedInfo.installReasons.put(userId, ps.getInstallReason(userId));
17235        }
17236
17237        final int childCount = (oldPackage.childPackages != null)
17238                ? oldPackage.childPackages.size() : 0;
17239        for (int i = 0; i < childCount; i++) {
17240            boolean childPackageUpdated = false;
17241            PackageParser.Package childPkg = oldPackage.childPackages.get(i);
17242            final PackageSetting childPs = mSettings.getPackageLPr(childPkg.packageName);
17243            if (res.addedChildPackages != null) {
17244                PackageInstalledInfo childRes = res.addedChildPackages.get(childPkg.packageName);
17245                if (childRes != null) {
17246                    childRes.removedInfo.uid = childPkg.applicationInfo.uid;
17247                    childRes.removedInfo.removedPackage = childPkg.packageName;
17248                    if (childPs != null) {
17249                        childRes.removedInfo.installerPackageName = childPs.installerPackageName;
17250                    }
17251                    childRes.removedInfo.isUpdate = true;
17252                    childRes.removedInfo.installReasons = res.removedInfo.installReasons;
17253                    childPackageUpdated = true;
17254                }
17255            }
17256            if (!childPackageUpdated) {
17257                PackageRemovedInfo childRemovedRes = new PackageRemovedInfo(this);
17258                childRemovedRes.removedPackage = childPkg.packageName;
17259                if (childPs != null) {
17260                    childRemovedRes.installerPackageName = childPs.installerPackageName;
17261                }
17262                childRemovedRes.isUpdate = false;
17263                childRemovedRes.dataRemoved = true;
17264                synchronized (mPackages) {
17265                    if (childPs != null) {
17266                        childRemovedRes.origUsers = childPs.queryInstalledUsers(allUsers, true);
17267                    }
17268                }
17269                if (res.removedInfo.removedChildPackages == null) {
17270                    res.removedInfo.removedChildPackages = new ArrayMap<>();
17271                }
17272                res.removedInfo.removedChildPackages.put(childPkg.packageName, childRemovedRes);
17273            }
17274        }
17275
17276        boolean sysPkg = (isSystemApp(oldPackage));
17277        if (sysPkg) {
17278            // Set the system/privileged flags as needed
17279            final boolean privileged =
17280                    (oldPackage.applicationInfo.privateFlags
17281                            & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0;
17282            final int systemPolicyFlags = policyFlags
17283                    | PackageParser.PARSE_IS_SYSTEM
17284                    | (privileged ? PackageParser.PARSE_IS_PRIVILEGED : 0);
17285
17286            replaceSystemPackageLIF(oldPackage, pkg, systemPolicyFlags, scanFlags,
17287                    user, allUsers, installerPackageName, res, installReason);
17288        } else {
17289            replaceNonSystemPackageLIF(oldPackage, pkg, policyFlags, scanFlags,
17290                    user, allUsers, installerPackageName, res, installReason);
17291        }
17292    }
17293
17294    @Override
17295    public List<String> getPreviousCodePaths(String packageName) {
17296        final int callingUid = Binder.getCallingUid();
17297        final List<String> result = new ArrayList<>();
17298        if (getInstantAppPackageName(callingUid) != null) {
17299            return result;
17300        }
17301        final PackageSetting ps = mSettings.mPackages.get(packageName);
17302        if (ps != null
17303                && ps.oldCodePaths != null
17304                && !filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
17305            result.addAll(ps.oldCodePaths);
17306        }
17307        return result;
17308    }
17309
17310    private void replaceNonSystemPackageLIF(PackageParser.Package deletedPackage,
17311            PackageParser.Package pkg, final int policyFlags, int scanFlags, UserHandle user,
17312            int[] allUsers, String installerPackageName, PackageInstalledInfo res,
17313            int installReason) {
17314        if (DEBUG_INSTALL) Slog.d(TAG, "replaceNonSystemPackageLI: new=" + pkg + ", old="
17315                + deletedPackage);
17316
17317        String pkgName = deletedPackage.packageName;
17318        boolean deletedPkg = true;
17319        boolean addedPkg = false;
17320        boolean updatedSettings = false;
17321        final boolean killApp = (scanFlags & SCAN_DONT_KILL_APP) == 0;
17322        final int deleteFlags = PackageManager.DELETE_KEEP_DATA
17323                | (killApp ? 0 : PackageManager.DELETE_DONT_KILL_APP);
17324
17325        final long origUpdateTime = (pkg.mExtras != null)
17326                ? ((PackageSetting)pkg.mExtras).lastUpdateTime : 0;
17327
17328        // First delete the existing package while retaining the data directory
17329        if (!deletePackageLIF(pkgName, null, true, allUsers, deleteFlags,
17330                res.removedInfo, true, pkg)) {
17331            // If the existing package wasn't successfully deleted
17332            res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, "replaceNonSystemPackageLI");
17333            deletedPkg = false;
17334        } else {
17335            // Successfully deleted the old package; proceed with replace.
17336
17337            // If deleted package lived in a container, give users a chance to
17338            // relinquish resources before killing.
17339            if (deletedPackage.isForwardLocked() || isExternal(deletedPackage)) {
17340                if (DEBUG_INSTALL) {
17341                    Slog.i(TAG, "upgrading pkg " + deletedPackage + " is ASEC-hosted -> UNAVAILABLE");
17342                }
17343                final int[] uidArray = new int[] { deletedPackage.applicationInfo.uid };
17344                final ArrayList<String> pkgList = new ArrayList<String>(1);
17345                pkgList.add(deletedPackage.applicationInfo.packageName);
17346                sendResourcesChangedBroadcast(false, true, pkgList, uidArray, null);
17347            }
17348
17349            clearAppDataLIF(pkg, UserHandle.USER_ALL, StorageManager.FLAG_STORAGE_DE
17350                    | StorageManager.FLAG_STORAGE_CE | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
17351            clearAppProfilesLIF(deletedPackage, UserHandle.USER_ALL);
17352
17353            try {
17354                final PackageParser.Package newPackage = scanPackageTracedLI(pkg, policyFlags,
17355                        scanFlags | SCAN_UPDATE_TIME, System.currentTimeMillis(), user);
17356                updateSettingsLI(newPackage, installerPackageName, allUsers, res, user,
17357                        installReason);
17358
17359                // Update the in-memory copy of the previous code paths.
17360                PackageSetting ps = mSettings.mPackages.get(pkgName);
17361                if (!killApp) {
17362                    if (ps.oldCodePaths == null) {
17363                        ps.oldCodePaths = new ArraySet<>();
17364                    }
17365                    Collections.addAll(ps.oldCodePaths, deletedPackage.baseCodePath);
17366                    if (deletedPackage.splitCodePaths != null) {
17367                        Collections.addAll(ps.oldCodePaths, deletedPackage.splitCodePaths);
17368                    }
17369                } else {
17370                    ps.oldCodePaths = null;
17371                }
17372                if (ps.childPackageNames != null) {
17373                    for (int i = ps.childPackageNames.size() - 1; i >= 0; --i) {
17374                        final String childPkgName = ps.childPackageNames.get(i);
17375                        final PackageSetting childPs = mSettings.mPackages.get(childPkgName);
17376                        childPs.oldCodePaths = ps.oldCodePaths;
17377                    }
17378                }
17379                // set instant app status, but, only if it's explicitly specified
17380                final boolean instantApp = (scanFlags & SCAN_AS_INSTANT_APP) != 0;
17381                final boolean fullApp = (scanFlags & SCAN_AS_FULL_APP) != 0;
17382                setInstantAppForUser(ps, user.getIdentifier(), instantApp, fullApp);
17383                prepareAppDataAfterInstallLIF(newPackage);
17384                addedPkg = true;
17385                mDexManager.notifyPackageUpdated(newPackage.packageName,
17386                        newPackage.baseCodePath, newPackage.splitCodePaths);
17387            } catch (PackageManagerException e) {
17388                res.setError("Package couldn't be installed in " + pkg.codePath, e);
17389            }
17390        }
17391
17392        if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
17393            if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, rolling pack: " + pkgName);
17394
17395            // Revert all internal state mutations and added folders for the failed install
17396            if (addedPkg) {
17397                deletePackageLIF(pkgName, null, true, allUsers, deleteFlags,
17398                        res.removedInfo, true, null);
17399            }
17400
17401            // Restore the old package
17402            if (deletedPkg) {
17403                if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, reinstalling: " + deletedPackage);
17404                File restoreFile = new File(deletedPackage.codePath);
17405                // Parse old package
17406                boolean oldExternal = isExternal(deletedPackage);
17407                int oldParseFlags  = mDefParseFlags | PackageParser.PARSE_CHATTY |
17408                        (deletedPackage.isForwardLocked() ? PackageParser.PARSE_FORWARD_LOCK : 0) |
17409                        (oldExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0);
17410                int oldScanFlags = SCAN_UPDATE_SIGNATURE | SCAN_UPDATE_TIME;
17411                try {
17412                    scanPackageTracedLI(restoreFile, oldParseFlags, oldScanFlags, origUpdateTime,
17413                            null);
17414                } catch (PackageManagerException e) {
17415                    Slog.e(TAG, "Failed to restore package : " + pkgName + " after failed upgrade: "
17416                            + e.getMessage());
17417                    return;
17418                }
17419
17420                synchronized (mPackages) {
17421                    // Ensure the installer package name up to date
17422                    setInstallerPackageNameLPw(deletedPackage, installerPackageName);
17423
17424                    // Update permissions for restored package
17425                    updatePermissionsLPw(deletedPackage, UPDATE_PERMISSIONS_ALL);
17426
17427                    mSettings.writeLPr();
17428                }
17429
17430                Slog.i(TAG, "Successfully restored package : " + pkgName + " after failed upgrade");
17431            }
17432        } else {
17433            synchronized (mPackages) {
17434                PackageSetting ps = mSettings.getPackageLPr(pkg.packageName);
17435                if (ps != null) {
17436                    res.removedInfo.removedForAllUsers = mPackages.get(ps.name) == null;
17437                    if (res.removedInfo.removedChildPackages != null) {
17438                        final int childCount = res.removedInfo.removedChildPackages.size();
17439                        // Iterate in reverse as we may modify the collection
17440                        for (int i = childCount - 1; i >= 0; i--) {
17441                            String childPackageName = res.removedInfo.removedChildPackages.keyAt(i);
17442                            if (res.addedChildPackages.containsKey(childPackageName)) {
17443                                res.removedInfo.removedChildPackages.removeAt(i);
17444                            } else {
17445                                PackageRemovedInfo childInfo = res.removedInfo
17446                                        .removedChildPackages.valueAt(i);
17447                                childInfo.removedForAllUsers = mPackages.get(
17448                                        childInfo.removedPackage) == null;
17449                            }
17450                        }
17451                    }
17452                }
17453            }
17454        }
17455    }
17456
17457    private void replaceSystemPackageLIF(PackageParser.Package deletedPackage,
17458            PackageParser.Package pkg, final int policyFlags, int scanFlags, UserHandle user,
17459            int[] allUsers, String installerPackageName, PackageInstalledInfo res,
17460            int installReason) {
17461        if (DEBUG_INSTALL) Slog.d(TAG, "replaceSystemPackageLI: new=" + pkg
17462                + ", old=" + deletedPackage);
17463
17464        final boolean disabledSystem;
17465
17466        // Remove existing system package
17467        removePackageLI(deletedPackage, true);
17468
17469        synchronized (mPackages) {
17470            disabledSystem = disableSystemPackageLPw(deletedPackage, pkg);
17471        }
17472        if (!disabledSystem) {
17473            // We didn't need to disable the .apk as a current system package,
17474            // which means we are replacing another update that is already
17475            // installed.  We need to make sure to delete the older one's .apk.
17476            res.removedInfo.args = createInstallArgsForExisting(0,
17477                    deletedPackage.applicationInfo.getCodePath(),
17478                    deletedPackage.applicationInfo.getResourcePath(),
17479                    getAppDexInstructionSets(deletedPackage.applicationInfo));
17480        } else {
17481            res.removedInfo.args = null;
17482        }
17483
17484        // Successfully disabled the old package. Now proceed with re-installation
17485        clearAppDataLIF(pkg, UserHandle.USER_ALL, StorageManager.FLAG_STORAGE_DE
17486                | StorageManager.FLAG_STORAGE_CE | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
17487        clearAppProfilesLIF(deletedPackage, UserHandle.USER_ALL);
17488
17489        res.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
17490        pkg.setApplicationInfoFlags(ApplicationInfo.FLAG_UPDATED_SYSTEM_APP,
17491                ApplicationInfo.FLAG_UPDATED_SYSTEM_APP);
17492
17493        PackageParser.Package newPackage = null;
17494        try {
17495            // Add the package to the internal data structures
17496            newPackage = scanPackageTracedLI(pkg, policyFlags, scanFlags, 0, user);
17497
17498            // Set the update and install times
17499            PackageSetting deletedPkgSetting = (PackageSetting) deletedPackage.mExtras;
17500            setInstallAndUpdateTime(newPackage, deletedPkgSetting.firstInstallTime,
17501                    System.currentTimeMillis());
17502
17503            // Update the package dynamic state if succeeded
17504            if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
17505                // Now that the install succeeded make sure we remove data
17506                // directories for any child package the update removed.
17507                final int deletedChildCount = (deletedPackage.childPackages != null)
17508                        ? deletedPackage.childPackages.size() : 0;
17509                final int newChildCount = (newPackage.childPackages != null)
17510                        ? newPackage.childPackages.size() : 0;
17511                for (int i = 0; i < deletedChildCount; i++) {
17512                    PackageParser.Package deletedChildPkg = deletedPackage.childPackages.get(i);
17513                    boolean childPackageDeleted = true;
17514                    for (int j = 0; j < newChildCount; j++) {
17515                        PackageParser.Package newChildPkg = newPackage.childPackages.get(j);
17516                        if (deletedChildPkg.packageName.equals(newChildPkg.packageName)) {
17517                            childPackageDeleted = false;
17518                            break;
17519                        }
17520                    }
17521                    if (childPackageDeleted) {
17522                        PackageSetting ps = mSettings.getDisabledSystemPkgLPr(
17523                                deletedChildPkg.packageName);
17524                        if (ps != null && res.removedInfo.removedChildPackages != null) {
17525                            PackageRemovedInfo removedChildRes = res.removedInfo
17526                                    .removedChildPackages.get(deletedChildPkg.packageName);
17527                            removePackageDataLIF(ps, allUsers, removedChildRes, 0, false);
17528                            removedChildRes.removedForAllUsers = mPackages.get(ps.name) == null;
17529                        }
17530                    }
17531                }
17532
17533                updateSettingsLI(newPackage, installerPackageName, allUsers, res, user,
17534                        installReason);
17535                prepareAppDataAfterInstallLIF(newPackage);
17536
17537                mDexManager.notifyPackageUpdated(newPackage.packageName,
17538                            newPackage.baseCodePath, newPackage.splitCodePaths);
17539            }
17540        } catch (PackageManagerException e) {
17541            res.setReturnCode(INSTALL_FAILED_INTERNAL_ERROR);
17542            res.setError("Package couldn't be installed in " + pkg.codePath, e);
17543        }
17544
17545        if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
17546            // Re installation failed. Restore old information
17547            // Remove new pkg information
17548            if (newPackage != null) {
17549                removeInstalledPackageLI(newPackage, true);
17550            }
17551            // Add back the old system package
17552            try {
17553                scanPackageTracedLI(deletedPackage, policyFlags, SCAN_UPDATE_SIGNATURE, 0, user);
17554            } catch (PackageManagerException e) {
17555                Slog.e(TAG, "Failed to restore original package: " + e.getMessage());
17556            }
17557
17558            synchronized (mPackages) {
17559                if (disabledSystem) {
17560                    enableSystemPackageLPw(deletedPackage);
17561                }
17562
17563                // Ensure the installer package name up to date
17564                setInstallerPackageNameLPw(deletedPackage, installerPackageName);
17565
17566                // Update permissions for restored package
17567                updatePermissionsLPw(deletedPackage, UPDATE_PERMISSIONS_ALL);
17568
17569                mSettings.writeLPr();
17570            }
17571
17572            Slog.i(TAG, "Successfully restored package : " + deletedPackage.packageName
17573                    + " after failed upgrade");
17574        }
17575    }
17576
17577    /**
17578     * Checks whether the parent or any of the child packages have a change shared
17579     * user. For a package to be a valid update the shred users of the parent and
17580     * the children should match. We may later support changing child shared users.
17581     * @param oldPkg The updated package.
17582     * @param newPkg The update package.
17583     * @return The shared user that change between the versions.
17584     */
17585    private String getParentOrChildPackageChangedSharedUser(PackageParser.Package oldPkg,
17586            PackageParser.Package newPkg) {
17587        // Check parent shared user
17588        if (!Objects.equals(oldPkg.mSharedUserId, newPkg.mSharedUserId)) {
17589            return newPkg.packageName;
17590        }
17591        // Check child shared users
17592        final int oldChildCount = (oldPkg.childPackages != null) ? oldPkg.childPackages.size() : 0;
17593        final int newChildCount = (newPkg.childPackages != null) ? newPkg.childPackages.size() : 0;
17594        for (int i = 0; i < newChildCount; i++) {
17595            PackageParser.Package newChildPkg = newPkg.childPackages.get(i);
17596            // If this child was present, did it have the same shared user?
17597            for (int j = 0; j < oldChildCount; j++) {
17598                PackageParser.Package oldChildPkg = oldPkg.childPackages.get(j);
17599                if (newChildPkg.packageName.equals(oldChildPkg.packageName)
17600                        && !Objects.equals(newChildPkg.mSharedUserId, oldChildPkg.mSharedUserId)) {
17601                    return newChildPkg.packageName;
17602                }
17603            }
17604        }
17605        return null;
17606    }
17607
17608    private void removeNativeBinariesLI(PackageSetting ps) {
17609        // Remove the lib path for the parent package
17610        if (ps != null) {
17611            NativeLibraryHelper.removeNativeBinariesLI(ps.legacyNativeLibraryPathString);
17612            // Remove the lib path for the child packages
17613            final int childCount = (ps.childPackageNames != null) ? ps.childPackageNames.size() : 0;
17614            for (int i = 0; i < childCount; i++) {
17615                PackageSetting childPs = null;
17616                synchronized (mPackages) {
17617                    childPs = mSettings.getPackageLPr(ps.childPackageNames.get(i));
17618                }
17619                if (childPs != null) {
17620                    NativeLibraryHelper.removeNativeBinariesLI(childPs
17621                            .legacyNativeLibraryPathString);
17622                }
17623            }
17624        }
17625    }
17626
17627    private void enableSystemPackageLPw(PackageParser.Package pkg) {
17628        // Enable the parent package
17629        mSettings.enableSystemPackageLPw(pkg.packageName);
17630        // Enable the child packages
17631        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
17632        for (int i = 0; i < childCount; i++) {
17633            PackageParser.Package childPkg = pkg.childPackages.get(i);
17634            mSettings.enableSystemPackageLPw(childPkg.packageName);
17635        }
17636    }
17637
17638    private boolean disableSystemPackageLPw(PackageParser.Package oldPkg,
17639            PackageParser.Package newPkg) {
17640        // Disable the parent package (parent always replaced)
17641        boolean disabled = mSettings.disableSystemPackageLPw(oldPkg.packageName, true);
17642        // Disable the child packages
17643        final int childCount = (oldPkg.childPackages != null) ? oldPkg.childPackages.size() : 0;
17644        for (int i = 0; i < childCount; i++) {
17645            PackageParser.Package childPkg = oldPkg.childPackages.get(i);
17646            final boolean replace = newPkg.hasChildPackage(childPkg.packageName);
17647            disabled |= mSettings.disableSystemPackageLPw(childPkg.packageName, replace);
17648        }
17649        return disabled;
17650    }
17651
17652    private void setInstallerPackageNameLPw(PackageParser.Package pkg,
17653            String installerPackageName) {
17654        // Enable the parent package
17655        mSettings.setInstallerPackageName(pkg.packageName, installerPackageName);
17656        // Enable the child packages
17657        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
17658        for (int i = 0; i < childCount; i++) {
17659            PackageParser.Package childPkg = pkg.childPackages.get(i);
17660            mSettings.setInstallerPackageName(childPkg.packageName, installerPackageName);
17661        }
17662    }
17663
17664    private int[] revokeUnusedSharedUserPermissionsLPw(SharedUserSetting su, int[] allUserIds) {
17665        // Collect all used permissions in the UID
17666        ArraySet<String> usedPermissions = new ArraySet<>();
17667        final int packageCount = su.packages.size();
17668        for (int i = 0; i < packageCount; i++) {
17669            PackageSetting ps = su.packages.valueAt(i);
17670            if (ps.pkg == null) {
17671                continue;
17672            }
17673            final int requestedPermCount = ps.pkg.requestedPermissions.size();
17674            for (int j = 0; j < requestedPermCount; j++) {
17675                String permission = ps.pkg.requestedPermissions.get(j);
17676                BasePermission bp = mSettings.mPermissions.get(permission);
17677                if (bp != null) {
17678                    usedPermissions.add(permission);
17679                }
17680            }
17681        }
17682
17683        PermissionsState permissionsState = su.getPermissionsState();
17684        // Prune install permissions
17685        List<PermissionState> installPermStates = permissionsState.getInstallPermissionStates();
17686        final int installPermCount = installPermStates.size();
17687        for (int i = installPermCount - 1; i >= 0;  i--) {
17688            PermissionState permissionState = installPermStates.get(i);
17689            if (!usedPermissions.contains(permissionState.getName())) {
17690                BasePermission bp = mSettings.mPermissions.get(permissionState.getName());
17691                if (bp != null) {
17692                    permissionsState.revokeInstallPermission(bp);
17693                    permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL,
17694                            PackageManager.MASK_PERMISSION_FLAGS, 0);
17695                }
17696            }
17697        }
17698
17699        int[] runtimePermissionChangedUserIds = EmptyArray.INT;
17700
17701        // Prune runtime permissions
17702        for (int userId : allUserIds) {
17703            List<PermissionState> runtimePermStates = permissionsState
17704                    .getRuntimePermissionStates(userId);
17705            final int runtimePermCount = runtimePermStates.size();
17706            for (int i = runtimePermCount - 1; i >= 0; i--) {
17707                PermissionState permissionState = runtimePermStates.get(i);
17708                if (!usedPermissions.contains(permissionState.getName())) {
17709                    BasePermission bp = mSettings.mPermissions.get(permissionState.getName());
17710                    if (bp != null) {
17711                        permissionsState.revokeRuntimePermission(bp, userId);
17712                        permissionsState.updatePermissionFlags(bp, userId,
17713                                PackageManager.MASK_PERMISSION_FLAGS, 0);
17714                        runtimePermissionChangedUserIds = ArrayUtils.appendInt(
17715                                runtimePermissionChangedUserIds, userId);
17716                    }
17717                }
17718            }
17719        }
17720
17721        return runtimePermissionChangedUserIds;
17722    }
17723
17724    private void updateSettingsLI(PackageParser.Package newPackage, String installerPackageName,
17725            int[] allUsers, PackageInstalledInfo res, UserHandle user, int installReason) {
17726        // Update the parent package setting
17727        updateSettingsInternalLI(newPackage, installerPackageName, allUsers, res.origUsers,
17728                res, user, installReason);
17729        // Update the child packages setting
17730        final int childCount = (newPackage.childPackages != null)
17731                ? newPackage.childPackages.size() : 0;
17732        for (int i = 0; i < childCount; i++) {
17733            PackageParser.Package childPackage = newPackage.childPackages.get(i);
17734            PackageInstalledInfo childRes = res.addedChildPackages.get(childPackage.packageName);
17735            updateSettingsInternalLI(childPackage, installerPackageName, allUsers,
17736                    childRes.origUsers, childRes, user, installReason);
17737        }
17738    }
17739
17740    private void updateSettingsInternalLI(PackageParser.Package newPackage,
17741            String installerPackageName, int[] allUsers, int[] installedForUsers,
17742            PackageInstalledInfo res, UserHandle user, int installReason) {
17743        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings");
17744
17745        String pkgName = newPackage.packageName;
17746        synchronized (mPackages) {
17747            //write settings. the installStatus will be incomplete at this stage.
17748            //note that the new package setting would have already been
17749            //added to mPackages. It hasn't been persisted yet.
17750            mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_INCOMPLETE);
17751            // TODO: Remove this write? It's also written at the end of this method
17752            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings");
17753            mSettings.writeLPr();
17754            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
17755        }
17756
17757        if (DEBUG_INSTALL) Slog.d(TAG, "New package installed in " + newPackage.codePath);
17758        synchronized (mPackages) {
17759            updatePermissionsLPw(newPackage.packageName, newPackage,
17760                    UPDATE_PERMISSIONS_REPLACE_PKG | (newPackage.permissions.size() > 0
17761                            ? UPDATE_PERMISSIONS_ALL : 0));
17762            // For system-bundled packages, we assume that installing an upgraded version
17763            // of the package implies that the user actually wants to run that new code,
17764            // so we enable the package.
17765            PackageSetting ps = mSettings.mPackages.get(pkgName);
17766            final int userId = user.getIdentifier();
17767            if (ps != null) {
17768                if (isSystemApp(newPackage)) {
17769                    if (DEBUG_INSTALL) {
17770                        Slog.d(TAG, "Implicitly enabling system package on upgrade: " + pkgName);
17771                    }
17772                    // Enable system package for requested users
17773                    if (res.origUsers != null) {
17774                        for (int origUserId : res.origUsers) {
17775                            if (userId == UserHandle.USER_ALL || userId == origUserId) {
17776                                ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT,
17777                                        origUserId, installerPackageName);
17778                            }
17779                        }
17780                    }
17781                    // Also convey the prior install/uninstall state
17782                    if (allUsers != null && installedForUsers != null) {
17783                        for (int currentUserId : allUsers) {
17784                            final boolean installed = ArrayUtils.contains(
17785                                    installedForUsers, currentUserId);
17786                            if (DEBUG_INSTALL) {
17787                                Slog.d(TAG, "    user " + currentUserId + " => " + installed);
17788                            }
17789                            ps.setInstalled(installed, currentUserId);
17790                        }
17791                        // these install state changes will be persisted in the
17792                        // upcoming call to mSettings.writeLPr().
17793                    }
17794                }
17795                // It's implied that when a user requests installation, they want the app to be
17796                // installed and enabled.
17797                if (userId != UserHandle.USER_ALL) {
17798                    ps.setInstalled(true, userId);
17799                    ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, userId, installerPackageName);
17800                }
17801
17802                // When replacing an existing package, preserve the original install reason for all
17803                // users that had the package installed before.
17804                final Set<Integer> previousUserIds = new ArraySet<>();
17805                if (res.removedInfo != null && res.removedInfo.installReasons != null) {
17806                    final int installReasonCount = res.removedInfo.installReasons.size();
17807                    for (int i = 0; i < installReasonCount; i++) {
17808                        final int previousUserId = res.removedInfo.installReasons.keyAt(i);
17809                        final int previousInstallReason = res.removedInfo.installReasons.valueAt(i);
17810                        ps.setInstallReason(previousInstallReason, previousUserId);
17811                        previousUserIds.add(previousUserId);
17812                    }
17813                }
17814
17815                // Set install reason for users that are having the package newly installed.
17816                if (userId == UserHandle.USER_ALL) {
17817                    for (int currentUserId : sUserManager.getUserIds()) {
17818                        if (!previousUserIds.contains(currentUserId)) {
17819                            ps.setInstallReason(installReason, currentUserId);
17820                        }
17821                    }
17822                } else if (!previousUserIds.contains(userId)) {
17823                    ps.setInstallReason(installReason, userId);
17824                }
17825                mSettings.writeKernelMappingLPr(ps);
17826            }
17827            res.name = pkgName;
17828            res.uid = newPackage.applicationInfo.uid;
17829            res.pkg = newPackage;
17830            mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_COMPLETE);
17831            mSettings.setInstallerPackageName(pkgName, installerPackageName);
17832            res.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
17833            //to update install status
17834            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings");
17835            mSettings.writeLPr();
17836            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
17837        }
17838
17839        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
17840    }
17841
17842    private void installPackageTracedLI(InstallArgs args, PackageInstalledInfo res) {
17843        try {
17844            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installPackage");
17845            installPackageLI(args, res);
17846        } finally {
17847            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
17848        }
17849    }
17850
17851    private void installPackageLI(InstallArgs args, PackageInstalledInfo res) {
17852        final int installFlags = args.installFlags;
17853        final String installerPackageName = args.installerPackageName;
17854        final String volumeUuid = args.volumeUuid;
17855        final File tmpPackageFile = new File(args.getCodePath());
17856        final boolean forwardLocked = ((installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0);
17857        final boolean onExternal = (((installFlags & PackageManager.INSTALL_EXTERNAL) != 0)
17858                || (args.volumeUuid != null));
17859        final boolean instantApp = ((installFlags & PackageManager.INSTALL_INSTANT_APP) != 0);
17860        final boolean fullApp = ((installFlags & PackageManager.INSTALL_FULL_APP) != 0);
17861        final boolean forceSdk = ((installFlags & PackageManager.INSTALL_FORCE_SDK) != 0);
17862        boolean replace = false;
17863        int scanFlags = SCAN_NEW_INSTALL | SCAN_UPDATE_SIGNATURE;
17864        if (args.move != null) {
17865            // moving a complete application; perform an initial scan on the new install location
17866            scanFlags |= SCAN_INITIAL;
17867        }
17868        if ((installFlags & PackageManager.INSTALL_DONT_KILL_APP) != 0) {
17869            scanFlags |= SCAN_DONT_KILL_APP;
17870        }
17871        if (instantApp) {
17872            scanFlags |= SCAN_AS_INSTANT_APP;
17873        }
17874        if (fullApp) {
17875            scanFlags |= SCAN_AS_FULL_APP;
17876        }
17877
17878        // Result object to be returned
17879        res.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
17880
17881        if (DEBUG_INSTALL) Slog.d(TAG, "installPackageLI: path=" + tmpPackageFile);
17882
17883        // Sanity check
17884        if (instantApp && (forwardLocked || onExternal)) {
17885            Slog.i(TAG, "Incompatible ephemeral install; fwdLocked=" + forwardLocked
17886                    + " external=" + onExternal);
17887            res.setReturnCode(PackageManager.INSTALL_FAILED_INSTANT_APP_INVALID);
17888            return;
17889        }
17890
17891        // Retrieve PackageSettings and parse package
17892        final int parseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY
17893                | PackageParser.PARSE_ENFORCE_CODE
17894                | (forwardLocked ? PackageParser.PARSE_FORWARD_LOCK : 0)
17895                | (onExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0)
17896                | (instantApp ? PackageParser.PARSE_IS_EPHEMERAL : 0)
17897                | (forceSdk ? PackageParser.PARSE_FORCE_SDK : 0);
17898        PackageParser pp = new PackageParser();
17899        pp.setSeparateProcesses(mSeparateProcesses);
17900        pp.setDisplayMetrics(mMetrics);
17901        pp.setCallback(mPackageParserCallback);
17902
17903        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "parsePackage");
17904        final PackageParser.Package pkg;
17905        try {
17906            pkg = pp.parsePackage(tmpPackageFile, parseFlags);
17907        } catch (PackageParserException e) {
17908            res.setError("Failed parse during installPackageLI", e);
17909            return;
17910        } finally {
17911            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
17912        }
17913
17914        // Instant apps must have target SDK >= O and have targetSanboxVersion >= 2
17915        if (instantApp && pkg.applicationInfo.targetSdkVersion <= Build.VERSION_CODES.N_MR1) {
17916            Slog.w(TAG, "Instant app package " + pkg.packageName + " does not target O");
17917            res.setError(INSTALL_FAILED_SANDBOX_VERSION_DOWNGRADE,
17918                    "Instant app package must target O");
17919            return;
17920        }
17921        if (instantApp && pkg.applicationInfo.targetSandboxVersion != 2) {
17922            Slog.w(TAG, "Instant app package " + pkg.packageName
17923                    + " does not target targetSandboxVersion 2");
17924            res.setError(INSTALL_FAILED_SANDBOX_VERSION_DOWNGRADE,
17925                    "Instant app package must use targetSanboxVersion 2");
17926            return;
17927        }
17928
17929        if (pkg.applicationInfo.isStaticSharedLibrary()) {
17930            // Static shared libraries have synthetic package names
17931            renameStaticSharedLibraryPackage(pkg);
17932
17933            // No static shared libs on external storage
17934            if (onExternal) {
17935                Slog.i(TAG, "Static shared libs can only be installed on internal storage.");
17936                res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION,
17937                        "Packages declaring static-shared libs cannot be updated");
17938                return;
17939            }
17940        }
17941
17942        // If we are installing a clustered package add results for the children
17943        if (pkg.childPackages != null) {
17944            synchronized (mPackages) {
17945                final int childCount = pkg.childPackages.size();
17946                for (int i = 0; i < childCount; i++) {
17947                    PackageParser.Package childPkg = pkg.childPackages.get(i);
17948                    PackageInstalledInfo childRes = new PackageInstalledInfo();
17949                    childRes.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
17950                    childRes.pkg = childPkg;
17951                    childRes.name = childPkg.packageName;
17952                    PackageSetting childPs = mSettings.getPackageLPr(childPkg.packageName);
17953                    if (childPs != null) {
17954                        childRes.origUsers = childPs.queryInstalledUsers(
17955                                sUserManager.getUserIds(), true);
17956                    }
17957                    if ((mPackages.containsKey(childPkg.packageName))) {
17958                        childRes.removedInfo = new PackageRemovedInfo(this);
17959                        childRes.removedInfo.removedPackage = childPkg.packageName;
17960                        childRes.removedInfo.installerPackageName = childPs.installerPackageName;
17961                    }
17962                    if (res.addedChildPackages == null) {
17963                        res.addedChildPackages = new ArrayMap<>();
17964                    }
17965                    res.addedChildPackages.put(childPkg.packageName, childRes);
17966                }
17967            }
17968        }
17969
17970        // If package doesn't declare API override, mark that we have an install
17971        // time CPU ABI override.
17972        if (TextUtils.isEmpty(pkg.cpuAbiOverride)) {
17973            pkg.cpuAbiOverride = args.abiOverride;
17974        }
17975
17976        String pkgName = res.name = pkg.packageName;
17977        if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_TEST_ONLY) != 0) {
17978            if ((installFlags & PackageManager.INSTALL_ALLOW_TEST) == 0) {
17979                res.setError(INSTALL_FAILED_TEST_ONLY, "installPackageLI");
17980                return;
17981            }
17982        }
17983
17984        try {
17985            // either use what we've been given or parse directly from the APK
17986            if (args.certificates != null) {
17987                try {
17988                    PackageParser.populateCertificates(pkg, args.certificates);
17989                } catch (PackageParserException e) {
17990                    // there was something wrong with the certificates we were given;
17991                    // try to pull them from the APK
17992                    PackageParser.collectCertificates(pkg, parseFlags);
17993                }
17994            } else {
17995                PackageParser.collectCertificates(pkg, parseFlags);
17996            }
17997        } catch (PackageParserException e) {
17998            res.setError("Failed collect during installPackageLI", e);
17999            return;
18000        }
18001
18002        // Get rid of all references to package scan path via parser.
18003        pp = null;
18004        String oldCodePath = null;
18005        boolean systemApp = false;
18006        synchronized (mPackages) {
18007            // Check if installing already existing package
18008            if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
18009                String oldName = mSettings.getRenamedPackageLPr(pkgName);
18010                if (pkg.mOriginalPackages != null
18011                        && pkg.mOriginalPackages.contains(oldName)
18012                        && mPackages.containsKey(oldName)) {
18013                    // This package is derived from an original package,
18014                    // and this device has been updating from that original
18015                    // name.  We must continue using the original name, so
18016                    // rename the new package here.
18017                    pkg.setPackageName(oldName);
18018                    pkgName = pkg.packageName;
18019                    replace = true;
18020                    if (DEBUG_INSTALL) Slog.d(TAG, "Replacing existing renamed package: oldName="
18021                            + oldName + " pkgName=" + pkgName);
18022                } else if (mPackages.containsKey(pkgName)) {
18023                    // This package, under its official name, already exists
18024                    // on the device; we should replace it.
18025                    replace = true;
18026                    if (DEBUG_INSTALL) Slog.d(TAG, "Replace existing pacakge: " + pkgName);
18027                }
18028
18029                // Child packages are installed through the parent package
18030                if (pkg.parentPackage != null) {
18031                    res.setError(PackageManager.INSTALL_PARSE_FAILED_BAD_PACKAGE_NAME,
18032                            "Package " + pkg.packageName + " is child of package "
18033                                    + pkg.parentPackage.parentPackage + ". Child packages "
18034                                    + "can be updated only through the parent package.");
18035                    return;
18036                }
18037
18038                if (replace) {
18039                    // Prevent apps opting out from runtime permissions
18040                    PackageParser.Package oldPackage = mPackages.get(pkgName);
18041                    final int oldTargetSdk = oldPackage.applicationInfo.targetSdkVersion;
18042                    final int newTargetSdk = pkg.applicationInfo.targetSdkVersion;
18043                    if (oldTargetSdk > Build.VERSION_CODES.LOLLIPOP_MR1
18044                            && newTargetSdk <= Build.VERSION_CODES.LOLLIPOP_MR1) {
18045                        res.setError(PackageManager.INSTALL_FAILED_PERMISSION_MODEL_DOWNGRADE,
18046                                "Package " + pkg.packageName + " new target SDK " + newTargetSdk
18047                                        + " doesn't support runtime permissions but the old"
18048                                        + " target SDK " + oldTargetSdk + " does.");
18049                        return;
18050                    }
18051                    // Prevent apps from downgrading their targetSandbox.
18052                    final int oldTargetSandbox = oldPackage.applicationInfo.targetSandboxVersion;
18053                    final int newTargetSandbox = pkg.applicationInfo.targetSandboxVersion;
18054                    if (oldTargetSandbox == 2 && newTargetSandbox != 2) {
18055                        res.setError(PackageManager.INSTALL_FAILED_SANDBOX_VERSION_DOWNGRADE,
18056                                "Package " + pkg.packageName + " new target sandbox "
18057                                + newTargetSandbox + " is incompatible with the previous value of"
18058                                + oldTargetSandbox + ".");
18059                        return;
18060                    }
18061
18062                    // Prevent installing of child packages
18063                    if (oldPackage.parentPackage != null) {
18064                        res.setError(PackageManager.INSTALL_PARSE_FAILED_BAD_PACKAGE_NAME,
18065                                "Package " + pkg.packageName + " is child of package "
18066                                        + oldPackage.parentPackage + ". Child packages "
18067                                        + "can be updated only through the parent package.");
18068                        return;
18069                    }
18070                }
18071            }
18072
18073            PackageSetting ps = mSettings.mPackages.get(pkgName);
18074            if (ps != null) {
18075                if (DEBUG_INSTALL) Slog.d(TAG, "Existing package: " + ps);
18076
18077                // Static shared libs have same package with different versions where
18078                // we internally use a synthetic package name to allow multiple versions
18079                // of the same package, therefore we need to compare signatures against
18080                // the package setting for the latest library version.
18081                PackageSetting signatureCheckPs = ps;
18082                if (pkg.applicationInfo.isStaticSharedLibrary()) {
18083                    SharedLibraryEntry libraryEntry = getLatestSharedLibraVersionLPr(pkg);
18084                    if (libraryEntry != null) {
18085                        signatureCheckPs = mSettings.getPackageLPr(libraryEntry.apk);
18086                    }
18087                }
18088
18089                // Quick sanity check that we're signed correctly if updating;
18090                // we'll check this again later when scanning, but we want to
18091                // bail early here before tripping over redefined permissions.
18092                if (shouldCheckUpgradeKeySetLP(signatureCheckPs, scanFlags)) {
18093                    if (!checkUpgradeKeySetLP(signatureCheckPs, pkg)) {
18094                        res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package "
18095                                + pkg.packageName + " upgrade keys do not match the "
18096                                + "previously installed version");
18097                        return;
18098                    }
18099                } else {
18100                    try {
18101                        verifySignaturesLP(signatureCheckPs, pkg);
18102                    } catch (PackageManagerException e) {
18103                        res.setError(e.error, e.getMessage());
18104                        return;
18105                    }
18106                }
18107
18108                oldCodePath = mSettings.mPackages.get(pkgName).codePathString;
18109                if (ps.pkg != null && ps.pkg.applicationInfo != null) {
18110                    systemApp = (ps.pkg.applicationInfo.flags &
18111                            ApplicationInfo.FLAG_SYSTEM) != 0;
18112                }
18113                res.origUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
18114            }
18115
18116            int N = pkg.permissions.size();
18117            for (int i = N-1; i >= 0; i--) {
18118                PackageParser.Permission perm = pkg.permissions.get(i);
18119                BasePermission bp = mSettings.mPermissions.get(perm.info.name);
18120
18121                // Don't allow anyone but the system to define ephemeral permissions.
18122                if ((perm.info.protectionLevel & PermissionInfo.PROTECTION_FLAG_EPHEMERAL) != 0
18123                        && !systemApp) {
18124                    Slog.w(TAG, "Non-System package " + pkg.packageName
18125                            + " attempting to delcare ephemeral permission "
18126                            + perm.info.name + "; Removing ephemeral.");
18127                    perm.info.protectionLevel &= ~PermissionInfo.PROTECTION_FLAG_EPHEMERAL;
18128                }
18129                // Check whether the newly-scanned package wants to define an already-defined perm
18130                if (bp != null) {
18131                    // If the defining package is signed with our cert, it's okay.  This
18132                    // also includes the "updating the same package" case, of course.
18133                    // "updating same package" could also involve key-rotation.
18134                    final boolean sigsOk;
18135                    if (bp.sourcePackage.equals(pkg.packageName)
18136                            && (bp.packageSetting instanceof PackageSetting)
18137                            && (shouldCheckUpgradeKeySetLP((PackageSetting) bp.packageSetting,
18138                                    scanFlags))) {
18139                        sigsOk = checkUpgradeKeySetLP((PackageSetting) bp.packageSetting, pkg);
18140                    } else {
18141                        sigsOk = compareSignatures(bp.packageSetting.signatures.mSignatures,
18142                                pkg.mSignatures) == PackageManager.SIGNATURE_MATCH;
18143                    }
18144                    if (!sigsOk) {
18145                        // If the owning package is the system itself, we log but allow
18146                        // install to proceed; we fail the install on all other permission
18147                        // redefinitions.
18148                        if (!bp.sourcePackage.equals("android")) {
18149                            res.setError(INSTALL_FAILED_DUPLICATE_PERMISSION, "Package "
18150                                    + pkg.packageName + " attempting to redeclare permission "
18151                                    + perm.info.name + " already owned by " + bp.sourcePackage);
18152                            res.origPermission = perm.info.name;
18153                            res.origPackage = bp.sourcePackage;
18154                            return;
18155                        } else {
18156                            Slog.w(TAG, "Package " + pkg.packageName
18157                                    + " attempting to redeclare system permission "
18158                                    + perm.info.name + "; ignoring new declaration");
18159                            pkg.permissions.remove(i);
18160                        }
18161                    } else if (!PLATFORM_PACKAGE_NAME.equals(pkg.packageName)) {
18162                        // Prevent apps to change protection level to dangerous from any other
18163                        // type as this would allow a privilege escalation where an app adds a
18164                        // normal/signature permission in other app's group and later redefines
18165                        // it as dangerous leading to the group auto-grant.
18166                        if ((perm.info.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE)
18167                                == PermissionInfo.PROTECTION_DANGEROUS) {
18168                            if (bp != null && !bp.isRuntime()) {
18169                                Slog.w(TAG, "Package " + pkg.packageName + " trying to change a "
18170                                        + "non-runtime permission " + perm.info.name
18171                                        + " to runtime; keeping old protection level");
18172                                perm.info.protectionLevel = bp.protectionLevel;
18173                            }
18174                        }
18175                    }
18176                }
18177            }
18178        }
18179
18180        if (systemApp) {
18181            if (onExternal) {
18182                // Abort update; system app can't be replaced with app on sdcard
18183                res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION,
18184                        "Cannot install updates to system apps on sdcard");
18185                return;
18186            } else if (instantApp) {
18187                // Abort update; system app can't be replaced with an instant app
18188                res.setError(INSTALL_FAILED_INSTANT_APP_INVALID,
18189                        "Cannot update a system app with an instant app");
18190                return;
18191            }
18192        }
18193
18194        if (args.move != null) {
18195            // We did an in-place move, so dex is ready to roll
18196            scanFlags |= SCAN_NO_DEX;
18197            scanFlags |= SCAN_MOVE;
18198
18199            synchronized (mPackages) {
18200                final PackageSetting ps = mSettings.mPackages.get(pkgName);
18201                if (ps == null) {
18202                    res.setError(INSTALL_FAILED_INTERNAL_ERROR,
18203                            "Missing settings for moved package " + pkgName);
18204                }
18205
18206                // We moved the entire application as-is, so bring over the
18207                // previously derived ABI information.
18208                pkg.applicationInfo.primaryCpuAbi = ps.primaryCpuAbiString;
18209                pkg.applicationInfo.secondaryCpuAbi = ps.secondaryCpuAbiString;
18210            }
18211
18212        } else if (!forwardLocked && !pkg.applicationInfo.isExternalAsec()) {
18213            // Enable SCAN_NO_DEX flag to skip dexopt at a later stage
18214            scanFlags |= SCAN_NO_DEX;
18215
18216            try {
18217                String abiOverride = (TextUtils.isEmpty(pkg.cpuAbiOverride) ?
18218                    args.abiOverride : pkg.cpuAbiOverride);
18219                final boolean extractNativeLibs = !pkg.isLibrary();
18220                derivePackageAbi(pkg, new File(pkg.codePath), abiOverride,
18221                        extractNativeLibs, mAppLib32InstallDir);
18222            } catch (PackageManagerException pme) {
18223                Slog.e(TAG, "Error deriving application ABI", pme);
18224                res.setError(INSTALL_FAILED_INTERNAL_ERROR, "Error deriving application ABI");
18225                return;
18226            }
18227
18228            // Shared libraries for the package need to be updated.
18229            synchronized (mPackages) {
18230                try {
18231                    updateSharedLibrariesLPr(pkg, null);
18232                } catch (PackageManagerException e) {
18233                    Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
18234                }
18235            }
18236
18237            // dexopt can take some time to complete, so, for instant apps, we skip this
18238            // step during installation. Instead, we'll take extra time the first time the
18239            // instant app starts. It's preferred to do it this way to provide continuous
18240            // progress to the user instead of mysteriously blocking somewhere in the
18241            // middle of running an instant app. The default behaviour can be overridden
18242            // via gservices.
18243            if (!instantApp || Global.getInt(
18244                        mContext.getContentResolver(), Global.INSTANT_APP_DEXOPT_ENABLED, 0) != 0) {
18245                Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt");
18246                // Do not run PackageDexOptimizer through the local performDexOpt
18247                // method because `pkg` may not be in `mPackages` yet.
18248                //
18249                // Also, don't fail application installs if the dexopt step fails.
18250                mPackageDexOptimizer.performDexOpt(pkg, pkg.usesLibraryFiles,
18251                        null /* instructionSets */, false /* checkProfiles */,
18252                        getCompilerFilterForReason(REASON_INSTALL),
18253                        getOrCreateCompilerPackageStats(pkg),
18254                        mDexManager.isUsedByOtherApps(pkg.packageName),
18255                        true /* bootComplete */);
18256                Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
18257            }
18258
18259            // Notify BackgroundDexOptService that the package has been changed.
18260            // If this is an update of a package which used to fail to compile,
18261            // BDOS will remove it from its blacklist.
18262            // TODO: Layering violation
18263            BackgroundDexOptService.notifyPackageChanged(pkg.packageName);
18264        }
18265
18266        if (!args.doRename(res.returnCode, pkg, oldCodePath)) {
18267            res.setError(INSTALL_FAILED_INSUFFICIENT_STORAGE, "Failed rename");
18268            return;
18269        }
18270
18271        startIntentFilterVerifications(args.user.getIdentifier(), replace, pkg);
18272
18273        try (PackageFreezer freezer = freezePackageForInstall(pkgName, installFlags,
18274                "installPackageLI")) {
18275            if (replace) {
18276                if (pkg.applicationInfo.isStaticSharedLibrary()) {
18277                    // Static libs have a synthetic package name containing the version
18278                    // and cannot be updated as an update would get a new package name,
18279                    // unless this is the exact same version code which is useful for
18280                    // development.
18281                    PackageParser.Package existingPkg = mPackages.get(pkg.packageName);
18282                    if (existingPkg != null && existingPkg.mVersionCode != pkg.mVersionCode) {
18283                        res.setError(INSTALL_FAILED_DUPLICATE_PACKAGE, "Packages declaring "
18284                                + "static-shared libs cannot be updated");
18285                        return;
18286                    }
18287                }
18288                replacePackageLIF(pkg, parseFlags, scanFlags | SCAN_REPLACING, args.user,
18289                        installerPackageName, res, args.installReason);
18290            } else {
18291                installNewPackageLIF(pkg, parseFlags, scanFlags | SCAN_DELETE_DATA_ON_FAILURES,
18292                        args.user, installerPackageName, volumeUuid, res, args.installReason);
18293            }
18294        }
18295
18296        synchronized (mPackages) {
18297            final PackageSetting ps = mSettings.mPackages.get(pkgName);
18298            if (ps != null) {
18299                res.newUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
18300                ps.setUpdateAvailable(false /*updateAvailable*/);
18301            }
18302
18303            final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
18304            for (int i = 0; i < childCount; i++) {
18305                PackageParser.Package childPkg = pkg.childPackages.get(i);
18306                PackageInstalledInfo childRes = res.addedChildPackages.get(childPkg.packageName);
18307                PackageSetting childPs = mSettings.getPackageLPr(childPkg.packageName);
18308                if (childPs != null) {
18309                    childRes.newUsers = childPs.queryInstalledUsers(
18310                            sUserManager.getUserIds(), true);
18311                }
18312            }
18313
18314            if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
18315                updateSequenceNumberLP(ps, res.newUsers);
18316                updateInstantAppInstallerLocked(pkgName);
18317            }
18318        }
18319    }
18320
18321    private void startIntentFilterVerifications(int userId, boolean replacing,
18322            PackageParser.Package pkg) {
18323        if (mIntentFilterVerifierComponent == null) {
18324            Slog.w(TAG, "No IntentFilter verification will not be done as "
18325                    + "there is no IntentFilterVerifier available!");
18326            return;
18327        }
18328
18329        final int verifierUid = getPackageUid(
18330                mIntentFilterVerifierComponent.getPackageName(),
18331                MATCH_DEBUG_TRIAGED_MISSING,
18332                (userId == UserHandle.USER_ALL) ? UserHandle.USER_SYSTEM : userId);
18333
18334        Message msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS);
18335        msg.obj = new IFVerificationParams(pkg, replacing, userId, verifierUid);
18336        mHandler.sendMessage(msg);
18337
18338        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
18339        for (int i = 0; i < childCount; i++) {
18340            PackageParser.Package childPkg = pkg.childPackages.get(i);
18341            msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS);
18342            msg.obj = new IFVerificationParams(childPkg, replacing, userId, verifierUid);
18343            mHandler.sendMessage(msg);
18344        }
18345    }
18346
18347    private void verifyIntentFiltersIfNeeded(int userId, int verifierUid, boolean replacing,
18348            PackageParser.Package pkg) {
18349        int size = pkg.activities.size();
18350        if (size == 0) {
18351            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
18352                    "No activity, so no need to verify any IntentFilter!");
18353            return;
18354        }
18355
18356        final boolean hasDomainURLs = hasDomainURLs(pkg);
18357        if (!hasDomainURLs) {
18358            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
18359                    "No domain URLs, so no need to verify any IntentFilter!");
18360            return;
18361        }
18362
18363        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Checking for userId:" + userId
18364                + " if any IntentFilter from the " + size
18365                + " Activities needs verification ...");
18366
18367        int count = 0;
18368        final String packageName = pkg.packageName;
18369
18370        synchronized (mPackages) {
18371            // If this is a new install and we see that we've already run verification for this
18372            // package, we have nothing to do: it means the state was restored from backup.
18373            if (!replacing) {
18374                IntentFilterVerificationInfo ivi =
18375                        mSettings.getIntentFilterVerificationLPr(packageName);
18376                if (ivi != null) {
18377                    if (DEBUG_DOMAIN_VERIFICATION) {
18378                        Slog.i(TAG, "Package " + packageName+ " already verified: status="
18379                                + ivi.getStatusString());
18380                    }
18381                    return;
18382                }
18383            }
18384
18385            // If any filters need to be verified, then all need to be.
18386            boolean needToVerify = false;
18387            for (PackageParser.Activity a : pkg.activities) {
18388                for (ActivityIntentInfo filter : a.intents) {
18389                    if (filter.needsVerification() && needsNetworkVerificationLPr(filter)) {
18390                        if (DEBUG_DOMAIN_VERIFICATION) {
18391                            Slog.d(TAG, "Intent filter needs verification, so processing all filters");
18392                        }
18393                        needToVerify = true;
18394                        break;
18395                    }
18396                }
18397            }
18398
18399            if (needToVerify) {
18400                final int verificationId = mIntentFilterVerificationToken++;
18401                for (PackageParser.Activity a : pkg.activities) {
18402                    for (ActivityIntentInfo filter : a.intents) {
18403                        if (filter.handlesWebUris(true) && needsNetworkVerificationLPr(filter)) {
18404                            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
18405                                    "Verification needed for IntentFilter:" + filter.toString());
18406                            mIntentFilterVerifier.addOneIntentFilterVerification(
18407                                    verifierUid, userId, verificationId, filter, packageName);
18408                            count++;
18409                        }
18410                    }
18411                }
18412            }
18413        }
18414
18415        if (count > 0) {
18416            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Starting " + count
18417                    + " IntentFilter verification" + (count > 1 ? "s" : "")
18418                    +  " for userId:" + userId);
18419            mIntentFilterVerifier.startVerifications(userId);
18420        } else {
18421            if (DEBUG_DOMAIN_VERIFICATION) {
18422                Slog.d(TAG, "No filters or not all autoVerify for " + packageName);
18423            }
18424        }
18425    }
18426
18427    private boolean needsNetworkVerificationLPr(ActivityIntentInfo filter) {
18428        final ComponentName cn  = filter.activity.getComponentName();
18429        final String packageName = cn.getPackageName();
18430
18431        IntentFilterVerificationInfo ivi = mSettings.getIntentFilterVerificationLPr(
18432                packageName);
18433        if (ivi == null) {
18434            return true;
18435        }
18436        int status = ivi.getStatus();
18437        switch (status) {
18438            case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED:
18439            case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK:
18440                return true;
18441
18442            default:
18443                // Nothing to do
18444                return false;
18445        }
18446    }
18447
18448    private static boolean isMultiArch(ApplicationInfo info) {
18449        return (info.flags & ApplicationInfo.FLAG_MULTIARCH) != 0;
18450    }
18451
18452    private static boolean isExternal(PackageParser.Package pkg) {
18453        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
18454    }
18455
18456    private static boolean isExternal(PackageSetting ps) {
18457        return (ps.pkgFlags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
18458    }
18459
18460    private static boolean isSystemApp(PackageParser.Package pkg) {
18461        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0;
18462    }
18463
18464    private static boolean isPrivilegedApp(PackageParser.Package pkg) {
18465        return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0;
18466    }
18467
18468    private static boolean hasDomainURLs(PackageParser.Package pkg) {
18469        return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_HAS_DOMAIN_URLS) != 0;
18470    }
18471
18472    private static boolean isSystemApp(PackageSetting ps) {
18473        return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0;
18474    }
18475
18476    private static boolean isUpdatedSystemApp(PackageSetting ps) {
18477        return (ps.pkgFlags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0;
18478    }
18479
18480    private int packageFlagsToInstallFlags(PackageSetting ps) {
18481        int installFlags = 0;
18482        if (isExternal(ps) && TextUtils.isEmpty(ps.volumeUuid)) {
18483            // This existing package was an external ASEC install when we have
18484            // the external flag without a UUID
18485            installFlags |= PackageManager.INSTALL_EXTERNAL;
18486        }
18487        if (ps.isForwardLocked()) {
18488            installFlags |= PackageManager.INSTALL_FORWARD_LOCK;
18489        }
18490        return installFlags;
18491    }
18492
18493    private String getVolumeUuidForPackage(PackageParser.Package pkg) {
18494        if (isExternal(pkg)) {
18495            if (TextUtils.isEmpty(pkg.volumeUuid)) {
18496                return StorageManager.UUID_PRIMARY_PHYSICAL;
18497            } else {
18498                return pkg.volumeUuid;
18499            }
18500        } else {
18501            return StorageManager.UUID_PRIVATE_INTERNAL;
18502        }
18503    }
18504
18505    private VersionInfo getSettingsVersionForPackage(PackageParser.Package pkg) {
18506        if (isExternal(pkg)) {
18507            if (TextUtils.isEmpty(pkg.volumeUuid)) {
18508                return mSettings.getExternalVersion();
18509            } else {
18510                return mSettings.findOrCreateVersion(pkg.volumeUuid);
18511            }
18512        } else {
18513            return mSettings.getInternalVersion();
18514        }
18515    }
18516
18517    private void deleteTempPackageFiles() {
18518        final FilenameFilter filter = new FilenameFilter() {
18519            public boolean accept(File dir, String name) {
18520                return name.startsWith("vmdl") && name.endsWith(".tmp");
18521            }
18522        };
18523        for (File file : mDrmAppPrivateInstallDir.listFiles(filter)) {
18524            file.delete();
18525        }
18526    }
18527
18528    @Override
18529    public void deletePackageAsUser(String packageName, int versionCode,
18530            IPackageDeleteObserver observer, int userId, int flags) {
18531        deletePackageVersioned(new VersionedPackage(packageName, versionCode),
18532                new LegacyPackageDeleteObserver(observer).getBinder(), userId, flags);
18533    }
18534
18535    @Override
18536    public void deletePackageVersioned(VersionedPackage versionedPackage,
18537            final IPackageDeleteObserver2 observer, final int userId, final int deleteFlags) {
18538        final int callingUid = Binder.getCallingUid();
18539        mContext.enforceCallingOrSelfPermission(
18540                android.Manifest.permission.DELETE_PACKAGES, null);
18541        final boolean canViewInstantApps = canViewInstantApps(callingUid, userId);
18542        Preconditions.checkNotNull(versionedPackage);
18543        Preconditions.checkNotNull(observer);
18544        Preconditions.checkArgumentInRange(versionedPackage.getVersionCode(),
18545                PackageManager.VERSION_CODE_HIGHEST,
18546                Integer.MAX_VALUE, "versionCode must be >= -1");
18547
18548        final String packageName = versionedPackage.getPackageName();
18549        final int versionCode = versionedPackage.getVersionCode();
18550        final String internalPackageName;
18551        synchronized (mPackages) {
18552            // Normalize package name to handle renamed packages and static libs
18553            internalPackageName = resolveInternalPackageNameLPr(versionedPackage.getPackageName(),
18554                    versionedPackage.getVersionCode());
18555        }
18556
18557        final int uid = Binder.getCallingUid();
18558        if (!isOrphaned(internalPackageName)
18559                && !isCallerAllowedToSilentlyUninstall(uid, internalPackageName)) {
18560            try {
18561                final Intent intent = new Intent(Intent.ACTION_UNINSTALL_PACKAGE);
18562                intent.setData(Uri.fromParts(PACKAGE_SCHEME, packageName, null));
18563                intent.putExtra(PackageInstaller.EXTRA_CALLBACK, observer.asBinder());
18564                observer.onUserActionRequired(intent);
18565            } catch (RemoteException re) {
18566            }
18567            return;
18568        }
18569        final boolean deleteAllUsers = (deleteFlags & PackageManager.DELETE_ALL_USERS) != 0;
18570        final int[] users = deleteAllUsers ? sUserManager.getUserIds() : new int[]{ userId };
18571        if (UserHandle.getUserId(uid) != userId || (deleteAllUsers && users.length > 1)) {
18572            mContext.enforceCallingOrSelfPermission(
18573                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
18574                    "deletePackage for user " + userId);
18575        }
18576
18577        if (isUserRestricted(userId, UserManager.DISALLOW_UNINSTALL_APPS)) {
18578            try {
18579                observer.onPackageDeleted(packageName,
18580                        PackageManager.DELETE_FAILED_USER_RESTRICTED, null);
18581            } catch (RemoteException re) {
18582            }
18583            return;
18584        }
18585
18586        if (!deleteAllUsers && getBlockUninstallForUser(internalPackageName, userId)) {
18587            try {
18588                observer.onPackageDeleted(packageName,
18589                        PackageManager.DELETE_FAILED_OWNER_BLOCKED, null);
18590            } catch (RemoteException re) {
18591            }
18592            return;
18593        }
18594
18595        if (DEBUG_REMOVE) {
18596            Slog.d(TAG, "deletePackageAsUser: pkg=" + internalPackageName + " user=" + userId
18597                    + " deleteAllUsers: " + deleteAllUsers + " version="
18598                    + (versionCode == PackageManager.VERSION_CODE_HIGHEST
18599                    ? "VERSION_CODE_HIGHEST" : versionCode));
18600        }
18601        // Queue up an async operation since the package deletion may take a little while.
18602        mHandler.post(new Runnable() {
18603            public void run() {
18604                mHandler.removeCallbacks(this);
18605                int returnCode;
18606                final PackageSetting ps = mSettings.mPackages.get(internalPackageName);
18607                boolean doDeletePackage = true;
18608                if (ps != null) {
18609                    final boolean targetIsInstantApp =
18610                            ps.getInstantApp(UserHandle.getUserId(callingUid));
18611                    doDeletePackage = !targetIsInstantApp
18612                            || canViewInstantApps;
18613                }
18614                if (doDeletePackage) {
18615                    if (!deleteAllUsers) {
18616                        returnCode = deletePackageX(internalPackageName, versionCode,
18617                                userId, deleteFlags);
18618                    } else {
18619                        int[] blockUninstallUserIds = getBlockUninstallForUsers(
18620                                internalPackageName, users);
18621                        // If nobody is blocking uninstall, proceed with delete for all users
18622                        if (ArrayUtils.isEmpty(blockUninstallUserIds)) {
18623                            returnCode = deletePackageX(internalPackageName, versionCode,
18624                                    userId, deleteFlags);
18625                        } else {
18626                            // Otherwise uninstall individually for users with blockUninstalls=false
18627                            final int userFlags = deleteFlags & ~PackageManager.DELETE_ALL_USERS;
18628                            for (int userId : users) {
18629                                if (!ArrayUtils.contains(blockUninstallUserIds, userId)) {
18630                                    returnCode = deletePackageX(internalPackageName, versionCode,
18631                                            userId, userFlags);
18632                                    if (returnCode != PackageManager.DELETE_SUCCEEDED) {
18633                                        Slog.w(TAG, "Package delete failed for user " + userId
18634                                                + ", returnCode " + returnCode);
18635                                    }
18636                                }
18637                            }
18638                            // The app has only been marked uninstalled for certain users.
18639                            // We still need to report that delete was blocked
18640                            returnCode = PackageManager.DELETE_FAILED_OWNER_BLOCKED;
18641                        }
18642                    }
18643                } else {
18644                    returnCode = PackageManager.DELETE_FAILED_INTERNAL_ERROR;
18645                }
18646                try {
18647                    observer.onPackageDeleted(packageName, returnCode, null);
18648                } catch (RemoteException e) {
18649                    Log.i(TAG, "Observer no longer exists.");
18650                } //end catch
18651            } //end run
18652        });
18653    }
18654
18655    private String resolveExternalPackageNameLPr(PackageParser.Package pkg) {
18656        if (pkg.staticSharedLibName != null) {
18657            return pkg.manifestPackageName;
18658        }
18659        return pkg.packageName;
18660    }
18661
18662    private String resolveInternalPackageNameLPr(String packageName, int versionCode) {
18663        // Handle renamed packages
18664        String normalizedPackageName = mSettings.getRenamedPackageLPr(packageName);
18665        packageName = normalizedPackageName != null ? normalizedPackageName : packageName;
18666
18667        // Is this a static library?
18668        SparseArray<SharedLibraryEntry> versionedLib =
18669                mStaticLibsByDeclaringPackage.get(packageName);
18670        if (versionedLib == null || versionedLib.size() <= 0) {
18671            return packageName;
18672        }
18673
18674        // Figure out which lib versions the caller can see
18675        SparseIntArray versionsCallerCanSee = null;
18676        final int callingAppId = UserHandle.getAppId(Binder.getCallingUid());
18677        if (callingAppId != Process.SYSTEM_UID && callingAppId != Process.SHELL_UID
18678                && callingAppId != Process.ROOT_UID) {
18679            versionsCallerCanSee = new SparseIntArray();
18680            String libName = versionedLib.valueAt(0).info.getName();
18681            String[] uidPackages = getPackagesForUid(Binder.getCallingUid());
18682            if (uidPackages != null) {
18683                for (String uidPackage : uidPackages) {
18684                    PackageSetting ps = mSettings.getPackageLPr(uidPackage);
18685                    final int libIdx = ArrayUtils.indexOf(ps.usesStaticLibraries, libName);
18686                    if (libIdx >= 0) {
18687                        final int libVersion = ps.usesStaticLibrariesVersions[libIdx];
18688                        versionsCallerCanSee.append(libVersion, libVersion);
18689                    }
18690                }
18691            }
18692        }
18693
18694        // Caller can see nothing - done
18695        if (versionsCallerCanSee != null && versionsCallerCanSee.size() <= 0) {
18696            return packageName;
18697        }
18698
18699        // Find the version the caller can see and the app version code
18700        SharedLibraryEntry highestVersion = null;
18701        final int versionCount = versionedLib.size();
18702        for (int i = 0; i < versionCount; i++) {
18703            SharedLibraryEntry libEntry = versionedLib.valueAt(i);
18704            if (versionsCallerCanSee != null && versionsCallerCanSee.indexOfKey(
18705                    libEntry.info.getVersion()) < 0) {
18706                continue;
18707            }
18708            final int libVersionCode = libEntry.info.getDeclaringPackage().getVersionCode();
18709            if (versionCode != PackageManager.VERSION_CODE_HIGHEST) {
18710                if (libVersionCode == versionCode) {
18711                    return libEntry.apk;
18712                }
18713            } else if (highestVersion == null) {
18714                highestVersion = libEntry;
18715            } else if (libVersionCode  > highestVersion.info
18716                    .getDeclaringPackage().getVersionCode()) {
18717                highestVersion = libEntry;
18718            }
18719        }
18720
18721        if (highestVersion != null) {
18722            return highestVersion.apk;
18723        }
18724
18725        return packageName;
18726    }
18727
18728    private boolean isCallerAllowedToSilentlyUninstall(int callingUid, String pkgName) {
18729        if (callingUid == Process.SHELL_UID || callingUid == Process.ROOT_UID
18730              || UserHandle.getAppId(callingUid) == Process.SYSTEM_UID) {
18731            return true;
18732        }
18733        final int callingUserId = UserHandle.getUserId(callingUid);
18734        // If the caller installed the pkgName, then allow it to silently uninstall.
18735        if (callingUid == getPackageUid(getInstallerPackageName(pkgName), 0, callingUserId)) {
18736            return true;
18737        }
18738
18739        // Allow package verifier to silently uninstall.
18740        if (mRequiredVerifierPackage != null &&
18741                callingUid == getPackageUid(mRequiredVerifierPackage, 0, callingUserId)) {
18742            return true;
18743        }
18744
18745        // Allow package uninstaller to silently uninstall.
18746        if (mRequiredUninstallerPackage != null &&
18747                callingUid == getPackageUid(mRequiredUninstallerPackage, 0, callingUserId)) {
18748            return true;
18749        }
18750
18751        // Allow storage manager to silently uninstall.
18752        if (mStorageManagerPackage != null &&
18753                callingUid == getPackageUid(mStorageManagerPackage, 0, callingUserId)) {
18754            return true;
18755        }
18756
18757        // Allow caller having MANAGE_PROFILE_AND_DEVICE_OWNERS permission to silently
18758        // uninstall for device owner provisioning.
18759        if (checkUidPermission(MANAGE_PROFILE_AND_DEVICE_OWNERS, callingUid)
18760                == PERMISSION_GRANTED) {
18761            return true;
18762        }
18763
18764        return false;
18765    }
18766
18767    private int[] getBlockUninstallForUsers(String packageName, int[] userIds) {
18768        int[] result = EMPTY_INT_ARRAY;
18769        for (int userId : userIds) {
18770            if (getBlockUninstallForUser(packageName, userId)) {
18771                result = ArrayUtils.appendInt(result, userId);
18772            }
18773        }
18774        return result;
18775    }
18776
18777    @Override
18778    public boolean isPackageDeviceAdminOnAnyUser(String packageName) {
18779        final int callingUid = Binder.getCallingUid();
18780        if (getInstantAppPackageName(callingUid) != null
18781                && !isCallerSameApp(packageName, callingUid)) {
18782            return false;
18783        }
18784        return isPackageDeviceAdmin(packageName, UserHandle.USER_ALL);
18785    }
18786
18787    private boolean isPackageDeviceAdmin(String packageName, int userId) {
18788        IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface(
18789                ServiceManager.getService(Context.DEVICE_POLICY_SERVICE));
18790        try {
18791            if (dpm != null) {
18792                final ComponentName deviceOwnerComponentName = dpm.getDeviceOwnerComponent(
18793                        /* callingUserOnly =*/ false);
18794                final String deviceOwnerPackageName = deviceOwnerComponentName == null ? null
18795                        : deviceOwnerComponentName.getPackageName();
18796                // Does the package contains the device owner?
18797                // TODO Do we have to do it even if userId != UserHandle.USER_ALL?  Otherwise,
18798                // this check is probably not needed, since DO should be registered as a device
18799                // admin on some user too. (Original bug for this: b/17657954)
18800                if (packageName.equals(deviceOwnerPackageName)) {
18801                    return true;
18802                }
18803                // Does it contain a device admin for any user?
18804                int[] users;
18805                if (userId == UserHandle.USER_ALL) {
18806                    users = sUserManager.getUserIds();
18807                } else {
18808                    users = new int[]{userId};
18809                }
18810                for (int i = 0; i < users.length; ++i) {
18811                    if (dpm.packageHasActiveAdmins(packageName, users[i])) {
18812                        return true;
18813                    }
18814                }
18815            }
18816        } catch (RemoteException e) {
18817        }
18818        return false;
18819    }
18820
18821    private boolean shouldKeepUninstalledPackageLPr(String packageName) {
18822        return mKeepUninstalledPackages != null && mKeepUninstalledPackages.contains(packageName);
18823    }
18824
18825    /**
18826     *  This method is an internal method that could be get invoked either
18827     *  to delete an installed package or to clean up a failed installation.
18828     *  After deleting an installed package, a broadcast is sent to notify any
18829     *  listeners that the package has been removed. For cleaning up a failed
18830     *  installation, the broadcast is not necessary since the package's
18831     *  installation wouldn't have sent the initial broadcast either
18832     *  The key steps in deleting a package are
18833     *  deleting the package information in internal structures like mPackages,
18834     *  deleting the packages base directories through installd
18835     *  updating mSettings to reflect current status
18836     *  persisting settings for later use
18837     *  sending a broadcast if necessary
18838     */
18839    int deletePackageX(String packageName, int versionCode, int userId, int deleteFlags) {
18840        final PackageRemovedInfo info = new PackageRemovedInfo(this);
18841        final boolean res;
18842
18843        final int removeUser = (deleteFlags & PackageManager.DELETE_ALL_USERS) != 0
18844                ? UserHandle.USER_ALL : userId;
18845
18846        if (isPackageDeviceAdmin(packageName, removeUser)) {
18847            Slog.w(TAG, "Not removing package " + packageName + ": has active device admin");
18848            return PackageManager.DELETE_FAILED_DEVICE_POLICY_MANAGER;
18849        }
18850
18851        PackageSetting uninstalledPs = null;
18852        PackageParser.Package pkg = null;
18853
18854        // for the uninstall-updates case and restricted profiles, remember the per-
18855        // user handle installed state
18856        int[] allUsers;
18857        synchronized (mPackages) {
18858            uninstalledPs = mSettings.mPackages.get(packageName);
18859            if (uninstalledPs == null) {
18860                Slog.w(TAG, "Not removing non-existent package " + packageName);
18861                return PackageManager.DELETE_FAILED_INTERNAL_ERROR;
18862            }
18863
18864            if (versionCode != PackageManager.VERSION_CODE_HIGHEST
18865                    && uninstalledPs.versionCode != versionCode) {
18866                Slog.w(TAG, "Not removing package " + packageName + " with versionCode "
18867                        + uninstalledPs.versionCode + " != " + versionCode);
18868                return PackageManager.DELETE_FAILED_INTERNAL_ERROR;
18869            }
18870
18871            // Static shared libs can be declared by any package, so let us not
18872            // allow removing a package if it provides a lib others depend on.
18873            pkg = mPackages.get(packageName);
18874
18875            allUsers = sUserManager.getUserIds();
18876
18877            if (pkg != null && pkg.staticSharedLibName != null) {
18878                SharedLibraryEntry libEntry = getSharedLibraryEntryLPr(pkg.staticSharedLibName,
18879                        pkg.staticSharedLibVersion);
18880                if (libEntry != null) {
18881                    for (int currUserId : allUsers) {
18882                        if (removeUser != UserHandle.USER_ALL && removeUser != currUserId) {
18883                            continue;
18884                        }
18885                        List<VersionedPackage> libClientPackages = getPackagesUsingSharedLibraryLPr(
18886                                libEntry.info, 0, currUserId);
18887                        if (!ArrayUtils.isEmpty(libClientPackages)) {
18888                            Slog.w(TAG, "Not removing package " + pkg.manifestPackageName
18889                                    + " hosting lib " + libEntry.info.getName() + " version "
18890                                    + libEntry.info.getVersion() + " used by " + libClientPackages
18891                                    + " for user " + currUserId);
18892                            return PackageManager.DELETE_FAILED_USED_SHARED_LIBRARY;
18893                        }
18894                    }
18895                }
18896            }
18897
18898            info.origUsers = uninstalledPs.queryInstalledUsers(allUsers, true);
18899        }
18900
18901        final int freezeUser;
18902        if (isUpdatedSystemApp(uninstalledPs)
18903                && ((deleteFlags & PackageManager.DELETE_SYSTEM_APP) == 0)) {
18904            // We're downgrading a system app, which will apply to all users, so
18905            // freeze them all during the downgrade
18906            freezeUser = UserHandle.USER_ALL;
18907        } else {
18908            freezeUser = removeUser;
18909        }
18910
18911        synchronized (mInstallLock) {
18912            if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageX: pkg=" + packageName + " user=" + userId);
18913            try (PackageFreezer freezer = freezePackageForDelete(packageName, freezeUser,
18914                    deleteFlags, "deletePackageX")) {
18915                res = deletePackageLIF(packageName, UserHandle.of(removeUser), true, allUsers,
18916                        deleteFlags | FLAGS_REMOVE_CHATTY, info, true, null);
18917            }
18918            synchronized (mPackages) {
18919                if (res) {
18920                    if (pkg != null) {
18921                        mInstantAppRegistry.onPackageUninstalledLPw(pkg, info.removedUsers);
18922                    }
18923                    updateSequenceNumberLP(uninstalledPs, info.removedUsers);
18924                    updateInstantAppInstallerLocked(packageName);
18925                }
18926            }
18927        }
18928
18929        if (res) {
18930            final boolean killApp = (deleteFlags & PackageManager.DELETE_DONT_KILL_APP) == 0;
18931            info.sendPackageRemovedBroadcasts(killApp);
18932            info.sendSystemPackageUpdatedBroadcasts();
18933            info.sendSystemPackageAppearedBroadcasts();
18934        }
18935        // Force a gc here.
18936        Runtime.getRuntime().gc();
18937        // Delete the resources here after sending the broadcast to let
18938        // other processes clean up before deleting resources.
18939        if (info.args != null) {
18940            synchronized (mInstallLock) {
18941                info.args.doPostDeleteLI(true);
18942            }
18943        }
18944
18945        return res ? PackageManager.DELETE_SUCCEEDED : PackageManager.DELETE_FAILED_INTERNAL_ERROR;
18946    }
18947
18948    static class PackageRemovedInfo {
18949        final PackageSender packageSender;
18950        String removedPackage;
18951        String installerPackageName;
18952        int uid = -1;
18953        int removedAppId = -1;
18954        int[] origUsers;
18955        int[] removedUsers = null;
18956        int[] broadcastUsers = null;
18957        SparseArray<Integer> installReasons;
18958        boolean isRemovedPackageSystemUpdate = false;
18959        boolean isUpdate;
18960        boolean dataRemoved;
18961        boolean removedForAllUsers;
18962        boolean isStaticSharedLib;
18963        // Clean up resources deleted packages.
18964        InstallArgs args = null;
18965        ArrayMap<String, PackageRemovedInfo> removedChildPackages;
18966        ArrayMap<String, PackageInstalledInfo> appearedChildPackages;
18967
18968        PackageRemovedInfo(PackageSender packageSender) {
18969            this.packageSender = packageSender;
18970        }
18971
18972        void sendPackageRemovedBroadcasts(boolean killApp) {
18973            sendPackageRemovedBroadcastInternal(killApp);
18974            final int childCount = removedChildPackages != null ? removedChildPackages.size() : 0;
18975            for (int i = 0; i < childCount; i++) {
18976                PackageRemovedInfo childInfo = removedChildPackages.valueAt(i);
18977                childInfo.sendPackageRemovedBroadcastInternal(killApp);
18978            }
18979        }
18980
18981        void sendSystemPackageUpdatedBroadcasts() {
18982            if (isRemovedPackageSystemUpdate) {
18983                sendSystemPackageUpdatedBroadcastsInternal();
18984                final int childCount = (removedChildPackages != null)
18985                        ? removedChildPackages.size() : 0;
18986                for (int i = 0; i < childCount; i++) {
18987                    PackageRemovedInfo childInfo = removedChildPackages.valueAt(i);
18988                    if (childInfo.isRemovedPackageSystemUpdate) {
18989                        childInfo.sendSystemPackageUpdatedBroadcastsInternal();
18990                    }
18991                }
18992            }
18993        }
18994
18995        void sendSystemPackageAppearedBroadcasts() {
18996            final int packageCount = (appearedChildPackages != null)
18997                    ? appearedChildPackages.size() : 0;
18998            for (int i = 0; i < packageCount; i++) {
18999                PackageInstalledInfo installedInfo = appearedChildPackages.valueAt(i);
19000                packageSender.sendPackageAddedForNewUsers(installedInfo.name,
19001                    true, UserHandle.getAppId(installedInfo.uid),
19002                    installedInfo.newUsers);
19003            }
19004        }
19005
19006        private void sendSystemPackageUpdatedBroadcastsInternal() {
19007            Bundle extras = new Bundle(2);
19008            extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid);
19009            extras.putBoolean(Intent.EXTRA_REPLACING, true);
19010            packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
19011                removedPackage, extras, 0, null /*targetPackage*/, null, null);
19012            packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED,
19013                removedPackage, extras, 0, null /*targetPackage*/, null, null);
19014            packageSender.sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED,
19015                null, null, 0, removedPackage, null, null);
19016            if (installerPackageName != null) {
19017                packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
19018                        removedPackage, extras, 0 /*flags*/,
19019                        installerPackageName, null, null);
19020                packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED,
19021                        removedPackage, extras, 0 /*flags*/,
19022                        installerPackageName, null, null);
19023            }
19024        }
19025
19026        private void sendPackageRemovedBroadcastInternal(boolean killApp) {
19027            // Don't send static shared library removal broadcasts as these
19028            // libs are visible only the the apps that depend on them an one
19029            // cannot remove the library if it has a dependency.
19030            if (isStaticSharedLib) {
19031                return;
19032            }
19033            Bundle extras = new Bundle(2);
19034            extras.putInt(Intent.EXTRA_UID, removedAppId >= 0  ? removedAppId : uid);
19035            extras.putBoolean(Intent.EXTRA_DATA_REMOVED, dataRemoved);
19036            extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, !killApp);
19037            if (isUpdate || isRemovedPackageSystemUpdate) {
19038                extras.putBoolean(Intent.EXTRA_REPLACING, true);
19039            }
19040            extras.putBoolean(Intent.EXTRA_REMOVED_FOR_ALL_USERS, removedForAllUsers);
19041            if (removedPackage != null) {
19042                packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED,
19043                    removedPackage, extras, 0, null /*targetPackage*/, null, broadcastUsers);
19044                if (installerPackageName != null) {
19045                    packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED,
19046                            removedPackage, extras, 0 /*flags*/,
19047                            installerPackageName, null, broadcastUsers);
19048                }
19049                if (dataRemoved && !isRemovedPackageSystemUpdate) {
19050                    packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_FULLY_REMOVED,
19051                        removedPackage, extras,
19052                        Intent.FLAG_RECEIVER_INCLUDE_BACKGROUND,
19053                        null, null, broadcastUsers);
19054                }
19055            }
19056            if (removedAppId >= 0) {
19057                packageSender.sendPackageBroadcast(Intent.ACTION_UID_REMOVED,
19058                    null, extras, Intent.FLAG_RECEIVER_INCLUDE_BACKGROUND,
19059                    null, null, broadcastUsers);
19060            }
19061        }
19062
19063        void populateUsers(int[] userIds, PackageSetting deletedPackageSetting) {
19064            removedUsers = userIds;
19065            if (removedUsers == null) {
19066                broadcastUsers = null;
19067                return;
19068            }
19069
19070            broadcastUsers = EMPTY_INT_ARRAY;
19071            for (int i = userIds.length - 1; i >= 0; --i) {
19072                final int userId = userIds[i];
19073                if (deletedPackageSetting.getInstantApp(userId)) {
19074                    continue;
19075                }
19076                broadcastUsers = ArrayUtils.appendInt(broadcastUsers, userId);
19077            }
19078        }
19079    }
19080
19081    /*
19082     * This method deletes the package from internal data structures. If the DONT_DELETE_DATA
19083     * flag is not set, the data directory is removed as well.
19084     * make sure this flag is set for partially installed apps. If not its meaningless to
19085     * delete a partially installed application.
19086     */
19087    private void removePackageDataLIF(PackageSetting ps, int[] allUserHandles,
19088            PackageRemovedInfo outInfo, int flags, boolean writeSettings) {
19089        String packageName = ps.name;
19090        if (DEBUG_REMOVE) Slog.d(TAG, "removePackageDataLI: " + ps);
19091        // Retrieve object to delete permissions for shared user later on
19092        final PackageParser.Package deletedPkg;
19093        final PackageSetting deletedPs;
19094        // reader
19095        synchronized (mPackages) {
19096            deletedPkg = mPackages.get(packageName);
19097            deletedPs = mSettings.mPackages.get(packageName);
19098            if (outInfo != null) {
19099                outInfo.removedPackage = packageName;
19100                outInfo.installerPackageName = ps.installerPackageName;
19101                outInfo.isStaticSharedLib = deletedPkg != null
19102                        && deletedPkg.staticSharedLibName != null;
19103                outInfo.populateUsers(deletedPs == null ? null
19104                        : deletedPs.queryInstalledUsers(sUserManager.getUserIds(), true), deletedPs);
19105            }
19106        }
19107
19108        removePackageLI(ps, (flags & FLAGS_REMOVE_CHATTY) != 0);
19109
19110        if ((flags & PackageManager.DELETE_KEEP_DATA) == 0) {
19111            final PackageParser.Package resolvedPkg;
19112            if (deletedPkg != null) {
19113                resolvedPkg = deletedPkg;
19114            } else {
19115                // We don't have a parsed package when it lives on an ejected
19116                // adopted storage device, so fake something together
19117                resolvedPkg = new PackageParser.Package(ps.name);
19118                resolvedPkg.setVolumeUuid(ps.volumeUuid);
19119            }
19120            destroyAppDataLIF(resolvedPkg, UserHandle.USER_ALL,
19121                    StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
19122            destroyAppProfilesLIF(resolvedPkg, UserHandle.USER_ALL);
19123            if (outInfo != null) {
19124                outInfo.dataRemoved = true;
19125            }
19126            schedulePackageCleaning(packageName, UserHandle.USER_ALL, true);
19127        }
19128
19129        int removedAppId = -1;
19130
19131        // writer
19132        synchronized (mPackages) {
19133            boolean installedStateChanged = false;
19134            if (deletedPs != null) {
19135                if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) {
19136                    clearIntentFilterVerificationsLPw(deletedPs.name, UserHandle.USER_ALL);
19137                    clearDefaultBrowserIfNeeded(packageName);
19138                    mSettings.mKeySetManagerService.removeAppKeySetDataLPw(packageName);
19139                    removedAppId = mSettings.removePackageLPw(packageName);
19140                    if (outInfo != null) {
19141                        outInfo.removedAppId = removedAppId;
19142                    }
19143                    updatePermissionsLPw(deletedPs.name, null, 0);
19144                    if (deletedPs.sharedUser != null) {
19145                        // Remove permissions associated with package. Since runtime
19146                        // permissions are per user we have to kill the removed package
19147                        // or packages running under the shared user of the removed
19148                        // package if revoking the permissions requested only by the removed
19149                        // package is successful and this causes a change in gids.
19150                        for (int userId : UserManagerService.getInstance().getUserIds()) {
19151                            final int userIdToKill = mSettings.updateSharedUserPermsLPw(deletedPs,
19152                                    userId);
19153                            if (userIdToKill == UserHandle.USER_ALL
19154                                    || userIdToKill >= UserHandle.USER_SYSTEM) {
19155                                // If gids changed for this user, kill all affected packages.
19156                                mHandler.post(new Runnable() {
19157                                    @Override
19158                                    public void run() {
19159                                        // This has to happen with no lock held.
19160                                        killApplication(deletedPs.name, deletedPs.appId,
19161                                                KILL_APP_REASON_GIDS_CHANGED);
19162                                    }
19163                                });
19164                                break;
19165                            }
19166                        }
19167                    }
19168                    clearPackagePreferredActivitiesLPw(deletedPs.name, UserHandle.USER_ALL);
19169                }
19170                // make sure to preserve per-user disabled state if this removal was just
19171                // a downgrade of a system app to the factory package
19172                if (allUserHandles != null && outInfo != null && outInfo.origUsers != null) {
19173                    if (DEBUG_REMOVE) {
19174                        Slog.d(TAG, "Propagating install state across downgrade");
19175                    }
19176                    for (int userId : allUserHandles) {
19177                        final boolean installed = ArrayUtils.contains(outInfo.origUsers, userId);
19178                        if (DEBUG_REMOVE) {
19179                            Slog.d(TAG, "    user " + userId + " => " + installed);
19180                        }
19181                        if (installed != ps.getInstalled(userId)) {
19182                            installedStateChanged = true;
19183                        }
19184                        ps.setInstalled(installed, userId);
19185                    }
19186                }
19187            }
19188            // can downgrade to reader
19189            if (writeSettings) {
19190                // Save settings now
19191                mSettings.writeLPr();
19192            }
19193            if (installedStateChanged) {
19194                mSettings.writeKernelMappingLPr(ps);
19195            }
19196        }
19197        if (removedAppId != -1) {
19198            // A user ID was deleted here. Go through all users and remove it
19199            // from KeyStore.
19200            removeKeystoreDataIfNeeded(UserHandle.USER_ALL, removedAppId);
19201        }
19202    }
19203
19204    static boolean locationIsPrivileged(File path) {
19205        try {
19206            final String privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app")
19207                    .getCanonicalPath();
19208            return path.getCanonicalPath().startsWith(privilegedAppDir);
19209        } catch (IOException e) {
19210            Slog.e(TAG, "Unable to access code path " + path);
19211        }
19212        return false;
19213    }
19214
19215    /*
19216     * Tries to delete system package.
19217     */
19218    private boolean deleteSystemPackageLIF(PackageParser.Package deletedPkg,
19219            PackageSetting deletedPs, int[] allUserHandles, int flags, PackageRemovedInfo outInfo,
19220            boolean writeSettings) {
19221        if (deletedPs.parentPackageName != null) {
19222            Slog.w(TAG, "Attempt to delete child system package " + deletedPkg.packageName);
19223            return false;
19224        }
19225
19226        final boolean applyUserRestrictions
19227                = (allUserHandles != null) && (outInfo.origUsers != null);
19228        final PackageSetting disabledPs;
19229        // Confirm if the system package has been updated
19230        // An updated system app can be deleted. This will also have to restore
19231        // the system pkg from system partition
19232        // reader
19233        synchronized (mPackages) {
19234            disabledPs = mSettings.getDisabledSystemPkgLPr(deletedPs.name);
19235        }
19236
19237        if (DEBUG_REMOVE) Slog.d(TAG, "deleteSystemPackageLI: newPs=" + deletedPkg.packageName
19238                + " disabledPs=" + disabledPs);
19239
19240        if (disabledPs == null) {
19241            Slog.w(TAG, "Attempt to delete unknown system package "+ deletedPkg.packageName);
19242            return false;
19243        } else if (DEBUG_REMOVE) {
19244            Slog.d(TAG, "Deleting system pkg from data partition");
19245        }
19246
19247        if (DEBUG_REMOVE) {
19248            if (applyUserRestrictions) {
19249                Slog.d(TAG, "Remembering install states:");
19250                for (int userId : allUserHandles) {
19251                    final boolean finstalled = ArrayUtils.contains(outInfo.origUsers, userId);
19252                    Slog.d(TAG, "   u=" + userId + " inst=" + finstalled);
19253                }
19254            }
19255        }
19256
19257        // Delete the updated package
19258        outInfo.isRemovedPackageSystemUpdate = true;
19259        if (outInfo.removedChildPackages != null) {
19260            final int childCount = (deletedPs.childPackageNames != null)
19261                    ? deletedPs.childPackageNames.size() : 0;
19262            for (int i = 0; i < childCount; i++) {
19263                String childPackageName = deletedPs.childPackageNames.get(i);
19264                if (disabledPs.childPackageNames != null && disabledPs.childPackageNames
19265                        .contains(childPackageName)) {
19266                    PackageRemovedInfo childInfo = outInfo.removedChildPackages.get(
19267                            childPackageName);
19268                    if (childInfo != null) {
19269                        childInfo.isRemovedPackageSystemUpdate = true;
19270                    }
19271                }
19272            }
19273        }
19274
19275        if (disabledPs.versionCode < deletedPs.versionCode) {
19276            // Delete data for downgrades
19277            flags &= ~PackageManager.DELETE_KEEP_DATA;
19278        } else {
19279            // Preserve data by setting flag
19280            flags |= PackageManager.DELETE_KEEP_DATA;
19281        }
19282
19283        boolean ret = deleteInstalledPackageLIF(deletedPs, true, flags, allUserHandles,
19284                outInfo, writeSettings, disabledPs.pkg);
19285        if (!ret) {
19286            return false;
19287        }
19288
19289        // writer
19290        synchronized (mPackages) {
19291            // Reinstate the old system package
19292            enableSystemPackageLPw(disabledPs.pkg);
19293            // Remove any native libraries from the upgraded package.
19294            removeNativeBinariesLI(deletedPs);
19295        }
19296
19297        // Install the system package
19298        if (DEBUG_REMOVE) Slog.d(TAG, "Re-installing system package: " + disabledPs);
19299        int parseFlags = mDefParseFlags
19300                | PackageParser.PARSE_MUST_BE_APK
19301                | PackageParser.PARSE_IS_SYSTEM
19302                | PackageParser.PARSE_IS_SYSTEM_DIR;
19303        if (locationIsPrivileged(disabledPs.codePath)) {
19304            parseFlags |= PackageParser.PARSE_IS_PRIVILEGED;
19305        }
19306
19307        final PackageParser.Package newPkg;
19308        try {
19309            newPkg = scanPackageTracedLI(disabledPs.codePath, parseFlags, 0 /* scanFlags */,
19310                0 /* currentTime */, null);
19311        } catch (PackageManagerException e) {
19312            Slog.w(TAG, "Failed to restore system package:" + deletedPkg.packageName + ": "
19313                    + e.getMessage());
19314            return false;
19315        }
19316
19317        try {
19318            // update shared libraries for the newly re-installed system package
19319            updateSharedLibrariesLPr(newPkg, null);
19320        } catch (PackageManagerException e) {
19321            Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
19322        }
19323
19324        prepareAppDataAfterInstallLIF(newPkg);
19325
19326        // writer
19327        synchronized (mPackages) {
19328            PackageSetting ps = mSettings.mPackages.get(newPkg.packageName);
19329
19330            // Propagate the permissions state as we do not want to drop on the floor
19331            // runtime permissions. The update permissions method below will take
19332            // care of removing obsolete permissions and grant install permissions.
19333            ps.getPermissionsState().copyFrom(deletedPs.getPermissionsState());
19334            updatePermissionsLPw(newPkg.packageName, newPkg,
19335                    UPDATE_PERMISSIONS_ALL | UPDATE_PERMISSIONS_REPLACE_PKG);
19336
19337            if (applyUserRestrictions) {
19338                boolean installedStateChanged = false;
19339                if (DEBUG_REMOVE) {
19340                    Slog.d(TAG, "Propagating install state across reinstall");
19341                }
19342                for (int userId : allUserHandles) {
19343                    final boolean installed = ArrayUtils.contains(outInfo.origUsers, userId);
19344                    if (DEBUG_REMOVE) {
19345                        Slog.d(TAG, "    user " + userId + " => " + installed);
19346                    }
19347                    if (installed != ps.getInstalled(userId)) {
19348                        installedStateChanged = true;
19349                    }
19350                    ps.setInstalled(installed, userId);
19351
19352                    mSettings.writeRuntimePermissionsForUserLPr(userId, false);
19353                }
19354                // Regardless of writeSettings we need to ensure that this restriction
19355                // state propagation is persisted
19356                mSettings.writeAllUsersPackageRestrictionsLPr();
19357                if (installedStateChanged) {
19358                    mSettings.writeKernelMappingLPr(ps);
19359                }
19360            }
19361            // can downgrade to reader here
19362            if (writeSettings) {
19363                mSettings.writeLPr();
19364            }
19365        }
19366        return true;
19367    }
19368
19369    private boolean deleteInstalledPackageLIF(PackageSetting ps,
19370            boolean deleteCodeAndResources, int flags, int[] allUserHandles,
19371            PackageRemovedInfo outInfo, boolean writeSettings,
19372            PackageParser.Package replacingPackage) {
19373        synchronized (mPackages) {
19374            if (outInfo != null) {
19375                outInfo.uid = ps.appId;
19376            }
19377
19378            if (outInfo != null && outInfo.removedChildPackages != null) {
19379                final int childCount = (ps.childPackageNames != null)
19380                        ? ps.childPackageNames.size() : 0;
19381                for (int i = 0; i < childCount; i++) {
19382                    String childPackageName = ps.childPackageNames.get(i);
19383                    PackageSetting childPs = mSettings.mPackages.get(childPackageName);
19384                    if (childPs == null) {
19385                        return false;
19386                    }
19387                    PackageRemovedInfo childInfo = outInfo.removedChildPackages.get(
19388                            childPackageName);
19389                    if (childInfo != null) {
19390                        childInfo.uid = childPs.appId;
19391                    }
19392                }
19393            }
19394        }
19395
19396        // Delete package data from internal structures and also remove data if flag is set
19397        removePackageDataLIF(ps, allUserHandles, outInfo, flags, writeSettings);
19398
19399        // Delete the child packages data
19400        final int childCount = (ps.childPackageNames != null) ? ps.childPackageNames.size() : 0;
19401        for (int i = 0; i < childCount; i++) {
19402            PackageSetting childPs;
19403            synchronized (mPackages) {
19404                childPs = mSettings.getPackageLPr(ps.childPackageNames.get(i));
19405            }
19406            if (childPs != null) {
19407                PackageRemovedInfo childOutInfo = (outInfo != null
19408                        && outInfo.removedChildPackages != null)
19409                        ? outInfo.removedChildPackages.get(childPs.name) : null;
19410                final int deleteFlags = (flags & DELETE_KEEP_DATA) != 0
19411                        && (replacingPackage != null
19412                        && !replacingPackage.hasChildPackage(childPs.name))
19413                        ? flags & ~DELETE_KEEP_DATA : flags;
19414                removePackageDataLIF(childPs, allUserHandles, childOutInfo,
19415                        deleteFlags, writeSettings);
19416            }
19417        }
19418
19419        // Delete application code and resources only for parent packages
19420        if (ps.parentPackageName == null) {
19421            if (deleteCodeAndResources && (outInfo != null)) {
19422                outInfo.args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
19423                        ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
19424                if (DEBUG_SD_INSTALL) Slog.i(TAG, "args=" + outInfo.args);
19425            }
19426        }
19427
19428        return true;
19429    }
19430
19431    @Override
19432    public boolean setBlockUninstallForUser(String packageName, boolean blockUninstall,
19433            int userId) {
19434        mContext.enforceCallingOrSelfPermission(
19435                android.Manifest.permission.DELETE_PACKAGES, null);
19436        synchronized (mPackages) {
19437            // Cannot block uninstall of static shared libs as they are
19438            // considered a part of the using app (emulating static linking).
19439            // Also static libs are installed always on internal storage.
19440            PackageParser.Package pkg = mPackages.get(packageName);
19441            if (pkg != null && pkg.staticSharedLibName != null) {
19442                Slog.w(TAG, "Cannot block uninstall of package: " + packageName
19443                        + " providing static shared library: " + pkg.staticSharedLibName);
19444                return false;
19445            }
19446            mSettings.setBlockUninstallLPw(userId, packageName, blockUninstall);
19447            mSettings.writePackageRestrictionsLPr(userId);
19448        }
19449        return true;
19450    }
19451
19452    @Override
19453    public boolean getBlockUninstallForUser(String packageName, int userId) {
19454        synchronized (mPackages) {
19455            final PackageSetting ps = mSettings.mPackages.get(packageName);
19456            if (ps == null || filterAppAccessLPr(ps, Binder.getCallingUid(), userId)) {
19457                return false;
19458            }
19459            return mSettings.getBlockUninstallLPr(userId, packageName);
19460        }
19461    }
19462
19463    @Override
19464    public boolean setRequiredForSystemUser(String packageName, boolean systemUserApp) {
19465        enforceSystemOrRoot("setRequiredForSystemUser can only be run by the system or root");
19466        synchronized (mPackages) {
19467            PackageSetting ps = mSettings.mPackages.get(packageName);
19468            if (ps == null) {
19469                Log.w(TAG, "Package doesn't exist: " + packageName);
19470                return false;
19471            }
19472            if (systemUserApp) {
19473                ps.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_REQUIRED_FOR_SYSTEM_USER;
19474            } else {
19475                ps.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_REQUIRED_FOR_SYSTEM_USER;
19476            }
19477            mSettings.writeLPr();
19478        }
19479        return true;
19480    }
19481
19482    /*
19483     * This method handles package deletion in general
19484     */
19485    private boolean deletePackageLIF(String packageName, UserHandle user,
19486            boolean deleteCodeAndResources, int[] allUserHandles, int flags,
19487            PackageRemovedInfo outInfo, boolean writeSettings,
19488            PackageParser.Package replacingPackage) {
19489        if (packageName == null) {
19490            Slog.w(TAG, "Attempt to delete null packageName.");
19491            return false;
19492        }
19493
19494        if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageLI: " + packageName + " user " + user);
19495
19496        PackageSetting ps;
19497        synchronized (mPackages) {
19498            ps = mSettings.mPackages.get(packageName);
19499            if (ps == null) {
19500                Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
19501                return false;
19502            }
19503
19504            if (ps.parentPackageName != null && (!isSystemApp(ps)
19505                    || (flags & PackageManager.DELETE_SYSTEM_APP) != 0)) {
19506                if (DEBUG_REMOVE) {
19507                    Slog.d(TAG, "Uninstalled child package:" + packageName + " for user:"
19508                            + ((user == null) ? UserHandle.USER_ALL : user));
19509                }
19510                final int removedUserId = (user != null) ? user.getIdentifier()
19511                        : UserHandle.USER_ALL;
19512                if (!clearPackageStateForUserLIF(ps, removedUserId, outInfo)) {
19513                    return false;
19514                }
19515                markPackageUninstalledForUserLPw(ps, user);
19516                scheduleWritePackageRestrictionsLocked(user);
19517                return true;
19518            }
19519        }
19520
19521        if (((!isSystemApp(ps) || (flags&PackageManager.DELETE_SYSTEM_APP) != 0) && user != null
19522                && user.getIdentifier() != UserHandle.USER_ALL)) {
19523            // The caller is asking that the package only be deleted for a single
19524            // user.  To do this, we just mark its uninstalled state and delete
19525            // its data. If this is a system app, we only allow this to happen if
19526            // they have set the special DELETE_SYSTEM_APP which requests different
19527            // semantics than normal for uninstalling system apps.
19528            markPackageUninstalledForUserLPw(ps, user);
19529
19530            if (!isSystemApp(ps)) {
19531                // Do not uninstall the APK if an app should be cached
19532                boolean keepUninstalledPackage = shouldKeepUninstalledPackageLPr(packageName);
19533                if (ps.isAnyInstalled(sUserManager.getUserIds()) || keepUninstalledPackage) {
19534                    // Other user still have this package installed, so all
19535                    // we need to do is clear this user's data and save that
19536                    // it is uninstalled.
19537                    if (DEBUG_REMOVE) Slog.d(TAG, "Still installed by other users");
19538                    if (!clearPackageStateForUserLIF(ps, user.getIdentifier(), outInfo)) {
19539                        return false;
19540                    }
19541                    scheduleWritePackageRestrictionsLocked(user);
19542                    return true;
19543                } else {
19544                    // We need to set it back to 'installed' so the uninstall
19545                    // broadcasts will be sent correctly.
19546                    if (DEBUG_REMOVE) Slog.d(TAG, "Not installed by other users, full delete");
19547                    ps.setInstalled(true, user.getIdentifier());
19548                    mSettings.writeKernelMappingLPr(ps);
19549                }
19550            } else {
19551                // This is a system app, so we assume that the
19552                // other users still have this package installed, so all
19553                // we need to do is clear this user's data and save that
19554                // it is uninstalled.
19555                if (DEBUG_REMOVE) Slog.d(TAG, "Deleting system app");
19556                if (!clearPackageStateForUserLIF(ps, user.getIdentifier(), outInfo)) {
19557                    return false;
19558                }
19559                scheduleWritePackageRestrictionsLocked(user);
19560                return true;
19561            }
19562        }
19563
19564        // If we are deleting a composite package for all users, keep track
19565        // of result for each child.
19566        if (ps.childPackageNames != null && outInfo != null) {
19567            synchronized (mPackages) {
19568                final int childCount = ps.childPackageNames.size();
19569                outInfo.removedChildPackages = new ArrayMap<>(childCount);
19570                for (int i = 0; i < childCount; i++) {
19571                    String childPackageName = ps.childPackageNames.get(i);
19572                    PackageRemovedInfo childInfo = new PackageRemovedInfo(this);
19573                    childInfo.removedPackage = childPackageName;
19574                    childInfo.installerPackageName = ps.installerPackageName;
19575                    outInfo.removedChildPackages.put(childPackageName, childInfo);
19576                    PackageSetting childPs = mSettings.getPackageLPr(childPackageName);
19577                    if (childPs != null) {
19578                        childInfo.origUsers = childPs.queryInstalledUsers(allUserHandles, true);
19579                    }
19580                }
19581            }
19582        }
19583
19584        boolean ret = false;
19585        if (isSystemApp(ps)) {
19586            if (DEBUG_REMOVE) Slog.d(TAG, "Removing system package: " + ps.name);
19587            // When an updated system application is deleted we delete the existing resources
19588            // as well and fall back to existing code in system partition
19589            ret = deleteSystemPackageLIF(ps.pkg, ps, allUserHandles, flags, outInfo, writeSettings);
19590        } else {
19591            if (DEBUG_REMOVE) Slog.d(TAG, "Removing non-system package: " + ps.name);
19592            ret = deleteInstalledPackageLIF(ps, deleteCodeAndResources, flags, allUserHandles,
19593                    outInfo, writeSettings, replacingPackage);
19594        }
19595
19596        // Take a note whether we deleted the package for all users
19597        if (outInfo != null) {
19598            outInfo.removedForAllUsers = mPackages.get(ps.name) == null;
19599            if (outInfo.removedChildPackages != null) {
19600                synchronized (mPackages) {
19601                    final int childCount = outInfo.removedChildPackages.size();
19602                    for (int i = 0; i < childCount; i++) {
19603                        PackageRemovedInfo childInfo = outInfo.removedChildPackages.valueAt(i);
19604                        if (childInfo != null) {
19605                            childInfo.removedForAllUsers = mPackages.get(
19606                                    childInfo.removedPackage) == null;
19607                        }
19608                    }
19609                }
19610            }
19611            // If we uninstalled an update to a system app there may be some
19612            // child packages that appeared as they are declared in the system
19613            // app but were not declared in the update.
19614            if (isSystemApp(ps)) {
19615                synchronized (mPackages) {
19616                    PackageSetting updatedPs = mSettings.getPackageLPr(ps.name);
19617                    final int childCount = (updatedPs.childPackageNames != null)
19618                            ? updatedPs.childPackageNames.size() : 0;
19619                    for (int i = 0; i < childCount; i++) {
19620                        String childPackageName = updatedPs.childPackageNames.get(i);
19621                        if (outInfo.removedChildPackages == null
19622                                || outInfo.removedChildPackages.indexOfKey(childPackageName) < 0) {
19623                            PackageSetting childPs = mSettings.getPackageLPr(childPackageName);
19624                            if (childPs == null) {
19625                                continue;
19626                            }
19627                            PackageInstalledInfo installRes = new PackageInstalledInfo();
19628                            installRes.name = childPackageName;
19629                            installRes.newUsers = childPs.queryInstalledUsers(allUserHandles, true);
19630                            installRes.pkg = mPackages.get(childPackageName);
19631                            installRes.uid = childPs.pkg.applicationInfo.uid;
19632                            if (outInfo.appearedChildPackages == null) {
19633                                outInfo.appearedChildPackages = new ArrayMap<>();
19634                            }
19635                            outInfo.appearedChildPackages.put(childPackageName, installRes);
19636                        }
19637                    }
19638                }
19639            }
19640        }
19641
19642        return ret;
19643    }
19644
19645    private void markPackageUninstalledForUserLPw(PackageSetting ps, UserHandle user) {
19646        final int[] userIds = (user == null || user.getIdentifier() == UserHandle.USER_ALL)
19647                ? sUserManager.getUserIds() : new int[] {user.getIdentifier()};
19648        for (int nextUserId : userIds) {
19649            if (DEBUG_REMOVE) {
19650                Slog.d(TAG, "Marking package:" + ps.name + " uninstalled for user:" + nextUserId);
19651            }
19652            ps.setUserState(nextUserId, 0, COMPONENT_ENABLED_STATE_DEFAULT,
19653                    false /*installed*/,
19654                    true /*stopped*/,
19655                    true /*notLaunched*/,
19656                    false /*hidden*/,
19657                    false /*suspended*/,
19658                    false /*instantApp*/,
19659                    null /*lastDisableAppCaller*/,
19660                    null /*enabledComponents*/,
19661                    null /*disabledComponents*/,
19662                    ps.readUserState(nextUserId).domainVerificationStatus,
19663                    0, PackageManager.INSTALL_REASON_UNKNOWN);
19664        }
19665        mSettings.writeKernelMappingLPr(ps);
19666    }
19667
19668    private boolean clearPackageStateForUserLIF(PackageSetting ps, int userId,
19669            PackageRemovedInfo outInfo) {
19670        final PackageParser.Package pkg;
19671        synchronized (mPackages) {
19672            pkg = mPackages.get(ps.name);
19673        }
19674
19675        final int[] userIds = (userId == UserHandle.USER_ALL) ? sUserManager.getUserIds()
19676                : new int[] {userId};
19677        for (int nextUserId : userIds) {
19678            if (DEBUG_REMOVE) {
19679                Slog.d(TAG, "Updating package:" + ps.name + " install state for user:"
19680                        + nextUserId);
19681            }
19682
19683            destroyAppDataLIF(pkg, userId,
19684                    StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
19685            destroyAppProfilesLIF(pkg, userId);
19686            clearDefaultBrowserIfNeededForUser(ps.name, userId);
19687            removeKeystoreDataIfNeeded(nextUserId, ps.appId);
19688            schedulePackageCleaning(ps.name, nextUserId, false);
19689            synchronized (mPackages) {
19690                if (clearPackagePreferredActivitiesLPw(ps.name, nextUserId)) {
19691                    scheduleWritePackageRestrictionsLocked(nextUserId);
19692                }
19693                resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, nextUserId);
19694            }
19695        }
19696
19697        if (outInfo != null) {
19698            outInfo.removedPackage = ps.name;
19699            outInfo.installerPackageName = ps.installerPackageName;
19700            outInfo.isStaticSharedLib = pkg != null && pkg.staticSharedLibName != null;
19701            outInfo.removedAppId = ps.appId;
19702            outInfo.removedUsers = userIds;
19703            outInfo.broadcastUsers = userIds;
19704        }
19705
19706        return true;
19707    }
19708
19709    private final class ClearStorageConnection implements ServiceConnection {
19710        IMediaContainerService mContainerService;
19711
19712        @Override
19713        public void onServiceConnected(ComponentName name, IBinder service) {
19714            synchronized (this) {
19715                mContainerService = IMediaContainerService.Stub
19716                        .asInterface(Binder.allowBlocking(service));
19717                notifyAll();
19718            }
19719        }
19720
19721        @Override
19722        public void onServiceDisconnected(ComponentName name) {
19723        }
19724    }
19725
19726    private void clearExternalStorageDataSync(String packageName, int userId, boolean allData) {
19727        if (DEFAULT_CONTAINER_PACKAGE.equals(packageName)) return;
19728
19729        final boolean mounted;
19730        if (Environment.isExternalStorageEmulated()) {
19731            mounted = true;
19732        } else {
19733            final String status = Environment.getExternalStorageState();
19734
19735            mounted = status.equals(Environment.MEDIA_MOUNTED)
19736                    || status.equals(Environment.MEDIA_MOUNTED_READ_ONLY);
19737        }
19738
19739        if (!mounted) {
19740            return;
19741        }
19742
19743        final Intent containerIntent = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
19744        int[] users;
19745        if (userId == UserHandle.USER_ALL) {
19746            users = sUserManager.getUserIds();
19747        } else {
19748            users = new int[] { userId };
19749        }
19750        final ClearStorageConnection conn = new ClearStorageConnection();
19751        if (mContext.bindServiceAsUser(
19752                containerIntent, conn, Context.BIND_AUTO_CREATE, UserHandle.SYSTEM)) {
19753            try {
19754                for (int curUser : users) {
19755                    long timeout = SystemClock.uptimeMillis() + 5000;
19756                    synchronized (conn) {
19757                        long now;
19758                        while (conn.mContainerService == null &&
19759                                (now = SystemClock.uptimeMillis()) < timeout) {
19760                            try {
19761                                conn.wait(timeout - now);
19762                            } catch (InterruptedException e) {
19763                            }
19764                        }
19765                    }
19766                    if (conn.mContainerService == null) {
19767                        return;
19768                    }
19769
19770                    final UserEnvironment userEnv = new UserEnvironment(curUser);
19771                    clearDirectory(conn.mContainerService,
19772                            userEnv.buildExternalStorageAppCacheDirs(packageName));
19773                    if (allData) {
19774                        clearDirectory(conn.mContainerService,
19775                                userEnv.buildExternalStorageAppDataDirs(packageName));
19776                        clearDirectory(conn.mContainerService,
19777                                userEnv.buildExternalStorageAppMediaDirs(packageName));
19778                    }
19779                }
19780            } finally {
19781                mContext.unbindService(conn);
19782            }
19783        }
19784    }
19785
19786    @Override
19787    public void clearApplicationProfileData(String packageName) {
19788        enforceSystemOrRoot("Only the system can clear all profile data");
19789
19790        final PackageParser.Package pkg;
19791        synchronized (mPackages) {
19792            pkg = mPackages.get(packageName);
19793        }
19794
19795        try (PackageFreezer freezer = freezePackage(packageName, "clearApplicationProfileData")) {
19796            synchronized (mInstallLock) {
19797                clearAppProfilesLIF(pkg, UserHandle.USER_ALL);
19798            }
19799        }
19800    }
19801
19802    @Override
19803    public void clearApplicationUserData(final String packageName,
19804            final IPackageDataObserver observer, final int userId) {
19805        mContext.enforceCallingOrSelfPermission(
19806                android.Manifest.permission.CLEAR_APP_USER_DATA, null);
19807
19808        final int callingUid = Binder.getCallingUid();
19809        enforceCrossUserPermission(callingUid, userId,
19810                true /* requireFullPermission */, false /* checkShell */, "clear application data");
19811
19812        final PackageSetting ps = mSettings.getPackageLPr(packageName);
19813        if (ps != null && filterAppAccessLPr(ps, callingUid, userId)) {
19814            return;
19815        }
19816        if (mProtectedPackages.isPackageDataProtected(userId, packageName)) {
19817            throw new SecurityException("Cannot clear data for a protected package: "
19818                    + packageName);
19819        }
19820        // Queue up an async operation since the package deletion may take a little while.
19821        mHandler.post(new Runnable() {
19822            public void run() {
19823                mHandler.removeCallbacks(this);
19824                final boolean succeeded;
19825                try (PackageFreezer freezer = freezePackage(packageName,
19826                        "clearApplicationUserData")) {
19827                    synchronized (mInstallLock) {
19828                        succeeded = clearApplicationUserDataLIF(packageName, userId);
19829                    }
19830                    clearExternalStorageDataSync(packageName, userId, true);
19831                    synchronized (mPackages) {
19832                        mInstantAppRegistry.deleteInstantApplicationMetadataLPw(
19833                                packageName, userId);
19834                    }
19835                }
19836                if (succeeded) {
19837                    // invoke DeviceStorageMonitor's update method to clear any notifications
19838                    DeviceStorageMonitorInternal dsm = LocalServices
19839                            .getService(DeviceStorageMonitorInternal.class);
19840                    if (dsm != null) {
19841                        dsm.checkMemory();
19842                    }
19843                }
19844                if(observer != null) {
19845                    try {
19846                        observer.onRemoveCompleted(packageName, succeeded);
19847                    } catch (RemoteException e) {
19848                        Log.i(TAG, "Observer no longer exists.");
19849                    }
19850                } //end if observer
19851            } //end run
19852        });
19853    }
19854
19855    private boolean clearApplicationUserDataLIF(String packageName, int userId) {
19856        if (packageName == null) {
19857            Slog.w(TAG, "Attempt to delete null packageName.");
19858            return false;
19859        }
19860
19861        // Try finding details about the requested package
19862        PackageParser.Package pkg;
19863        synchronized (mPackages) {
19864            pkg = mPackages.get(packageName);
19865            if (pkg == null) {
19866                final PackageSetting ps = mSettings.mPackages.get(packageName);
19867                if (ps != null) {
19868                    pkg = ps.pkg;
19869                }
19870            }
19871
19872            if (pkg == null) {
19873                Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
19874                return false;
19875            }
19876
19877            PackageSetting ps = (PackageSetting) pkg.mExtras;
19878            resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
19879        }
19880
19881        clearAppDataLIF(pkg, userId,
19882                StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
19883
19884        final int appId = UserHandle.getAppId(pkg.applicationInfo.uid);
19885        removeKeystoreDataIfNeeded(userId, appId);
19886
19887        UserManagerInternal umInternal = getUserManagerInternal();
19888        final int flags;
19889        if (umInternal.isUserUnlockingOrUnlocked(userId)) {
19890            flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
19891        } else if (umInternal.isUserRunning(userId)) {
19892            flags = StorageManager.FLAG_STORAGE_DE;
19893        } else {
19894            flags = 0;
19895        }
19896        prepareAppDataContentsLIF(pkg, userId, flags);
19897
19898        return true;
19899    }
19900
19901    /**
19902     * Reverts user permission state changes (permissions and flags) in
19903     * all packages for a given user.
19904     *
19905     * @param userId The device user for which to do a reset.
19906     */
19907    private void resetUserChangesToRuntimePermissionsAndFlagsLPw(int userId) {
19908        final int packageCount = mPackages.size();
19909        for (int i = 0; i < packageCount; i++) {
19910            PackageParser.Package pkg = mPackages.valueAt(i);
19911            PackageSetting ps = (PackageSetting) pkg.mExtras;
19912            resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
19913        }
19914    }
19915
19916    private void resetNetworkPolicies(int userId) {
19917        LocalServices.getService(NetworkPolicyManagerInternal.class).resetUserState(userId);
19918    }
19919
19920    /**
19921     * Reverts user permission state changes (permissions and flags).
19922     *
19923     * @param ps The package for which to reset.
19924     * @param userId The device user for which to do a reset.
19925     */
19926    private void resetUserChangesToRuntimePermissionsAndFlagsLPw(
19927            final PackageSetting ps, final int userId) {
19928        if (ps.pkg == null) {
19929            return;
19930        }
19931
19932        // These are flags that can change base on user actions.
19933        final int userSettableMask = FLAG_PERMISSION_USER_SET
19934                | FLAG_PERMISSION_USER_FIXED
19935                | FLAG_PERMISSION_REVOKE_ON_UPGRADE
19936                | FLAG_PERMISSION_REVIEW_REQUIRED;
19937
19938        final int policyOrSystemFlags = FLAG_PERMISSION_SYSTEM_FIXED
19939                | FLAG_PERMISSION_POLICY_FIXED;
19940
19941        boolean writeInstallPermissions = false;
19942        boolean writeRuntimePermissions = false;
19943
19944        final int permissionCount = ps.pkg.requestedPermissions.size();
19945        for (int i = 0; i < permissionCount; i++) {
19946            String permission = ps.pkg.requestedPermissions.get(i);
19947
19948            BasePermission bp = mSettings.mPermissions.get(permission);
19949            if (bp == null) {
19950                continue;
19951            }
19952
19953            // If shared user we just reset the state to which only this app contributed.
19954            if (ps.sharedUser != null) {
19955                boolean used = false;
19956                final int packageCount = ps.sharedUser.packages.size();
19957                for (int j = 0; j < packageCount; j++) {
19958                    PackageSetting pkg = ps.sharedUser.packages.valueAt(j);
19959                    if (pkg.pkg != null && !pkg.pkg.packageName.equals(ps.pkg.packageName)
19960                            && pkg.pkg.requestedPermissions.contains(permission)) {
19961                        used = true;
19962                        break;
19963                    }
19964                }
19965                if (used) {
19966                    continue;
19967                }
19968            }
19969
19970            PermissionsState permissionsState = ps.getPermissionsState();
19971
19972            final int oldFlags = permissionsState.getPermissionFlags(bp.name, userId);
19973
19974            // Always clear the user settable flags.
19975            final boolean hasInstallState = permissionsState.getInstallPermissionState(
19976                    bp.name) != null;
19977            // If permission review is enabled and this is a legacy app, mark the
19978            // permission as requiring a review as this is the initial state.
19979            int flags = 0;
19980            if (mPermissionReviewRequired
19981                    && ps.pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) {
19982                flags |= FLAG_PERMISSION_REVIEW_REQUIRED;
19983            }
19984            if (permissionsState.updatePermissionFlags(bp, userId, userSettableMask, flags)) {
19985                if (hasInstallState) {
19986                    writeInstallPermissions = true;
19987                } else {
19988                    writeRuntimePermissions = true;
19989                }
19990            }
19991
19992            // Below is only runtime permission handling.
19993            if (!bp.isRuntime()) {
19994                continue;
19995            }
19996
19997            // Never clobber system or policy.
19998            if ((oldFlags & policyOrSystemFlags) != 0) {
19999                continue;
20000            }
20001
20002            // If this permission was granted by default, make sure it is.
20003            if ((oldFlags & FLAG_PERMISSION_GRANTED_BY_DEFAULT) != 0) {
20004                if (permissionsState.grantRuntimePermission(bp, userId)
20005                        != PERMISSION_OPERATION_FAILURE) {
20006                    writeRuntimePermissions = true;
20007                }
20008            // If permission review is enabled the permissions for a legacy apps
20009            // are represented as constantly granted runtime ones, so don't revoke.
20010            } else if ((flags & FLAG_PERMISSION_REVIEW_REQUIRED) == 0) {
20011                // Otherwise, reset the permission.
20012                final int revokeResult = permissionsState.revokeRuntimePermission(bp, userId);
20013                switch (revokeResult) {
20014                    case PERMISSION_OPERATION_SUCCESS:
20015                    case PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: {
20016                        writeRuntimePermissions = true;
20017                        final int appId = ps.appId;
20018                        mHandler.post(new Runnable() {
20019                            @Override
20020                            public void run() {
20021                                killUid(appId, userId, KILL_APP_REASON_PERMISSIONS_REVOKED);
20022                            }
20023                        });
20024                    } break;
20025                }
20026            }
20027        }
20028
20029        // Synchronously write as we are taking permissions away.
20030        if (writeRuntimePermissions) {
20031            mSettings.writeRuntimePermissionsForUserLPr(userId, true);
20032        }
20033
20034        // Synchronously write as we are taking permissions away.
20035        if (writeInstallPermissions) {
20036            mSettings.writeLPr();
20037        }
20038    }
20039
20040    /**
20041     * Remove entries from the keystore daemon. Will only remove it if the
20042     * {@code appId} is valid.
20043     */
20044    private static void removeKeystoreDataIfNeeded(int userId, int appId) {
20045        if (appId < 0) {
20046            return;
20047        }
20048
20049        final KeyStore keyStore = KeyStore.getInstance();
20050        if (keyStore != null) {
20051            if (userId == UserHandle.USER_ALL) {
20052                for (final int individual : sUserManager.getUserIds()) {
20053                    keyStore.clearUid(UserHandle.getUid(individual, appId));
20054                }
20055            } else {
20056                keyStore.clearUid(UserHandle.getUid(userId, appId));
20057            }
20058        } else {
20059            Slog.w(TAG, "Could not contact keystore to clear entries for app id " + appId);
20060        }
20061    }
20062
20063    @Override
20064    public void deleteApplicationCacheFiles(final String packageName,
20065            final IPackageDataObserver observer) {
20066        final int userId = UserHandle.getCallingUserId();
20067        deleteApplicationCacheFilesAsUser(packageName, userId, observer);
20068    }
20069
20070    @Override
20071    public void deleteApplicationCacheFilesAsUser(final String packageName, final int userId,
20072            final IPackageDataObserver observer) {
20073        final int callingUid = Binder.getCallingUid();
20074        mContext.enforceCallingOrSelfPermission(
20075                android.Manifest.permission.DELETE_CACHE_FILES, null);
20076        enforceCrossUserPermission(callingUid, userId,
20077                /* requireFullPermission= */ true, /* checkShell= */ false,
20078                "delete application cache files");
20079        final int hasAccessInstantApps = mContext.checkCallingOrSelfPermission(
20080                android.Manifest.permission.ACCESS_INSTANT_APPS);
20081
20082        final PackageParser.Package pkg;
20083        synchronized (mPackages) {
20084            pkg = mPackages.get(packageName);
20085        }
20086
20087        // Queue up an async operation since the package deletion may take a little while.
20088        mHandler.post(new Runnable() {
20089            public void run() {
20090                final PackageSetting ps = pkg == null ? null : (PackageSetting) pkg.mExtras;
20091                boolean doClearData = true;
20092                if (ps != null) {
20093                    final boolean targetIsInstantApp =
20094                            ps.getInstantApp(UserHandle.getUserId(callingUid));
20095                    doClearData = !targetIsInstantApp
20096                            || hasAccessInstantApps == PackageManager.PERMISSION_GRANTED;
20097                }
20098                if (doClearData) {
20099                    synchronized (mInstallLock) {
20100                        final int flags = StorageManager.FLAG_STORAGE_DE
20101                                | StorageManager.FLAG_STORAGE_CE;
20102                        // We're only clearing cache files, so we don't care if the
20103                        // app is unfrozen and still able to run
20104                        clearAppDataLIF(pkg, userId, flags | Installer.FLAG_CLEAR_CACHE_ONLY);
20105                        clearAppDataLIF(pkg, userId, flags | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
20106                    }
20107                    clearExternalStorageDataSync(packageName, userId, false);
20108                }
20109                if (observer != null) {
20110                    try {
20111                        observer.onRemoveCompleted(packageName, true);
20112                    } catch (RemoteException e) {
20113                        Log.i(TAG, "Observer no longer exists.");
20114                    }
20115                }
20116            }
20117        });
20118    }
20119
20120    @Override
20121    public void getPackageSizeInfo(final String packageName, int userHandle,
20122            final IPackageStatsObserver observer) {
20123        throw new UnsupportedOperationException(
20124                "Shame on you for calling the hidden API getPackageSizeInfo(). Shame!");
20125    }
20126
20127    private boolean getPackageSizeInfoLI(String packageName, int userId, PackageStats stats) {
20128        final PackageSetting ps;
20129        synchronized (mPackages) {
20130            ps = mSettings.mPackages.get(packageName);
20131            if (ps == null) {
20132                Slog.w(TAG, "Failed to find settings for " + packageName);
20133                return false;
20134            }
20135        }
20136
20137        final String[] packageNames = { packageName };
20138        final long[] ceDataInodes = { ps.getCeDataInode(userId) };
20139        final String[] codePaths = { ps.codePathString };
20140
20141        try {
20142            mInstaller.getAppSize(ps.volumeUuid, packageNames, userId, 0,
20143                    ps.appId, ceDataInodes, codePaths, stats);
20144
20145            // For now, ignore code size of packages on system partition
20146            if (isSystemApp(ps) && !isUpdatedSystemApp(ps)) {
20147                stats.codeSize = 0;
20148            }
20149
20150            // External clients expect these to be tracked separately
20151            stats.dataSize -= stats.cacheSize;
20152
20153        } catch (InstallerException e) {
20154            Slog.w(TAG, String.valueOf(e));
20155            return false;
20156        }
20157
20158        return true;
20159    }
20160
20161    private int getUidTargetSdkVersionLockedLPr(int uid) {
20162        Object obj = mSettings.getUserIdLPr(uid);
20163        if (obj instanceof SharedUserSetting) {
20164            final SharedUserSetting sus = (SharedUserSetting) obj;
20165            int vers = Build.VERSION_CODES.CUR_DEVELOPMENT;
20166            final Iterator<PackageSetting> it = sus.packages.iterator();
20167            while (it.hasNext()) {
20168                final PackageSetting ps = it.next();
20169                if (ps.pkg != null) {
20170                    int v = ps.pkg.applicationInfo.targetSdkVersion;
20171                    if (v < vers) vers = v;
20172                }
20173            }
20174            return vers;
20175        } else if (obj instanceof PackageSetting) {
20176            final PackageSetting ps = (PackageSetting) obj;
20177            if (ps.pkg != null) {
20178                return ps.pkg.applicationInfo.targetSdkVersion;
20179            }
20180        }
20181        return Build.VERSION_CODES.CUR_DEVELOPMENT;
20182    }
20183
20184    @Override
20185    public void addPreferredActivity(IntentFilter filter, int match,
20186            ComponentName[] set, ComponentName activity, int userId) {
20187        addPreferredActivityInternal(filter, match, set, activity, true, userId,
20188                "Adding preferred");
20189    }
20190
20191    private void addPreferredActivityInternal(IntentFilter filter, int match,
20192            ComponentName[] set, ComponentName activity, boolean always, int userId,
20193            String opname) {
20194        // writer
20195        int callingUid = Binder.getCallingUid();
20196        enforceCrossUserPermission(callingUid, userId,
20197                true /* requireFullPermission */, false /* checkShell */, "add preferred activity");
20198        if (filter.countActions() == 0) {
20199            Slog.w(TAG, "Cannot set a preferred activity with no filter actions");
20200            return;
20201        }
20202        synchronized (mPackages) {
20203            if (mContext.checkCallingOrSelfPermission(
20204                    android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
20205                    != PackageManager.PERMISSION_GRANTED) {
20206                if (getUidTargetSdkVersionLockedLPr(callingUid)
20207                        < Build.VERSION_CODES.FROYO) {
20208                    Slog.w(TAG, "Ignoring addPreferredActivity() from uid "
20209                            + callingUid);
20210                    return;
20211                }
20212                mContext.enforceCallingOrSelfPermission(
20213                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
20214            }
20215
20216            PreferredIntentResolver pir = mSettings.editPreferredActivitiesLPw(userId);
20217            Slog.i(TAG, opname + " activity " + activity.flattenToShortString() + " for user "
20218                    + userId + ":");
20219            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
20220            pir.addFilter(new PreferredActivity(filter, match, set, activity, always));
20221            scheduleWritePackageRestrictionsLocked(userId);
20222            postPreferredActivityChangedBroadcast(userId);
20223        }
20224    }
20225
20226    private void postPreferredActivityChangedBroadcast(int userId) {
20227        mHandler.post(() -> {
20228            final IActivityManager am = ActivityManager.getService();
20229            if (am == null) {
20230                return;
20231            }
20232
20233            final Intent intent = new Intent(Intent.ACTION_PREFERRED_ACTIVITY_CHANGED);
20234            intent.putExtra(Intent.EXTRA_USER_HANDLE, userId);
20235            try {
20236                am.broadcastIntent(null, intent, null, null,
20237                        0, null, null, null, android.app.AppOpsManager.OP_NONE,
20238                        null, false, false, userId);
20239            } catch (RemoteException e) {
20240            }
20241        });
20242    }
20243
20244    @Override
20245    public void replacePreferredActivity(IntentFilter filter, int match,
20246            ComponentName[] set, ComponentName activity, int userId) {
20247        if (filter.countActions() != 1) {
20248            throw new IllegalArgumentException(
20249                    "replacePreferredActivity expects filter to have only 1 action.");
20250        }
20251        if (filter.countDataAuthorities() != 0
20252                || filter.countDataPaths() != 0
20253                || filter.countDataSchemes() > 1
20254                || filter.countDataTypes() != 0) {
20255            throw new IllegalArgumentException(
20256                    "replacePreferredActivity expects filter to have no data authorities, " +
20257                    "paths, or types; and at most one scheme.");
20258        }
20259
20260        final int callingUid = Binder.getCallingUid();
20261        enforceCrossUserPermission(callingUid, userId,
20262                true /* requireFullPermission */, false /* checkShell */,
20263                "replace preferred activity");
20264        synchronized (mPackages) {
20265            if (mContext.checkCallingOrSelfPermission(
20266                    android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
20267                    != PackageManager.PERMISSION_GRANTED) {
20268                if (getUidTargetSdkVersionLockedLPr(callingUid)
20269                        < Build.VERSION_CODES.FROYO) {
20270                    Slog.w(TAG, "Ignoring replacePreferredActivity() from uid "
20271                            + Binder.getCallingUid());
20272                    return;
20273                }
20274                mContext.enforceCallingOrSelfPermission(
20275                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
20276            }
20277
20278            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
20279            if (pir != null) {
20280                // Get all of the existing entries that exactly match this filter.
20281                ArrayList<PreferredActivity> existing = pir.findFilters(filter);
20282                if (existing != null && existing.size() == 1) {
20283                    PreferredActivity cur = existing.get(0);
20284                    if (DEBUG_PREFERRED) {
20285                        Slog.i(TAG, "Checking replace of preferred:");
20286                        filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
20287                        if (!cur.mPref.mAlways) {
20288                            Slog.i(TAG, "  -- CUR; not mAlways!");
20289                        } else {
20290                            Slog.i(TAG, "  -- CUR: mMatch=" + cur.mPref.mMatch);
20291                            Slog.i(TAG, "  -- CUR: mSet="
20292                                    + Arrays.toString(cur.mPref.mSetComponents));
20293                            Slog.i(TAG, "  -- CUR: mComponent=" + cur.mPref.mShortComponent);
20294                            Slog.i(TAG, "  -- NEW: mMatch="
20295                                    + (match&IntentFilter.MATCH_CATEGORY_MASK));
20296                            Slog.i(TAG, "  -- CUR: mSet=" + Arrays.toString(set));
20297                            Slog.i(TAG, "  -- CUR: mComponent=" + activity.flattenToShortString());
20298                        }
20299                    }
20300                    if (cur.mPref.mAlways && cur.mPref.mComponent.equals(activity)
20301                            && cur.mPref.mMatch == (match&IntentFilter.MATCH_CATEGORY_MASK)
20302                            && cur.mPref.sameSet(set)) {
20303                        // Setting the preferred activity to what it happens to be already
20304                        if (DEBUG_PREFERRED) {
20305                            Slog.i(TAG, "Replacing with same preferred activity "
20306                                    + cur.mPref.mShortComponent + " for user "
20307                                    + userId + ":");
20308                            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
20309                        }
20310                        return;
20311                    }
20312                }
20313
20314                if (existing != null) {
20315                    if (DEBUG_PREFERRED) {
20316                        Slog.i(TAG, existing.size() + " existing preferred matches for:");
20317                        filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
20318                    }
20319                    for (int i = 0; i < existing.size(); i++) {
20320                        PreferredActivity pa = existing.get(i);
20321                        if (DEBUG_PREFERRED) {
20322                            Slog.i(TAG, "Removing existing preferred activity "
20323                                    + pa.mPref.mComponent + ":");
20324                            pa.dump(new LogPrinter(Log.INFO, TAG), "  ");
20325                        }
20326                        pir.removeFilter(pa);
20327                    }
20328                }
20329            }
20330            addPreferredActivityInternal(filter, match, set, activity, true, userId,
20331                    "Replacing preferred");
20332        }
20333    }
20334
20335    @Override
20336    public void clearPackagePreferredActivities(String packageName) {
20337        final int callingUid = Binder.getCallingUid();
20338        if (getInstantAppPackageName(callingUid) != null) {
20339            return;
20340        }
20341        // writer
20342        synchronized (mPackages) {
20343            PackageParser.Package pkg = mPackages.get(packageName);
20344            if (pkg == null || pkg.applicationInfo.uid != callingUid) {
20345                if (mContext.checkCallingOrSelfPermission(
20346                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
20347                        != PackageManager.PERMISSION_GRANTED) {
20348                    if (getUidTargetSdkVersionLockedLPr(callingUid)
20349                            < Build.VERSION_CODES.FROYO) {
20350                        Slog.w(TAG, "Ignoring clearPackagePreferredActivities() from uid "
20351                                + callingUid);
20352                        return;
20353                    }
20354                    mContext.enforceCallingOrSelfPermission(
20355                            android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
20356                }
20357            }
20358            final PackageSetting ps = mSettings.getPackageLPr(packageName);
20359            if (ps != null
20360                    && filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
20361                return;
20362            }
20363            int user = UserHandle.getCallingUserId();
20364            if (clearPackagePreferredActivitiesLPw(packageName, user)) {
20365                scheduleWritePackageRestrictionsLocked(user);
20366            }
20367        }
20368    }
20369
20370    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
20371    boolean clearPackagePreferredActivitiesLPw(String packageName, int userId) {
20372        ArrayList<PreferredActivity> removed = null;
20373        boolean changed = false;
20374        for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
20375            final int thisUserId = mSettings.mPreferredActivities.keyAt(i);
20376            PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
20377            if (userId != UserHandle.USER_ALL && userId != thisUserId) {
20378                continue;
20379            }
20380            Iterator<PreferredActivity> it = pir.filterIterator();
20381            while (it.hasNext()) {
20382                PreferredActivity pa = it.next();
20383                // Mark entry for removal only if it matches the package name
20384                // and the entry is of type "always".
20385                if (packageName == null ||
20386                        (pa.mPref.mComponent.getPackageName().equals(packageName)
20387                                && pa.mPref.mAlways)) {
20388                    if (removed == null) {
20389                        removed = new ArrayList<PreferredActivity>();
20390                    }
20391                    removed.add(pa);
20392                }
20393            }
20394            if (removed != null) {
20395                for (int j=0; j<removed.size(); j++) {
20396                    PreferredActivity pa = removed.get(j);
20397                    pir.removeFilter(pa);
20398                }
20399                changed = true;
20400            }
20401        }
20402        if (changed) {
20403            postPreferredActivityChangedBroadcast(userId);
20404        }
20405        return changed;
20406    }
20407
20408    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
20409    private void clearIntentFilterVerificationsLPw(int userId) {
20410        final int packageCount = mPackages.size();
20411        for (int i = 0; i < packageCount; i++) {
20412            PackageParser.Package pkg = mPackages.valueAt(i);
20413            clearIntentFilterVerificationsLPw(pkg.packageName, userId);
20414        }
20415    }
20416
20417    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
20418    void clearIntentFilterVerificationsLPw(String packageName, int userId) {
20419        if (userId == UserHandle.USER_ALL) {
20420            if (mSettings.removeIntentFilterVerificationLPw(packageName,
20421                    sUserManager.getUserIds())) {
20422                for (int oneUserId : sUserManager.getUserIds()) {
20423                    scheduleWritePackageRestrictionsLocked(oneUserId);
20424                }
20425            }
20426        } else {
20427            if (mSettings.removeIntentFilterVerificationLPw(packageName, userId)) {
20428                scheduleWritePackageRestrictionsLocked(userId);
20429            }
20430        }
20431    }
20432
20433    /** Clears state for all users, and touches intent filter verification policy */
20434    void clearDefaultBrowserIfNeeded(String packageName) {
20435        for (int oneUserId : sUserManager.getUserIds()) {
20436            clearDefaultBrowserIfNeededForUser(packageName, oneUserId);
20437        }
20438    }
20439
20440    private void clearDefaultBrowserIfNeededForUser(String packageName, int userId) {
20441        final String defaultBrowserPackageName = getDefaultBrowserPackageName(userId);
20442        if (!TextUtils.isEmpty(defaultBrowserPackageName)) {
20443            if (packageName.equals(defaultBrowserPackageName)) {
20444                setDefaultBrowserPackageName(null, userId);
20445            }
20446        }
20447    }
20448
20449    @Override
20450    public void resetApplicationPreferences(int userId) {
20451        mContext.enforceCallingOrSelfPermission(
20452                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
20453        final long identity = Binder.clearCallingIdentity();
20454        // writer
20455        try {
20456            synchronized (mPackages) {
20457                clearPackagePreferredActivitiesLPw(null, userId);
20458                mSettings.applyDefaultPreferredAppsLPw(this, userId);
20459                // TODO: We have to reset the default SMS and Phone. This requires
20460                // significant refactoring to keep all default apps in the package
20461                // manager (cleaner but more work) or have the services provide
20462                // callbacks to the package manager to request a default app reset.
20463                applyFactoryDefaultBrowserLPw(userId);
20464                clearIntentFilterVerificationsLPw(userId);
20465                primeDomainVerificationsLPw(userId);
20466                resetUserChangesToRuntimePermissionsAndFlagsLPw(userId);
20467                scheduleWritePackageRestrictionsLocked(userId);
20468            }
20469            resetNetworkPolicies(userId);
20470        } finally {
20471            Binder.restoreCallingIdentity(identity);
20472        }
20473    }
20474
20475    @Override
20476    public int getPreferredActivities(List<IntentFilter> outFilters,
20477            List<ComponentName> outActivities, String packageName) {
20478        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
20479            return 0;
20480        }
20481        int num = 0;
20482        final int userId = UserHandle.getCallingUserId();
20483        // reader
20484        synchronized (mPackages) {
20485            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
20486            if (pir != null) {
20487                final Iterator<PreferredActivity> it = pir.filterIterator();
20488                while (it.hasNext()) {
20489                    final PreferredActivity pa = it.next();
20490                    if (packageName == null
20491                            || (pa.mPref.mComponent.getPackageName().equals(packageName)
20492                                    && pa.mPref.mAlways)) {
20493                        if (outFilters != null) {
20494                            outFilters.add(new IntentFilter(pa));
20495                        }
20496                        if (outActivities != null) {
20497                            outActivities.add(pa.mPref.mComponent);
20498                        }
20499                    }
20500                }
20501            }
20502        }
20503
20504        return num;
20505    }
20506
20507    @Override
20508    public void addPersistentPreferredActivity(IntentFilter filter, ComponentName activity,
20509            int userId) {
20510        int callingUid = Binder.getCallingUid();
20511        if (callingUid != Process.SYSTEM_UID) {
20512            throw new SecurityException(
20513                    "addPersistentPreferredActivity can only be run by the system");
20514        }
20515        if (filter.countActions() == 0) {
20516            Slog.w(TAG, "Cannot set a preferred activity with no filter actions");
20517            return;
20518        }
20519        synchronized (mPackages) {
20520            Slog.i(TAG, "Adding persistent preferred activity " + activity + " for user " + userId +
20521                    ":");
20522            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
20523            mSettings.editPersistentPreferredActivitiesLPw(userId).addFilter(
20524                    new PersistentPreferredActivity(filter, activity));
20525            scheduleWritePackageRestrictionsLocked(userId);
20526            postPreferredActivityChangedBroadcast(userId);
20527        }
20528    }
20529
20530    @Override
20531    public void clearPackagePersistentPreferredActivities(String packageName, int userId) {
20532        int callingUid = Binder.getCallingUid();
20533        if (callingUid != Process.SYSTEM_UID) {
20534            throw new SecurityException(
20535                    "clearPackagePersistentPreferredActivities can only be run by the system");
20536        }
20537        ArrayList<PersistentPreferredActivity> removed = null;
20538        boolean changed = false;
20539        synchronized (mPackages) {
20540            for (int i=0; i<mSettings.mPersistentPreferredActivities.size(); i++) {
20541                final int thisUserId = mSettings.mPersistentPreferredActivities.keyAt(i);
20542                PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities
20543                        .valueAt(i);
20544                if (userId != thisUserId) {
20545                    continue;
20546                }
20547                Iterator<PersistentPreferredActivity> it = ppir.filterIterator();
20548                while (it.hasNext()) {
20549                    PersistentPreferredActivity ppa = it.next();
20550                    // Mark entry for removal only if it matches the package name.
20551                    if (ppa.mComponent.getPackageName().equals(packageName)) {
20552                        if (removed == null) {
20553                            removed = new ArrayList<PersistentPreferredActivity>();
20554                        }
20555                        removed.add(ppa);
20556                    }
20557                }
20558                if (removed != null) {
20559                    for (int j=0; j<removed.size(); j++) {
20560                        PersistentPreferredActivity ppa = removed.get(j);
20561                        ppir.removeFilter(ppa);
20562                    }
20563                    changed = true;
20564                }
20565            }
20566
20567            if (changed) {
20568                scheduleWritePackageRestrictionsLocked(userId);
20569                postPreferredActivityChangedBroadcast(userId);
20570            }
20571        }
20572    }
20573
20574    /**
20575     * Common machinery for picking apart a restored XML blob and passing
20576     * it to a caller-supplied functor to be applied to the running system.
20577     */
20578    private void restoreFromXml(XmlPullParser parser, int userId,
20579            String expectedStartTag, BlobXmlRestorer functor)
20580            throws IOException, XmlPullParserException {
20581        int type;
20582        while ((type = parser.next()) != XmlPullParser.START_TAG
20583                && type != XmlPullParser.END_DOCUMENT) {
20584        }
20585        if (type != XmlPullParser.START_TAG) {
20586            // oops didn't find a start tag?!
20587            if (DEBUG_BACKUP) {
20588                Slog.e(TAG, "Didn't find start tag during restore");
20589            }
20590            return;
20591        }
20592Slog.v(TAG, ":: restoreFromXml() : got to tag " + parser.getName());
20593        // this is supposed to be TAG_PREFERRED_BACKUP
20594        if (!expectedStartTag.equals(parser.getName())) {
20595            if (DEBUG_BACKUP) {
20596                Slog.e(TAG, "Found unexpected tag " + parser.getName());
20597            }
20598            return;
20599        }
20600
20601        // skip interfering stuff, then we're aligned with the backing implementation
20602        while ((type = parser.next()) == XmlPullParser.TEXT) { }
20603Slog.v(TAG, ":: stepped forward, applying functor at tag " + parser.getName());
20604        functor.apply(parser, userId);
20605    }
20606
20607    private interface BlobXmlRestorer {
20608        public void apply(XmlPullParser parser, int userId) throws IOException, XmlPullParserException;
20609    }
20610
20611    /**
20612     * Non-Binder method, support for the backup/restore mechanism: write the
20613     * full set of preferred activities in its canonical XML format.  Returns the
20614     * XML output as a byte array, or null if there is none.
20615     */
20616    @Override
20617    public byte[] getPreferredActivityBackup(int userId) {
20618        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
20619            throw new SecurityException("Only the system may call getPreferredActivityBackup()");
20620        }
20621
20622        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
20623        try {
20624            final XmlSerializer serializer = new FastXmlSerializer();
20625            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
20626            serializer.startDocument(null, true);
20627            serializer.startTag(null, TAG_PREFERRED_BACKUP);
20628
20629            synchronized (mPackages) {
20630                mSettings.writePreferredActivitiesLPr(serializer, userId, true);
20631            }
20632
20633            serializer.endTag(null, TAG_PREFERRED_BACKUP);
20634            serializer.endDocument();
20635            serializer.flush();
20636        } catch (Exception e) {
20637            if (DEBUG_BACKUP) {
20638                Slog.e(TAG, "Unable to write preferred activities for backup", e);
20639            }
20640            return null;
20641        }
20642
20643        return dataStream.toByteArray();
20644    }
20645
20646    @Override
20647    public void restorePreferredActivities(byte[] backup, int userId) {
20648        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
20649            throw new SecurityException("Only the system may call restorePreferredActivities()");
20650        }
20651
20652        try {
20653            final XmlPullParser parser = Xml.newPullParser();
20654            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
20655            restoreFromXml(parser, userId, TAG_PREFERRED_BACKUP,
20656                    new BlobXmlRestorer() {
20657                        @Override
20658                        public void apply(XmlPullParser parser, int userId)
20659                                throws XmlPullParserException, IOException {
20660                            synchronized (mPackages) {
20661                                mSettings.readPreferredActivitiesLPw(parser, userId);
20662                            }
20663                        }
20664                    } );
20665        } catch (Exception e) {
20666            if (DEBUG_BACKUP) {
20667                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
20668            }
20669        }
20670    }
20671
20672    /**
20673     * Non-Binder method, support for the backup/restore mechanism: write the
20674     * default browser (etc) settings in its canonical XML format.  Returns the default
20675     * browser XML representation as a byte array, or null if there is none.
20676     */
20677    @Override
20678    public byte[] getDefaultAppsBackup(int userId) {
20679        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
20680            throw new SecurityException("Only the system may call getDefaultAppsBackup()");
20681        }
20682
20683        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
20684        try {
20685            final XmlSerializer serializer = new FastXmlSerializer();
20686            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
20687            serializer.startDocument(null, true);
20688            serializer.startTag(null, TAG_DEFAULT_APPS);
20689
20690            synchronized (mPackages) {
20691                mSettings.writeDefaultAppsLPr(serializer, userId);
20692            }
20693
20694            serializer.endTag(null, TAG_DEFAULT_APPS);
20695            serializer.endDocument();
20696            serializer.flush();
20697        } catch (Exception e) {
20698            if (DEBUG_BACKUP) {
20699                Slog.e(TAG, "Unable to write default apps for backup", e);
20700            }
20701            return null;
20702        }
20703
20704        return dataStream.toByteArray();
20705    }
20706
20707    @Override
20708    public void restoreDefaultApps(byte[] backup, int userId) {
20709        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
20710            throw new SecurityException("Only the system may call restoreDefaultApps()");
20711        }
20712
20713        try {
20714            final XmlPullParser parser = Xml.newPullParser();
20715            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
20716            restoreFromXml(parser, userId, TAG_DEFAULT_APPS,
20717                    new BlobXmlRestorer() {
20718                        @Override
20719                        public void apply(XmlPullParser parser, int userId)
20720                                throws XmlPullParserException, IOException {
20721                            synchronized (mPackages) {
20722                                mSettings.readDefaultAppsLPw(parser, userId);
20723                            }
20724                        }
20725                    } );
20726        } catch (Exception e) {
20727            if (DEBUG_BACKUP) {
20728                Slog.e(TAG, "Exception restoring default apps: " + e.getMessage());
20729            }
20730        }
20731    }
20732
20733    @Override
20734    public byte[] getIntentFilterVerificationBackup(int userId) {
20735        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
20736            throw new SecurityException("Only the system may call getIntentFilterVerificationBackup()");
20737        }
20738
20739        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
20740        try {
20741            final XmlSerializer serializer = new FastXmlSerializer();
20742            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
20743            serializer.startDocument(null, true);
20744            serializer.startTag(null, TAG_INTENT_FILTER_VERIFICATION);
20745
20746            synchronized (mPackages) {
20747                mSettings.writeAllDomainVerificationsLPr(serializer, userId);
20748            }
20749
20750            serializer.endTag(null, TAG_INTENT_FILTER_VERIFICATION);
20751            serializer.endDocument();
20752            serializer.flush();
20753        } catch (Exception e) {
20754            if (DEBUG_BACKUP) {
20755                Slog.e(TAG, "Unable to write default apps for backup", e);
20756            }
20757            return null;
20758        }
20759
20760        return dataStream.toByteArray();
20761    }
20762
20763    @Override
20764    public void restoreIntentFilterVerification(byte[] backup, int userId) {
20765        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
20766            throw new SecurityException("Only the system may call restorePreferredActivities()");
20767        }
20768
20769        try {
20770            final XmlPullParser parser = Xml.newPullParser();
20771            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
20772            restoreFromXml(parser, userId, TAG_INTENT_FILTER_VERIFICATION,
20773                    new BlobXmlRestorer() {
20774                        @Override
20775                        public void apply(XmlPullParser parser, int userId)
20776                                throws XmlPullParserException, IOException {
20777                            synchronized (mPackages) {
20778                                mSettings.readAllDomainVerificationsLPr(parser, userId);
20779                                mSettings.writeLPr();
20780                            }
20781                        }
20782                    } );
20783        } catch (Exception e) {
20784            if (DEBUG_BACKUP) {
20785                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
20786            }
20787        }
20788    }
20789
20790    @Override
20791    public byte[] getPermissionGrantBackup(int userId) {
20792        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
20793            throw new SecurityException("Only the system may call getPermissionGrantBackup()");
20794        }
20795
20796        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
20797        try {
20798            final XmlSerializer serializer = new FastXmlSerializer();
20799            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
20800            serializer.startDocument(null, true);
20801            serializer.startTag(null, TAG_PERMISSION_BACKUP);
20802
20803            synchronized (mPackages) {
20804                serializeRuntimePermissionGrantsLPr(serializer, userId);
20805            }
20806
20807            serializer.endTag(null, TAG_PERMISSION_BACKUP);
20808            serializer.endDocument();
20809            serializer.flush();
20810        } catch (Exception e) {
20811            if (DEBUG_BACKUP) {
20812                Slog.e(TAG, "Unable to write default apps for backup", e);
20813            }
20814            return null;
20815        }
20816
20817        return dataStream.toByteArray();
20818    }
20819
20820    @Override
20821    public void restorePermissionGrants(byte[] backup, int userId) {
20822        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
20823            throw new SecurityException("Only the system may call restorePermissionGrants()");
20824        }
20825
20826        try {
20827            final XmlPullParser parser = Xml.newPullParser();
20828            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
20829            restoreFromXml(parser, userId, TAG_PERMISSION_BACKUP,
20830                    new BlobXmlRestorer() {
20831                        @Override
20832                        public void apply(XmlPullParser parser, int userId)
20833                                throws XmlPullParserException, IOException {
20834                            synchronized (mPackages) {
20835                                processRestoredPermissionGrantsLPr(parser, userId);
20836                            }
20837                        }
20838                    } );
20839        } catch (Exception e) {
20840            if (DEBUG_BACKUP) {
20841                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
20842            }
20843        }
20844    }
20845
20846    private void serializeRuntimePermissionGrantsLPr(XmlSerializer serializer, final int userId)
20847            throws IOException {
20848        serializer.startTag(null, TAG_ALL_GRANTS);
20849
20850        final int N = mSettings.mPackages.size();
20851        for (int i = 0; i < N; i++) {
20852            final PackageSetting ps = mSettings.mPackages.valueAt(i);
20853            boolean pkgGrantsKnown = false;
20854
20855            PermissionsState packagePerms = ps.getPermissionsState();
20856
20857            for (PermissionState state : packagePerms.getRuntimePermissionStates(userId)) {
20858                final int grantFlags = state.getFlags();
20859                // only look at grants that are not system/policy fixed
20860                if ((grantFlags & SYSTEM_RUNTIME_GRANT_MASK) == 0) {
20861                    final boolean isGranted = state.isGranted();
20862                    // And only back up the user-twiddled state bits
20863                    if (isGranted || (grantFlags & USER_RUNTIME_GRANT_MASK) != 0) {
20864                        final String packageName = mSettings.mPackages.keyAt(i);
20865                        if (!pkgGrantsKnown) {
20866                            serializer.startTag(null, TAG_GRANT);
20867                            serializer.attribute(null, ATTR_PACKAGE_NAME, packageName);
20868                            pkgGrantsKnown = true;
20869                        }
20870
20871                        final boolean userSet =
20872                                (grantFlags & FLAG_PERMISSION_USER_SET) != 0;
20873                        final boolean userFixed =
20874                                (grantFlags & FLAG_PERMISSION_USER_FIXED) != 0;
20875                        final boolean revoke =
20876                                (grantFlags & FLAG_PERMISSION_REVOKE_ON_UPGRADE) != 0;
20877
20878                        serializer.startTag(null, TAG_PERMISSION);
20879                        serializer.attribute(null, ATTR_PERMISSION_NAME, state.getName());
20880                        if (isGranted) {
20881                            serializer.attribute(null, ATTR_IS_GRANTED, "true");
20882                        }
20883                        if (userSet) {
20884                            serializer.attribute(null, ATTR_USER_SET, "true");
20885                        }
20886                        if (userFixed) {
20887                            serializer.attribute(null, ATTR_USER_FIXED, "true");
20888                        }
20889                        if (revoke) {
20890                            serializer.attribute(null, ATTR_REVOKE_ON_UPGRADE, "true");
20891                        }
20892                        serializer.endTag(null, TAG_PERMISSION);
20893                    }
20894                }
20895            }
20896
20897            if (pkgGrantsKnown) {
20898                serializer.endTag(null, TAG_GRANT);
20899            }
20900        }
20901
20902        serializer.endTag(null, TAG_ALL_GRANTS);
20903    }
20904
20905    private void processRestoredPermissionGrantsLPr(XmlPullParser parser, int userId)
20906            throws XmlPullParserException, IOException {
20907        String pkgName = null;
20908        int outerDepth = parser.getDepth();
20909        int type;
20910        while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
20911                && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) {
20912            if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) {
20913                continue;
20914            }
20915
20916            final String tagName = parser.getName();
20917            if (tagName.equals(TAG_GRANT)) {
20918                pkgName = parser.getAttributeValue(null, ATTR_PACKAGE_NAME);
20919                if (DEBUG_BACKUP) {
20920                    Slog.v(TAG, "+++ Restoring grants for package " + pkgName);
20921                }
20922            } else if (tagName.equals(TAG_PERMISSION)) {
20923
20924                final boolean isGranted = "true".equals(parser.getAttributeValue(null, ATTR_IS_GRANTED));
20925                final String permName = parser.getAttributeValue(null, ATTR_PERMISSION_NAME);
20926
20927                int newFlagSet = 0;
20928                if ("true".equals(parser.getAttributeValue(null, ATTR_USER_SET))) {
20929                    newFlagSet |= FLAG_PERMISSION_USER_SET;
20930                }
20931                if ("true".equals(parser.getAttributeValue(null, ATTR_USER_FIXED))) {
20932                    newFlagSet |= FLAG_PERMISSION_USER_FIXED;
20933                }
20934                if ("true".equals(parser.getAttributeValue(null, ATTR_REVOKE_ON_UPGRADE))) {
20935                    newFlagSet |= FLAG_PERMISSION_REVOKE_ON_UPGRADE;
20936                }
20937                if (DEBUG_BACKUP) {
20938                    Slog.v(TAG, "  + Restoring grant: pkg=" + pkgName + " perm=" + permName
20939                            + " granted=" + isGranted + " bits=0x" + Integer.toHexString(newFlagSet));
20940                }
20941                final PackageSetting ps = mSettings.mPackages.get(pkgName);
20942                if (ps != null) {
20943                    // Already installed so we apply the grant immediately
20944                    if (DEBUG_BACKUP) {
20945                        Slog.v(TAG, "        + already installed; applying");
20946                    }
20947                    PermissionsState perms = ps.getPermissionsState();
20948                    BasePermission bp = mSettings.mPermissions.get(permName);
20949                    if (bp != null) {
20950                        if (isGranted) {
20951                            perms.grantRuntimePermission(bp, userId);
20952                        }
20953                        if (newFlagSet != 0) {
20954                            perms.updatePermissionFlags(bp, userId, USER_RUNTIME_GRANT_MASK, newFlagSet);
20955                        }
20956                    }
20957                } else {
20958                    // Need to wait for post-restore install to apply the grant
20959                    if (DEBUG_BACKUP) {
20960                        Slog.v(TAG, "        - not yet installed; saving for later");
20961                    }
20962                    mSettings.processRestoredPermissionGrantLPr(pkgName, permName,
20963                            isGranted, newFlagSet, userId);
20964                }
20965            } else {
20966                PackageManagerService.reportSettingsProblem(Log.WARN,
20967                        "Unknown element under <" + TAG_PERMISSION_BACKUP + ">: " + tagName);
20968                XmlUtils.skipCurrentTag(parser);
20969            }
20970        }
20971
20972        scheduleWriteSettingsLocked();
20973        mSettings.writeRuntimePermissionsForUserLPr(userId, false);
20974    }
20975
20976    @Override
20977    public void addCrossProfileIntentFilter(IntentFilter intentFilter, String ownerPackage,
20978            int sourceUserId, int targetUserId, int flags) {
20979        mContext.enforceCallingOrSelfPermission(
20980                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
20981        int callingUid = Binder.getCallingUid();
20982        enforceOwnerRights(ownerPackage, callingUid);
20983        enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId);
20984        if (intentFilter.countActions() == 0) {
20985            Slog.w(TAG, "Cannot set a crossProfile intent filter with no filter actions");
20986            return;
20987        }
20988        synchronized (mPackages) {
20989            CrossProfileIntentFilter newFilter = new CrossProfileIntentFilter(intentFilter,
20990                    ownerPackage, targetUserId, flags);
20991            CrossProfileIntentResolver resolver =
20992                    mSettings.editCrossProfileIntentResolverLPw(sourceUserId);
20993            ArrayList<CrossProfileIntentFilter> existing = resolver.findFilters(intentFilter);
20994            // We have all those whose filter is equal. Now checking if the rest is equal as well.
20995            if (existing != null) {
20996                int size = existing.size();
20997                for (int i = 0; i < size; i++) {
20998                    if (newFilter.equalsIgnoreFilter(existing.get(i))) {
20999                        return;
21000                    }
21001                }
21002            }
21003            resolver.addFilter(newFilter);
21004            scheduleWritePackageRestrictionsLocked(sourceUserId);
21005        }
21006    }
21007
21008    @Override
21009    public void clearCrossProfileIntentFilters(int sourceUserId, String ownerPackage) {
21010        mContext.enforceCallingOrSelfPermission(
21011                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
21012        final int callingUid = Binder.getCallingUid();
21013        enforceOwnerRights(ownerPackage, callingUid);
21014        enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId);
21015        synchronized (mPackages) {
21016            CrossProfileIntentResolver resolver =
21017                    mSettings.editCrossProfileIntentResolverLPw(sourceUserId);
21018            ArraySet<CrossProfileIntentFilter> set =
21019                    new ArraySet<CrossProfileIntentFilter>(resolver.filterSet());
21020            for (CrossProfileIntentFilter filter : set) {
21021                if (filter.getOwnerPackage().equals(ownerPackage)) {
21022                    resolver.removeFilter(filter);
21023                }
21024            }
21025            scheduleWritePackageRestrictionsLocked(sourceUserId);
21026        }
21027    }
21028
21029    // Enforcing that callingUid is owning pkg on userId
21030    private void enforceOwnerRights(String pkg, int callingUid) {
21031        // The system owns everything.
21032        if (UserHandle.getAppId(callingUid) == Process.SYSTEM_UID) {
21033            return;
21034        }
21035        final int callingUserId = UserHandle.getUserId(callingUid);
21036        PackageInfo pi = getPackageInfo(pkg, 0, callingUserId);
21037        if (pi == null) {
21038            throw new IllegalArgumentException("Unknown package " + pkg + " on user "
21039                    + callingUserId);
21040        }
21041        if (!UserHandle.isSameApp(pi.applicationInfo.uid, callingUid)) {
21042            throw new SecurityException("Calling uid " + callingUid
21043                    + " does not own package " + pkg);
21044        }
21045    }
21046
21047    @Override
21048    public ComponentName getHomeActivities(List<ResolveInfo> allHomeCandidates) {
21049        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
21050            return null;
21051        }
21052        return getHomeActivitiesAsUser(allHomeCandidates, UserHandle.getCallingUserId());
21053    }
21054
21055    public void sendSessionCommitBroadcast(PackageInstaller.SessionInfo sessionInfo, int userId) {
21056        UserManagerService ums = UserManagerService.getInstance();
21057        if (ums != null) {
21058            final UserInfo parent = ums.getProfileParent(userId);
21059            final int launcherUid = (parent != null) ? parent.id : userId;
21060            final ComponentName launcherComponent = getDefaultHomeActivity(launcherUid);
21061            if (launcherComponent != null) {
21062                Intent launcherIntent = new Intent(PackageInstaller.ACTION_SESSION_COMMITTED)
21063                        .putExtra(PackageInstaller.EXTRA_SESSION, sessionInfo)
21064                        .putExtra(Intent.EXTRA_USER, UserHandle.of(userId))
21065                        .setPackage(launcherComponent.getPackageName());
21066                mContext.sendBroadcastAsUser(launcherIntent, UserHandle.of(launcherUid));
21067            }
21068        }
21069    }
21070
21071    /**
21072     * Report the 'Home' activity which is currently set as "always use this one". If non is set
21073     * then reports the most likely home activity or null if there are more than one.
21074     */
21075    private ComponentName getDefaultHomeActivity(int userId) {
21076        List<ResolveInfo> allHomeCandidates = new ArrayList<>();
21077        ComponentName cn = getHomeActivitiesAsUser(allHomeCandidates, userId);
21078        if (cn != null) {
21079            return cn;
21080        }
21081
21082        // Find the launcher with the highest priority and return that component if there are no
21083        // other home activity with the same priority.
21084        int lastPriority = Integer.MIN_VALUE;
21085        ComponentName lastComponent = null;
21086        final int size = allHomeCandidates.size();
21087        for (int i = 0; i < size; i++) {
21088            final ResolveInfo ri = allHomeCandidates.get(i);
21089            if (ri.priority > lastPriority) {
21090                lastComponent = ri.activityInfo.getComponentName();
21091                lastPriority = ri.priority;
21092            } else if (ri.priority == lastPriority) {
21093                // Two components found with same priority.
21094                lastComponent = null;
21095            }
21096        }
21097        return lastComponent;
21098    }
21099
21100    private Intent getHomeIntent() {
21101        Intent intent = new Intent(Intent.ACTION_MAIN);
21102        intent.addCategory(Intent.CATEGORY_HOME);
21103        intent.addCategory(Intent.CATEGORY_DEFAULT);
21104        return intent;
21105    }
21106
21107    private IntentFilter getHomeFilter() {
21108        IntentFilter filter = new IntentFilter(Intent.ACTION_MAIN);
21109        filter.addCategory(Intent.CATEGORY_HOME);
21110        filter.addCategory(Intent.CATEGORY_DEFAULT);
21111        return filter;
21112    }
21113
21114    ComponentName getHomeActivitiesAsUser(List<ResolveInfo> allHomeCandidates,
21115            int userId) {
21116        Intent intent  = getHomeIntent();
21117        List<ResolveInfo> list = queryIntentActivitiesInternal(intent, null,
21118                PackageManager.GET_META_DATA, userId);
21119        ResolveInfo preferred = findPreferredActivity(intent, null, 0, list, 0,
21120                true, false, false, userId);
21121
21122        allHomeCandidates.clear();
21123        if (list != null) {
21124            for (ResolveInfo ri : list) {
21125                allHomeCandidates.add(ri);
21126            }
21127        }
21128        return (preferred == null || preferred.activityInfo == null)
21129                ? null
21130                : new ComponentName(preferred.activityInfo.packageName,
21131                        preferred.activityInfo.name);
21132    }
21133
21134    @Override
21135    public void setHomeActivity(ComponentName comp, int userId) {
21136        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
21137            return;
21138        }
21139        ArrayList<ResolveInfo> homeActivities = new ArrayList<>();
21140        getHomeActivitiesAsUser(homeActivities, userId);
21141
21142        boolean found = false;
21143
21144        final int size = homeActivities.size();
21145        final ComponentName[] set = new ComponentName[size];
21146        for (int i = 0; i < size; i++) {
21147            final ResolveInfo candidate = homeActivities.get(i);
21148            final ActivityInfo info = candidate.activityInfo;
21149            final ComponentName activityName = new ComponentName(info.packageName, info.name);
21150            set[i] = activityName;
21151            if (!found && activityName.equals(comp)) {
21152                found = true;
21153            }
21154        }
21155        if (!found) {
21156            throw new IllegalArgumentException("Component " + comp + " cannot be home on user "
21157                    + userId);
21158        }
21159        replacePreferredActivity(getHomeFilter(), IntentFilter.MATCH_CATEGORY_EMPTY,
21160                set, comp, userId);
21161    }
21162
21163    private @Nullable String getSetupWizardPackageName() {
21164        final Intent intent = new Intent(Intent.ACTION_MAIN);
21165        intent.addCategory(Intent.CATEGORY_SETUP_WIZARD);
21166
21167        final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, null,
21168                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE
21169                        | MATCH_DISABLED_COMPONENTS,
21170                UserHandle.myUserId());
21171        if (matches.size() == 1) {
21172            return matches.get(0).getComponentInfo().packageName;
21173        } else {
21174            Slog.e(TAG, "There should probably be exactly one setup wizard; found " + matches.size()
21175                    + ": matches=" + matches);
21176            return null;
21177        }
21178    }
21179
21180    private @Nullable String getStorageManagerPackageName() {
21181        final Intent intent = new Intent(StorageManager.ACTION_MANAGE_STORAGE);
21182
21183        final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, null,
21184                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE
21185                        | MATCH_DISABLED_COMPONENTS,
21186                UserHandle.myUserId());
21187        if (matches.size() == 1) {
21188            return matches.get(0).getComponentInfo().packageName;
21189        } else {
21190            Slog.e(TAG, "There should probably be exactly one storage manager; found "
21191                    + matches.size() + ": matches=" + matches);
21192            return null;
21193        }
21194    }
21195
21196    @Override
21197    public void setApplicationEnabledSetting(String appPackageName,
21198            int newState, int flags, int userId, String callingPackage) {
21199        if (!sUserManager.exists(userId)) return;
21200        if (callingPackage == null) {
21201            callingPackage = Integer.toString(Binder.getCallingUid());
21202        }
21203        setEnabledSetting(appPackageName, null, newState, flags, userId, callingPackage);
21204    }
21205
21206    @Override
21207    public void setUpdateAvailable(String packageName, boolean updateAvailable) {
21208        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, null);
21209        synchronized (mPackages) {
21210            final PackageSetting pkgSetting = mSettings.mPackages.get(packageName);
21211            if (pkgSetting != null) {
21212                pkgSetting.setUpdateAvailable(updateAvailable);
21213            }
21214        }
21215    }
21216
21217    @Override
21218    public void setComponentEnabledSetting(ComponentName componentName,
21219            int newState, int flags, int userId) {
21220        if (!sUserManager.exists(userId)) return;
21221        setEnabledSetting(componentName.getPackageName(),
21222                componentName.getClassName(), newState, flags, userId, null);
21223    }
21224
21225    private void setEnabledSetting(final String packageName, String className, int newState,
21226            final int flags, int userId, String callingPackage) {
21227        if (!(newState == COMPONENT_ENABLED_STATE_DEFAULT
21228              || newState == COMPONENT_ENABLED_STATE_ENABLED
21229              || newState == COMPONENT_ENABLED_STATE_DISABLED
21230              || newState == COMPONENT_ENABLED_STATE_DISABLED_USER
21231              || newState == COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED)) {
21232            throw new IllegalArgumentException("Invalid new component state: "
21233                    + newState);
21234        }
21235        PackageSetting pkgSetting;
21236        final int callingUid = Binder.getCallingUid();
21237        final int permission;
21238        if (callingUid == Process.SYSTEM_UID) {
21239            permission = PackageManager.PERMISSION_GRANTED;
21240        } else {
21241            permission = mContext.checkCallingOrSelfPermission(
21242                    android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
21243        }
21244        enforceCrossUserPermission(callingUid, userId,
21245                false /* requireFullPermission */, true /* checkShell */, "set enabled");
21246        final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
21247        boolean sendNow = false;
21248        boolean isApp = (className == null);
21249        final boolean isCallerInstantApp = (getInstantAppPackageName(callingUid) != null);
21250        String componentName = isApp ? packageName : className;
21251        int packageUid = -1;
21252        ArrayList<String> components;
21253
21254        // reader
21255        synchronized (mPackages) {
21256            pkgSetting = mSettings.mPackages.get(packageName);
21257            if (pkgSetting == null) {
21258                if (!isCallerInstantApp) {
21259                    if (className == null) {
21260                        throw new IllegalArgumentException("Unknown package: " + packageName);
21261                    }
21262                    throw new IllegalArgumentException(
21263                            "Unknown component: " + packageName + "/" + className);
21264                } else {
21265                    // throw SecurityException to prevent leaking package information
21266                    throw new SecurityException(
21267                            "Attempt to change component state; "
21268                            + "pid=" + Binder.getCallingPid()
21269                            + ", uid=" + callingUid
21270                            + (className == null
21271                                    ? ", package=" + packageName
21272                                    : ", component=" + packageName + "/" + className));
21273                }
21274            }
21275        }
21276
21277        // Limit who can change which apps
21278        if (!UserHandle.isSameApp(callingUid, pkgSetting.appId)) {
21279            // Don't allow apps that don't have permission to modify other apps
21280            if (!allowedByPermission
21281                    || filterAppAccessLPr(pkgSetting, callingUid, userId)) {
21282                throw new SecurityException(
21283                        "Attempt to change component state; "
21284                        + "pid=" + Binder.getCallingPid()
21285                        + ", uid=" + callingUid
21286                        + (className == null
21287                                ? ", package=" + packageName
21288                                : ", component=" + packageName + "/" + className));
21289            }
21290            // Don't allow changing protected packages.
21291            if (mProtectedPackages.isPackageStateProtected(userId, packageName)) {
21292                throw new SecurityException("Cannot disable a protected package: " + packageName);
21293            }
21294        }
21295
21296        synchronized (mPackages) {
21297            if (callingUid == Process.SHELL_UID
21298                    && (pkgSetting.pkgFlags & ApplicationInfo.FLAG_TEST_ONLY) == 0) {
21299                // Shell can only change whole packages between ENABLED and DISABLED_USER states
21300                // unless it is a test package.
21301                int oldState = pkgSetting.getEnabled(userId);
21302                if (className == null
21303                    &&
21304                    (oldState == COMPONENT_ENABLED_STATE_DISABLED_USER
21305                     || oldState == COMPONENT_ENABLED_STATE_DEFAULT
21306                     || oldState == COMPONENT_ENABLED_STATE_ENABLED)
21307                    &&
21308                    (newState == COMPONENT_ENABLED_STATE_DISABLED_USER
21309                     || newState == COMPONENT_ENABLED_STATE_DEFAULT
21310                     || newState == COMPONENT_ENABLED_STATE_ENABLED)) {
21311                    // ok
21312                } else {
21313                    throw new SecurityException(
21314                            "Shell cannot change component state for " + packageName + "/"
21315                            + className + " to " + newState);
21316                }
21317            }
21318            if (className == null) {
21319                // We're dealing with an application/package level state change
21320                if (pkgSetting.getEnabled(userId) == newState) {
21321                    // Nothing to do
21322                    return;
21323                }
21324                if (newState == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT
21325                    || newState == PackageManager.COMPONENT_ENABLED_STATE_ENABLED) {
21326                    // Don't care about who enables an app.
21327                    callingPackage = null;
21328                }
21329                pkgSetting.setEnabled(newState, userId, callingPackage);
21330                // pkgSetting.pkg.mSetEnabled = newState;
21331            } else {
21332                // We're dealing with a component level state change
21333                // First, verify that this is a valid class name.
21334                PackageParser.Package pkg = pkgSetting.pkg;
21335                if (pkg == null || !pkg.hasComponentClassName(className)) {
21336                    if (pkg != null &&
21337                            pkg.applicationInfo.targetSdkVersion >=
21338                                    Build.VERSION_CODES.JELLY_BEAN) {
21339                        throw new IllegalArgumentException("Component class " + className
21340                                + " does not exist in " + packageName);
21341                    } else {
21342                        Slog.w(TAG, "Failed setComponentEnabledSetting: component class "
21343                                + className + " does not exist in " + packageName);
21344                    }
21345                }
21346                switch (newState) {
21347                case COMPONENT_ENABLED_STATE_ENABLED:
21348                    if (!pkgSetting.enableComponentLPw(className, userId)) {
21349                        return;
21350                    }
21351                    break;
21352                case COMPONENT_ENABLED_STATE_DISABLED:
21353                    if (!pkgSetting.disableComponentLPw(className, userId)) {
21354                        return;
21355                    }
21356                    break;
21357                case COMPONENT_ENABLED_STATE_DEFAULT:
21358                    if (!pkgSetting.restoreComponentLPw(className, userId)) {
21359                        return;
21360                    }
21361                    break;
21362                default:
21363                    Slog.e(TAG, "Invalid new component state: " + newState);
21364                    return;
21365                }
21366            }
21367            scheduleWritePackageRestrictionsLocked(userId);
21368            updateSequenceNumberLP(pkgSetting, new int[] { userId });
21369            final long callingId = Binder.clearCallingIdentity();
21370            try {
21371                updateInstantAppInstallerLocked(packageName);
21372            } finally {
21373                Binder.restoreCallingIdentity(callingId);
21374            }
21375            components = mPendingBroadcasts.get(userId, packageName);
21376            final boolean newPackage = components == null;
21377            if (newPackage) {
21378                components = new ArrayList<String>();
21379            }
21380            if (!components.contains(componentName)) {
21381                components.add(componentName);
21382            }
21383            if ((flags&PackageManager.DONT_KILL_APP) == 0) {
21384                sendNow = true;
21385                // Purge entry from pending broadcast list if another one exists already
21386                // since we are sending one right away.
21387                mPendingBroadcasts.remove(userId, packageName);
21388            } else {
21389                if (newPackage) {
21390                    mPendingBroadcasts.put(userId, packageName, components);
21391                }
21392                if (!mHandler.hasMessages(SEND_PENDING_BROADCAST)) {
21393                    // Schedule a message
21394                    mHandler.sendEmptyMessageDelayed(SEND_PENDING_BROADCAST, BROADCAST_DELAY);
21395                }
21396            }
21397        }
21398
21399        long callingId = Binder.clearCallingIdentity();
21400        try {
21401            if (sendNow) {
21402                packageUid = UserHandle.getUid(userId, pkgSetting.appId);
21403                sendPackageChangedBroadcast(packageName,
21404                        (flags&PackageManager.DONT_KILL_APP) != 0, components, packageUid);
21405            }
21406        } finally {
21407            Binder.restoreCallingIdentity(callingId);
21408        }
21409    }
21410
21411    @Override
21412    public void flushPackageRestrictionsAsUser(int userId) {
21413        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
21414            return;
21415        }
21416        if (!sUserManager.exists(userId)) {
21417            return;
21418        }
21419        enforceCrossUserPermission(Binder.getCallingUid(), userId, false /* requireFullPermission*/,
21420                false /* checkShell */, "flushPackageRestrictions");
21421        synchronized (mPackages) {
21422            mSettings.writePackageRestrictionsLPr(userId);
21423            mDirtyUsers.remove(userId);
21424            if (mDirtyUsers.isEmpty()) {
21425                mHandler.removeMessages(WRITE_PACKAGE_RESTRICTIONS);
21426            }
21427        }
21428    }
21429
21430    private void sendPackageChangedBroadcast(String packageName,
21431            boolean killFlag, ArrayList<String> componentNames, int packageUid) {
21432        if (DEBUG_INSTALL)
21433            Log.v(TAG, "Sending package changed: package=" + packageName + " components="
21434                    + componentNames);
21435        Bundle extras = new Bundle(4);
21436        extras.putString(Intent.EXTRA_CHANGED_COMPONENT_NAME, componentNames.get(0));
21437        String nameList[] = new String[componentNames.size()];
21438        componentNames.toArray(nameList);
21439        extras.putStringArray(Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST, nameList);
21440        extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, killFlag);
21441        extras.putInt(Intent.EXTRA_UID, packageUid);
21442        // If this is not reporting a change of the overall package, then only send it
21443        // to registered receivers.  We don't want to launch a swath of apps for every
21444        // little component state change.
21445        final int flags = !componentNames.contains(packageName)
21446                ? Intent.FLAG_RECEIVER_REGISTERED_ONLY : 0;
21447        sendPackageBroadcast(Intent.ACTION_PACKAGE_CHANGED,  packageName, extras, flags, null, null,
21448                new int[] {UserHandle.getUserId(packageUid)});
21449    }
21450
21451    @Override
21452    public void setPackageStoppedState(String packageName, boolean stopped, int userId) {
21453        if (!sUserManager.exists(userId)) return;
21454        final int callingUid = Binder.getCallingUid();
21455        if (getInstantAppPackageName(callingUid) != null) {
21456            return;
21457        }
21458        final int permission = mContext.checkCallingOrSelfPermission(
21459                android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
21460        final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
21461        enforceCrossUserPermission(callingUid, userId,
21462                true /* requireFullPermission */, true /* checkShell */, "stop package");
21463        // writer
21464        synchronized (mPackages) {
21465            final PackageSetting ps = mSettings.mPackages.get(packageName);
21466            if (!filterAppAccessLPr(ps, callingUid, userId)
21467                    && mSettings.setPackageStoppedStateLPw(this, packageName, stopped,
21468                            allowedByPermission, callingUid, userId)) {
21469                scheduleWritePackageRestrictionsLocked(userId);
21470            }
21471        }
21472    }
21473
21474    @Override
21475    public String getInstallerPackageName(String packageName) {
21476        final int callingUid = Binder.getCallingUid();
21477        if (getInstantAppPackageName(callingUid) != null) {
21478            return null;
21479        }
21480        // reader
21481        synchronized (mPackages) {
21482            final PackageSetting ps = mSettings.mPackages.get(packageName);
21483            if (filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
21484                return null;
21485            }
21486            return mSettings.getInstallerPackageNameLPr(packageName);
21487        }
21488    }
21489
21490    public boolean isOrphaned(String packageName) {
21491        // reader
21492        synchronized (mPackages) {
21493            return mSettings.isOrphaned(packageName);
21494        }
21495    }
21496
21497    @Override
21498    public int getApplicationEnabledSetting(String packageName, int userId) {
21499        if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
21500        int callingUid = Binder.getCallingUid();
21501        enforceCrossUserPermission(callingUid, userId,
21502                false /* requireFullPermission */, false /* checkShell */, "get enabled");
21503        // reader
21504        synchronized (mPackages) {
21505            if (filterAppAccessLPr(mSettings.getPackageLPr(packageName), callingUid, userId)) {
21506                return COMPONENT_ENABLED_STATE_DISABLED;
21507            }
21508            return mSettings.getApplicationEnabledSettingLPr(packageName, userId);
21509        }
21510    }
21511
21512    @Override
21513    public int getComponentEnabledSetting(ComponentName component, int userId) {
21514        if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
21515        int callingUid = Binder.getCallingUid();
21516        enforceCrossUserPermission(callingUid, userId,
21517                false /*requireFullPermission*/, false /*checkShell*/, "getComponentEnabled");
21518        synchronized (mPackages) {
21519            if (filterAppAccessLPr(mSettings.getPackageLPr(component.getPackageName()), callingUid,
21520                    component, TYPE_UNKNOWN, userId)) {
21521                return COMPONENT_ENABLED_STATE_DISABLED;
21522            }
21523            return mSettings.getComponentEnabledSettingLPr(component, userId);
21524        }
21525    }
21526
21527    @Override
21528    public void enterSafeMode() {
21529        enforceSystemOrRoot("Only the system can request entering safe mode");
21530
21531        if (!mSystemReady) {
21532            mSafeMode = true;
21533        }
21534    }
21535
21536    @Override
21537    public void systemReady() {
21538        enforceSystemOrRoot("Only the system can claim the system is ready");
21539
21540        mSystemReady = true;
21541        final ContentResolver resolver = mContext.getContentResolver();
21542        ContentObserver co = new ContentObserver(mHandler) {
21543            @Override
21544            public void onChange(boolean selfChange) {
21545                mEphemeralAppsDisabled =
21546                        (Global.getInt(resolver, Global.ENABLE_EPHEMERAL_FEATURE, 1) == 0) ||
21547                                (Secure.getInt(resolver, Secure.INSTANT_APPS_ENABLED, 1) == 0);
21548            }
21549        };
21550        mContext.getContentResolver().registerContentObserver(android.provider.Settings.Global
21551                        .getUriFor(Global.ENABLE_EPHEMERAL_FEATURE),
21552                false, co, UserHandle.USER_SYSTEM);
21553        mContext.getContentResolver().registerContentObserver(android.provider.Settings.Global
21554                        .getUriFor(Secure.INSTANT_APPS_ENABLED), false, co, UserHandle.USER_SYSTEM);
21555        co.onChange(true);
21556
21557        // Disable any carrier apps. We do this very early in boot to prevent the apps from being
21558        // disabled after already being started.
21559        CarrierAppUtils.disableCarrierAppsUntilPrivileged(mContext.getOpPackageName(), this,
21560                mContext.getContentResolver(), UserHandle.USER_SYSTEM);
21561
21562        // Read the compatibilty setting when the system is ready.
21563        boolean compatibilityModeEnabled = android.provider.Settings.Global.getInt(
21564                mContext.getContentResolver(),
21565                android.provider.Settings.Global.COMPATIBILITY_MODE, 1) == 1;
21566        PackageParser.setCompatibilityModeEnabled(compatibilityModeEnabled);
21567        if (DEBUG_SETTINGS) {
21568            Log.d(TAG, "compatibility mode:" + compatibilityModeEnabled);
21569        }
21570
21571        int[] grantPermissionsUserIds = EMPTY_INT_ARRAY;
21572
21573        synchronized (mPackages) {
21574            // Verify that all of the preferred activity components actually
21575            // exist.  It is possible for applications to be updated and at
21576            // that point remove a previously declared activity component that
21577            // had been set as a preferred activity.  We try to clean this up
21578            // the next time we encounter that preferred activity, but it is
21579            // possible for the user flow to never be able to return to that
21580            // situation so here we do a sanity check to make sure we haven't
21581            // left any junk around.
21582            ArrayList<PreferredActivity> removed = new ArrayList<PreferredActivity>();
21583            for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
21584                PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
21585                removed.clear();
21586                for (PreferredActivity pa : pir.filterSet()) {
21587                    if (mActivities.mActivities.get(pa.mPref.mComponent) == null) {
21588                        removed.add(pa);
21589                    }
21590                }
21591                if (removed.size() > 0) {
21592                    for (int r=0; r<removed.size(); r++) {
21593                        PreferredActivity pa = removed.get(r);
21594                        Slog.w(TAG, "Removing dangling preferred activity: "
21595                                + pa.mPref.mComponent);
21596                        pir.removeFilter(pa);
21597                    }
21598                    mSettings.writePackageRestrictionsLPr(
21599                            mSettings.mPreferredActivities.keyAt(i));
21600                }
21601            }
21602
21603            for (int userId : UserManagerService.getInstance().getUserIds()) {
21604                if (!mSettings.areDefaultRuntimePermissionsGrantedLPr(userId)) {
21605                    grantPermissionsUserIds = ArrayUtils.appendInt(
21606                            grantPermissionsUserIds, userId);
21607                }
21608            }
21609        }
21610        sUserManager.systemReady();
21611
21612        // If we upgraded grant all default permissions before kicking off.
21613        for (int userId : grantPermissionsUserIds) {
21614            mDefaultPermissionPolicy.grantDefaultPermissions(userId);
21615        }
21616
21617        // If we did not grant default permissions, we preload from this the
21618        // default permission exceptions lazily to ensure we don't hit the
21619        // disk on a new user creation.
21620        if (grantPermissionsUserIds == EMPTY_INT_ARRAY) {
21621            mDefaultPermissionPolicy.scheduleReadDefaultPermissionExceptions();
21622        }
21623
21624        // Kick off any messages waiting for system ready
21625        if (mPostSystemReadyMessages != null) {
21626            for (Message msg : mPostSystemReadyMessages) {
21627                msg.sendToTarget();
21628            }
21629            mPostSystemReadyMessages = null;
21630        }
21631
21632        // Watch for external volumes that come and go over time
21633        final StorageManager storage = mContext.getSystemService(StorageManager.class);
21634        storage.registerListener(mStorageListener);
21635
21636        mInstallerService.systemReady();
21637        mPackageDexOptimizer.systemReady();
21638
21639        StorageManagerInternal StorageManagerInternal = LocalServices.getService(
21640                StorageManagerInternal.class);
21641        StorageManagerInternal.addExternalStoragePolicy(
21642                new StorageManagerInternal.ExternalStorageMountPolicy() {
21643            @Override
21644            public int getMountMode(int uid, String packageName) {
21645                if (Process.isIsolated(uid)) {
21646                    return Zygote.MOUNT_EXTERNAL_NONE;
21647                }
21648                if (checkUidPermission(WRITE_MEDIA_STORAGE, uid) == PERMISSION_GRANTED) {
21649                    return Zygote.MOUNT_EXTERNAL_DEFAULT;
21650                }
21651                if (checkUidPermission(READ_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) {
21652                    return Zygote.MOUNT_EXTERNAL_DEFAULT;
21653                }
21654                if (checkUidPermission(WRITE_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) {
21655                    return Zygote.MOUNT_EXTERNAL_READ;
21656                }
21657                return Zygote.MOUNT_EXTERNAL_WRITE;
21658            }
21659
21660            @Override
21661            public boolean hasExternalStorage(int uid, String packageName) {
21662                return true;
21663            }
21664        });
21665
21666        // Now that we're mostly running, clean up stale users and apps
21667        sUserManager.reconcileUsers(StorageManager.UUID_PRIVATE_INTERNAL);
21668        reconcileApps(StorageManager.UUID_PRIVATE_INTERNAL);
21669
21670        if (mPrivappPermissionsViolations != null) {
21671            Slog.wtf(TAG,"Signature|privileged permissions not in "
21672                    + "privapp-permissions whitelist: " + mPrivappPermissionsViolations);
21673            mPrivappPermissionsViolations = null;
21674        }
21675    }
21676
21677    public void waitForAppDataPrepared() {
21678        if (mPrepareAppDataFuture == null) {
21679            return;
21680        }
21681        ConcurrentUtils.waitForFutureNoInterrupt(mPrepareAppDataFuture, "wait for prepareAppData");
21682        mPrepareAppDataFuture = null;
21683    }
21684
21685    @Override
21686    public boolean isSafeMode() {
21687        // allow instant applications
21688        return mSafeMode;
21689    }
21690
21691    @Override
21692    public boolean hasSystemUidErrors() {
21693        // allow instant applications
21694        return mHasSystemUidErrors;
21695    }
21696
21697    static String arrayToString(int[] array) {
21698        StringBuffer buf = new StringBuffer(128);
21699        buf.append('[');
21700        if (array != null) {
21701            for (int i=0; i<array.length; i++) {
21702                if (i > 0) buf.append(", ");
21703                buf.append(array[i]);
21704            }
21705        }
21706        buf.append(']');
21707        return buf.toString();
21708    }
21709
21710    static class DumpState {
21711        public static final int DUMP_LIBS = 1 << 0;
21712        public static final int DUMP_FEATURES = 1 << 1;
21713        public static final int DUMP_ACTIVITY_RESOLVERS = 1 << 2;
21714        public static final int DUMP_SERVICE_RESOLVERS = 1 << 3;
21715        public static final int DUMP_RECEIVER_RESOLVERS = 1 << 4;
21716        public static final int DUMP_CONTENT_RESOLVERS = 1 << 5;
21717        public static final int DUMP_PERMISSIONS = 1 << 6;
21718        public static final int DUMP_PACKAGES = 1 << 7;
21719        public static final int DUMP_SHARED_USERS = 1 << 8;
21720        public static final int DUMP_MESSAGES = 1 << 9;
21721        public static final int DUMP_PROVIDERS = 1 << 10;
21722        public static final int DUMP_VERIFIERS = 1 << 11;
21723        public static final int DUMP_PREFERRED = 1 << 12;
21724        public static final int DUMP_PREFERRED_XML = 1 << 13;
21725        public static final int DUMP_KEYSETS = 1 << 14;
21726        public static final int DUMP_VERSION = 1 << 15;
21727        public static final int DUMP_INSTALLS = 1 << 16;
21728        public static final int DUMP_INTENT_FILTER_VERIFIERS = 1 << 17;
21729        public static final int DUMP_DOMAIN_PREFERRED = 1 << 18;
21730        public static final int DUMP_FROZEN = 1 << 19;
21731        public static final int DUMP_DEXOPT = 1 << 20;
21732        public static final int DUMP_COMPILER_STATS = 1 << 21;
21733        public static final int DUMP_CHANGES = 1 << 22;
21734
21735        public static final int OPTION_SHOW_FILTERS = 1 << 0;
21736
21737        private int mTypes;
21738
21739        private int mOptions;
21740
21741        private boolean mTitlePrinted;
21742
21743        private SharedUserSetting mSharedUser;
21744
21745        public boolean isDumping(int type) {
21746            if (mTypes == 0 && type != DUMP_PREFERRED_XML) {
21747                return true;
21748            }
21749
21750            return (mTypes & type) != 0;
21751        }
21752
21753        public void setDump(int type) {
21754            mTypes |= type;
21755        }
21756
21757        public boolean isOptionEnabled(int option) {
21758            return (mOptions & option) != 0;
21759        }
21760
21761        public void setOptionEnabled(int option) {
21762            mOptions |= option;
21763        }
21764
21765        public boolean onTitlePrinted() {
21766            final boolean printed = mTitlePrinted;
21767            mTitlePrinted = true;
21768            return printed;
21769        }
21770
21771        public boolean getTitlePrinted() {
21772            return mTitlePrinted;
21773        }
21774
21775        public void setTitlePrinted(boolean enabled) {
21776            mTitlePrinted = enabled;
21777        }
21778
21779        public SharedUserSetting getSharedUser() {
21780            return mSharedUser;
21781        }
21782
21783        public void setSharedUser(SharedUserSetting user) {
21784            mSharedUser = user;
21785        }
21786    }
21787
21788    @Override
21789    public void onShellCommand(FileDescriptor in, FileDescriptor out,
21790            FileDescriptor err, String[] args, ShellCallback callback,
21791            ResultReceiver resultReceiver) {
21792        (new PackageManagerShellCommand(this)).exec(
21793                this, in, out, err, args, callback, resultReceiver);
21794    }
21795
21796    @Override
21797    protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
21798        if (!DumpUtils.checkDumpAndUsageStatsPermission(mContext, TAG, pw)) return;
21799
21800        DumpState dumpState = new DumpState();
21801        boolean fullPreferred = false;
21802        boolean checkin = false;
21803
21804        String packageName = null;
21805        ArraySet<String> permissionNames = null;
21806
21807        int opti = 0;
21808        while (opti < args.length) {
21809            String opt = args[opti];
21810            if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') {
21811                break;
21812            }
21813            opti++;
21814
21815            if ("-a".equals(opt)) {
21816                // Right now we only know how to print all.
21817            } else if ("-h".equals(opt)) {
21818                pw.println("Package manager dump options:");
21819                pw.println("  [-h] [-f] [--checkin] [cmd] ...");
21820                pw.println("    --checkin: dump for a checkin");
21821                pw.println("    -f: print details of intent filters");
21822                pw.println("    -h: print this help");
21823                pw.println("  cmd may be one of:");
21824                pw.println("    l[ibraries]: list known shared libraries");
21825                pw.println("    f[eatures]: list device features");
21826                pw.println("    k[eysets]: print known keysets");
21827                pw.println("    r[esolvers] [activity|service|receiver|content]: dump intent resolvers");
21828                pw.println("    perm[issions]: dump permissions");
21829                pw.println("    permission [name ...]: dump declaration and use of given permission");
21830                pw.println("    pref[erred]: print preferred package settings");
21831                pw.println("    preferred-xml [--full]: print preferred package settings as xml");
21832                pw.println("    prov[iders]: dump content providers");
21833                pw.println("    p[ackages]: dump installed packages");
21834                pw.println("    s[hared-users]: dump shared user IDs");
21835                pw.println("    m[essages]: print collected runtime messages");
21836                pw.println("    v[erifiers]: print package verifier info");
21837                pw.println("    d[omain-preferred-apps]: print domains preferred apps");
21838                pw.println("    i[ntent-filter-verifiers]|ifv: print intent filter verifier info");
21839                pw.println("    version: print database version info");
21840                pw.println("    write: write current settings now");
21841                pw.println("    installs: details about install sessions");
21842                pw.println("    check-permission <permission> <package> [<user>]: does pkg hold perm?");
21843                pw.println("    dexopt: dump dexopt state");
21844                pw.println("    compiler-stats: dump compiler statistics");
21845                pw.println("    enabled-overlays: dump list of enabled overlay packages");
21846                pw.println("    <package.name>: info about given package");
21847                return;
21848            } else if ("--checkin".equals(opt)) {
21849                checkin = true;
21850            } else if ("-f".equals(opt)) {
21851                dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS);
21852            } else if ("--proto".equals(opt)) {
21853                dumpProto(fd);
21854                return;
21855            } else {
21856                pw.println("Unknown argument: " + opt + "; use -h for help");
21857            }
21858        }
21859
21860        // Is the caller requesting to dump a particular piece of data?
21861        if (opti < args.length) {
21862            String cmd = args[opti];
21863            opti++;
21864            // Is this a package name?
21865            if ("android".equals(cmd) || cmd.contains(".")) {
21866                packageName = cmd;
21867                // When dumping a single package, we always dump all of its
21868                // filter information since the amount of data will be reasonable.
21869                dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS);
21870            } else if ("check-permission".equals(cmd)) {
21871                if (opti >= args.length) {
21872                    pw.println("Error: check-permission missing permission argument");
21873                    return;
21874                }
21875                String perm = args[opti];
21876                opti++;
21877                if (opti >= args.length) {
21878                    pw.println("Error: check-permission missing package argument");
21879                    return;
21880                }
21881
21882                String pkg = args[opti];
21883                opti++;
21884                int user = UserHandle.getUserId(Binder.getCallingUid());
21885                if (opti < args.length) {
21886                    try {
21887                        user = Integer.parseInt(args[opti]);
21888                    } catch (NumberFormatException e) {
21889                        pw.println("Error: check-permission user argument is not a number: "
21890                                + args[opti]);
21891                        return;
21892                    }
21893                }
21894
21895                // Normalize package name to handle renamed packages and static libs
21896                pkg = resolveInternalPackageNameLPr(pkg, PackageManager.VERSION_CODE_HIGHEST);
21897
21898                pw.println(checkPermission(perm, pkg, user));
21899                return;
21900            } else if ("l".equals(cmd) || "libraries".equals(cmd)) {
21901                dumpState.setDump(DumpState.DUMP_LIBS);
21902            } else if ("f".equals(cmd) || "features".equals(cmd)) {
21903                dumpState.setDump(DumpState.DUMP_FEATURES);
21904            } else if ("r".equals(cmd) || "resolvers".equals(cmd)) {
21905                if (opti >= args.length) {
21906                    dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS
21907                            | DumpState.DUMP_SERVICE_RESOLVERS
21908                            | DumpState.DUMP_RECEIVER_RESOLVERS
21909                            | DumpState.DUMP_CONTENT_RESOLVERS);
21910                } else {
21911                    while (opti < args.length) {
21912                        String name = args[opti];
21913                        if ("a".equals(name) || "activity".equals(name)) {
21914                            dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS);
21915                        } else if ("s".equals(name) || "service".equals(name)) {
21916                            dumpState.setDump(DumpState.DUMP_SERVICE_RESOLVERS);
21917                        } else if ("r".equals(name) || "receiver".equals(name)) {
21918                            dumpState.setDump(DumpState.DUMP_RECEIVER_RESOLVERS);
21919                        } else if ("c".equals(name) || "content".equals(name)) {
21920                            dumpState.setDump(DumpState.DUMP_CONTENT_RESOLVERS);
21921                        } else {
21922                            pw.println("Error: unknown resolver table type: " + name);
21923                            return;
21924                        }
21925                        opti++;
21926                    }
21927                }
21928            } else if ("perm".equals(cmd) || "permissions".equals(cmd)) {
21929                dumpState.setDump(DumpState.DUMP_PERMISSIONS);
21930            } else if ("permission".equals(cmd)) {
21931                if (opti >= args.length) {
21932                    pw.println("Error: permission requires permission name");
21933                    return;
21934                }
21935                permissionNames = new ArraySet<>();
21936                while (opti < args.length) {
21937                    permissionNames.add(args[opti]);
21938                    opti++;
21939                }
21940                dumpState.setDump(DumpState.DUMP_PERMISSIONS
21941                        | DumpState.DUMP_PACKAGES | DumpState.DUMP_SHARED_USERS);
21942            } else if ("pref".equals(cmd) || "preferred".equals(cmd)) {
21943                dumpState.setDump(DumpState.DUMP_PREFERRED);
21944            } else if ("preferred-xml".equals(cmd)) {
21945                dumpState.setDump(DumpState.DUMP_PREFERRED_XML);
21946                if (opti < args.length && "--full".equals(args[opti])) {
21947                    fullPreferred = true;
21948                    opti++;
21949                }
21950            } else if ("d".equals(cmd) || "domain-preferred-apps".equals(cmd)) {
21951                dumpState.setDump(DumpState.DUMP_DOMAIN_PREFERRED);
21952            } else if ("p".equals(cmd) || "packages".equals(cmd)) {
21953                dumpState.setDump(DumpState.DUMP_PACKAGES);
21954            } else if ("s".equals(cmd) || "shared-users".equals(cmd)) {
21955                dumpState.setDump(DumpState.DUMP_SHARED_USERS);
21956            } else if ("prov".equals(cmd) || "providers".equals(cmd)) {
21957                dumpState.setDump(DumpState.DUMP_PROVIDERS);
21958            } else if ("m".equals(cmd) || "messages".equals(cmd)) {
21959                dumpState.setDump(DumpState.DUMP_MESSAGES);
21960            } else if ("v".equals(cmd) || "verifiers".equals(cmd)) {
21961                dumpState.setDump(DumpState.DUMP_VERIFIERS);
21962            } else if ("i".equals(cmd) || "ifv".equals(cmd)
21963                    || "intent-filter-verifiers".equals(cmd)) {
21964                dumpState.setDump(DumpState.DUMP_INTENT_FILTER_VERIFIERS);
21965            } else if ("version".equals(cmd)) {
21966                dumpState.setDump(DumpState.DUMP_VERSION);
21967            } else if ("k".equals(cmd) || "keysets".equals(cmd)) {
21968                dumpState.setDump(DumpState.DUMP_KEYSETS);
21969            } else if ("installs".equals(cmd)) {
21970                dumpState.setDump(DumpState.DUMP_INSTALLS);
21971            } else if ("frozen".equals(cmd)) {
21972                dumpState.setDump(DumpState.DUMP_FROZEN);
21973            } else if ("dexopt".equals(cmd)) {
21974                dumpState.setDump(DumpState.DUMP_DEXOPT);
21975            } else if ("compiler-stats".equals(cmd)) {
21976                dumpState.setDump(DumpState.DUMP_COMPILER_STATS);
21977            } else if ("changes".equals(cmd)) {
21978                dumpState.setDump(DumpState.DUMP_CHANGES);
21979            } else if ("write".equals(cmd)) {
21980                synchronized (mPackages) {
21981                    mSettings.writeLPr();
21982                    pw.println("Settings written.");
21983                    return;
21984                }
21985            }
21986        }
21987
21988        if (checkin) {
21989            pw.println("vers,1");
21990        }
21991
21992        // reader
21993        synchronized (mPackages) {
21994            if (dumpState.isDumping(DumpState.DUMP_VERSION) && packageName == null) {
21995                if (!checkin) {
21996                    if (dumpState.onTitlePrinted())
21997                        pw.println();
21998                    pw.println("Database versions:");
21999                    mSettings.dumpVersionLPr(new IndentingPrintWriter(pw, "  "));
22000                }
22001            }
22002
22003            if (dumpState.isDumping(DumpState.DUMP_VERIFIERS) && packageName == null) {
22004                if (!checkin) {
22005                    if (dumpState.onTitlePrinted())
22006                        pw.println();
22007                    pw.println("Verifiers:");
22008                    pw.print("  Required: ");
22009                    pw.print(mRequiredVerifierPackage);
22010                    pw.print(" (uid=");
22011                    pw.print(getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING,
22012                            UserHandle.USER_SYSTEM));
22013                    pw.println(")");
22014                } else if (mRequiredVerifierPackage != null) {
22015                    pw.print("vrfy,"); pw.print(mRequiredVerifierPackage);
22016                    pw.print(",");
22017                    pw.println(getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING,
22018                            UserHandle.USER_SYSTEM));
22019                }
22020            }
22021
22022            if (dumpState.isDumping(DumpState.DUMP_INTENT_FILTER_VERIFIERS) &&
22023                    packageName == null) {
22024                if (mIntentFilterVerifierComponent != null) {
22025                    String verifierPackageName = mIntentFilterVerifierComponent.getPackageName();
22026                    if (!checkin) {
22027                        if (dumpState.onTitlePrinted())
22028                            pw.println();
22029                        pw.println("Intent Filter Verifier:");
22030                        pw.print("  Using: ");
22031                        pw.print(verifierPackageName);
22032                        pw.print(" (uid=");
22033                        pw.print(getPackageUid(verifierPackageName, MATCH_DEBUG_TRIAGED_MISSING,
22034                                UserHandle.USER_SYSTEM));
22035                        pw.println(")");
22036                    } else if (verifierPackageName != null) {
22037                        pw.print("ifv,"); pw.print(verifierPackageName);
22038                        pw.print(",");
22039                        pw.println(getPackageUid(verifierPackageName, MATCH_DEBUG_TRIAGED_MISSING,
22040                                UserHandle.USER_SYSTEM));
22041                    }
22042                } else {
22043                    pw.println();
22044                    pw.println("No Intent Filter Verifier available!");
22045                }
22046            }
22047
22048            if (dumpState.isDumping(DumpState.DUMP_LIBS) && packageName == null) {
22049                boolean printedHeader = false;
22050                final Iterator<String> it = mSharedLibraries.keySet().iterator();
22051                while (it.hasNext()) {
22052                    String libName = it.next();
22053                    SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(libName);
22054                    if (versionedLib == null) {
22055                        continue;
22056                    }
22057                    final int versionCount = versionedLib.size();
22058                    for (int i = 0; i < versionCount; i++) {
22059                        SharedLibraryEntry libEntry = versionedLib.valueAt(i);
22060                        if (!checkin) {
22061                            if (!printedHeader) {
22062                                if (dumpState.onTitlePrinted())
22063                                    pw.println();
22064                                pw.println("Libraries:");
22065                                printedHeader = true;
22066                            }
22067                            pw.print("  ");
22068                        } else {
22069                            pw.print("lib,");
22070                        }
22071                        pw.print(libEntry.info.getName());
22072                        if (libEntry.info.isStatic()) {
22073                            pw.print(" version=" + libEntry.info.getVersion());
22074                        }
22075                        if (!checkin) {
22076                            pw.print(" -> ");
22077                        }
22078                        if (libEntry.path != null) {
22079                            pw.print(" (jar) ");
22080                            pw.print(libEntry.path);
22081                        } else {
22082                            pw.print(" (apk) ");
22083                            pw.print(libEntry.apk);
22084                        }
22085                        pw.println();
22086                    }
22087                }
22088            }
22089
22090            if (dumpState.isDumping(DumpState.DUMP_FEATURES) && packageName == null) {
22091                if (dumpState.onTitlePrinted())
22092                    pw.println();
22093                if (!checkin) {
22094                    pw.println("Features:");
22095                }
22096
22097                synchronized (mAvailableFeatures) {
22098                    for (FeatureInfo feat : mAvailableFeatures.values()) {
22099                        if (checkin) {
22100                            pw.print("feat,");
22101                            pw.print(feat.name);
22102                            pw.print(",");
22103                            pw.println(feat.version);
22104                        } else {
22105                            pw.print("  ");
22106                            pw.print(feat.name);
22107                            if (feat.version > 0) {
22108                                pw.print(" version=");
22109                                pw.print(feat.version);
22110                            }
22111                            pw.println();
22112                        }
22113                    }
22114                }
22115            }
22116
22117            if (!checkin && dumpState.isDumping(DumpState.DUMP_ACTIVITY_RESOLVERS)) {
22118                if (mActivities.dump(pw, dumpState.getTitlePrinted() ? "\nActivity Resolver Table:"
22119                        : "Activity Resolver Table:", "  ", packageName,
22120                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
22121                    dumpState.setTitlePrinted(true);
22122                }
22123            }
22124            if (!checkin && dumpState.isDumping(DumpState.DUMP_RECEIVER_RESOLVERS)) {
22125                if (mReceivers.dump(pw, dumpState.getTitlePrinted() ? "\nReceiver Resolver Table:"
22126                        : "Receiver Resolver Table:", "  ", packageName,
22127                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
22128                    dumpState.setTitlePrinted(true);
22129                }
22130            }
22131            if (!checkin && dumpState.isDumping(DumpState.DUMP_SERVICE_RESOLVERS)) {
22132                if (mServices.dump(pw, dumpState.getTitlePrinted() ? "\nService Resolver Table:"
22133                        : "Service Resolver Table:", "  ", packageName,
22134                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
22135                    dumpState.setTitlePrinted(true);
22136                }
22137            }
22138            if (!checkin && dumpState.isDumping(DumpState.DUMP_CONTENT_RESOLVERS)) {
22139                if (mProviders.dump(pw, dumpState.getTitlePrinted() ? "\nProvider Resolver Table:"
22140                        : "Provider Resolver Table:", "  ", packageName,
22141                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
22142                    dumpState.setTitlePrinted(true);
22143                }
22144            }
22145
22146            if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED)) {
22147                for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
22148                    PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
22149                    int user = mSettings.mPreferredActivities.keyAt(i);
22150                    if (pir.dump(pw,
22151                            dumpState.getTitlePrinted()
22152                                ? "\nPreferred Activities User " + user + ":"
22153                                : "Preferred Activities User " + user + ":", "  ",
22154                            packageName, true, false)) {
22155                        dumpState.setTitlePrinted(true);
22156                    }
22157                }
22158            }
22159
22160            if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED_XML)) {
22161                pw.flush();
22162                FileOutputStream fout = new FileOutputStream(fd);
22163                BufferedOutputStream str = new BufferedOutputStream(fout);
22164                XmlSerializer serializer = new FastXmlSerializer();
22165                try {
22166                    serializer.setOutput(str, StandardCharsets.UTF_8.name());
22167                    serializer.startDocument(null, true);
22168                    serializer.setFeature(
22169                            "http://xmlpull.org/v1/doc/features.html#indent-output", true);
22170                    mSettings.writePreferredActivitiesLPr(serializer, 0, fullPreferred);
22171                    serializer.endDocument();
22172                    serializer.flush();
22173                } catch (IllegalArgumentException e) {
22174                    pw.println("Failed writing: " + e);
22175                } catch (IllegalStateException e) {
22176                    pw.println("Failed writing: " + e);
22177                } catch (IOException e) {
22178                    pw.println("Failed writing: " + e);
22179                }
22180            }
22181
22182            if (!checkin
22183                    && dumpState.isDumping(DumpState.DUMP_DOMAIN_PREFERRED)
22184                    && packageName == null) {
22185                pw.println();
22186                int count = mSettings.mPackages.size();
22187                if (count == 0) {
22188                    pw.println("No applications!");
22189                    pw.println();
22190                } else {
22191                    final String prefix = "  ";
22192                    Collection<PackageSetting> allPackageSettings = mSettings.mPackages.values();
22193                    if (allPackageSettings.size() == 0) {
22194                        pw.println("No domain preferred apps!");
22195                        pw.println();
22196                    } else {
22197                        pw.println("App verification status:");
22198                        pw.println();
22199                        count = 0;
22200                        for (PackageSetting ps : allPackageSettings) {
22201                            IntentFilterVerificationInfo ivi = ps.getIntentFilterVerificationInfo();
22202                            if (ivi == null || ivi.getPackageName() == null) continue;
22203                            pw.println(prefix + "Package: " + ivi.getPackageName());
22204                            pw.println(prefix + "Domains: " + ivi.getDomainsString());
22205                            pw.println(prefix + "Status:  " + ivi.getStatusString());
22206                            pw.println();
22207                            count++;
22208                        }
22209                        if (count == 0) {
22210                            pw.println(prefix + "No app verification established.");
22211                            pw.println();
22212                        }
22213                        for (int userId : sUserManager.getUserIds()) {
22214                            pw.println("App linkages for user " + userId + ":");
22215                            pw.println();
22216                            count = 0;
22217                            for (PackageSetting ps : allPackageSettings) {
22218                                final long status = ps.getDomainVerificationStatusForUser(userId);
22219                                if (status >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED
22220                                        && !DEBUG_DOMAIN_VERIFICATION) {
22221                                    continue;
22222                                }
22223                                pw.println(prefix + "Package: " + ps.name);
22224                                pw.println(prefix + "Domains: " + dumpDomainString(ps.name));
22225                                String statusStr = IntentFilterVerificationInfo.
22226                                        getStatusStringFromValue(status);
22227                                pw.println(prefix + "Status:  " + statusStr);
22228                                pw.println();
22229                                count++;
22230                            }
22231                            if (count == 0) {
22232                                pw.println(prefix + "No configured app linkages.");
22233                                pw.println();
22234                            }
22235                        }
22236                    }
22237                }
22238            }
22239
22240            if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS)) {
22241                mSettings.dumpPermissionsLPr(pw, packageName, permissionNames, dumpState);
22242                if (packageName == null && permissionNames == null) {
22243                    for (int iperm=0; iperm<mAppOpPermissionPackages.size(); iperm++) {
22244                        if (iperm == 0) {
22245                            if (dumpState.onTitlePrinted())
22246                                pw.println();
22247                            pw.println("AppOp Permissions:");
22248                        }
22249                        pw.print("  AppOp Permission ");
22250                        pw.print(mAppOpPermissionPackages.keyAt(iperm));
22251                        pw.println(":");
22252                        ArraySet<String> pkgs = mAppOpPermissionPackages.valueAt(iperm);
22253                        for (int ipkg=0; ipkg<pkgs.size(); ipkg++) {
22254                            pw.print("    "); pw.println(pkgs.valueAt(ipkg));
22255                        }
22256                    }
22257                }
22258            }
22259
22260            if (!checkin && dumpState.isDumping(DumpState.DUMP_PROVIDERS)) {
22261                boolean printedSomething = false;
22262                for (PackageParser.Provider p : mProviders.mProviders.values()) {
22263                    if (packageName != null && !packageName.equals(p.info.packageName)) {
22264                        continue;
22265                    }
22266                    if (!printedSomething) {
22267                        if (dumpState.onTitlePrinted())
22268                            pw.println();
22269                        pw.println("Registered ContentProviders:");
22270                        printedSomething = true;
22271                    }
22272                    pw.print("  "); p.printComponentShortName(pw); pw.println(":");
22273                    pw.print("    "); pw.println(p.toString());
22274                }
22275                printedSomething = false;
22276                for (Map.Entry<String, PackageParser.Provider> entry :
22277                        mProvidersByAuthority.entrySet()) {
22278                    PackageParser.Provider p = entry.getValue();
22279                    if (packageName != null && !packageName.equals(p.info.packageName)) {
22280                        continue;
22281                    }
22282                    if (!printedSomething) {
22283                        if (dumpState.onTitlePrinted())
22284                            pw.println();
22285                        pw.println("ContentProvider Authorities:");
22286                        printedSomething = true;
22287                    }
22288                    pw.print("  ["); pw.print(entry.getKey()); pw.println("]:");
22289                    pw.print("    "); pw.println(p.toString());
22290                    if (p.info != null && p.info.applicationInfo != null) {
22291                        final String appInfo = p.info.applicationInfo.toString();
22292                        pw.print("      applicationInfo="); pw.println(appInfo);
22293                    }
22294                }
22295            }
22296
22297            if (!checkin && dumpState.isDumping(DumpState.DUMP_KEYSETS)) {
22298                mSettings.mKeySetManagerService.dumpLPr(pw, packageName, dumpState);
22299            }
22300
22301            if (dumpState.isDumping(DumpState.DUMP_PACKAGES)) {
22302                mSettings.dumpPackagesLPr(pw, packageName, permissionNames, dumpState, checkin);
22303            }
22304
22305            if (dumpState.isDumping(DumpState.DUMP_SHARED_USERS)) {
22306                mSettings.dumpSharedUsersLPr(pw, packageName, permissionNames, dumpState, checkin);
22307            }
22308
22309            if (dumpState.isDumping(DumpState.DUMP_CHANGES)) {
22310                if (dumpState.onTitlePrinted()) pw.println();
22311                pw.println("Package Changes:");
22312                pw.print("  Sequence number="); pw.println(mChangedPackagesSequenceNumber);
22313                final int K = mChangedPackages.size();
22314                for (int i = 0; i < K; i++) {
22315                    final SparseArray<String> changes = mChangedPackages.valueAt(i);
22316                    pw.print("  User "); pw.print(mChangedPackages.keyAt(i)); pw.println(":");
22317                    final int N = changes.size();
22318                    if (N == 0) {
22319                        pw.print("    "); pw.println("No packages changed");
22320                    } else {
22321                        for (int j = 0; j < N; j++) {
22322                            final String pkgName = changes.valueAt(j);
22323                            final int sequenceNumber = changes.keyAt(j);
22324                            pw.print("    ");
22325                            pw.print("seq=");
22326                            pw.print(sequenceNumber);
22327                            pw.print(", package=");
22328                            pw.println(pkgName);
22329                        }
22330                    }
22331                }
22332            }
22333
22334            if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS) && packageName == null) {
22335                mSettings.dumpRestoredPermissionGrantsLPr(pw, dumpState);
22336            }
22337
22338            if (!checkin && dumpState.isDumping(DumpState.DUMP_FROZEN) && packageName == null) {
22339                // XXX should handle packageName != null by dumping only install data that
22340                // the given package is involved with.
22341                if (dumpState.onTitlePrinted()) pw.println();
22342
22343                final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, "  ", 120);
22344                ipw.println();
22345                ipw.println("Frozen packages:");
22346                ipw.increaseIndent();
22347                if (mFrozenPackages.size() == 0) {
22348                    ipw.println("(none)");
22349                } else {
22350                    for (int i = 0; i < mFrozenPackages.size(); i++) {
22351                        ipw.println(mFrozenPackages.valueAt(i));
22352                    }
22353                }
22354                ipw.decreaseIndent();
22355            }
22356
22357            if (!checkin && dumpState.isDumping(DumpState.DUMP_DEXOPT)) {
22358                if (dumpState.onTitlePrinted()) pw.println();
22359                dumpDexoptStateLPr(pw, packageName);
22360            }
22361
22362            if (!checkin && dumpState.isDumping(DumpState.DUMP_COMPILER_STATS)) {
22363                if (dumpState.onTitlePrinted()) pw.println();
22364                dumpCompilerStatsLPr(pw, packageName);
22365            }
22366
22367            if (!checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES) && packageName == null) {
22368                if (dumpState.onTitlePrinted()) pw.println();
22369                mSettings.dumpReadMessagesLPr(pw, dumpState);
22370
22371                pw.println();
22372                pw.println("Package warning messages:");
22373                BufferedReader in = null;
22374                String line = null;
22375                try {
22376                    in = new BufferedReader(new FileReader(getSettingsProblemFile()));
22377                    while ((line = in.readLine()) != null) {
22378                        if (line.contains("ignored: updated version")) continue;
22379                        pw.println(line);
22380                    }
22381                } catch (IOException ignored) {
22382                } finally {
22383                    IoUtils.closeQuietly(in);
22384                }
22385            }
22386
22387            if (checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES)) {
22388                BufferedReader in = null;
22389                String line = null;
22390                try {
22391                    in = new BufferedReader(new FileReader(getSettingsProblemFile()));
22392                    while ((line = in.readLine()) != null) {
22393                        if (line.contains("ignored: updated version")) continue;
22394                        pw.print("msg,");
22395                        pw.println(line);
22396                    }
22397                } catch (IOException ignored) {
22398                } finally {
22399                    IoUtils.closeQuietly(in);
22400                }
22401            }
22402        }
22403
22404        // PackageInstaller should be called outside of mPackages lock
22405        if (!checkin && dumpState.isDumping(DumpState.DUMP_INSTALLS) && packageName == null) {
22406            // XXX should handle packageName != null by dumping only install data that
22407            // the given package is involved with.
22408            if (dumpState.onTitlePrinted()) pw.println();
22409            mInstallerService.dump(new IndentingPrintWriter(pw, "  ", 120));
22410        }
22411    }
22412
22413    private void dumpProto(FileDescriptor fd) {
22414        final ProtoOutputStream proto = new ProtoOutputStream(fd);
22415
22416        synchronized (mPackages) {
22417            final long requiredVerifierPackageToken =
22418                    proto.start(PackageServiceDumpProto.REQUIRED_VERIFIER_PACKAGE);
22419            proto.write(PackageServiceDumpProto.PackageShortProto.NAME, mRequiredVerifierPackage);
22420            proto.write(
22421                    PackageServiceDumpProto.PackageShortProto.UID,
22422                    getPackageUid(
22423                            mRequiredVerifierPackage,
22424                            MATCH_DEBUG_TRIAGED_MISSING,
22425                            UserHandle.USER_SYSTEM));
22426            proto.end(requiredVerifierPackageToken);
22427
22428            if (mIntentFilterVerifierComponent != null) {
22429                String verifierPackageName = mIntentFilterVerifierComponent.getPackageName();
22430                final long verifierPackageToken =
22431                        proto.start(PackageServiceDumpProto.VERIFIER_PACKAGE);
22432                proto.write(PackageServiceDumpProto.PackageShortProto.NAME, verifierPackageName);
22433                proto.write(
22434                        PackageServiceDumpProto.PackageShortProto.UID,
22435                        getPackageUid(
22436                                verifierPackageName,
22437                                MATCH_DEBUG_TRIAGED_MISSING,
22438                                UserHandle.USER_SYSTEM));
22439                proto.end(verifierPackageToken);
22440            }
22441
22442            dumpSharedLibrariesProto(proto);
22443            dumpFeaturesProto(proto);
22444            mSettings.dumpPackagesProto(proto);
22445            mSettings.dumpSharedUsersProto(proto);
22446            dumpMessagesProto(proto);
22447        }
22448        proto.flush();
22449    }
22450
22451    private void dumpMessagesProto(ProtoOutputStream proto) {
22452        BufferedReader in = null;
22453        String line = null;
22454        try {
22455            in = new BufferedReader(new FileReader(getSettingsProblemFile()));
22456            while ((line = in.readLine()) != null) {
22457                if (line.contains("ignored: updated version")) continue;
22458                proto.write(PackageServiceDumpProto.MESSAGES, line);
22459            }
22460        } catch (IOException ignored) {
22461        } finally {
22462            IoUtils.closeQuietly(in);
22463        }
22464    }
22465
22466    private void dumpFeaturesProto(ProtoOutputStream proto) {
22467        synchronized (mAvailableFeatures) {
22468            final int count = mAvailableFeatures.size();
22469            for (int i = 0; i < count; i++) {
22470                final FeatureInfo feat = mAvailableFeatures.valueAt(i);
22471                final long featureToken = proto.start(PackageServiceDumpProto.FEATURES);
22472                proto.write(PackageServiceDumpProto.FeatureProto.NAME, feat.name);
22473                proto.write(PackageServiceDumpProto.FeatureProto.VERSION, feat.version);
22474                proto.end(featureToken);
22475            }
22476        }
22477    }
22478
22479    private void dumpSharedLibrariesProto(ProtoOutputStream proto) {
22480        final int count = mSharedLibraries.size();
22481        for (int i = 0; i < count; i++) {
22482            final String libName = mSharedLibraries.keyAt(i);
22483            SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(libName);
22484            if (versionedLib == null) {
22485                continue;
22486            }
22487            final int versionCount = versionedLib.size();
22488            for (int j = 0; j < versionCount; j++) {
22489                final SharedLibraryEntry libEntry = versionedLib.valueAt(j);
22490                final long sharedLibraryToken =
22491                        proto.start(PackageServiceDumpProto.SHARED_LIBRARIES);
22492                proto.write(PackageServiceDumpProto.SharedLibraryProto.NAME, libEntry.info.getName());
22493                final boolean isJar = (libEntry.path != null);
22494                proto.write(PackageServiceDumpProto.SharedLibraryProto.IS_JAR, isJar);
22495                if (isJar) {
22496                    proto.write(PackageServiceDumpProto.SharedLibraryProto.PATH, libEntry.path);
22497                } else {
22498                    proto.write(PackageServiceDumpProto.SharedLibraryProto.APK, libEntry.apk);
22499                }
22500                proto.end(sharedLibraryToken);
22501            }
22502        }
22503    }
22504
22505    private void dumpDexoptStateLPr(PrintWriter pw, String packageName) {
22506        final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, "  ", 120);
22507        ipw.println();
22508        ipw.println("Dexopt state:");
22509        ipw.increaseIndent();
22510        Collection<PackageParser.Package> packages = null;
22511        if (packageName != null) {
22512            PackageParser.Package targetPackage = mPackages.get(packageName);
22513            if (targetPackage != null) {
22514                packages = Collections.singletonList(targetPackage);
22515            } else {
22516                ipw.println("Unable to find package: " + packageName);
22517                return;
22518            }
22519        } else {
22520            packages = mPackages.values();
22521        }
22522
22523        for (PackageParser.Package pkg : packages) {
22524            ipw.println("[" + pkg.packageName + "]");
22525            ipw.increaseIndent();
22526            mPackageDexOptimizer.dumpDexoptState(ipw, pkg);
22527            ipw.decreaseIndent();
22528        }
22529    }
22530
22531    private void dumpCompilerStatsLPr(PrintWriter pw, String packageName) {
22532        final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, "  ", 120);
22533        ipw.println();
22534        ipw.println("Compiler stats:");
22535        ipw.increaseIndent();
22536        Collection<PackageParser.Package> packages = null;
22537        if (packageName != null) {
22538            PackageParser.Package targetPackage = mPackages.get(packageName);
22539            if (targetPackage != null) {
22540                packages = Collections.singletonList(targetPackage);
22541            } else {
22542                ipw.println("Unable to find package: " + packageName);
22543                return;
22544            }
22545        } else {
22546            packages = mPackages.values();
22547        }
22548
22549        for (PackageParser.Package pkg : packages) {
22550            ipw.println("[" + pkg.packageName + "]");
22551            ipw.increaseIndent();
22552
22553            CompilerStats.PackageStats stats = getCompilerPackageStats(pkg.packageName);
22554            if (stats == null) {
22555                ipw.println("(No recorded stats)");
22556            } else {
22557                stats.dump(ipw);
22558            }
22559            ipw.decreaseIndent();
22560        }
22561    }
22562
22563    private String dumpDomainString(String packageName) {
22564        List<IntentFilterVerificationInfo> iviList = getIntentFilterVerifications(packageName)
22565                .getList();
22566        List<IntentFilter> filters = getAllIntentFilters(packageName).getList();
22567
22568        ArraySet<String> result = new ArraySet<>();
22569        if (iviList.size() > 0) {
22570            for (IntentFilterVerificationInfo ivi : iviList) {
22571                for (String host : ivi.getDomains()) {
22572                    result.add(host);
22573                }
22574            }
22575        }
22576        if (filters != null && filters.size() > 0) {
22577            for (IntentFilter filter : filters) {
22578                if (filter.hasCategory(Intent.CATEGORY_BROWSABLE)
22579                        && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) ||
22580                                filter.hasDataScheme(IntentFilter.SCHEME_HTTPS))) {
22581                    result.addAll(filter.getHostsList());
22582                }
22583            }
22584        }
22585
22586        StringBuilder sb = new StringBuilder(result.size() * 16);
22587        for (String domain : result) {
22588            if (sb.length() > 0) sb.append(" ");
22589            sb.append(domain);
22590        }
22591        return sb.toString();
22592    }
22593
22594    // ------- apps on sdcard specific code -------
22595    static final boolean DEBUG_SD_INSTALL = false;
22596
22597    private static final String SD_ENCRYPTION_KEYSTORE_NAME = "AppsOnSD";
22598
22599    private static final String SD_ENCRYPTION_ALGORITHM = "AES";
22600
22601    private boolean mMediaMounted = false;
22602
22603    static String getEncryptKey() {
22604        try {
22605            String sdEncKey = SystemKeyStore.getInstance().retrieveKeyHexString(
22606                    SD_ENCRYPTION_KEYSTORE_NAME);
22607            if (sdEncKey == null) {
22608                sdEncKey = SystemKeyStore.getInstance().generateNewKeyHexString(128,
22609                        SD_ENCRYPTION_ALGORITHM, SD_ENCRYPTION_KEYSTORE_NAME);
22610                if (sdEncKey == null) {
22611                    Slog.e(TAG, "Failed to create encryption keys");
22612                    return null;
22613                }
22614            }
22615            return sdEncKey;
22616        } catch (NoSuchAlgorithmException nsae) {
22617            Slog.e(TAG, "Failed to create encryption keys with exception: " + nsae);
22618            return null;
22619        } catch (IOException ioe) {
22620            Slog.e(TAG, "Failed to retrieve encryption keys with exception: " + ioe);
22621            return null;
22622        }
22623    }
22624
22625    /*
22626     * Update media status on PackageManager.
22627     */
22628    @Override
22629    public void updateExternalMediaStatus(final boolean mediaStatus, final boolean reportStatus) {
22630        enforceSystemOrRoot("Media status can only be updated by the system");
22631        // reader; this apparently protects mMediaMounted, but should probably
22632        // be a different lock in that case.
22633        synchronized (mPackages) {
22634            Log.i(TAG, "Updating external media status from "
22635                    + (mMediaMounted ? "mounted" : "unmounted") + " to "
22636                    + (mediaStatus ? "mounted" : "unmounted"));
22637            if (DEBUG_SD_INSTALL)
22638                Log.i(TAG, "updateExternalMediaStatus:: mediaStatus=" + mediaStatus
22639                        + ", mMediaMounted=" + mMediaMounted);
22640            if (mediaStatus == mMediaMounted) {
22641                final Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1
22642                        : 0, -1);
22643                mHandler.sendMessage(msg);
22644                return;
22645            }
22646            mMediaMounted = mediaStatus;
22647        }
22648        // Queue up an async operation since the package installation may take a
22649        // little while.
22650        mHandler.post(new Runnable() {
22651            public void run() {
22652                updateExternalMediaStatusInner(mediaStatus, reportStatus, true);
22653            }
22654        });
22655    }
22656
22657    /**
22658     * Called by StorageManagerService when the initial ASECs to scan are available.
22659     * Should block until all the ASEC containers are finished being scanned.
22660     */
22661    public void scanAvailableAsecs() {
22662        updateExternalMediaStatusInner(true, false, false);
22663    }
22664
22665    /*
22666     * Collect information of applications on external media, map them against
22667     * existing containers and update information based on current mount status.
22668     * Please note that we always have to report status if reportStatus has been
22669     * set to true especially when unloading packages.
22670     */
22671    private void updateExternalMediaStatusInner(boolean isMounted, boolean reportStatus,
22672            boolean externalStorage) {
22673        ArrayMap<AsecInstallArgs, String> processCids = new ArrayMap<>();
22674        int[] uidArr = EmptyArray.INT;
22675
22676        final String[] list = PackageHelper.getSecureContainerList();
22677        if (ArrayUtils.isEmpty(list)) {
22678            Log.i(TAG, "No secure containers found");
22679        } else {
22680            // Process list of secure containers and categorize them
22681            // as active or stale based on their package internal state.
22682
22683            // reader
22684            synchronized (mPackages) {
22685                for (String cid : list) {
22686                    // Leave stages untouched for now; installer service owns them
22687                    if (PackageInstallerService.isStageName(cid)) continue;
22688
22689                    if (DEBUG_SD_INSTALL)
22690                        Log.i(TAG, "Processing container " + cid);
22691                    String pkgName = getAsecPackageName(cid);
22692                    if (pkgName == null) {
22693                        Slog.i(TAG, "Found stale container " + cid + " with no package name");
22694                        continue;
22695                    }
22696                    if (DEBUG_SD_INSTALL)
22697                        Log.i(TAG, "Looking for pkg : " + pkgName);
22698
22699                    final PackageSetting ps = mSettings.mPackages.get(pkgName);
22700                    if (ps == null) {
22701                        Slog.i(TAG, "Found stale container " + cid + " with no matching settings");
22702                        continue;
22703                    }
22704
22705                    /*
22706                     * Skip packages that are not external if we're unmounting
22707                     * external storage.
22708                     */
22709                    if (externalStorage && !isMounted && !isExternal(ps)) {
22710                        continue;
22711                    }
22712
22713                    final AsecInstallArgs args = new AsecInstallArgs(cid,
22714                            getAppDexInstructionSets(ps), ps.isForwardLocked());
22715                    // The package status is changed only if the code path
22716                    // matches between settings and the container id.
22717                    if (ps.codePathString != null
22718                            && ps.codePathString.startsWith(args.getCodePath())) {
22719                        if (DEBUG_SD_INSTALL) {
22720                            Log.i(TAG, "Container : " + cid + " corresponds to pkg : " + pkgName
22721                                    + " at code path: " + ps.codePathString);
22722                        }
22723
22724                        // We do have a valid package installed on sdcard
22725                        processCids.put(args, ps.codePathString);
22726                        final int uid = ps.appId;
22727                        if (uid != -1) {
22728                            uidArr = ArrayUtils.appendInt(uidArr, uid);
22729                        }
22730                    } else {
22731                        Slog.i(TAG, "Found stale container " + cid + ": expected codePath="
22732                                + ps.codePathString);
22733                    }
22734                }
22735            }
22736
22737            Arrays.sort(uidArr);
22738        }
22739
22740        // Process packages with valid entries.
22741        if (isMounted) {
22742            if (DEBUG_SD_INSTALL)
22743                Log.i(TAG, "Loading packages");
22744            loadMediaPackages(processCids, uidArr, externalStorage);
22745            startCleaningPackages();
22746            mInstallerService.onSecureContainersAvailable();
22747        } else {
22748            if (DEBUG_SD_INSTALL)
22749                Log.i(TAG, "Unloading packages");
22750            unloadMediaPackages(processCids, uidArr, reportStatus);
22751        }
22752    }
22753
22754    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
22755            ArrayList<ApplicationInfo> infos, IIntentReceiver finishedReceiver) {
22756        final int size = infos.size();
22757        final String[] packageNames = new String[size];
22758        final int[] packageUids = new int[size];
22759        for (int i = 0; i < size; i++) {
22760            final ApplicationInfo info = infos.get(i);
22761            packageNames[i] = info.packageName;
22762            packageUids[i] = info.uid;
22763        }
22764        sendResourcesChangedBroadcast(mediaStatus, replacing, packageNames, packageUids,
22765                finishedReceiver);
22766    }
22767
22768    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
22769            ArrayList<String> pkgList, int uidArr[], IIntentReceiver finishedReceiver) {
22770        sendResourcesChangedBroadcast(mediaStatus, replacing,
22771                pkgList.toArray(new String[pkgList.size()]), uidArr, finishedReceiver);
22772    }
22773
22774    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
22775            String[] pkgList, int uidArr[], IIntentReceiver finishedReceiver) {
22776        int size = pkgList.length;
22777        if (size > 0) {
22778            // Send broadcasts here
22779            Bundle extras = new Bundle();
22780            extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList);
22781            if (uidArr != null) {
22782                extras.putIntArray(Intent.EXTRA_CHANGED_UID_LIST, uidArr);
22783            }
22784            if (replacing) {
22785                extras.putBoolean(Intent.EXTRA_REPLACING, replacing);
22786            }
22787            String action = mediaStatus ? Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE
22788                    : Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE;
22789            sendPackageBroadcast(action, null, extras, 0, null, finishedReceiver, null);
22790        }
22791    }
22792
22793   /*
22794     * Look at potentially valid container ids from processCids If package
22795     * information doesn't match the one on record or package scanning fails,
22796     * the cid is added to list of removeCids. We currently don't delete stale
22797     * containers.
22798     */
22799    private void loadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int[] uidArr,
22800            boolean externalStorage) {
22801        ArrayList<String> pkgList = new ArrayList<String>();
22802        Set<AsecInstallArgs> keys = processCids.keySet();
22803
22804        for (AsecInstallArgs args : keys) {
22805            String codePath = processCids.get(args);
22806            if (DEBUG_SD_INSTALL)
22807                Log.i(TAG, "Loading container : " + args.cid);
22808            int retCode = PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
22809            try {
22810                // Make sure there are no container errors first.
22811                if (args.doPreInstall(PackageManager.INSTALL_SUCCEEDED) != PackageManager.INSTALL_SUCCEEDED) {
22812                    Slog.e(TAG, "Failed to mount cid : " + args.cid
22813                            + " when installing from sdcard");
22814                    continue;
22815                }
22816                // Check code path here.
22817                if (codePath == null || !codePath.startsWith(args.getCodePath())) {
22818                    Slog.e(TAG, "Container " + args.cid + " cachepath " + args.getCodePath()
22819                            + " does not match one in settings " + codePath);
22820                    continue;
22821                }
22822                // Parse package
22823                int parseFlags = mDefParseFlags;
22824                if (args.isExternalAsec()) {
22825                    parseFlags |= PackageParser.PARSE_EXTERNAL_STORAGE;
22826                }
22827                if (args.isFwdLocked()) {
22828                    parseFlags |= PackageParser.PARSE_FORWARD_LOCK;
22829                }
22830
22831                synchronized (mInstallLock) {
22832                    PackageParser.Package pkg = null;
22833                    try {
22834                        // Sadly we don't know the package name yet to freeze it
22835                        pkg = scanPackageTracedLI(new File(codePath), parseFlags,
22836                                SCAN_IGNORE_FROZEN, 0, null);
22837                    } catch (PackageManagerException e) {
22838                        Slog.w(TAG, "Failed to scan " + codePath + ": " + e.getMessage());
22839                    }
22840                    // Scan the package
22841                    if (pkg != null) {
22842                        /*
22843                         * TODO why is the lock being held? doPostInstall is
22844                         * called in other places without the lock. This needs
22845                         * to be straightened out.
22846                         */
22847                        // writer
22848                        synchronized (mPackages) {
22849                            retCode = PackageManager.INSTALL_SUCCEEDED;
22850                            pkgList.add(pkg.packageName);
22851                            // Post process args
22852                            args.doPostInstall(PackageManager.INSTALL_SUCCEEDED,
22853                                    pkg.applicationInfo.uid);
22854                        }
22855                    } else {
22856                        Slog.i(TAG, "Failed to install pkg from  " + codePath + " from sdcard");
22857                    }
22858                }
22859
22860            } finally {
22861                if (retCode != PackageManager.INSTALL_SUCCEEDED) {
22862                    Log.w(TAG, "Container " + args.cid + " is stale, retCode=" + retCode);
22863                }
22864            }
22865        }
22866        // writer
22867        synchronized (mPackages) {
22868            // If the platform SDK has changed since the last time we booted,
22869            // we need to re-grant app permission to catch any new ones that
22870            // appear. This is really a hack, and means that apps can in some
22871            // cases get permissions that the user didn't initially explicitly
22872            // allow... it would be nice to have some better way to handle
22873            // this situation.
22874            final VersionInfo ver = externalStorage ? mSettings.getExternalVersion()
22875                    : mSettings.getInternalVersion();
22876            final String volumeUuid = externalStorage ? StorageManager.UUID_PRIMARY_PHYSICAL
22877                    : StorageManager.UUID_PRIVATE_INTERNAL;
22878
22879            int updateFlags = UPDATE_PERMISSIONS_ALL;
22880            if (ver.sdkVersion != mSdkVersion) {
22881                logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to "
22882                        + mSdkVersion + "; regranting permissions for external");
22883                updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL;
22884            }
22885            updatePermissionsLPw(null, null, volumeUuid, updateFlags);
22886
22887            // Yay, everything is now upgraded
22888            ver.forceCurrent();
22889
22890            // can downgrade to reader
22891            // Persist settings
22892            mSettings.writeLPr();
22893        }
22894        // Send a broadcast to let everyone know we are done processing
22895        if (pkgList.size() > 0) {
22896            sendResourcesChangedBroadcast(true, false, pkgList, uidArr, null);
22897        }
22898    }
22899
22900   /*
22901     * Utility method to unload a list of specified containers
22902     */
22903    private void unloadAllContainers(Set<AsecInstallArgs> cidArgs) {
22904        // Just unmount all valid containers.
22905        for (AsecInstallArgs arg : cidArgs) {
22906            synchronized (mInstallLock) {
22907                arg.doPostDeleteLI(false);
22908           }
22909       }
22910   }
22911
22912    /*
22913     * Unload packages mounted on external media. This involves deleting package
22914     * data from internal structures, sending broadcasts about disabled packages,
22915     * gc'ing to free up references, unmounting all secure containers
22916     * corresponding to packages on external media, and posting a
22917     * UPDATED_MEDIA_STATUS message if status has been requested. Please note
22918     * that we always have to post this message if status has been requested no
22919     * matter what.
22920     */
22921    private void unloadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int uidArr[],
22922            final boolean reportStatus) {
22923        if (DEBUG_SD_INSTALL)
22924            Log.i(TAG, "unloading media packages");
22925        ArrayList<String> pkgList = new ArrayList<String>();
22926        ArrayList<AsecInstallArgs> failedList = new ArrayList<AsecInstallArgs>();
22927        final Set<AsecInstallArgs> keys = processCids.keySet();
22928        for (AsecInstallArgs args : keys) {
22929            String pkgName = args.getPackageName();
22930            if (DEBUG_SD_INSTALL)
22931                Log.i(TAG, "Trying to unload pkg : " + pkgName);
22932            // Delete package internally
22933            PackageRemovedInfo outInfo = new PackageRemovedInfo(this);
22934            synchronized (mInstallLock) {
22935                final int deleteFlags = PackageManager.DELETE_KEEP_DATA;
22936                final boolean res;
22937                try (PackageFreezer freezer = freezePackageForDelete(pkgName, deleteFlags,
22938                        "unloadMediaPackages")) {
22939                    res = deletePackageLIF(pkgName, null, false, null, deleteFlags, outInfo, false,
22940                            null);
22941                }
22942                if (res) {
22943                    pkgList.add(pkgName);
22944                } else {
22945                    Slog.e(TAG, "Failed to delete pkg from sdcard : " + pkgName);
22946                    failedList.add(args);
22947                }
22948            }
22949        }
22950
22951        // reader
22952        synchronized (mPackages) {
22953            // We didn't update the settings after removing each package;
22954            // write them now for all packages.
22955            mSettings.writeLPr();
22956        }
22957
22958        // We have to absolutely send UPDATED_MEDIA_STATUS only
22959        // after confirming that all the receivers processed the ordered
22960        // broadcast when packages get disabled, force a gc to clean things up.
22961        // and unload all the containers.
22962        if (pkgList.size() > 0) {
22963            sendResourcesChangedBroadcast(false, false, pkgList, uidArr,
22964                    new IIntentReceiver.Stub() {
22965                public void performReceive(Intent intent, int resultCode, String data,
22966                        Bundle extras, boolean ordered, boolean sticky,
22967                        int sendingUser) throws RemoteException {
22968                    Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS,
22969                            reportStatus ? 1 : 0, 1, keys);
22970                    mHandler.sendMessage(msg);
22971                }
22972            });
22973        } else {
22974            Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 : 0, -1,
22975                    keys);
22976            mHandler.sendMessage(msg);
22977        }
22978    }
22979
22980    private void loadPrivatePackages(final VolumeInfo vol) {
22981        mHandler.post(new Runnable() {
22982            @Override
22983            public void run() {
22984                loadPrivatePackagesInner(vol);
22985            }
22986        });
22987    }
22988
22989    private void loadPrivatePackagesInner(VolumeInfo vol) {
22990        final String volumeUuid = vol.fsUuid;
22991        if (TextUtils.isEmpty(volumeUuid)) {
22992            Slog.e(TAG, "Loading internal storage is probably a mistake; ignoring");
22993            return;
22994        }
22995
22996        final ArrayList<PackageFreezer> freezers = new ArrayList<>();
22997        final ArrayList<ApplicationInfo> loaded = new ArrayList<>();
22998        final int parseFlags = mDefParseFlags | PackageParser.PARSE_EXTERNAL_STORAGE;
22999
23000        final VersionInfo ver;
23001        final List<PackageSetting> packages;
23002        synchronized (mPackages) {
23003            ver = mSettings.findOrCreateVersion(volumeUuid);
23004            packages = mSettings.getVolumePackagesLPr(volumeUuid);
23005        }
23006
23007        for (PackageSetting ps : packages) {
23008            freezers.add(freezePackage(ps.name, "loadPrivatePackagesInner"));
23009            synchronized (mInstallLock) {
23010                final PackageParser.Package pkg;
23011                try {
23012                    pkg = scanPackageTracedLI(ps.codePath, parseFlags, SCAN_INITIAL, 0, null);
23013                    loaded.add(pkg.applicationInfo);
23014
23015                } catch (PackageManagerException e) {
23016                    Slog.w(TAG, "Failed to scan " + ps.codePath + ": " + e.getMessage());
23017                }
23018
23019                if (!Build.FINGERPRINT.equals(ver.fingerprint)) {
23020                    clearAppDataLIF(ps.pkg, UserHandle.USER_ALL,
23021                            StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE
23022                                    | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
23023                }
23024            }
23025        }
23026
23027        // Reconcile app data for all started/unlocked users
23028        final StorageManager sm = mContext.getSystemService(StorageManager.class);
23029        final UserManager um = mContext.getSystemService(UserManager.class);
23030        UserManagerInternal umInternal = getUserManagerInternal();
23031        for (UserInfo user : um.getUsers()) {
23032            final int flags;
23033            if (umInternal.isUserUnlockingOrUnlocked(user.id)) {
23034                flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
23035            } else if (umInternal.isUserRunning(user.id)) {
23036                flags = StorageManager.FLAG_STORAGE_DE;
23037            } else {
23038                continue;
23039            }
23040
23041            try {
23042                sm.prepareUserStorage(volumeUuid, user.id, user.serialNumber, flags);
23043                synchronized (mInstallLock) {
23044                    reconcileAppsDataLI(volumeUuid, user.id, flags, true /* migrateAppData */);
23045                }
23046            } catch (IllegalStateException e) {
23047                // Device was probably ejected, and we'll process that event momentarily
23048                Slog.w(TAG, "Failed to prepare storage: " + e);
23049            }
23050        }
23051
23052        synchronized (mPackages) {
23053            int updateFlags = UPDATE_PERMISSIONS_ALL;
23054            if (ver.sdkVersion != mSdkVersion) {
23055                logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to "
23056                        + mSdkVersion + "; regranting permissions for " + volumeUuid);
23057                updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL;
23058            }
23059            updatePermissionsLPw(null, null, volumeUuid, updateFlags);
23060
23061            // Yay, everything is now upgraded
23062            ver.forceCurrent();
23063
23064            mSettings.writeLPr();
23065        }
23066
23067        for (PackageFreezer freezer : freezers) {
23068            freezer.close();
23069        }
23070
23071        if (DEBUG_INSTALL) Slog.d(TAG, "Loaded packages " + loaded);
23072        sendResourcesChangedBroadcast(true, false, loaded, null);
23073    }
23074
23075    private void unloadPrivatePackages(final VolumeInfo vol) {
23076        mHandler.post(new Runnable() {
23077            @Override
23078            public void run() {
23079                unloadPrivatePackagesInner(vol);
23080            }
23081        });
23082    }
23083
23084    private void unloadPrivatePackagesInner(VolumeInfo vol) {
23085        final String volumeUuid = vol.fsUuid;
23086        if (TextUtils.isEmpty(volumeUuid)) {
23087            Slog.e(TAG, "Unloading internal storage is probably a mistake; ignoring");
23088            return;
23089        }
23090
23091        final ArrayList<ApplicationInfo> unloaded = new ArrayList<>();
23092        synchronized (mInstallLock) {
23093        synchronized (mPackages) {
23094            final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(volumeUuid);
23095            for (PackageSetting ps : packages) {
23096                if (ps.pkg == null) continue;
23097
23098                final ApplicationInfo info = ps.pkg.applicationInfo;
23099                final int deleteFlags = PackageManager.DELETE_KEEP_DATA;
23100                final PackageRemovedInfo outInfo = new PackageRemovedInfo(this);
23101
23102                try (PackageFreezer freezer = freezePackageForDelete(ps.name, deleteFlags,
23103                        "unloadPrivatePackagesInner")) {
23104                    if (deletePackageLIF(ps.name, null, false, null, deleteFlags, outInfo,
23105                            false, null)) {
23106                        unloaded.add(info);
23107                    } else {
23108                        Slog.w(TAG, "Failed to unload " + ps.codePath);
23109                    }
23110                }
23111
23112                // Try very hard to release any references to this package
23113                // so we don't risk the system server being killed due to
23114                // open FDs
23115                AttributeCache.instance().removePackage(ps.name);
23116            }
23117
23118            mSettings.writeLPr();
23119        }
23120        }
23121
23122        if (DEBUG_INSTALL) Slog.d(TAG, "Unloaded packages " + unloaded);
23123        sendResourcesChangedBroadcast(false, false, unloaded, null);
23124
23125        // Try very hard to release any references to this path so we don't risk
23126        // the system server being killed due to open FDs
23127        ResourcesManager.getInstance().invalidatePath(vol.getPath().getAbsolutePath());
23128
23129        for (int i = 0; i < 3; i++) {
23130            System.gc();
23131            System.runFinalization();
23132        }
23133    }
23134
23135    private void assertPackageKnown(String volumeUuid, String packageName)
23136            throws PackageManagerException {
23137        synchronized (mPackages) {
23138            // Normalize package name to handle renamed packages
23139            packageName = normalizePackageNameLPr(packageName);
23140
23141            final PackageSetting ps = mSettings.mPackages.get(packageName);
23142            if (ps == null) {
23143                throw new PackageManagerException("Package " + packageName + " is unknown");
23144            } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) {
23145                throw new PackageManagerException(
23146                        "Package " + packageName + " found on unknown volume " + volumeUuid
23147                                + "; expected volume " + ps.volumeUuid);
23148            }
23149        }
23150    }
23151
23152    private void assertPackageKnownAndInstalled(String volumeUuid, String packageName, int userId)
23153            throws PackageManagerException {
23154        synchronized (mPackages) {
23155            // Normalize package name to handle renamed packages
23156            packageName = normalizePackageNameLPr(packageName);
23157
23158            final PackageSetting ps = mSettings.mPackages.get(packageName);
23159            if (ps == null) {
23160                throw new PackageManagerException("Package " + packageName + " is unknown");
23161            } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) {
23162                throw new PackageManagerException(
23163                        "Package " + packageName + " found on unknown volume " + volumeUuid
23164                                + "; expected volume " + ps.volumeUuid);
23165            } else if (!ps.getInstalled(userId)) {
23166                throw new PackageManagerException(
23167                        "Package " + packageName + " not installed for user " + userId);
23168            }
23169        }
23170    }
23171
23172    private List<String> collectAbsoluteCodePaths() {
23173        synchronized (mPackages) {
23174            List<String> codePaths = new ArrayList<>();
23175            final int packageCount = mSettings.mPackages.size();
23176            for (int i = 0; i < packageCount; i++) {
23177                final PackageSetting ps = mSettings.mPackages.valueAt(i);
23178                codePaths.add(ps.codePath.getAbsolutePath());
23179            }
23180            return codePaths;
23181        }
23182    }
23183
23184    /**
23185     * Examine all apps present on given mounted volume, and destroy apps that
23186     * aren't expected, either due to uninstallation or reinstallation on
23187     * another volume.
23188     */
23189    private void reconcileApps(String volumeUuid) {
23190        List<String> absoluteCodePaths = collectAbsoluteCodePaths();
23191        List<File> filesToDelete = null;
23192
23193        final File[] files = FileUtils.listFilesOrEmpty(
23194                Environment.getDataAppDirectory(volumeUuid));
23195        for (File file : files) {
23196            final boolean isPackage = (isApkFile(file) || file.isDirectory())
23197                    && !PackageInstallerService.isStageName(file.getName());
23198            if (!isPackage) {
23199                // Ignore entries which are not packages
23200                continue;
23201            }
23202
23203            String absolutePath = file.getAbsolutePath();
23204
23205            boolean pathValid = false;
23206            final int absoluteCodePathCount = absoluteCodePaths.size();
23207            for (int i = 0; i < absoluteCodePathCount; i++) {
23208                String absoluteCodePath = absoluteCodePaths.get(i);
23209                if (absolutePath.startsWith(absoluteCodePath)) {
23210                    pathValid = true;
23211                    break;
23212                }
23213            }
23214
23215            if (!pathValid) {
23216                if (filesToDelete == null) {
23217                    filesToDelete = new ArrayList<>();
23218                }
23219                filesToDelete.add(file);
23220            }
23221        }
23222
23223        if (filesToDelete != null) {
23224            final int fileToDeleteCount = filesToDelete.size();
23225            for (int i = 0; i < fileToDeleteCount; i++) {
23226                File fileToDelete = filesToDelete.get(i);
23227                logCriticalInfo(Log.WARN, "Destroying orphaned" + fileToDelete);
23228                synchronized (mInstallLock) {
23229                    removeCodePathLI(fileToDelete);
23230                }
23231            }
23232        }
23233    }
23234
23235    /**
23236     * Reconcile all app data for the given user.
23237     * <p>
23238     * Verifies that directories exist and that ownership and labeling is
23239     * correct for all installed apps on all mounted volumes.
23240     */
23241    void reconcileAppsData(int userId, int flags, boolean migrateAppsData) {
23242        final StorageManager storage = mContext.getSystemService(StorageManager.class);
23243        for (VolumeInfo vol : storage.getWritablePrivateVolumes()) {
23244            final String volumeUuid = vol.getFsUuid();
23245            synchronized (mInstallLock) {
23246                reconcileAppsDataLI(volumeUuid, userId, flags, migrateAppsData);
23247            }
23248        }
23249    }
23250
23251    private void reconcileAppsDataLI(String volumeUuid, int userId, int flags,
23252            boolean migrateAppData) {
23253        reconcileAppsDataLI(volumeUuid, userId, flags, migrateAppData, false /* onlyCoreApps */);
23254    }
23255
23256    /**
23257     * Reconcile all app data on given mounted volume.
23258     * <p>
23259     * Destroys app data that isn't expected, either due to uninstallation or
23260     * reinstallation on another volume.
23261     * <p>
23262     * Verifies that directories exist and that ownership and labeling is
23263     * correct for all installed apps.
23264     * @returns list of skipped non-core packages (if {@code onlyCoreApps} is true)
23265     */
23266    private List<String> reconcileAppsDataLI(String volumeUuid, int userId, int flags,
23267            boolean migrateAppData, boolean onlyCoreApps) {
23268        Slog.v(TAG, "reconcileAppsData for " + volumeUuid + " u" + userId + " 0x"
23269                + Integer.toHexString(flags) + " migrateAppData=" + migrateAppData);
23270        List<String> result = onlyCoreApps ? new ArrayList<>() : null;
23271
23272        final File ceDir = Environment.getDataUserCeDirectory(volumeUuid, userId);
23273        final File deDir = Environment.getDataUserDeDirectory(volumeUuid, userId);
23274
23275        // First look for stale data that doesn't belong, and check if things
23276        // have changed since we did our last restorecon
23277        if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) {
23278            if (StorageManager.isFileEncryptedNativeOrEmulated()
23279                    && !StorageManager.isUserKeyUnlocked(userId)) {
23280                throw new RuntimeException(
23281                        "Yikes, someone asked us to reconcile CE storage while " + userId
23282                                + " was still locked; this would have caused massive data loss!");
23283            }
23284
23285            final File[] files = FileUtils.listFilesOrEmpty(ceDir);
23286            for (File file : files) {
23287                final String packageName = file.getName();
23288                try {
23289                    assertPackageKnownAndInstalled(volumeUuid, packageName, userId);
23290                } catch (PackageManagerException e) {
23291                    logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e);
23292                    try {
23293                        mInstaller.destroyAppData(volumeUuid, packageName, userId,
23294                                StorageManager.FLAG_STORAGE_CE, 0);
23295                    } catch (InstallerException e2) {
23296                        logCriticalInfo(Log.WARN, "Failed to destroy: " + e2);
23297                    }
23298                }
23299            }
23300        }
23301        if ((flags & StorageManager.FLAG_STORAGE_DE) != 0) {
23302            final File[] files = FileUtils.listFilesOrEmpty(deDir);
23303            for (File file : files) {
23304                final String packageName = file.getName();
23305                try {
23306                    assertPackageKnownAndInstalled(volumeUuid, packageName, userId);
23307                } catch (PackageManagerException e) {
23308                    logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e);
23309                    try {
23310                        mInstaller.destroyAppData(volumeUuid, packageName, userId,
23311                                StorageManager.FLAG_STORAGE_DE, 0);
23312                    } catch (InstallerException e2) {
23313                        logCriticalInfo(Log.WARN, "Failed to destroy: " + e2);
23314                    }
23315                }
23316            }
23317        }
23318
23319        // Ensure that data directories are ready to roll for all packages
23320        // installed for this volume and user
23321        final List<PackageSetting> packages;
23322        synchronized (mPackages) {
23323            packages = mSettings.getVolumePackagesLPr(volumeUuid);
23324        }
23325        int preparedCount = 0;
23326        for (PackageSetting ps : packages) {
23327            final String packageName = ps.name;
23328            if (ps.pkg == null) {
23329                Slog.w(TAG, "Odd, missing scanned package " + packageName);
23330                // TODO: might be due to legacy ASEC apps; we should circle back
23331                // and reconcile again once they're scanned
23332                continue;
23333            }
23334            // Skip non-core apps if requested
23335            if (onlyCoreApps && !ps.pkg.coreApp) {
23336                result.add(packageName);
23337                continue;
23338            }
23339
23340            if (ps.getInstalled(userId)) {
23341                prepareAppDataAndMigrateLIF(ps.pkg, userId, flags, migrateAppData);
23342                preparedCount++;
23343            }
23344        }
23345
23346        Slog.v(TAG, "reconcileAppsData finished " + preparedCount + " packages");
23347        return result;
23348    }
23349
23350    /**
23351     * Prepare app data for the given app just after it was installed or
23352     * upgraded. This method carefully only touches users that it's installed
23353     * for, and it forces a restorecon to handle any seinfo changes.
23354     * <p>
23355     * Verifies that directories exist and that ownership and labeling is
23356     * correct for all installed apps. If there is an ownership mismatch, it
23357     * will try recovering system apps by wiping data; third-party app data is
23358     * left intact.
23359     * <p>
23360     * <em>Note: To avoid a deadlock, do not call this method with {@code mPackages} lock held</em>
23361     */
23362    private void prepareAppDataAfterInstallLIF(PackageParser.Package pkg) {
23363        final PackageSetting ps;
23364        synchronized (mPackages) {
23365            ps = mSettings.mPackages.get(pkg.packageName);
23366            mSettings.writeKernelMappingLPr(ps);
23367        }
23368
23369        final UserManager um = mContext.getSystemService(UserManager.class);
23370        UserManagerInternal umInternal = getUserManagerInternal();
23371        for (UserInfo user : um.getUsers()) {
23372            final int flags;
23373            if (umInternal.isUserUnlockingOrUnlocked(user.id)) {
23374                flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
23375            } else if (umInternal.isUserRunning(user.id)) {
23376                flags = StorageManager.FLAG_STORAGE_DE;
23377            } else {
23378                continue;
23379            }
23380
23381            if (ps.getInstalled(user.id)) {
23382                // TODO: when user data is locked, mark that we're still dirty
23383                prepareAppDataLIF(pkg, user.id, flags);
23384            }
23385        }
23386    }
23387
23388    /**
23389     * Prepare app data for the given app.
23390     * <p>
23391     * Verifies that directories exist and that ownership and labeling is
23392     * correct for all installed apps. If there is an ownership mismatch, this
23393     * will try recovering system apps by wiping data; third-party app data is
23394     * left intact.
23395     */
23396    private void prepareAppDataLIF(PackageParser.Package pkg, int userId, int flags) {
23397        if (pkg == null) {
23398            Slog.wtf(TAG, "Package was null!", new Throwable());
23399            return;
23400        }
23401        prepareAppDataLeafLIF(pkg, userId, flags);
23402        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
23403        for (int i = 0; i < childCount; i++) {
23404            prepareAppDataLeafLIF(pkg.childPackages.get(i), userId, flags);
23405        }
23406    }
23407
23408    private void prepareAppDataAndMigrateLIF(PackageParser.Package pkg, int userId, int flags,
23409            boolean maybeMigrateAppData) {
23410        prepareAppDataLIF(pkg, userId, flags);
23411
23412        if (maybeMigrateAppData && maybeMigrateAppDataLIF(pkg, userId)) {
23413            // We may have just shuffled around app data directories, so
23414            // prepare them one more time
23415            prepareAppDataLIF(pkg, userId, flags);
23416        }
23417    }
23418
23419    private void prepareAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) {
23420        if (DEBUG_APP_DATA) {
23421            Slog.v(TAG, "prepareAppData for " + pkg.packageName + " u" + userId + " 0x"
23422                    + Integer.toHexString(flags));
23423        }
23424
23425        final String volumeUuid = pkg.volumeUuid;
23426        final String packageName = pkg.packageName;
23427        final ApplicationInfo app = pkg.applicationInfo;
23428        final int appId = UserHandle.getAppId(app.uid);
23429
23430        Preconditions.checkNotNull(app.seInfo);
23431
23432        long ceDataInode = -1;
23433        try {
23434            ceDataInode = mInstaller.createAppData(volumeUuid, packageName, userId, flags,
23435                    appId, app.seInfo, app.targetSdkVersion);
23436        } catch (InstallerException e) {
23437            if (app.isSystemApp()) {
23438                logCriticalInfo(Log.ERROR, "Failed to create app data for " + packageName
23439                        + ", but trying to recover: " + e);
23440                destroyAppDataLeafLIF(pkg, userId, flags);
23441                try {
23442                    ceDataInode = mInstaller.createAppData(volumeUuid, packageName, userId, flags,
23443                            appId, app.seInfo, app.targetSdkVersion);
23444                    logCriticalInfo(Log.DEBUG, "Recovery succeeded!");
23445                } catch (InstallerException e2) {
23446                    logCriticalInfo(Log.DEBUG, "Recovery failed!");
23447                }
23448            } else {
23449                Slog.e(TAG, "Failed to create app data for " + packageName + ": " + e);
23450            }
23451        }
23452
23453        if ((flags & StorageManager.FLAG_STORAGE_CE) != 0 && ceDataInode != -1) {
23454            // TODO: mark this structure as dirty so we persist it!
23455            synchronized (mPackages) {
23456                final PackageSetting ps = mSettings.mPackages.get(packageName);
23457                if (ps != null) {
23458                    ps.setCeDataInode(ceDataInode, userId);
23459                }
23460            }
23461        }
23462
23463        prepareAppDataContentsLeafLIF(pkg, userId, flags);
23464    }
23465
23466    private void prepareAppDataContentsLIF(PackageParser.Package pkg, int userId, int flags) {
23467        if (pkg == null) {
23468            Slog.wtf(TAG, "Package was null!", new Throwable());
23469            return;
23470        }
23471        prepareAppDataContentsLeafLIF(pkg, userId, flags);
23472        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
23473        for (int i = 0; i < childCount; i++) {
23474            prepareAppDataContentsLeafLIF(pkg.childPackages.get(i), userId, flags);
23475        }
23476    }
23477
23478    private void prepareAppDataContentsLeafLIF(PackageParser.Package pkg, int userId, int flags) {
23479        final String volumeUuid = pkg.volumeUuid;
23480        final String packageName = pkg.packageName;
23481        final ApplicationInfo app = pkg.applicationInfo;
23482
23483        if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) {
23484            // Create a native library symlink only if we have native libraries
23485            // and if the native libraries are 32 bit libraries. We do not provide
23486            // this symlink for 64 bit libraries.
23487            if (app.primaryCpuAbi != null && !VMRuntime.is64BitAbi(app.primaryCpuAbi)) {
23488                final String nativeLibPath = app.nativeLibraryDir;
23489                try {
23490                    mInstaller.linkNativeLibraryDirectory(volumeUuid, packageName,
23491                            nativeLibPath, userId);
23492                } catch (InstallerException e) {
23493                    Slog.e(TAG, "Failed to link native for " + packageName + ": " + e);
23494                }
23495            }
23496        }
23497    }
23498
23499    /**
23500     * For system apps on non-FBE devices, this method migrates any existing
23501     * CE/DE data to match the {@code defaultToDeviceProtectedStorage} flag
23502     * requested by the app.
23503     */
23504    private boolean maybeMigrateAppDataLIF(PackageParser.Package pkg, int userId) {
23505        if (pkg.isSystemApp() && !StorageManager.isFileEncryptedNativeOrEmulated()
23506                && PackageManager.APPLY_DEFAULT_TO_DEVICE_PROTECTED_STORAGE) {
23507            final int storageTarget = pkg.applicationInfo.isDefaultToDeviceProtectedStorage()
23508                    ? StorageManager.FLAG_STORAGE_DE : StorageManager.FLAG_STORAGE_CE;
23509            try {
23510                mInstaller.migrateAppData(pkg.volumeUuid, pkg.packageName, userId,
23511                        storageTarget);
23512            } catch (InstallerException e) {
23513                logCriticalInfo(Log.WARN,
23514                        "Failed to migrate " + pkg.packageName + ": " + e.getMessage());
23515            }
23516            return true;
23517        } else {
23518            return false;
23519        }
23520    }
23521
23522    public PackageFreezer freezePackage(String packageName, String killReason) {
23523        return freezePackage(packageName, UserHandle.USER_ALL, killReason);
23524    }
23525
23526    public PackageFreezer freezePackage(String packageName, int userId, String killReason) {
23527        return new PackageFreezer(packageName, userId, killReason);
23528    }
23529
23530    public PackageFreezer freezePackageForInstall(String packageName, int installFlags,
23531            String killReason) {
23532        return freezePackageForInstall(packageName, UserHandle.USER_ALL, installFlags, killReason);
23533    }
23534
23535    public PackageFreezer freezePackageForInstall(String packageName, int userId, int installFlags,
23536            String killReason) {
23537        if ((installFlags & PackageManager.INSTALL_DONT_KILL_APP) != 0) {
23538            return new PackageFreezer();
23539        } else {
23540            return freezePackage(packageName, userId, killReason);
23541        }
23542    }
23543
23544    public PackageFreezer freezePackageForDelete(String packageName, int deleteFlags,
23545            String killReason) {
23546        return freezePackageForDelete(packageName, UserHandle.USER_ALL, deleteFlags, killReason);
23547    }
23548
23549    public PackageFreezer freezePackageForDelete(String packageName, int userId, int deleteFlags,
23550            String killReason) {
23551        if ((deleteFlags & PackageManager.DELETE_DONT_KILL_APP) != 0) {
23552            return new PackageFreezer();
23553        } else {
23554            return freezePackage(packageName, userId, killReason);
23555        }
23556    }
23557
23558    /**
23559     * Class that freezes and kills the given package upon creation, and
23560     * unfreezes it upon closing. This is typically used when doing surgery on
23561     * app code/data to prevent the app from running while you're working.
23562     */
23563    private class PackageFreezer implements AutoCloseable {
23564        private final String mPackageName;
23565        private final PackageFreezer[] mChildren;
23566
23567        private final boolean mWeFroze;
23568
23569        private final AtomicBoolean mClosed = new AtomicBoolean();
23570        private final CloseGuard mCloseGuard = CloseGuard.get();
23571
23572        /**
23573         * Create and return a stub freezer that doesn't actually do anything,
23574         * typically used when someone requested
23575         * {@link PackageManager#INSTALL_DONT_KILL_APP} or
23576         * {@link PackageManager#DELETE_DONT_KILL_APP}.
23577         */
23578        public PackageFreezer() {
23579            mPackageName = null;
23580            mChildren = null;
23581            mWeFroze = false;
23582            mCloseGuard.open("close");
23583        }
23584
23585        public PackageFreezer(String packageName, int userId, String killReason) {
23586            synchronized (mPackages) {
23587                mPackageName = packageName;
23588                mWeFroze = mFrozenPackages.add(mPackageName);
23589
23590                final PackageSetting ps = mSettings.mPackages.get(mPackageName);
23591                if (ps != null) {
23592                    killApplication(ps.name, ps.appId, userId, killReason);
23593                }
23594
23595                final PackageParser.Package p = mPackages.get(packageName);
23596                if (p != null && p.childPackages != null) {
23597                    final int N = p.childPackages.size();
23598                    mChildren = new PackageFreezer[N];
23599                    for (int i = 0; i < N; i++) {
23600                        mChildren[i] = new PackageFreezer(p.childPackages.get(i).packageName,
23601                                userId, killReason);
23602                    }
23603                } else {
23604                    mChildren = null;
23605                }
23606            }
23607            mCloseGuard.open("close");
23608        }
23609
23610        @Override
23611        protected void finalize() throws Throwable {
23612            try {
23613                if (mCloseGuard != null) {
23614                    mCloseGuard.warnIfOpen();
23615                }
23616
23617                close();
23618            } finally {
23619                super.finalize();
23620            }
23621        }
23622
23623        @Override
23624        public void close() {
23625            mCloseGuard.close();
23626            if (mClosed.compareAndSet(false, true)) {
23627                synchronized (mPackages) {
23628                    if (mWeFroze) {
23629                        mFrozenPackages.remove(mPackageName);
23630                    }
23631
23632                    if (mChildren != null) {
23633                        for (PackageFreezer freezer : mChildren) {
23634                            freezer.close();
23635                        }
23636                    }
23637                }
23638            }
23639        }
23640    }
23641
23642    /**
23643     * Verify that given package is currently frozen.
23644     */
23645    private void checkPackageFrozen(String packageName) {
23646        synchronized (mPackages) {
23647            if (!mFrozenPackages.contains(packageName)) {
23648                Slog.wtf(TAG, "Expected " + packageName + " to be frozen!", new Throwable());
23649            }
23650        }
23651    }
23652
23653    @Override
23654    public int movePackage(final String packageName, final String volumeUuid) {
23655        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null);
23656
23657        final int callingUid = Binder.getCallingUid();
23658        final UserHandle user = new UserHandle(UserHandle.getUserId(callingUid));
23659        final int moveId = mNextMoveId.getAndIncrement();
23660        mHandler.post(new Runnable() {
23661            @Override
23662            public void run() {
23663                try {
23664                    movePackageInternal(packageName, volumeUuid, moveId, callingUid, user);
23665                } catch (PackageManagerException e) {
23666                    Slog.w(TAG, "Failed to move " + packageName, e);
23667                    mMoveCallbacks.notifyStatusChanged(moveId,
23668                            PackageManager.MOVE_FAILED_INTERNAL_ERROR);
23669                }
23670            }
23671        });
23672        return moveId;
23673    }
23674
23675    private void movePackageInternal(final String packageName, final String volumeUuid,
23676            final int moveId, final int callingUid, UserHandle user)
23677                    throws PackageManagerException {
23678        final StorageManager storage = mContext.getSystemService(StorageManager.class);
23679        final PackageManager pm = mContext.getPackageManager();
23680
23681        final boolean currentAsec;
23682        final String currentVolumeUuid;
23683        final File codeFile;
23684        final String installerPackageName;
23685        final String packageAbiOverride;
23686        final int appId;
23687        final String seinfo;
23688        final String label;
23689        final int targetSdkVersion;
23690        final PackageFreezer freezer;
23691        final int[] installedUserIds;
23692
23693        // reader
23694        synchronized (mPackages) {
23695            final PackageParser.Package pkg = mPackages.get(packageName);
23696            final PackageSetting ps = mSettings.mPackages.get(packageName);
23697            if (pkg == null
23698                    || ps == null
23699                    || filterAppAccessLPr(ps, callingUid, user.getIdentifier())) {
23700                throw new PackageManagerException(MOVE_FAILED_DOESNT_EXIST, "Missing package");
23701            }
23702            if (pkg.applicationInfo.isSystemApp()) {
23703                throw new PackageManagerException(MOVE_FAILED_SYSTEM_PACKAGE,
23704                        "Cannot move system application");
23705            }
23706
23707            final boolean isInternalStorage = VolumeInfo.ID_PRIVATE_INTERNAL.equals(volumeUuid);
23708            final boolean allow3rdPartyOnInternal = mContext.getResources().getBoolean(
23709                    com.android.internal.R.bool.config_allow3rdPartyAppOnInternal);
23710            if (isInternalStorage && !allow3rdPartyOnInternal) {
23711                throw new PackageManagerException(MOVE_FAILED_3RD_PARTY_NOT_ALLOWED_ON_INTERNAL,
23712                        "3rd party apps are not allowed on internal storage");
23713            }
23714
23715            if (pkg.applicationInfo.isExternalAsec()) {
23716                currentAsec = true;
23717                currentVolumeUuid = StorageManager.UUID_PRIMARY_PHYSICAL;
23718            } else if (pkg.applicationInfo.isForwardLocked()) {
23719                currentAsec = true;
23720                currentVolumeUuid = "forward_locked";
23721            } else {
23722                currentAsec = false;
23723                currentVolumeUuid = ps.volumeUuid;
23724
23725                final File probe = new File(pkg.codePath);
23726                final File probeOat = new File(probe, "oat");
23727                if (!probe.isDirectory() || !probeOat.isDirectory()) {
23728                    throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
23729                            "Move only supported for modern cluster style installs");
23730                }
23731            }
23732
23733            if (Objects.equals(currentVolumeUuid, volumeUuid)) {
23734                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
23735                        "Package already moved to " + volumeUuid);
23736            }
23737            if (pkg.applicationInfo.isInternal() && isPackageDeviceAdminOnAnyUser(packageName)) {
23738                throw new PackageManagerException(MOVE_FAILED_DEVICE_ADMIN,
23739                        "Device admin cannot be moved");
23740            }
23741
23742            if (mFrozenPackages.contains(packageName)) {
23743                throw new PackageManagerException(MOVE_FAILED_OPERATION_PENDING,
23744                        "Failed to move already frozen package");
23745            }
23746
23747            codeFile = new File(pkg.codePath);
23748            installerPackageName = ps.installerPackageName;
23749            packageAbiOverride = ps.cpuAbiOverrideString;
23750            appId = UserHandle.getAppId(pkg.applicationInfo.uid);
23751            seinfo = pkg.applicationInfo.seInfo;
23752            label = String.valueOf(pm.getApplicationLabel(pkg.applicationInfo));
23753            targetSdkVersion = pkg.applicationInfo.targetSdkVersion;
23754            freezer = freezePackage(packageName, "movePackageInternal");
23755            installedUserIds = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
23756        }
23757
23758        final Bundle extras = new Bundle();
23759        extras.putString(Intent.EXTRA_PACKAGE_NAME, packageName);
23760        extras.putString(Intent.EXTRA_TITLE, label);
23761        mMoveCallbacks.notifyCreated(moveId, extras);
23762
23763        int installFlags;
23764        final boolean moveCompleteApp;
23765        final File measurePath;
23766
23767        if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, volumeUuid)) {
23768            installFlags = INSTALL_INTERNAL;
23769            moveCompleteApp = !currentAsec;
23770            measurePath = Environment.getDataAppDirectory(volumeUuid);
23771        } else if (Objects.equals(StorageManager.UUID_PRIMARY_PHYSICAL, volumeUuid)) {
23772            installFlags = INSTALL_EXTERNAL;
23773            moveCompleteApp = false;
23774            measurePath = storage.getPrimaryPhysicalVolume().getPath();
23775        } else {
23776            final VolumeInfo volume = storage.findVolumeByUuid(volumeUuid);
23777            if (volume == null || volume.getType() != VolumeInfo.TYPE_PRIVATE
23778                    || !volume.isMountedWritable()) {
23779                freezer.close();
23780                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
23781                        "Move location not mounted private volume");
23782            }
23783
23784            Preconditions.checkState(!currentAsec);
23785
23786            installFlags = INSTALL_INTERNAL;
23787            moveCompleteApp = true;
23788            measurePath = Environment.getDataAppDirectory(volumeUuid);
23789        }
23790
23791        final PackageStats stats = new PackageStats(null, -1);
23792        synchronized (mInstaller) {
23793            for (int userId : installedUserIds) {
23794                if (!getPackageSizeInfoLI(packageName, userId, stats)) {
23795                    freezer.close();
23796                    throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
23797                            "Failed to measure package size");
23798                }
23799            }
23800        }
23801
23802        if (DEBUG_INSTALL) Slog.d(TAG, "Measured code size " + stats.codeSize + ", data size "
23803                + stats.dataSize);
23804
23805        final long startFreeBytes = measurePath.getUsableSpace();
23806        final long sizeBytes;
23807        if (moveCompleteApp) {
23808            sizeBytes = stats.codeSize + stats.dataSize;
23809        } else {
23810            sizeBytes = stats.codeSize;
23811        }
23812
23813        if (sizeBytes > storage.getStorageBytesUntilLow(measurePath)) {
23814            freezer.close();
23815            throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
23816                    "Not enough free space to move");
23817        }
23818
23819        mMoveCallbacks.notifyStatusChanged(moveId, 10);
23820
23821        final CountDownLatch installedLatch = new CountDownLatch(1);
23822        final IPackageInstallObserver2 installObserver = new IPackageInstallObserver2.Stub() {
23823            @Override
23824            public void onUserActionRequired(Intent intent) throws RemoteException {
23825                throw new IllegalStateException();
23826            }
23827
23828            @Override
23829            public void onPackageInstalled(String basePackageName, int returnCode, String msg,
23830                    Bundle extras) throws RemoteException {
23831                if (DEBUG_INSTALL) Slog.d(TAG, "Install result for move: "
23832                        + PackageManager.installStatusToString(returnCode, msg));
23833
23834                installedLatch.countDown();
23835                freezer.close();
23836
23837                final int status = PackageManager.installStatusToPublicStatus(returnCode);
23838                switch (status) {
23839                    case PackageInstaller.STATUS_SUCCESS:
23840                        mMoveCallbacks.notifyStatusChanged(moveId,
23841                                PackageManager.MOVE_SUCCEEDED);
23842                        break;
23843                    case PackageInstaller.STATUS_FAILURE_STORAGE:
23844                        mMoveCallbacks.notifyStatusChanged(moveId,
23845                                PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE);
23846                        break;
23847                    default:
23848                        mMoveCallbacks.notifyStatusChanged(moveId,
23849                                PackageManager.MOVE_FAILED_INTERNAL_ERROR);
23850                        break;
23851                }
23852            }
23853        };
23854
23855        final MoveInfo move;
23856        if (moveCompleteApp) {
23857            // Kick off a thread to report progress estimates
23858            new Thread() {
23859                @Override
23860                public void run() {
23861                    while (true) {
23862                        try {
23863                            if (installedLatch.await(1, TimeUnit.SECONDS)) {
23864                                break;
23865                            }
23866                        } catch (InterruptedException ignored) {
23867                        }
23868
23869                        final long deltaFreeBytes = startFreeBytes - measurePath.getUsableSpace();
23870                        final int progress = 10 + (int) MathUtils.constrain(
23871                                ((deltaFreeBytes * 80) / sizeBytes), 0, 80);
23872                        mMoveCallbacks.notifyStatusChanged(moveId, progress);
23873                    }
23874                }
23875            }.start();
23876
23877            final String dataAppName = codeFile.getName();
23878            move = new MoveInfo(moveId, currentVolumeUuid, volumeUuid, packageName,
23879                    dataAppName, appId, seinfo, targetSdkVersion);
23880        } else {
23881            move = null;
23882        }
23883
23884        installFlags |= PackageManager.INSTALL_REPLACE_EXISTING;
23885
23886        final Message msg = mHandler.obtainMessage(INIT_COPY);
23887        final OriginInfo origin = OriginInfo.fromExistingFile(codeFile);
23888        final InstallParams params = new InstallParams(origin, move, installObserver, installFlags,
23889                installerPackageName, volumeUuid, null /*verificationInfo*/, user,
23890                packageAbiOverride, null /*grantedPermissions*/, null /*certificates*/,
23891                PackageManager.INSTALL_REASON_UNKNOWN);
23892        params.setTraceMethod("movePackage").setTraceCookie(System.identityHashCode(params));
23893        msg.obj = params;
23894
23895        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "movePackage",
23896                System.identityHashCode(msg.obj));
23897        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
23898                System.identityHashCode(msg.obj));
23899
23900        mHandler.sendMessage(msg);
23901    }
23902
23903    @Override
23904    public int movePrimaryStorage(String volumeUuid) throws RemoteException {
23905        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null);
23906
23907        final int realMoveId = mNextMoveId.getAndIncrement();
23908        final Bundle extras = new Bundle();
23909        extras.putString(VolumeRecord.EXTRA_FS_UUID, volumeUuid);
23910        mMoveCallbacks.notifyCreated(realMoveId, extras);
23911
23912        final IPackageMoveObserver callback = new IPackageMoveObserver.Stub() {
23913            @Override
23914            public void onCreated(int moveId, Bundle extras) {
23915                // Ignored
23916            }
23917
23918            @Override
23919            public void onStatusChanged(int moveId, int status, long estMillis) {
23920                mMoveCallbacks.notifyStatusChanged(realMoveId, status, estMillis);
23921            }
23922        };
23923
23924        final StorageManager storage = mContext.getSystemService(StorageManager.class);
23925        storage.setPrimaryStorageUuid(volumeUuid, callback);
23926        return realMoveId;
23927    }
23928
23929    @Override
23930    public int getMoveStatus(int moveId) {
23931        mContext.enforceCallingOrSelfPermission(
23932                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
23933        return mMoveCallbacks.mLastStatus.get(moveId);
23934    }
23935
23936    @Override
23937    public void registerMoveCallback(IPackageMoveObserver callback) {
23938        mContext.enforceCallingOrSelfPermission(
23939                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
23940        mMoveCallbacks.register(callback);
23941    }
23942
23943    @Override
23944    public void unregisterMoveCallback(IPackageMoveObserver callback) {
23945        mContext.enforceCallingOrSelfPermission(
23946                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
23947        mMoveCallbacks.unregister(callback);
23948    }
23949
23950    @Override
23951    public boolean setInstallLocation(int loc) {
23952        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WRITE_SECURE_SETTINGS,
23953                null);
23954        if (getInstallLocation() == loc) {
23955            return true;
23956        }
23957        if (loc == PackageHelper.APP_INSTALL_AUTO || loc == PackageHelper.APP_INSTALL_INTERNAL
23958                || loc == PackageHelper.APP_INSTALL_EXTERNAL) {
23959            android.provider.Settings.Global.putInt(mContext.getContentResolver(),
23960                    android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, loc);
23961            return true;
23962        }
23963        return false;
23964   }
23965
23966    @Override
23967    public int getInstallLocation() {
23968        // allow instant app access
23969        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
23970                android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION,
23971                PackageHelper.APP_INSTALL_AUTO);
23972    }
23973
23974    /** Called by UserManagerService */
23975    void cleanUpUser(UserManagerService userManager, int userHandle) {
23976        synchronized (mPackages) {
23977            mDirtyUsers.remove(userHandle);
23978            mUserNeedsBadging.delete(userHandle);
23979            mSettings.removeUserLPw(userHandle);
23980            mPendingBroadcasts.remove(userHandle);
23981            mInstantAppRegistry.onUserRemovedLPw(userHandle);
23982            removeUnusedPackagesLPw(userManager, userHandle);
23983        }
23984    }
23985
23986    /**
23987     * We're removing userHandle and would like to remove any downloaded packages
23988     * that are no longer in use by any other user.
23989     * @param userHandle the user being removed
23990     */
23991    private void removeUnusedPackagesLPw(UserManagerService userManager, final int userHandle) {
23992        final boolean DEBUG_CLEAN_APKS = false;
23993        int [] users = userManager.getUserIds();
23994        Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator();
23995        while (psit.hasNext()) {
23996            PackageSetting ps = psit.next();
23997            if (ps.pkg == null) {
23998                continue;
23999            }
24000            final String packageName = ps.pkg.packageName;
24001            // Skip over if system app
24002            if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0) {
24003                continue;
24004            }
24005            if (DEBUG_CLEAN_APKS) {
24006                Slog.i(TAG, "Checking package " + packageName);
24007            }
24008            boolean keep = shouldKeepUninstalledPackageLPr(packageName);
24009            if (keep) {
24010                if (DEBUG_CLEAN_APKS) {
24011                    Slog.i(TAG, "  Keeping package " + packageName + " - requested by DO");
24012                }
24013            } else {
24014                for (int i = 0; i < users.length; i++) {
24015                    if (users[i] != userHandle && ps.getInstalled(users[i])) {
24016                        keep = true;
24017                        if (DEBUG_CLEAN_APKS) {
24018                            Slog.i(TAG, "  Keeping package " + packageName + " for user "
24019                                    + users[i]);
24020                        }
24021                        break;
24022                    }
24023                }
24024            }
24025            if (!keep) {
24026                if (DEBUG_CLEAN_APKS) {
24027                    Slog.i(TAG, "  Removing package " + packageName);
24028                }
24029                mHandler.post(new Runnable() {
24030                    public void run() {
24031                        deletePackageX(packageName, PackageManager.VERSION_CODE_HIGHEST,
24032                                userHandle, 0);
24033                    } //end run
24034                });
24035            }
24036        }
24037    }
24038
24039    /** Called by UserManagerService */
24040    void createNewUser(int userId, String[] disallowedPackages) {
24041        synchronized (mInstallLock) {
24042            mSettings.createNewUserLI(this, mInstaller, userId, disallowedPackages);
24043        }
24044        synchronized (mPackages) {
24045            scheduleWritePackageRestrictionsLocked(userId);
24046            scheduleWritePackageListLocked(userId);
24047            applyFactoryDefaultBrowserLPw(userId);
24048            primeDomainVerificationsLPw(userId);
24049        }
24050    }
24051
24052    void onNewUserCreated(final int userId) {
24053        mDefaultPermissionPolicy.grantDefaultPermissions(userId);
24054        // If permission review for legacy apps is required, we represent
24055        // dagerous permissions for such apps as always granted runtime
24056        // permissions to keep per user flag state whether review is needed.
24057        // Hence, if a new user is added we have to propagate dangerous
24058        // permission grants for these legacy apps.
24059        if (mPermissionReviewRequired) {
24060            updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL
24061                    | UPDATE_PERMISSIONS_REPLACE_ALL);
24062        }
24063    }
24064
24065    @Override
24066    public VerifierDeviceIdentity getVerifierDeviceIdentity() throws RemoteException {
24067        mContext.enforceCallingOrSelfPermission(
24068                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
24069                "Only package verification agents can read the verifier device identity");
24070
24071        synchronized (mPackages) {
24072            return mSettings.getVerifierDeviceIdentityLPw();
24073        }
24074    }
24075
24076    @Override
24077    public void setPermissionEnforced(String permission, boolean enforced) {
24078        // TODO: Now that we no longer change GID for storage, this should to away.
24079        mContext.enforceCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS,
24080                "setPermissionEnforced");
24081        if (READ_EXTERNAL_STORAGE.equals(permission)) {
24082            synchronized (mPackages) {
24083                if (mSettings.mReadExternalStorageEnforced == null
24084                        || mSettings.mReadExternalStorageEnforced != enforced) {
24085                    mSettings.mReadExternalStorageEnforced = enforced;
24086                    mSettings.writeLPr();
24087                }
24088            }
24089            // kill any non-foreground processes so we restart them and
24090            // grant/revoke the GID.
24091            final IActivityManager am = ActivityManager.getService();
24092            if (am != null) {
24093                final long token = Binder.clearCallingIdentity();
24094                try {
24095                    am.killProcessesBelowForeground("setPermissionEnforcement");
24096                } catch (RemoteException e) {
24097                } finally {
24098                    Binder.restoreCallingIdentity(token);
24099                }
24100            }
24101        } else {
24102            throw new IllegalArgumentException("No selective enforcement for " + permission);
24103        }
24104    }
24105
24106    @Override
24107    @Deprecated
24108    public boolean isPermissionEnforced(String permission) {
24109        // allow instant applications
24110        return true;
24111    }
24112
24113    @Override
24114    public boolean isStorageLow() {
24115        // allow instant applications
24116        final long token = Binder.clearCallingIdentity();
24117        try {
24118            final DeviceStorageMonitorInternal
24119                    dsm = LocalServices.getService(DeviceStorageMonitorInternal.class);
24120            if (dsm != null) {
24121                return dsm.isMemoryLow();
24122            } else {
24123                return false;
24124            }
24125        } finally {
24126            Binder.restoreCallingIdentity(token);
24127        }
24128    }
24129
24130    @Override
24131    public IPackageInstaller getPackageInstaller() {
24132        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
24133            return null;
24134        }
24135        return mInstallerService;
24136    }
24137
24138    private boolean userNeedsBadging(int userId) {
24139        int index = mUserNeedsBadging.indexOfKey(userId);
24140        if (index < 0) {
24141            final UserInfo userInfo;
24142            final long token = Binder.clearCallingIdentity();
24143            try {
24144                userInfo = sUserManager.getUserInfo(userId);
24145            } finally {
24146                Binder.restoreCallingIdentity(token);
24147            }
24148            final boolean b;
24149            if (userInfo != null && userInfo.isManagedProfile()) {
24150                b = true;
24151            } else {
24152                b = false;
24153            }
24154            mUserNeedsBadging.put(userId, b);
24155            return b;
24156        }
24157        return mUserNeedsBadging.valueAt(index);
24158    }
24159
24160    @Override
24161    public KeySet getKeySetByAlias(String packageName, String alias) {
24162        if (packageName == null || alias == null) {
24163            return null;
24164        }
24165        synchronized(mPackages) {
24166            final PackageParser.Package pkg = mPackages.get(packageName);
24167            if (pkg == null) {
24168                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
24169                throw new IllegalArgumentException("Unknown package: " + packageName);
24170            }
24171            final PackageSetting ps = (PackageSetting) pkg.mExtras;
24172            if (filterAppAccessLPr(ps, Binder.getCallingUid(), UserHandle.getCallingUserId())) {
24173                Slog.w(TAG, "KeySet requested for filtered package: " + packageName);
24174                throw new IllegalArgumentException("Unknown package: " + packageName);
24175            }
24176            KeySetManagerService ksms = mSettings.mKeySetManagerService;
24177            return new KeySet(ksms.getKeySetByAliasAndPackageNameLPr(packageName, alias));
24178        }
24179    }
24180
24181    @Override
24182    public KeySet getSigningKeySet(String packageName) {
24183        if (packageName == null) {
24184            return null;
24185        }
24186        synchronized(mPackages) {
24187            final int callingUid = Binder.getCallingUid();
24188            final int callingUserId = UserHandle.getUserId(callingUid);
24189            final PackageParser.Package pkg = mPackages.get(packageName);
24190            if (pkg == null) {
24191                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
24192                throw new IllegalArgumentException("Unknown package: " + packageName);
24193            }
24194            final PackageSetting ps = (PackageSetting) pkg.mExtras;
24195            if (filterAppAccessLPr(ps, callingUid, callingUserId)) {
24196                // filter and pretend the package doesn't exist
24197                Slog.w(TAG, "KeySet requested for filtered package: " + packageName
24198                        + ", uid:" + callingUid);
24199                throw new IllegalArgumentException("Unknown package: " + packageName);
24200            }
24201            if (pkg.applicationInfo.uid != callingUid
24202                    && Process.SYSTEM_UID != callingUid) {
24203                throw new SecurityException("May not access signing KeySet of other apps.");
24204            }
24205            KeySetManagerService ksms = mSettings.mKeySetManagerService;
24206            return new KeySet(ksms.getSigningKeySetByPackageNameLPr(packageName));
24207        }
24208    }
24209
24210    @Override
24211    public boolean isPackageSignedByKeySet(String packageName, KeySet ks) {
24212        final int callingUid = Binder.getCallingUid();
24213        if (getInstantAppPackageName(callingUid) != null) {
24214            return false;
24215        }
24216        if (packageName == null || ks == null) {
24217            return false;
24218        }
24219        synchronized(mPackages) {
24220            final PackageParser.Package pkg = mPackages.get(packageName);
24221            if (pkg == null
24222                    || filterAppAccessLPr((PackageSetting) pkg.mExtras, callingUid,
24223                            UserHandle.getUserId(callingUid))) {
24224                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
24225                throw new IllegalArgumentException("Unknown package: " + packageName);
24226            }
24227            IBinder ksh = ks.getToken();
24228            if (ksh instanceof KeySetHandle) {
24229                KeySetManagerService ksms = mSettings.mKeySetManagerService;
24230                return ksms.packageIsSignedByLPr(packageName, (KeySetHandle) ksh);
24231            }
24232            return false;
24233        }
24234    }
24235
24236    @Override
24237    public boolean isPackageSignedByKeySetExactly(String packageName, KeySet ks) {
24238        final int callingUid = Binder.getCallingUid();
24239        if (getInstantAppPackageName(callingUid) != null) {
24240            return false;
24241        }
24242        if (packageName == null || ks == null) {
24243            return false;
24244        }
24245        synchronized(mPackages) {
24246            final PackageParser.Package pkg = mPackages.get(packageName);
24247            if (pkg == null
24248                    || filterAppAccessLPr((PackageSetting) pkg.mExtras, callingUid,
24249                            UserHandle.getUserId(callingUid))) {
24250                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
24251                throw new IllegalArgumentException("Unknown package: " + packageName);
24252            }
24253            IBinder ksh = ks.getToken();
24254            if (ksh instanceof KeySetHandle) {
24255                KeySetManagerService ksms = mSettings.mKeySetManagerService;
24256                return ksms.packageIsSignedByExactlyLPr(packageName, (KeySetHandle) ksh);
24257            }
24258            return false;
24259        }
24260    }
24261
24262    private void deletePackageIfUnusedLPr(final String packageName) {
24263        PackageSetting ps = mSettings.mPackages.get(packageName);
24264        if (ps == null) {
24265            return;
24266        }
24267        if (!ps.isAnyInstalled(sUserManager.getUserIds())) {
24268            // TODO Implement atomic delete if package is unused
24269            // It is currently possible that the package will be deleted even if it is installed
24270            // after this method returns.
24271            mHandler.post(new Runnable() {
24272                public void run() {
24273                    deletePackageX(packageName, PackageManager.VERSION_CODE_HIGHEST,
24274                            0, PackageManager.DELETE_ALL_USERS);
24275                }
24276            });
24277        }
24278    }
24279
24280    /**
24281     * Check and throw if the given before/after packages would be considered a
24282     * downgrade.
24283     */
24284    private static void checkDowngrade(PackageParser.Package before, PackageInfoLite after)
24285            throws PackageManagerException {
24286        if (after.versionCode < before.mVersionCode) {
24287            throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
24288                    "Update version code " + after.versionCode + " is older than current "
24289                    + before.mVersionCode);
24290        } else if (after.versionCode == before.mVersionCode) {
24291            if (after.baseRevisionCode < before.baseRevisionCode) {
24292                throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
24293                        "Update base revision code " + after.baseRevisionCode
24294                        + " is older than current " + before.baseRevisionCode);
24295            }
24296
24297            if (!ArrayUtils.isEmpty(after.splitNames)) {
24298                for (int i = 0; i < after.splitNames.length; i++) {
24299                    final String splitName = after.splitNames[i];
24300                    final int j = ArrayUtils.indexOf(before.splitNames, splitName);
24301                    if (j != -1) {
24302                        if (after.splitRevisionCodes[i] < before.splitRevisionCodes[j]) {
24303                            throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
24304                                    "Update split " + splitName + " revision code "
24305                                    + after.splitRevisionCodes[i] + " is older than current "
24306                                    + before.splitRevisionCodes[j]);
24307                        }
24308                    }
24309                }
24310            }
24311        }
24312    }
24313
24314    private static class MoveCallbacks extends Handler {
24315        private static final int MSG_CREATED = 1;
24316        private static final int MSG_STATUS_CHANGED = 2;
24317
24318        private final RemoteCallbackList<IPackageMoveObserver>
24319                mCallbacks = new RemoteCallbackList<>();
24320
24321        private final SparseIntArray mLastStatus = new SparseIntArray();
24322
24323        public MoveCallbacks(Looper looper) {
24324            super(looper);
24325        }
24326
24327        public void register(IPackageMoveObserver callback) {
24328            mCallbacks.register(callback);
24329        }
24330
24331        public void unregister(IPackageMoveObserver callback) {
24332            mCallbacks.unregister(callback);
24333        }
24334
24335        @Override
24336        public void handleMessage(Message msg) {
24337            final SomeArgs args = (SomeArgs) msg.obj;
24338            final int n = mCallbacks.beginBroadcast();
24339            for (int i = 0; i < n; i++) {
24340                final IPackageMoveObserver callback = mCallbacks.getBroadcastItem(i);
24341                try {
24342                    invokeCallback(callback, msg.what, args);
24343                } catch (RemoteException ignored) {
24344                }
24345            }
24346            mCallbacks.finishBroadcast();
24347            args.recycle();
24348        }
24349
24350        private void invokeCallback(IPackageMoveObserver callback, int what, SomeArgs args)
24351                throws RemoteException {
24352            switch (what) {
24353                case MSG_CREATED: {
24354                    callback.onCreated(args.argi1, (Bundle) args.arg2);
24355                    break;
24356                }
24357                case MSG_STATUS_CHANGED: {
24358                    callback.onStatusChanged(args.argi1, args.argi2, (long) args.arg3);
24359                    break;
24360                }
24361            }
24362        }
24363
24364        private void notifyCreated(int moveId, Bundle extras) {
24365            Slog.v(TAG, "Move " + moveId + " created " + extras.toString());
24366
24367            final SomeArgs args = SomeArgs.obtain();
24368            args.argi1 = moveId;
24369            args.arg2 = extras;
24370            obtainMessage(MSG_CREATED, args).sendToTarget();
24371        }
24372
24373        private void notifyStatusChanged(int moveId, int status) {
24374            notifyStatusChanged(moveId, status, -1);
24375        }
24376
24377        private void notifyStatusChanged(int moveId, int status, long estMillis) {
24378            Slog.v(TAG, "Move " + moveId + " status " + status);
24379
24380            final SomeArgs args = SomeArgs.obtain();
24381            args.argi1 = moveId;
24382            args.argi2 = status;
24383            args.arg3 = estMillis;
24384            obtainMessage(MSG_STATUS_CHANGED, args).sendToTarget();
24385
24386            synchronized (mLastStatus) {
24387                mLastStatus.put(moveId, status);
24388            }
24389        }
24390    }
24391
24392    private final static class OnPermissionChangeListeners extends Handler {
24393        private static final int MSG_ON_PERMISSIONS_CHANGED = 1;
24394
24395        private final RemoteCallbackList<IOnPermissionsChangeListener> mPermissionListeners =
24396                new RemoteCallbackList<>();
24397
24398        public OnPermissionChangeListeners(Looper looper) {
24399            super(looper);
24400        }
24401
24402        @Override
24403        public void handleMessage(Message msg) {
24404            switch (msg.what) {
24405                case MSG_ON_PERMISSIONS_CHANGED: {
24406                    final int uid = msg.arg1;
24407                    handleOnPermissionsChanged(uid);
24408                } break;
24409            }
24410        }
24411
24412        public void addListenerLocked(IOnPermissionsChangeListener listener) {
24413            mPermissionListeners.register(listener);
24414
24415        }
24416
24417        public void removeListenerLocked(IOnPermissionsChangeListener listener) {
24418            mPermissionListeners.unregister(listener);
24419        }
24420
24421        public void onPermissionsChanged(int uid) {
24422            if (mPermissionListeners.getRegisteredCallbackCount() > 0) {
24423                obtainMessage(MSG_ON_PERMISSIONS_CHANGED, uid, 0).sendToTarget();
24424            }
24425        }
24426
24427        private void handleOnPermissionsChanged(int uid) {
24428            final int count = mPermissionListeners.beginBroadcast();
24429            try {
24430                for (int i = 0; i < count; i++) {
24431                    IOnPermissionsChangeListener callback = mPermissionListeners
24432                            .getBroadcastItem(i);
24433                    try {
24434                        callback.onPermissionsChanged(uid);
24435                    } catch (RemoteException e) {
24436                        Log.e(TAG, "Permission listener is dead", e);
24437                    }
24438                }
24439            } finally {
24440                mPermissionListeners.finishBroadcast();
24441            }
24442        }
24443    }
24444
24445    private class PackageManagerInternalImpl extends PackageManagerInternal {
24446        @Override
24447        public void setLocationPackagesProvider(PackagesProvider provider) {
24448            synchronized (mPackages) {
24449                mDefaultPermissionPolicy.setLocationPackagesProviderLPw(provider);
24450            }
24451        }
24452
24453        @Override
24454        public void setVoiceInteractionPackagesProvider(PackagesProvider provider) {
24455            synchronized (mPackages) {
24456                mDefaultPermissionPolicy.setVoiceInteractionPackagesProviderLPw(provider);
24457            }
24458        }
24459
24460        @Override
24461        public void setSmsAppPackagesProvider(PackagesProvider provider) {
24462            synchronized (mPackages) {
24463                mDefaultPermissionPolicy.setSmsAppPackagesProviderLPw(provider);
24464            }
24465        }
24466
24467        @Override
24468        public void setDialerAppPackagesProvider(PackagesProvider provider) {
24469            synchronized (mPackages) {
24470                mDefaultPermissionPolicy.setDialerAppPackagesProviderLPw(provider);
24471            }
24472        }
24473
24474        @Override
24475        public void setSimCallManagerPackagesProvider(PackagesProvider provider) {
24476            synchronized (mPackages) {
24477                mDefaultPermissionPolicy.setSimCallManagerPackagesProviderLPw(provider);
24478            }
24479        }
24480
24481        @Override
24482        public void setSyncAdapterPackagesprovider(SyncAdapterPackagesProvider provider) {
24483            synchronized (mPackages) {
24484                mDefaultPermissionPolicy.setSyncAdapterPackagesProviderLPw(provider);
24485            }
24486        }
24487
24488        @Override
24489        public void grantDefaultPermissionsToDefaultSmsApp(String packageName, int userId) {
24490            synchronized (mPackages) {
24491                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSmsAppLPr(
24492                        packageName, userId);
24493            }
24494        }
24495
24496        @Override
24497        public void grantDefaultPermissionsToDefaultDialerApp(String packageName, int userId) {
24498            synchronized (mPackages) {
24499                mSettings.setDefaultDialerPackageNameLPw(packageName, userId);
24500                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultDialerAppLPr(
24501                        packageName, userId);
24502            }
24503        }
24504
24505        @Override
24506        public void grantDefaultPermissionsToDefaultSimCallManager(String packageName, int userId) {
24507            synchronized (mPackages) {
24508                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSimCallManagerLPr(
24509                        packageName, userId);
24510            }
24511        }
24512
24513        @Override
24514        public void setKeepUninstalledPackages(final List<String> packageList) {
24515            Preconditions.checkNotNull(packageList);
24516            List<String> removedFromList = null;
24517            synchronized (mPackages) {
24518                if (mKeepUninstalledPackages != null) {
24519                    final int packagesCount = mKeepUninstalledPackages.size();
24520                    for (int i = 0; i < packagesCount; i++) {
24521                        String oldPackage = mKeepUninstalledPackages.get(i);
24522                        if (packageList != null && packageList.contains(oldPackage)) {
24523                            continue;
24524                        }
24525                        if (removedFromList == null) {
24526                            removedFromList = new ArrayList<>();
24527                        }
24528                        removedFromList.add(oldPackage);
24529                    }
24530                }
24531                mKeepUninstalledPackages = new ArrayList<>(packageList);
24532                if (removedFromList != null) {
24533                    final int removedCount = removedFromList.size();
24534                    for (int i = 0; i < removedCount; i++) {
24535                        deletePackageIfUnusedLPr(removedFromList.get(i));
24536                    }
24537                }
24538            }
24539        }
24540
24541        @Override
24542        public boolean isPermissionsReviewRequired(String packageName, int userId) {
24543            synchronized (mPackages) {
24544                // If we do not support permission review, done.
24545                if (!mPermissionReviewRequired) {
24546                    return false;
24547                }
24548
24549                PackageSetting packageSetting = mSettings.mPackages.get(packageName);
24550                if (packageSetting == null) {
24551                    return false;
24552                }
24553
24554                // Permission review applies only to apps not supporting the new permission model.
24555                if (packageSetting.pkg.applicationInfo.targetSdkVersion >= Build.VERSION_CODES.M) {
24556                    return false;
24557                }
24558
24559                // Legacy apps have the permission and get user consent on launch.
24560                PermissionsState permissionsState = packageSetting.getPermissionsState();
24561                return permissionsState.isPermissionReviewRequired(userId);
24562            }
24563        }
24564
24565        @Override
24566        public PackageInfo getPackageInfo(
24567                String packageName, int flags, int filterCallingUid, int userId) {
24568            return PackageManagerService.this
24569                    .getPackageInfoInternal(packageName, PackageManager.VERSION_CODE_HIGHEST,
24570                            flags, filterCallingUid, userId);
24571        }
24572
24573        @Override
24574        public ApplicationInfo getApplicationInfo(
24575                String packageName, int flags, int filterCallingUid, int userId) {
24576            return PackageManagerService.this
24577                    .getApplicationInfoInternal(packageName, flags, filterCallingUid, userId);
24578        }
24579
24580        @Override
24581        public ActivityInfo getActivityInfo(
24582                ComponentName component, int flags, int filterCallingUid, int userId) {
24583            return PackageManagerService.this
24584                    .getActivityInfoInternal(component, flags, filterCallingUid, userId);
24585        }
24586
24587        @Override
24588        public List<ResolveInfo> queryIntentActivities(
24589                Intent intent, int flags, int filterCallingUid, int userId) {
24590            final String resolvedType = intent.resolveTypeIfNeeded(mContext.getContentResolver());
24591            return PackageManagerService.this
24592                    .queryIntentActivitiesInternal(intent, resolvedType, flags, filterCallingUid,
24593                            userId, false /*resolveForStart*/);
24594        }
24595
24596        @Override
24597        public ComponentName getHomeActivitiesAsUser(List<ResolveInfo> allHomeCandidates,
24598                int userId) {
24599            return PackageManagerService.this.getHomeActivitiesAsUser(allHomeCandidates, userId);
24600        }
24601
24602        @Override
24603        public void setDeviceAndProfileOwnerPackages(
24604                int deviceOwnerUserId, String deviceOwnerPackage,
24605                SparseArray<String> profileOwnerPackages) {
24606            mProtectedPackages.setDeviceAndProfileOwnerPackages(
24607                    deviceOwnerUserId, deviceOwnerPackage, profileOwnerPackages);
24608        }
24609
24610        @Override
24611        public boolean isPackageDataProtected(int userId, String packageName) {
24612            return mProtectedPackages.isPackageDataProtected(userId, packageName);
24613        }
24614
24615        @Override
24616        public boolean isPackageEphemeral(int userId, String packageName) {
24617            synchronized (mPackages) {
24618                final PackageSetting ps = mSettings.mPackages.get(packageName);
24619                return ps != null ? ps.getInstantApp(userId) : false;
24620            }
24621        }
24622
24623        @Override
24624        public boolean wasPackageEverLaunched(String packageName, int userId) {
24625            synchronized (mPackages) {
24626                return mSettings.wasPackageEverLaunchedLPr(packageName, userId);
24627            }
24628        }
24629
24630        @Override
24631        public void grantRuntimePermission(String packageName, String name, int userId,
24632                boolean overridePolicy) {
24633            PackageManagerService.this.grantRuntimePermission(packageName, name, userId,
24634                    overridePolicy);
24635        }
24636
24637        @Override
24638        public void revokeRuntimePermission(String packageName, String name, int userId,
24639                boolean overridePolicy) {
24640            PackageManagerService.this.revokeRuntimePermission(packageName, name, userId,
24641                    overridePolicy);
24642        }
24643
24644        @Override
24645        public String getNameForUid(int uid) {
24646            return PackageManagerService.this.getNameForUid(uid);
24647        }
24648
24649        @Override
24650        public void requestInstantAppResolutionPhaseTwo(AuxiliaryResolveInfo responseObj,
24651                Intent origIntent, String resolvedType, String callingPackage,
24652                Bundle verificationBundle, int userId) {
24653            PackageManagerService.this.requestInstantAppResolutionPhaseTwo(
24654                    responseObj, origIntent, resolvedType, callingPackage, verificationBundle,
24655                    userId);
24656        }
24657
24658        @Override
24659        public void grantEphemeralAccess(int userId, Intent intent,
24660                int targetAppId, int ephemeralAppId) {
24661            synchronized (mPackages) {
24662                mInstantAppRegistry.grantInstantAccessLPw(userId, intent,
24663                        targetAppId, ephemeralAppId);
24664            }
24665        }
24666
24667        @Override
24668        public boolean isInstantAppInstallerComponent(ComponentName component) {
24669            synchronized (mPackages) {
24670                return mInstantAppInstallerActivity != null
24671                        && mInstantAppInstallerActivity.getComponentName().equals(component);
24672            }
24673        }
24674
24675        @Override
24676        public void pruneInstantApps() {
24677            mInstantAppRegistry.pruneInstantApps();
24678        }
24679
24680        @Override
24681        public String getSetupWizardPackageName() {
24682            return mSetupWizardPackage;
24683        }
24684
24685        public void setExternalSourcesPolicy(ExternalSourcesPolicy policy) {
24686            if (policy != null) {
24687                mExternalSourcesPolicy = policy;
24688            }
24689        }
24690
24691        @Override
24692        public boolean isPackagePersistent(String packageName) {
24693            synchronized (mPackages) {
24694                PackageParser.Package pkg = mPackages.get(packageName);
24695                return pkg != null
24696                        ? ((pkg.applicationInfo.flags&(ApplicationInfo.FLAG_SYSTEM
24697                                        | ApplicationInfo.FLAG_PERSISTENT)) ==
24698                                (ApplicationInfo.FLAG_SYSTEM | ApplicationInfo.FLAG_PERSISTENT))
24699                        : false;
24700            }
24701        }
24702
24703        @Override
24704        public List<PackageInfo> getOverlayPackages(int userId) {
24705            final ArrayList<PackageInfo> overlayPackages = new ArrayList<PackageInfo>();
24706            synchronized (mPackages) {
24707                for (PackageParser.Package p : mPackages.values()) {
24708                    if (p.mOverlayTarget != null) {
24709                        PackageInfo pkg = generatePackageInfo((PackageSetting)p.mExtras, 0, userId);
24710                        if (pkg != null) {
24711                            overlayPackages.add(pkg);
24712                        }
24713                    }
24714                }
24715            }
24716            return overlayPackages;
24717        }
24718
24719        @Override
24720        public List<String> getTargetPackageNames(int userId) {
24721            List<String> targetPackages = new ArrayList<>();
24722            synchronized (mPackages) {
24723                for (PackageParser.Package p : mPackages.values()) {
24724                    if (p.mOverlayTarget == null) {
24725                        targetPackages.add(p.packageName);
24726                    }
24727                }
24728            }
24729            return targetPackages;
24730        }
24731
24732        @Override
24733        public boolean setEnabledOverlayPackages(int userId, @NonNull String targetPackageName,
24734                @Nullable List<String> overlayPackageNames) {
24735            synchronized (mPackages) {
24736                if (targetPackageName == null || mPackages.get(targetPackageName) == null) {
24737                    Slog.e(TAG, "failed to find package " + targetPackageName);
24738                    return false;
24739                }
24740                ArrayList<String> overlayPaths = null;
24741                if (overlayPackageNames != null && overlayPackageNames.size() > 0) {
24742                    final int N = overlayPackageNames.size();
24743                    overlayPaths = new ArrayList<>(N);
24744                    for (int i = 0; i < N; i++) {
24745                        final String packageName = overlayPackageNames.get(i);
24746                        final PackageParser.Package pkg = mPackages.get(packageName);
24747                        if (pkg == null) {
24748                            Slog.e(TAG, "failed to find package " + packageName);
24749                            return false;
24750                        }
24751                        overlayPaths.add(pkg.baseCodePath);
24752                    }
24753                }
24754
24755                final PackageSetting ps = mSettings.mPackages.get(targetPackageName);
24756                ps.setOverlayPaths(overlayPaths, userId);
24757                return true;
24758            }
24759        }
24760
24761        @Override
24762        public ResolveInfo resolveIntent(Intent intent, String resolvedType,
24763                int flags, int userId) {
24764            return resolveIntentInternal(
24765                    intent, resolvedType, flags, userId, true /*resolveForStart*/);
24766        }
24767
24768        @Override
24769        public ResolveInfo resolveService(Intent intent, String resolvedType,
24770                int flags, int userId, int callingUid) {
24771            return resolveServiceInternal(intent, resolvedType, flags, userId, callingUid);
24772        }
24773
24774        @Override
24775        public void addIsolatedUid(int isolatedUid, int ownerUid) {
24776            synchronized (mPackages) {
24777                mIsolatedOwners.put(isolatedUid, ownerUid);
24778            }
24779        }
24780
24781        @Override
24782        public void removeIsolatedUid(int isolatedUid) {
24783            synchronized (mPackages) {
24784                mIsolatedOwners.delete(isolatedUid);
24785            }
24786        }
24787
24788        @Override
24789        public int getUidTargetSdkVersion(int uid) {
24790            synchronized (mPackages) {
24791                return getUidTargetSdkVersionLockedLPr(uid);
24792            }
24793        }
24794
24795        @Override
24796        public boolean canAccessInstantApps(int callingUid, int userId) {
24797            return PackageManagerService.this.canViewInstantApps(callingUid, userId);
24798        }
24799    }
24800
24801    @Override
24802    public void grantDefaultPermissionsToEnabledCarrierApps(String[] packageNames, int userId) {
24803        enforceSystemOrPhoneCaller("grantPermissionsToEnabledCarrierApps");
24804        synchronized (mPackages) {
24805            final long identity = Binder.clearCallingIdentity();
24806            try {
24807                mDefaultPermissionPolicy.grantDefaultPermissionsToEnabledCarrierAppsLPr(
24808                        packageNames, userId);
24809            } finally {
24810                Binder.restoreCallingIdentity(identity);
24811            }
24812        }
24813    }
24814
24815    @Override
24816    public void grantDefaultPermissionsToEnabledImsServices(String[] packageNames, int userId) {
24817        enforceSystemOrPhoneCaller("grantDefaultPermissionsToEnabledImsServices");
24818        synchronized (mPackages) {
24819            final long identity = Binder.clearCallingIdentity();
24820            try {
24821                mDefaultPermissionPolicy.grantDefaultPermissionsToEnabledImsServicesLPr(
24822                        packageNames, userId);
24823            } finally {
24824                Binder.restoreCallingIdentity(identity);
24825            }
24826        }
24827    }
24828
24829    private static void enforceSystemOrPhoneCaller(String tag) {
24830        int callingUid = Binder.getCallingUid();
24831        if (callingUid != Process.PHONE_UID && callingUid != Process.SYSTEM_UID) {
24832            throw new SecurityException(
24833                    "Cannot call " + tag + " from UID " + callingUid);
24834        }
24835    }
24836
24837    boolean isHistoricalPackageUsageAvailable() {
24838        return mPackageUsage.isHistoricalPackageUsageAvailable();
24839    }
24840
24841    /**
24842     * Return a <b>copy</b> of the collection of packages known to the package manager.
24843     * @return A copy of the values of mPackages.
24844     */
24845    Collection<PackageParser.Package> getPackages() {
24846        synchronized (mPackages) {
24847            return new ArrayList<>(mPackages.values());
24848        }
24849    }
24850
24851    /**
24852     * Logs process start information (including base APK hash) to the security log.
24853     * @hide
24854     */
24855    @Override
24856    public void logAppProcessStartIfNeeded(String processName, int uid, String seinfo,
24857            String apkFile, int pid) {
24858        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
24859            return;
24860        }
24861        if (!SecurityLog.isLoggingEnabled()) {
24862            return;
24863        }
24864        Bundle data = new Bundle();
24865        data.putLong("startTimestamp", System.currentTimeMillis());
24866        data.putString("processName", processName);
24867        data.putInt("uid", uid);
24868        data.putString("seinfo", seinfo);
24869        data.putString("apkFile", apkFile);
24870        data.putInt("pid", pid);
24871        Message msg = mProcessLoggingHandler.obtainMessage(
24872                ProcessLoggingHandler.LOG_APP_PROCESS_START_MSG);
24873        msg.setData(data);
24874        mProcessLoggingHandler.sendMessage(msg);
24875    }
24876
24877    public CompilerStats.PackageStats getCompilerPackageStats(String pkgName) {
24878        return mCompilerStats.getPackageStats(pkgName);
24879    }
24880
24881    public CompilerStats.PackageStats getOrCreateCompilerPackageStats(PackageParser.Package pkg) {
24882        return getOrCreateCompilerPackageStats(pkg.packageName);
24883    }
24884
24885    public CompilerStats.PackageStats getOrCreateCompilerPackageStats(String pkgName) {
24886        return mCompilerStats.getOrCreatePackageStats(pkgName);
24887    }
24888
24889    public void deleteCompilerPackageStats(String pkgName) {
24890        mCompilerStats.deletePackageStats(pkgName);
24891    }
24892
24893    @Override
24894    public int getInstallReason(String packageName, int userId) {
24895        final int callingUid = Binder.getCallingUid();
24896        enforceCrossUserPermission(callingUid, userId,
24897                true /* requireFullPermission */, false /* checkShell */,
24898                "get install reason");
24899        synchronized (mPackages) {
24900            final PackageSetting ps = mSettings.mPackages.get(packageName);
24901            if (filterAppAccessLPr(ps, callingUid, userId)) {
24902                return PackageManager.INSTALL_REASON_UNKNOWN;
24903            }
24904            if (ps != null) {
24905                return ps.getInstallReason(userId);
24906            }
24907        }
24908        return PackageManager.INSTALL_REASON_UNKNOWN;
24909    }
24910
24911    @Override
24912    public boolean canRequestPackageInstalls(String packageName, int userId) {
24913        return canRequestPackageInstallsInternal(packageName, 0, userId,
24914                true /* throwIfPermNotDeclared*/);
24915    }
24916
24917    private boolean canRequestPackageInstallsInternal(String packageName, int flags, int userId,
24918            boolean throwIfPermNotDeclared) {
24919        int callingUid = Binder.getCallingUid();
24920        int uid = getPackageUid(packageName, 0, userId);
24921        if (callingUid != uid && callingUid != Process.ROOT_UID
24922                && callingUid != Process.SYSTEM_UID) {
24923            throw new SecurityException(
24924                    "Caller uid " + callingUid + " does not own package " + packageName);
24925        }
24926        ApplicationInfo info = getApplicationInfo(packageName, flags, userId);
24927        if (info == null) {
24928            return false;
24929        }
24930        if (info.targetSdkVersion < Build.VERSION_CODES.O) {
24931            return false;
24932        }
24933        String appOpPermission = Manifest.permission.REQUEST_INSTALL_PACKAGES;
24934        String[] packagesDeclaringPermission = getAppOpPermissionPackages(appOpPermission);
24935        if (!ArrayUtils.contains(packagesDeclaringPermission, packageName)) {
24936            if (throwIfPermNotDeclared) {
24937                throw new SecurityException("Need to declare " + appOpPermission
24938                        + " to call this api");
24939            } else {
24940                Slog.e(TAG, "Need to declare " + appOpPermission + " to call this api");
24941                return false;
24942            }
24943        }
24944        if (sUserManager.hasUserRestriction(UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES, userId)) {
24945            return false;
24946        }
24947        if (mExternalSourcesPolicy != null) {
24948            int isTrusted = mExternalSourcesPolicy.getPackageTrustedToInstallApps(packageName, uid);
24949            if (isTrusted != PackageManagerInternal.ExternalSourcesPolicy.USER_DEFAULT) {
24950                return isTrusted == PackageManagerInternal.ExternalSourcesPolicy.USER_TRUSTED;
24951            }
24952        }
24953        return checkUidPermission(appOpPermission, uid) == PERMISSION_GRANTED;
24954    }
24955
24956    @Override
24957    public ComponentName getInstantAppResolverSettingsComponent() {
24958        return mInstantAppResolverSettingsComponent;
24959    }
24960
24961    @Override
24962    public ComponentName getInstantAppInstallerComponent() {
24963        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
24964            return null;
24965        }
24966        return mInstantAppInstallerActivity == null
24967                ? null : mInstantAppInstallerActivity.getComponentName();
24968    }
24969
24970    @Override
24971    public String getInstantAppAndroidId(String packageName, int userId) {
24972        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.ACCESS_INSTANT_APPS,
24973                "getInstantAppAndroidId");
24974        enforceCrossUserPermission(Binder.getCallingUid(), userId,
24975                true /* requireFullPermission */, false /* checkShell */,
24976                "getInstantAppAndroidId");
24977        // Make sure the target is an Instant App.
24978        if (!isInstantApp(packageName, userId)) {
24979            return null;
24980        }
24981        synchronized (mPackages) {
24982            return mInstantAppRegistry.getInstantAppAndroidIdLPw(packageName, userId);
24983        }
24984    }
24985}
24986
24987interface PackageSender {
24988    void sendPackageBroadcast(final String action, final String pkg,
24989        final Bundle extras, final int flags, final String targetPkg,
24990        final IIntentReceiver finishedReceiver, final int[] userIds);
24991    void sendPackageAddedForNewUsers(String packageName, boolean isSystem,
24992        int appId, int... userIds);
24993}
24994