PackageManagerService.java revision 2fc7c3f7e0c2f96caa9478e333e7741c82680029
1/*
2 * Copyright (C) 2006 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 *      http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17package com.android.server.pm;
18
19import static android.Manifest.permission.DELETE_PACKAGES;
20import static android.Manifest.permission.INSTALL_PACKAGES;
21import static android.Manifest.permission.READ_EXTERNAL_STORAGE;
22import static android.Manifest.permission.REQUEST_DELETE_PACKAGES;
23import static android.Manifest.permission.REQUEST_INSTALL_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_SHARED_USER_INCOMPATIBLE;
53import static android.content.pm.PackageManager.INSTALL_FAILED_TEST_ONLY;
54import static android.content.pm.PackageManager.INSTALL_FAILED_UPDATE_INCOMPATIBLE;
55import static android.content.pm.PackageManager.INSTALL_FAILED_USER_RESTRICTED;
56import static android.content.pm.PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE;
57import static android.content.pm.PackageManager.INSTALL_FORWARD_LOCK;
58import static android.content.pm.PackageManager.INSTALL_INTERNAL;
59import static android.content.pm.PackageManager.INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES;
60import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS;
61import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK;
62import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK;
63import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER;
64import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED;
65import static android.content.pm.PackageManager.MATCH_ALL;
66import static android.content.pm.PackageManager.MATCH_ANY_USER;
67import static android.content.pm.PackageManager.MATCH_DEBUG_TRIAGED_MISSING;
68import static android.content.pm.PackageManager.MATCH_DIRECT_BOOT_AWARE;
69import static android.content.pm.PackageManager.MATCH_DIRECT_BOOT_UNAWARE;
70import static android.content.pm.PackageManager.MATCH_DISABLED_COMPONENTS;
71import static android.content.pm.PackageManager.MATCH_FACTORY_ONLY;
72import static android.content.pm.PackageManager.MATCH_KNOWN_PACKAGES;
73import static android.content.pm.PackageManager.MATCH_SYSTEM_ONLY;
74import static android.content.pm.PackageManager.MATCH_UNINSTALLED_PACKAGES;
75import static android.content.pm.PackageManager.MOVE_FAILED_3RD_PARTY_NOT_ALLOWED_ON_INTERNAL;
76import static android.content.pm.PackageManager.MOVE_FAILED_DEVICE_ADMIN;
77import static android.content.pm.PackageManager.MOVE_FAILED_DOESNT_EXIST;
78import static android.content.pm.PackageManager.MOVE_FAILED_INTERNAL_ERROR;
79import static android.content.pm.PackageManager.MOVE_FAILED_OPERATION_PENDING;
80import static android.content.pm.PackageManager.MOVE_FAILED_SYSTEM_PACKAGE;
81import static android.content.pm.PackageManager.PERMISSION_DENIED;
82import static android.content.pm.PackageManager.PERMISSION_GRANTED;
83import static android.content.pm.PackageParser.PARSE_IS_PRIVILEGED;
84import static android.content.pm.PackageParser.isApkFile;
85import static android.os.Trace.TRACE_TAG_PACKAGE_MANAGER;
86import static android.system.OsConstants.O_CREAT;
87import static android.system.OsConstants.O_RDWR;
88import static com.android.internal.app.IntentForwarderActivity.FORWARD_INTENT_TO_MANAGED_PROFILE;
89import static com.android.internal.app.IntentForwarderActivity.FORWARD_INTENT_TO_PARENT;
90import static com.android.internal.content.NativeLibraryHelper.LIB64_DIR_NAME;
91import static com.android.internal.content.NativeLibraryHelper.LIB_DIR_NAME;
92import static com.android.internal.util.ArrayUtils.appendInt;
93import static com.android.server.pm.Installer.DEXOPT_PUBLIC;
94import static com.android.server.pm.InstructionSets.getAppDexInstructionSets;
95import static com.android.server.pm.InstructionSets.getDexCodeInstructionSet;
96import static com.android.server.pm.InstructionSets.getDexCodeInstructionSets;
97import static com.android.server.pm.InstructionSets.getPreferredInstructionSet;
98import static com.android.server.pm.InstructionSets.getPrimaryInstructionSet;
99import static com.android.server.pm.PackageManagerServiceCompilerMapping.getCompilerFilterForReason;
100import static com.android.server.pm.PackageManagerServiceCompilerMapping.getFullCompilerFilter;
101import static com.android.server.pm.PackageManagerServiceCompilerMapping.getNonProfileGuidedCompilerFilter;
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;
105
106import android.Manifest;
107import android.annotation.NonNull;
108import android.annotation.Nullable;
109import android.app.ActivityManager;
110import android.app.AppOpsManager;
111import android.app.IActivityManager;
112import android.app.ResourcesManager;
113import android.app.admin.IDevicePolicyManager;
114import android.app.admin.SecurityLog;
115import android.app.backup.IBackupManager;
116import android.content.BroadcastReceiver;
117import android.content.ComponentName;
118import android.content.ContentResolver;
119import android.content.Context;
120import android.content.IIntentReceiver;
121import android.content.Intent;
122import android.content.IntentFilter;
123import android.content.IntentSender;
124import android.content.IntentSender.SendIntentException;
125import android.content.ServiceConnection;
126import android.content.pm.ActivityInfo;
127import android.content.pm.ApplicationInfo;
128import android.content.pm.AppsQueryHelper;
129import android.content.pm.ChangedPackages;
130import android.content.pm.ComponentInfo;
131import android.content.pm.InstantAppInfo;
132import android.content.pm.EphemeralRequest;
133import android.content.pm.EphemeralResolveInfo;
134import android.content.pm.AuxiliaryResolveInfo;
135import android.content.pm.FallbackCategoryProvider;
136import android.content.pm.FeatureInfo;
137import android.content.pm.IOnPermissionsChangeListener;
138import android.content.pm.IPackageDataObserver;
139import android.content.pm.IPackageDeleteObserver;
140import android.content.pm.IPackageDeleteObserver2;
141import android.content.pm.IPackageInstallObserver2;
142import android.content.pm.IPackageInstaller;
143import android.content.pm.IPackageManager;
144import android.content.pm.IPackageMoveObserver;
145import android.content.pm.IPackageStatsObserver;
146import android.content.pm.InstrumentationInfo;
147import android.content.pm.IntentFilterVerificationInfo;
148import android.content.pm.KeySet;
149import android.content.pm.PackageCleanItem;
150import android.content.pm.PackageInfo;
151import android.content.pm.PackageInfoLite;
152import android.content.pm.PackageInstaller;
153import android.content.pm.PackageManager;
154import android.content.pm.PackageManager.LegacyPackageDeleteObserver;
155import android.content.pm.PackageManagerInternal;
156import android.content.pm.PackageParser;
157import android.content.pm.PackageParser.ActivityIntentInfo;
158import android.content.pm.PackageParser.PackageLite;
159import android.content.pm.PackageParser.PackageParserException;
160import android.content.pm.PackageStats;
161import android.content.pm.PackageUserState;
162import android.content.pm.ParceledListSlice;
163import android.content.pm.PermissionGroupInfo;
164import android.content.pm.PermissionInfo;
165import android.content.pm.ProviderInfo;
166import android.content.pm.ResolveInfo;
167import android.content.pm.SELinuxUtil;
168import android.content.pm.ServiceInfo;
169import android.content.pm.SharedLibraryInfo;
170import android.content.pm.Signature;
171import android.content.pm.UserInfo;
172import android.content.pm.VerifierDeviceIdentity;
173import android.content.pm.VerifierInfo;
174import android.content.pm.VersionedPackage;
175import android.content.res.Resources;
176import android.graphics.Bitmap;
177import android.hardware.display.DisplayManager;
178import android.net.Uri;
179import android.os.Binder;
180import android.os.Build;
181import android.os.Bundle;
182import android.os.Debug;
183import android.os.Environment;
184import android.os.Environment.UserEnvironment;
185import android.os.FileUtils;
186import android.os.Handler;
187import android.os.IBinder;
188import android.os.Looper;
189import android.os.Message;
190import android.os.Parcel;
191import android.os.ParcelFileDescriptor;
192import android.os.PatternMatcher;
193import android.os.Process;
194import android.os.RemoteCallbackList;
195import android.os.RemoteException;
196import android.os.ResultReceiver;
197import android.os.SELinux;
198import android.os.ServiceManager;
199import android.os.ShellCallback;
200import android.os.SystemClock;
201import android.os.SystemProperties;
202import android.os.Trace;
203import android.os.UserHandle;
204import android.os.UserManager;
205import android.os.UserManagerInternal;
206import android.os.storage.IStorageManager;
207import android.os.storage.StorageManagerInternal;
208import android.os.storage.StorageEventListener;
209import android.os.storage.StorageManager;
210import android.os.storage.VolumeInfo;
211import android.os.storage.VolumeRecord;
212import android.provider.Settings.Global;
213import android.provider.Settings.Secure;
214import android.security.KeyStore;
215import android.security.SystemKeyStore;
216import android.system.ErrnoException;
217import android.system.Os;
218import android.text.TextUtils;
219import android.text.format.DateUtils;
220import android.util.ArrayMap;
221import android.util.ArraySet;
222import android.util.Base64;
223import android.util.DisplayMetrics;
224import android.util.EventLog;
225import android.util.ExceptionUtils;
226import android.util.Log;
227import android.util.LogPrinter;
228import android.util.MathUtils;
229import android.util.PackageUtils;
230import android.util.Pair;
231import android.util.PrintStreamPrinter;
232import android.util.Slog;
233import android.util.SparseArray;
234import android.util.SparseBooleanArray;
235import android.util.SparseIntArray;
236import android.util.Xml;
237import android.util.jar.StrictJarFile;
238import android.view.Display;
239
240import com.android.internal.R;
241import com.android.internal.annotations.GuardedBy;
242import com.android.internal.app.IMediaContainerService;
243import com.android.internal.app.ResolverActivity;
244import com.android.internal.content.NativeLibraryHelper;
245import com.android.internal.content.PackageHelper;
246import com.android.internal.logging.MetricsLogger;
247import com.android.internal.logging.nano.MetricsProto.MetricsEvent;
248import com.android.internal.os.IParcelFileDescriptorFactory;
249import com.android.internal.os.RoSystemProperties;
250import com.android.internal.os.SomeArgs;
251import com.android.internal.os.Zygote;
252import com.android.internal.telephony.CarrierAppUtils;
253import com.android.internal.util.ArrayUtils;
254import com.android.internal.util.ConcurrentUtils;
255import com.android.internal.util.FastPrintWriter;
256import com.android.internal.util.FastXmlSerializer;
257import com.android.internal.util.IndentingPrintWriter;
258import com.android.internal.util.Preconditions;
259import com.android.internal.util.XmlUtils;
260import com.android.server.AttributeCache;
261import com.android.server.BackgroundDexOptJobService;
262import com.android.server.DeviceIdleController;
263import com.android.server.EventLogTags;
264import com.android.server.FgThread;
265import com.android.server.IntentResolver;
266import com.android.server.LocalServices;
267import com.android.server.ServiceThread;
268import com.android.server.SystemConfig;
269import com.android.server.SystemServerInitThreadPool;
270import com.android.server.Watchdog;
271import com.android.server.net.NetworkPolicyManagerInternal;
272import com.android.server.pm.Installer.InstallerException;
273import com.android.server.pm.PermissionsState.PermissionState;
274import com.android.server.pm.Settings.DatabaseVersion;
275import com.android.server.pm.Settings.VersionInfo;
276import com.android.server.pm.dex.DexManager;
277import com.android.server.storage.DeviceStorageMonitorInternal;
278
279import dalvik.system.CloseGuard;
280import dalvik.system.DexFile;
281import dalvik.system.VMRuntime;
282
283import libcore.io.IoUtils;
284import libcore.util.EmptyArray;
285
286import org.xmlpull.v1.XmlPullParser;
287import org.xmlpull.v1.XmlPullParserException;
288import org.xmlpull.v1.XmlSerializer;
289
290import java.io.BufferedOutputStream;
291import java.io.BufferedReader;
292import java.io.ByteArrayInputStream;
293import java.io.ByteArrayOutputStream;
294import java.io.File;
295import java.io.FileDescriptor;
296import java.io.FileInputStream;
297import java.io.FileNotFoundException;
298import java.io.FileOutputStream;
299import java.io.FileReader;
300import java.io.FilenameFilter;
301import java.io.IOException;
302import java.io.PrintWriter;
303import java.nio.charset.StandardCharsets;
304import java.security.DigestInputStream;
305import java.security.MessageDigest;
306import java.security.NoSuchAlgorithmException;
307import java.security.PublicKey;
308import java.security.SecureRandom;
309import java.security.cert.Certificate;
310import java.security.cert.CertificateEncodingException;
311import java.security.cert.CertificateException;
312import java.text.SimpleDateFormat;
313import java.util.ArrayList;
314import java.util.Arrays;
315import java.util.Collection;
316import java.util.Collections;
317import java.util.Comparator;
318import java.util.Date;
319import java.util.HashSet;
320import java.util.HashMap;
321import java.util.Iterator;
322import java.util.List;
323import java.util.Map;
324import java.util.Objects;
325import java.util.Set;
326import java.util.concurrent.CountDownLatch;
327import java.util.concurrent.Future;
328import java.util.concurrent.TimeUnit;
329import java.util.concurrent.atomic.AtomicBoolean;
330import java.util.concurrent.atomic.AtomicInteger;
331
332/**
333 * Keep track of all those APKs everywhere.
334 * <p>
335 * Internally there are two important locks:
336 * <ul>
337 * <li>{@link #mPackages} is used to guard all in-memory parsed package details
338 * and other related state. It is a fine-grained lock that should only be held
339 * momentarily, as it's one of the most contended locks in the system.
340 * <li>{@link #mInstallLock} is used to guard all {@code installd} access, whose
341 * operations typically involve heavy lifting of application data on disk. Since
342 * {@code installd} is single-threaded, and it's operations can often be slow,
343 * this lock should never be acquired while already holding {@link #mPackages}.
344 * Conversely, it's safe to acquire {@link #mPackages} momentarily while already
345 * holding {@link #mInstallLock}.
346 * </ul>
347 * Many internal methods rely on the caller to hold the appropriate locks, and
348 * this contract is expressed through method name suffixes:
349 * <ul>
350 * <li>fooLI(): the caller must hold {@link #mInstallLock}
351 * <li>fooLIF(): the caller must hold {@link #mInstallLock} and the package
352 * being modified must be frozen
353 * <li>fooLPr(): the caller must hold {@link #mPackages} for reading
354 * <li>fooLPw(): the caller must hold {@link #mPackages} for writing
355 * </ul>
356 * <p>
357 * Because this class is very central to the platform's security; please run all
358 * CTS and unit tests whenever making modifications:
359 *
360 * <pre>
361 * $ runtest -c android.content.pm.PackageManagerTests frameworks-core
362 * $ cts-tradefed run commandAndExit cts -m CtsAppSecurityHostTestCases
363 * </pre>
364 */
365public class PackageManagerService extends IPackageManager.Stub {
366    static final String TAG = "PackageManager";
367    static final boolean DEBUG_SETTINGS = false;
368    static final boolean DEBUG_PREFERRED = false;
369    static final boolean DEBUG_UPGRADE = false;
370    static final boolean DEBUG_DOMAIN_VERIFICATION = false;
371    private static final boolean DEBUG_BACKUP = false;
372    private static final boolean DEBUG_INSTALL = false;
373    private static final boolean DEBUG_REMOVE = false;
374    private static final boolean DEBUG_BROADCASTS = false;
375    private static final boolean DEBUG_SHOW_INFO = false;
376    private static final boolean DEBUG_PACKAGE_INFO = false;
377    private static final boolean DEBUG_INTENT_MATCHING = false;
378    private static final boolean DEBUG_PACKAGE_SCANNING = false;
379    private static final boolean DEBUG_VERIFY = false;
380    private static final boolean DEBUG_FILTERS = false;
381
382    // Debug output for dexopting. This is shared between PackageManagerService, OtaDexoptService
383    // and PackageDexOptimizer. All these classes have their own flag to allow switching a single
384    // user, but by default initialize to this.
385    public static final boolean DEBUG_DEXOPT = false;
386
387    private static final boolean DEBUG_ABI_SELECTION = false;
388    private static final boolean DEBUG_EPHEMERAL = Build.IS_DEBUGGABLE;
389    private static final boolean DEBUG_TRIAGED_MISSING = false;
390    private static final boolean DEBUG_APP_DATA = false;
391
392    /** REMOVE. According to Svet, this was only used to reset permissions during development. */
393    static final boolean CLEAR_RUNTIME_PERMISSIONS_ON_UPGRADE = false;
394
395    private static final boolean DISABLE_EPHEMERAL_APPS = false;
396    private static final boolean HIDE_EPHEMERAL_APIS = false;
397
398    private static final boolean ENABLE_FREE_CACHE_V2 =
399            SystemProperties.getBoolean("fw.free_cache_v2", false);
400
401    private static final int RADIO_UID = Process.PHONE_UID;
402    private static final int LOG_UID = Process.LOG_UID;
403    private static final int NFC_UID = Process.NFC_UID;
404    private static final int BLUETOOTH_UID = Process.BLUETOOTH_UID;
405    private static final int SHELL_UID = Process.SHELL_UID;
406
407    // Cap the size of permission trees that 3rd party apps can define
408    private static final int MAX_PERMISSION_TREE_FOOTPRINT = 32768;     // characters of text
409
410    // Suffix used during package installation when copying/moving
411    // package apks to install directory.
412    private static final String INSTALL_PACKAGE_SUFFIX = "-";
413
414    static final int SCAN_NO_DEX = 1<<1;
415    static final int SCAN_FORCE_DEX = 1<<2;
416    static final int SCAN_UPDATE_SIGNATURE = 1<<3;
417    static final int SCAN_NEW_INSTALL = 1<<4;
418    static final int SCAN_UPDATE_TIME = 1<<5;
419    static final int SCAN_BOOTING = 1<<6;
420    static final int SCAN_TRUSTED_OVERLAY = 1<<7;
421    static final int SCAN_DELETE_DATA_ON_FAILURES = 1<<8;
422    static final int SCAN_REPLACING = 1<<9;
423    static final int SCAN_REQUIRE_KNOWN = 1<<10;
424    static final int SCAN_MOVE = 1<<11;
425    static final int SCAN_INITIAL = 1<<12;
426    static final int SCAN_CHECK_ONLY = 1<<13;
427    static final int SCAN_DONT_KILL_APP = 1<<14;
428    static final int SCAN_IGNORE_FROZEN = 1<<15;
429    static final int SCAN_FIRST_BOOT_OR_UPGRADE = 1<<16;
430    static final int SCAN_AS_INSTANT_APP = 1<<17;
431    static final int SCAN_AS_FULL_APP = 1<<18;
432    /** Should not be with the scan flags */
433    static final int FLAGS_REMOVE_CHATTY = 1<<31;
434
435    private static final String STATIC_SHARED_LIB_DELIMITER = "_";
436
437    private static final int[] EMPTY_INT_ARRAY = new int[0];
438
439    /**
440     * Timeout (in milliseconds) after which the watchdog should declare that
441     * our handler thread is wedged.  The usual default for such things is one
442     * minute but we sometimes do very lengthy I/O operations on this thread,
443     * such as installing multi-gigabyte applications, so ours needs to be longer.
444     */
445    private static final long WATCHDOG_TIMEOUT = 1000*60*10;     // ten minutes
446
447    /**
448     * Wall-clock timeout (in milliseconds) after which we *require* that an fstrim
449     * be run on this device.  We use the value in the Settings.Global.MANDATORY_FSTRIM_INTERVAL
450     * settings entry if available, otherwise we use the hardcoded default.  If it's been
451     * more than this long since the last fstrim, we force one during the boot sequence.
452     *
453     * This backstops other fstrim scheduling:  if the device is alive at midnight+idle,
454     * one gets run at the next available charging+idle time.  This final mandatory
455     * no-fstrim check kicks in only of the other scheduling criteria is never met.
456     */
457    private static final long DEFAULT_MANDATORY_FSTRIM_INTERVAL = 3 * DateUtils.DAY_IN_MILLIS;
458
459    /**
460     * Whether verification is enabled by default.
461     */
462    private static final boolean DEFAULT_VERIFY_ENABLE = true;
463
464    /**
465     * The default maximum time to wait for the verification agent to return in
466     * milliseconds.
467     */
468    private static final long DEFAULT_VERIFICATION_TIMEOUT = 10 * 1000;
469
470    /**
471     * The default response for package verification timeout.
472     *
473     * This can be either PackageManager.VERIFICATION_ALLOW or
474     * PackageManager.VERIFICATION_REJECT.
475     */
476    private static final int DEFAULT_VERIFICATION_RESPONSE = PackageManager.VERIFICATION_ALLOW;
477
478    static final String PLATFORM_PACKAGE_NAME = "android";
479
480    static final String DEFAULT_CONTAINER_PACKAGE = "com.android.defcontainer";
481
482    static final ComponentName DEFAULT_CONTAINER_COMPONENT = new ComponentName(
483            DEFAULT_CONTAINER_PACKAGE,
484            "com.android.defcontainer.DefaultContainerService");
485
486    private static final String KILL_APP_REASON_GIDS_CHANGED =
487            "permission grant or revoke changed gids";
488
489    private static final String KILL_APP_REASON_PERMISSIONS_REVOKED =
490            "permissions revoked";
491
492    private static final String PACKAGE_MIME_TYPE = "application/vnd.android.package-archive";
493
494    private static final String PACKAGE_SCHEME = "package";
495
496    private static final String VENDOR_OVERLAY_DIR = "/vendor/overlay";
497    /**
498     * If VENDOR_OVERLAY_THEME_PROPERTY is set, search for runtime resource overlay APKs also in
499     * VENDOR_OVERLAY_DIR/<value of VENDOR_OVERLAY_THEME_PROPERTY> in addition to
500     * VENDOR_OVERLAY_DIR.
501     */
502    private static final String VENDOR_OVERLAY_THEME_PROPERTY = "ro.boot.vendor.overlay.theme";
503    /**
504     * Same as VENDOR_OVERLAY_THEME_PROPERTY, except persistent. If set will override whatever
505     * is in VENDOR_OVERLAY_THEME_PROPERTY.
506     */
507    private static final String VENDOR_OVERLAY_THEME_PERSIST_PROPERTY
508            = "persist.vendor.overlay.theme";
509
510    /** Permission grant: not grant the permission. */
511    private static final int GRANT_DENIED = 1;
512
513    /** Permission grant: grant the permission as an install permission. */
514    private static final int GRANT_INSTALL = 2;
515
516    /** Permission grant: grant the permission as a runtime one. */
517    private static final int GRANT_RUNTIME = 3;
518
519    /** Permission grant: grant as runtime a permission that was granted as an install time one. */
520    private static final int GRANT_UPGRADE = 4;
521
522    /** Canonical intent used to identify what counts as a "web browser" app */
523    private static final Intent sBrowserIntent;
524    static {
525        sBrowserIntent = new Intent();
526        sBrowserIntent.setAction(Intent.ACTION_VIEW);
527        sBrowserIntent.addCategory(Intent.CATEGORY_BROWSABLE);
528        sBrowserIntent.setData(Uri.parse("http:"));
529    }
530
531    /**
532     * The set of all protected actions [i.e. those actions for which a high priority
533     * intent filter is disallowed].
534     */
535    private static final Set<String> PROTECTED_ACTIONS = new ArraySet<>();
536    static {
537        PROTECTED_ACTIONS.add(Intent.ACTION_SEND);
538        PROTECTED_ACTIONS.add(Intent.ACTION_SENDTO);
539        PROTECTED_ACTIONS.add(Intent.ACTION_SEND_MULTIPLE);
540        PROTECTED_ACTIONS.add(Intent.ACTION_VIEW);
541    }
542
543    // Compilation reasons.
544    public static final int REASON_FIRST_BOOT = 0;
545    public static final int REASON_BOOT = 1;
546    public static final int REASON_INSTALL = 2;
547    public static final int REASON_BACKGROUND_DEXOPT = 3;
548    public static final int REASON_AB_OTA = 4;
549    public static final int REASON_NON_SYSTEM_LIBRARY = 5;
550    public static final int REASON_SHARED_APK = 6;
551    public static final int REASON_FORCED_DEXOPT = 7;
552    public static final int REASON_CORE_APP = 8;
553
554    public static final int REASON_LAST = REASON_CORE_APP;
555
556    /** All dangerous permission names in the same order as the events in MetricsEvent */
557    private static final List<String> ALL_DANGEROUS_PERMISSIONS = Arrays.asList(
558            Manifest.permission.READ_CALENDAR,
559            Manifest.permission.WRITE_CALENDAR,
560            Manifest.permission.CAMERA,
561            Manifest.permission.READ_CONTACTS,
562            Manifest.permission.WRITE_CONTACTS,
563            Manifest.permission.GET_ACCOUNTS,
564            Manifest.permission.ACCESS_FINE_LOCATION,
565            Manifest.permission.ACCESS_COARSE_LOCATION,
566            Manifest.permission.RECORD_AUDIO,
567            Manifest.permission.READ_PHONE_STATE,
568            Manifest.permission.CALL_PHONE,
569            Manifest.permission.READ_CALL_LOG,
570            Manifest.permission.WRITE_CALL_LOG,
571            Manifest.permission.ADD_VOICEMAIL,
572            Manifest.permission.USE_SIP,
573            Manifest.permission.PROCESS_OUTGOING_CALLS,
574            Manifest.permission.READ_CELL_BROADCASTS,
575            Manifest.permission.BODY_SENSORS,
576            Manifest.permission.SEND_SMS,
577            Manifest.permission.RECEIVE_SMS,
578            Manifest.permission.READ_SMS,
579            Manifest.permission.RECEIVE_WAP_PUSH,
580            Manifest.permission.RECEIVE_MMS,
581            Manifest.permission.READ_EXTERNAL_STORAGE,
582            Manifest.permission.WRITE_EXTERNAL_STORAGE,
583            Manifest.permission.READ_PHONE_NUMBER);
584
585
586    /**
587     * Version number for the package parser cache. Increment this whenever the format or
588     * extent of cached data changes. See {@code PackageParser#setCacheDir}.
589     */
590    private static final String PACKAGE_PARSER_CACHE_VERSION = "1";
591
592    /**
593     * Whether the package parser cache is enabled.
594     */
595    private static final boolean DEFAULT_PACKAGE_PARSER_CACHE_ENABLED = true;
596
597    final ServiceThread mHandlerThread;
598
599    final PackageHandler mHandler;
600
601    private final ProcessLoggingHandler mProcessLoggingHandler;
602
603    /**
604     * Messages for {@link #mHandler} that need to wait for system ready before
605     * being dispatched.
606     */
607    private ArrayList<Message> mPostSystemReadyMessages;
608
609    final int mSdkVersion = Build.VERSION.SDK_INT;
610
611    final Context mContext;
612    final boolean mFactoryTest;
613    final boolean mOnlyCore;
614    final DisplayMetrics mMetrics;
615    final int mDefParseFlags;
616    final String[] mSeparateProcesses;
617    final boolean mIsUpgrade;
618    final boolean mIsPreNUpgrade;
619    final boolean mIsPreNMR1Upgrade;
620
621    @GuardedBy("mPackages")
622    private boolean mDexOptDialogShown;
623
624    /** The location for ASEC container files on internal storage. */
625    final String mAsecInternalPath;
626
627    // Used for privilege escalation. MUST NOT BE CALLED WITH mPackages
628    // LOCK HELD.  Can be called with mInstallLock held.
629    @GuardedBy("mInstallLock")
630    final Installer mInstaller;
631
632    /** Directory where installed third-party apps stored */
633    final File mAppInstallDir;
634
635    /**
636     * Directory to which applications installed internally have their
637     * 32 bit native libraries copied.
638     */
639    private File mAppLib32InstallDir;
640
641    // Directory containing the private parts (e.g. code and non-resource assets) of forward-locked
642    // apps.
643    final File mDrmAppPrivateInstallDir;
644
645    // ----------------------------------------------------------------
646
647    // Lock for state used when installing and doing other long running
648    // operations.  Methods that must be called with this lock held have
649    // the suffix "LI".
650    final Object mInstallLock = new Object();
651
652    // ----------------------------------------------------------------
653
654    // Keys are String (package name), values are Package.  This also serves
655    // as the lock for the global state.  Methods that must be called with
656    // this lock held have the prefix "LP".
657    @GuardedBy("mPackages")
658    final ArrayMap<String, PackageParser.Package> mPackages =
659            new ArrayMap<String, PackageParser.Package>();
660
661    final ArrayMap<String, Set<String>> mKnownCodebase =
662            new ArrayMap<String, Set<String>>();
663
664    // Tracks available target package names -> overlay package paths.
665    final ArrayMap<String, ArrayMap<String, PackageParser.Package>> mOverlays =
666        new ArrayMap<String, ArrayMap<String, PackageParser.Package>>();
667
668    /**
669     * Tracks new system packages [received in an OTA] that we expect to
670     * find updated user-installed versions. Keys are package name, values
671     * are package location.
672     */
673    final private ArrayMap<String, File> mExpectingBetter = new ArrayMap<>();
674    /**
675     * Tracks high priority intent filters for protected actions. During boot, certain
676     * filter actions are protected and should never be allowed to have a high priority
677     * intent filter for them. However, there is one, and only one exception -- the
678     * setup wizard. It must be able to define a high priority intent filter for these
679     * actions to ensure there are no escapes from the wizard. We need to delay processing
680     * of these during boot as we need to look at all of the system packages in order
681     * to know which component is the setup wizard.
682     */
683    private final List<PackageParser.ActivityIntentInfo> mProtectedFilters = new ArrayList<>();
684    /**
685     * Whether or not processing protected filters should be deferred.
686     */
687    private boolean mDeferProtectedFilters = true;
688
689    /**
690     * Tracks existing system packages prior to receiving an OTA. Keys are package name.
691     */
692    final private ArraySet<String> mExistingSystemPackages = new ArraySet<>();
693    /**
694     * Whether or not system app permissions should be promoted from install to runtime.
695     */
696    boolean mPromoteSystemApps;
697
698    @GuardedBy("mPackages")
699    final Settings mSettings;
700
701    /**
702     * Set of package names that are currently "frozen", which means active
703     * surgery is being done on the code/data for that package. The platform
704     * will refuse to launch frozen packages to avoid race conditions.
705     *
706     * @see PackageFreezer
707     */
708    @GuardedBy("mPackages")
709    final ArraySet<String> mFrozenPackages = new ArraySet<>();
710
711    final ProtectedPackages mProtectedPackages;
712
713    boolean mFirstBoot;
714
715    PackageManagerInternal.ExternalSourcesPolicy mExternalSourcesPolicy;
716
717    // System configuration read by SystemConfig.
718    final int[] mGlobalGids;
719    final SparseArray<ArraySet<String>> mSystemPermissions;
720    @GuardedBy("mAvailableFeatures")
721    final ArrayMap<String, FeatureInfo> mAvailableFeatures;
722
723    // If mac_permissions.xml was found for seinfo labeling.
724    boolean mFoundPolicyFile;
725
726    private final InstantAppRegistry mInstantAppRegistry;
727
728    @GuardedBy("mPackages")
729    int mChangedPackagesSequenceNumber;
730    /**
731     * List of changed [installed, removed or updated] packages.
732     * mapping from user id -> sequence number -> package name
733     */
734    @GuardedBy("mPackages")
735    final SparseArray<SparseArray<String>> mChangedPackages = new SparseArray<>();
736    /**
737     * The sequence number of the last change to a package.
738     * mapping from user id -> package name -> sequence number
739     */
740    @GuardedBy("mPackages")
741    final SparseArray<Map<String, Integer>> mChangedPackagesSequenceNumbers = new SparseArray<>();
742
743    public static final class SharedLibraryEntry {
744        public final String path;
745        public final String apk;
746        public final SharedLibraryInfo info;
747
748        SharedLibraryEntry(String _path, String _apk, String name, int version, int type,
749                String declaringPackageName, int declaringPackageVersionCode) {
750            path = _path;
751            apk = _apk;
752            info = new SharedLibraryInfo(name, version, type, new VersionedPackage(
753                    declaringPackageName, declaringPackageVersionCode), null);
754        }
755    }
756
757    // Currently known shared libraries.
758    final ArrayMap<String, SparseArray<SharedLibraryEntry>> mSharedLibraries = new ArrayMap<>();
759    final ArrayMap<String, SparseArray<SharedLibraryEntry>> mStaticLibsByDeclaringPackage =
760            new ArrayMap<>();
761
762    // All available activities, for your resolving pleasure.
763    final ActivityIntentResolver mActivities =
764            new ActivityIntentResolver();
765
766    // All available receivers, for your resolving pleasure.
767    final ActivityIntentResolver mReceivers =
768            new ActivityIntentResolver();
769
770    // All available services, for your resolving pleasure.
771    final ServiceIntentResolver mServices = new ServiceIntentResolver();
772
773    // All available providers, for your resolving pleasure.
774    final ProviderIntentResolver mProviders = new ProviderIntentResolver();
775
776    // Mapping from provider base names (first directory in content URI codePath)
777    // to the provider information.
778    final ArrayMap<String, PackageParser.Provider> mProvidersByAuthority =
779            new ArrayMap<String, PackageParser.Provider>();
780
781    // Mapping from instrumentation class names to info about them.
782    final ArrayMap<ComponentName, PackageParser.Instrumentation> mInstrumentation =
783            new ArrayMap<ComponentName, PackageParser.Instrumentation>();
784
785    // Mapping from permission names to info about them.
786    final ArrayMap<String, PackageParser.PermissionGroup> mPermissionGroups =
787            new ArrayMap<String, PackageParser.PermissionGroup>();
788
789    // Packages whose data we have transfered into another package, thus
790    // should no longer exist.
791    final ArraySet<String> mTransferedPackages = new ArraySet<String>();
792
793    // Broadcast actions that are only available to the system.
794    final ArraySet<String> mProtectedBroadcasts = new ArraySet<String>();
795
796    /** List of packages waiting for verification. */
797    final SparseArray<PackageVerificationState> mPendingVerification
798            = new SparseArray<PackageVerificationState>();
799
800    /** Set of packages associated with each app op permission. */
801    final ArrayMap<String, ArraySet<String>> mAppOpPermissionPackages = new ArrayMap<>();
802
803    final PackageInstallerService mInstallerService;
804
805    private final PackageDexOptimizer mPackageDexOptimizer;
806    // DexManager handles the usage of dex files (e.g. secondary files, whether or not a package
807    // is used by other apps).
808    private final DexManager mDexManager;
809
810    private AtomicInteger mNextMoveId = new AtomicInteger();
811    private final MoveCallbacks mMoveCallbacks;
812
813    private final OnPermissionChangeListeners mOnPermissionChangeListeners;
814
815    // Cache of users who need badging.
816    SparseBooleanArray mUserNeedsBadging = new SparseBooleanArray();
817
818    /** Token for keys in mPendingVerification. */
819    private int mPendingVerificationToken = 0;
820
821    volatile boolean mSystemReady;
822    volatile boolean mSafeMode;
823    volatile boolean mHasSystemUidErrors;
824
825    ApplicationInfo mAndroidApplication;
826    final ActivityInfo mResolveActivity = new ActivityInfo();
827    final ResolveInfo mResolveInfo = new ResolveInfo();
828    ComponentName mResolveComponentName;
829    PackageParser.Package mPlatformPackage;
830    ComponentName mCustomResolverComponentName;
831
832    boolean mResolverReplaced = false;
833
834    private final @Nullable ComponentName mIntentFilterVerifierComponent;
835    private final @Nullable IntentFilterVerifier<ActivityIntentInfo> mIntentFilterVerifier;
836
837    private int mIntentFilterVerificationToken = 0;
838
839    /** The service connection to the ephemeral resolver */
840    final EphemeralResolverConnection mInstantAppResolverConnection;
841
842    /** Component used to install ephemeral applications */
843    ComponentName mInstantAppInstallerComponent;
844    final ActivityInfo mInstantAppInstallerActivity = new ActivityInfo();
845    final ResolveInfo mInstantAppInstallerInfo = new ResolveInfo();
846
847    final SparseArray<IntentFilterVerificationState> mIntentFilterVerificationStates
848            = new SparseArray<IntentFilterVerificationState>();
849
850    final DefaultPermissionGrantPolicy mDefaultPermissionPolicy;
851
852    // List of packages names to keep cached, even if they are uninstalled for all users
853    private List<String> mKeepUninstalledPackages;
854
855    private UserManagerInternal mUserManagerInternal;
856
857    private DeviceIdleController.LocalService mDeviceIdleController;
858
859    private File mCacheDir;
860
861    private ArraySet<String> mPrivappPermissionsViolations;
862
863    private Future<?> mPrepareAppDataFuture;
864
865    private static class IFVerificationParams {
866        PackageParser.Package pkg;
867        boolean replacing;
868        int userId;
869        int verifierUid;
870
871        public IFVerificationParams(PackageParser.Package _pkg, boolean _replacing,
872                int _userId, int _verifierUid) {
873            pkg = _pkg;
874            replacing = _replacing;
875            userId = _userId;
876            replacing = _replacing;
877            verifierUid = _verifierUid;
878        }
879    }
880
881    private interface IntentFilterVerifier<T extends IntentFilter> {
882        boolean addOneIntentFilterVerification(int verifierId, int userId, int verificationId,
883                                               T filter, String packageName);
884        void startVerifications(int userId);
885        void receiveVerificationResponse(int verificationId);
886    }
887
888    private class IntentVerifierProxy implements IntentFilterVerifier<ActivityIntentInfo> {
889        private Context mContext;
890        private ComponentName mIntentFilterVerifierComponent;
891        private ArrayList<Integer> mCurrentIntentFilterVerifications = new ArrayList<Integer>();
892
893        public IntentVerifierProxy(Context context, ComponentName verifierComponent) {
894            mContext = context;
895            mIntentFilterVerifierComponent = verifierComponent;
896        }
897
898        private String getDefaultScheme() {
899            return IntentFilter.SCHEME_HTTPS;
900        }
901
902        @Override
903        public void startVerifications(int userId) {
904            // Launch verifications requests
905            int count = mCurrentIntentFilterVerifications.size();
906            for (int n=0; n<count; n++) {
907                int verificationId = mCurrentIntentFilterVerifications.get(n);
908                final IntentFilterVerificationState ivs =
909                        mIntentFilterVerificationStates.get(verificationId);
910
911                String packageName = ivs.getPackageName();
912
913                ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters();
914                final int filterCount = filters.size();
915                ArraySet<String> domainsSet = new ArraySet<>();
916                for (int m=0; m<filterCount; m++) {
917                    PackageParser.ActivityIntentInfo filter = filters.get(m);
918                    domainsSet.addAll(filter.getHostsList());
919                }
920                synchronized (mPackages) {
921                    if (mSettings.createIntentFilterVerificationIfNeededLPw(
922                            packageName, domainsSet) != null) {
923                        scheduleWriteSettingsLocked();
924                    }
925                }
926                sendVerificationRequest(userId, verificationId, ivs);
927            }
928            mCurrentIntentFilterVerifications.clear();
929        }
930
931        private void sendVerificationRequest(int userId, int verificationId,
932                IntentFilterVerificationState ivs) {
933
934            Intent verificationIntent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION);
935            verificationIntent.putExtra(
936                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_ID,
937                    verificationId);
938            verificationIntent.putExtra(
939                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_URI_SCHEME,
940                    getDefaultScheme());
941            verificationIntent.putExtra(
942                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_HOSTS,
943                    ivs.getHostsString());
944            verificationIntent.putExtra(
945                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_PACKAGE_NAME,
946                    ivs.getPackageName());
947            verificationIntent.setComponent(mIntentFilterVerifierComponent);
948            verificationIntent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
949
950            UserHandle user = new UserHandle(userId);
951            mContext.sendBroadcastAsUser(verificationIntent, user);
952            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
953                    "Sending IntentFilter verification broadcast");
954        }
955
956        public void receiveVerificationResponse(int verificationId) {
957            IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId);
958
959            final boolean verified = ivs.isVerified();
960
961            ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters();
962            final int count = filters.size();
963            if (DEBUG_DOMAIN_VERIFICATION) {
964                Slog.i(TAG, "Received verification response " + verificationId
965                        + " for " + count + " filters, verified=" + verified);
966            }
967            for (int n=0; n<count; n++) {
968                PackageParser.ActivityIntentInfo filter = filters.get(n);
969                filter.setVerified(verified);
970
971                if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "IntentFilter " + filter.toString()
972                        + " verified with result:" + verified + " and hosts:"
973                        + ivs.getHostsString());
974            }
975
976            mIntentFilterVerificationStates.remove(verificationId);
977
978            final String packageName = ivs.getPackageName();
979            IntentFilterVerificationInfo ivi = null;
980
981            synchronized (mPackages) {
982                ivi = mSettings.getIntentFilterVerificationLPr(packageName);
983            }
984            if (ivi == null) {
985                Slog.w(TAG, "IntentFilterVerificationInfo not found for verificationId:"
986                        + verificationId + " packageName:" + packageName);
987                return;
988            }
989            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
990                    "Updating IntentFilterVerificationInfo for package " + packageName
991                            +" verificationId:" + verificationId);
992
993            synchronized (mPackages) {
994                if (verified) {
995                    ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS);
996                } else {
997                    ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK);
998                }
999                scheduleWriteSettingsLocked();
1000
1001                final int userId = ivs.getUserId();
1002                if (userId != UserHandle.USER_ALL) {
1003                    final int userStatus =
1004                            mSettings.getIntentFilterVerificationStatusLPr(packageName, userId);
1005
1006                    int updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED;
1007                    boolean needUpdate = false;
1008
1009                    // We cannot override the STATUS_ALWAYS / STATUS_NEVER states if they have
1010                    // already been set by the User thru the Disambiguation dialog
1011                    switch (userStatus) {
1012                        case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED:
1013                            if (verified) {
1014                                updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS;
1015                            } else {
1016                                updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK;
1017                            }
1018                            needUpdate = true;
1019                            break;
1020
1021                        case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK:
1022                            if (verified) {
1023                                updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS;
1024                                needUpdate = true;
1025                            }
1026                            break;
1027
1028                        default:
1029                            // Nothing to do
1030                    }
1031
1032                    if (needUpdate) {
1033                        mSettings.updateIntentFilterVerificationStatusLPw(
1034                                packageName, updatedStatus, userId);
1035                        scheduleWritePackageRestrictionsLocked(userId);
1036                    }
1037                }
1038            }
1039        }
1040
1041        @Override
1042        public boolean addOneIntentFilterVerification(int verifierUid, int userId, int verificationId,
1043                    ActivityIntentInfo filter, String packageName) {
1044            if (!hasValidDomains(filter)) {
1045                return false;
1046            }
1047            IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId);
1048            if (ivs == null) {
1049                ivs = createDomainVerificationState(verifierUid, userId, verificationId,
1050                        packageName);
1051            }
1052            if (DEBUG_DOMAIN_VERIFICATION) {
1053                Slog.d(TAG, "Adding verification filter for " + packageName + ": " + filter);
1054            }
1055            ivs.addFilter(filter);
1056            return true;
1057        }
1058
1059        private IntentFilterVerificationState createDomainVerificationState(int verifierUid,
1060                int userId, int verificationId, String packageName) {
1061            IntentFilterVerificationState ivs = new IntentFilterVerificationState(
1062                    verifierUid, userId, packageName);
1063            ivs.setPendingState();
1064            synchronized (mPackages) {
1065                mIntentFilterVerificationStates.append(verificationId, ivs);
1066                mCurrentIntentFilterVerifications.add(verificationId);
1067            }
1068            return ivs;
1069        }
1070    }
1071
1072    private static boolean hasValidDomains(ActivityIntentInfo filter) {
1073        return filter.hasCategory(Intent.CATEGORY_BROWSABLE)
1074                && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) ||
1075                        filter.hasDataScheme(IntentFilter.SCHEME_HTTPS));
1076    }
1077
1078    // Set of pending broadcasts for aggregating enable/disable of components.
1079    static class PendingPackageBroadcasts {
1080        // for each user id, a map of <package name -> components within that package>
1081        final SparseArray<ArrayMap<String, ArrayList<String>>> mUidMap;
1082
1083        public PendingPackageBroadcasts() {
1084            mUidMap = new SparseArray<ArrayMap<String, ArrayList<String>>>(2);
1085        }
1086
1087        public ArrayList<String> get(int userId, String packageName) {
1088            ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId);
1089            return packages.get(packageName);
1090        }
1091
1092        public void put(int userId, String packageName, ArrayList<String> components) {
1093            ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId);
1094            packages.put(packageName, components);
1095        }
1096
1097        public void remove(int userId, String packageName) {
1098            ArrayMap<String, ArrayList<String>> packages = mUidMap.get(userId);
1099            if (packages != null) {
1100                packages.remove(packageName);
1101            }
1102        }
1103
1104        public void remove(int userId) {
1105            mUidMap.remove(userId);
1106        }
1107
1108        public int userIdCount() {
1109            return mUidMap.size();
1110        }
1111
1112        public int userIdAt(int n) {
1113            return mUidMap.keyAt(n);
1114        }
1115
1116        public ArrayMap<String, ArrayList<String>> packagesForUserId(int userId) {
1117            return mUidMap.get(userId);
1118        }
1119
1120        public int size() {
1121            // total number of pending broadcast entries across all userIds
1122            int num = 0;
1123            for (int i = 0; i< mUidMap.size(); i++) {
1124                num += mUidMap.valueAt(i).size();
1125            }
1126            return num;
1127        }
1128
1129        public void clear() {
1130            mUidMap.clear();
1131        }
1132
1133        private ArrayMap<String, ArrayList<String>> getOrAllocate(int userId) {
1134            ArrayMap<String, ArrayList<String>> map = mUidMap.get(userId);
1135            if (map == null) {
1136                map = new ArrayMap<String, ArrayList<String>>();
1137                mUidMap.put(userId, map);
1138            }
1139            return map;
1140        }
1141    }
1142    final PendingPackageBroadcasts mPendingBroadcasts = new PendingPackageBroadcasts();
1143
1144    // Service Connection to remote media container service to copy
1145    // package uri's from external media onto secure containers
1146    // or internal storage.
1147    private IMediaContainerService mContainerService = null;
1148
1149    static final int SEND_PENDING_BROADCAST = 1;
1150    static final int MCS_BOUND = 3;
1151    static final int END_COPY = 4;
1152    static final int INIT_COPY = 5;
1153    static final int MCS_UNBIND = 6;
1154    static final int START_CLEANING_PACKAGE = 7;
1155    static final int FIND_INSTALL_LOC = 8;
1156    static final int POST_INSTALL = 9;
1157    static final int MCS_RECONNECT = 10;
1158    static final int MCS_GIVE_UP = 11;
1159    static final int UPDATED_MEDIA_STATUS = 12;
1160    static final int WRITE_SETTINGS = 13;
1161    static final int WRITE_PACKAGE_RESTRICTIONS = 14;
1162    static final int PACKAGE_VERIFIED = 15;
1163    static final int CHECK_PENDING_VERIFICATION = 16;
1164    static final int START_INTENT_FILTER_VERIFICATIONS = 17;
1165    static final int INTENT_FILTER_VERIFIED = 18;
1166    static final int WRITE_PACKAGE_LIST = 19;
1167    static final int INSTANT_APP_RESOLUTION_PHASE_TWO = 20;
1168
1169    static final int WRITE_SETTINGS_DELAY = 10*1000;  // 10 seconds
1170
1171    // Delay time in millisecs
1172    static final int BROADCAST_DELAY = 10 * 1000;
1173
1174    static UserManagerService sUserManager;
1175
1176    // Stores a list of users whose package restrictions file needs to be updated
1177    private ArraySet<Integer> mDirtyUsers = new ArraySet<Integer>();
1178
1179    final private DefaultContainerConnection mDefContainerConn =
1180            new DefaultContainerConnection();
1181    class DefaultContainerConnection implements ServiceConnection {
1182        public void onServiceConnected(ComponentName name, IBinder service) {
1183            if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceConnected");
1184            final IMediaContainerService imcs = IMediaContainerService.Stub
1185                    .asInterface(Binder.allowBlocking(service));
1186            mHandler.sendMessage(mHandler.obtainMessage(MCS_BOUND, imcs));
1187        }
1188
1189        public void onServiceDisconnected(ComponentName name) {
1190            if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceDisconnected");
1191        }
1192    }
1193
1194    // Recordkeeping of restore-after-install operations that are currently in flight
1195    // between the Package Manager and the Backup Manager
1196    static class PostInstallData {
1197        public InstallArgs args;
1198        public PackageInstalledInfo res;
1199
1200        PostInstallData(InstallArgs _a, PackageInstalledInfo _r) {
1201            args = _a;
1202            res = _r;
1203        }
1204    }
1205
1206    final SparseArray<PostInstallData> mRunningInstalls = new SparseArray<PostInstallData>();
1207    int mNextInstallToken = 1;  // nonzero; will be wrapped back to 1 when ++ overflows
1208
1209    // XML tags for backup/restore of various bits of state
1210    private static final String TAG_PREFERRED_BACKUP = "pa";
1211    private static final String TAG_DEFAULT_APPS = "da";
1212    private static final String TAG_INTENT_FILTER_VERIFICATION = "iv";
1213
1214    private static final String TAG_PERMISSION_BACKUP = "perm-grant-backup";
1215    private static final String TAG_ALL_GRANTS = "rt-grants";
1216    private static final String TAG_GRANT = "grant";
1217    private static final String ATTR_PACKAGE_NAME = "pkg";
1218
1219    private static final String TAG_PERMISSION = "perm";
1220    private static final String ATTR_PERMISSION_NAME = "name";
1221    private static final String ATTR_IS_GRANTED = "g";
1222    private static final String ATTR_USER_SET = "set";
1223    private static final String ATTR_USER_FIXED = "fixed";
1224    private static final String ATTR_REVOKE_ON_UPGRADE = "rou";
1225
1226    // System/policy permission grants are not backed up
1227    private static final int SYSTEM_RUNTIME_GRANT_MASK =
1228            FLAG_PERMISSION_POLICY_FIXED
1229            | FLAG_PERMISSION_SYSTEM_FIXED
1230            | FLAG_PERMISSION_GRANTED_BY_DEFAULT;
1231
1232    // And we back up these user-adjusted states
1233    private static final int USER_RUNTIME_GRANT_MASK =
1234            FLAG_PERMISSION_USER_SET
1235            | FLAG_PERMISSION_USER_FIXED
1236            | FLAG_PERMISSION_REVOKE_ON_UPGRADE;
1237
1238    final @Nullable String mRequiredVerifierPackage;
1239    final @NonNull String mRequiredInstallerPackage;
1240    final @NonNull String mRequiredUninstallerPackage;
1241    final @Nullable String mSetupWizardPackage;
1242    final @Nullable String mStorageManagerPackage;
1243    final @NonNull String mServicesSystemSharedLibraryPackageName;
1244    final @NonNull String mSharedSystemSharedLibraryPackageName;
1245
1246    final boolean mPermissionReviewRequired;
1247
1248    private final PackageUsage mPackageUsage = new PackageUsage();
1249    private final CompilerStats mCompilerStats = new CompilerStats();
1250
1251    class PackageHandler extends Handler {
1252        private boolean mBound = false;
1253        final ArrayList<HandlerParams> mPendingInstalls =
1254            new ArrayList<HandlerParams>();
1255
1256        private boolean connectToService() {
1257            if (DEBUG_SD_INSTALL) Log.i(TAG, "Trying to bind to" +
1258                    " DefaultContainerService");
1259            Intent service = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
1260            Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1261            if (mContext.bindServiceAsUser(service, mDefContainerConn,
1262                    Context.BIND_AUTO_CREATE, UserHandle.SYSTEM)) {
1263                Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1264                mBound = true;
1265                return true;
1266            }
1267            Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1268            return false;
1269        }
1270
1271        private void disconnectService() {
1272            mContainerService = null;
1273            mBound = false;
1274            Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1275            mContext.unbindService(mDefContainerConn);
1276            Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1277        }
1278
1279        PackageHandler(Looper looper) {
1280            super(looper);
1281        }
1282
1283        public void handleMessage(Message msg) {
1284            try {
1285                doHandleMessage(msg);
1286            } finally {
1287                Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1288            }
1289        }
1290
1291        void doHandleMessage(Message msg) {
1292            switch (msg.what) {
1293                case INIT_COPY: {
1294                    HandlerParams params = (HandlerParams) msg.obj;
1295                    int idx = mPendingInstalls.size();
1296                    if (DEBUG_INSTALL) Slog.i(TAG, "init_copy idx=" + idx + ": " + params);
1297                    // If a bind was already initiated we dont really
1298                    // need to do anything. The pending install
1299                    // will be processed later on.
1300                    if (!mBound) {
1301                        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS",
1302                                System.identityHashCode(mHandler));
1303                        // If this is the only one pending we might
1304                        // have to bind to the service again.
1305                        if (!connectToService()) {
1306                            Slog.e(TAG, "Failed to bind to media container service");
1307                            params.serviceError();
1308                            Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS",
1309                                    System.identityHashCode(mHandler));
1310                            if (params.traceMethod != null) {
1311                                Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, params.traceMethod,
1312                                        params.traceCookie);
1313                            }
1314                            return;
1315                        } else {
1316                            // Once we bind to the service, the first
1317                            // pending request will be processed.
1318                            mPendingInstalls.add(idx, params);
1319                        }
1320                    } else {
1321                        mPendingInstalls.add(idx, params);
1322                        // Already bound to the service. Just make
1323                        // sure we trigger off processing the first request.
1324                        if (idx == 0) {
1325                            mHandler.sendEmptyMessage(MCS_BOUND);
1326                        }
1327                    }
1328                    break;
1329                }
1330                case MCS_BOUND: {
1331                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_bound");
1332                    if (msg.obj != null) {
1333                        mContainerService = (IMediaContainerService) msg.obj;
1334                        Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS",
1335                                System.identityHashCode(mHandler));
1336                    }
1337                    if (mContainerService == null) {
1338                        if (!mBound) {
1339                            // Something seriously wrong since we are not bound and we are not
1340                            // waiting for connection. Bail out.
1341                            Slog.e(TAG, "Cannot bind to media container service");
1342                            for (HandlerParams params : mPendingInstalls) {
1343                                // Indicate service bind error
1344                                params.serviceError();
1345                                Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1346                                        System.identityHashCode(params));
1347                                if (params.traceMethod != null) {
1348                                    Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER,
1349                                            params.traceMethod, params.traceCookie);
1350                                }
1351                                return;
1352                            }
1353                            mPendingInstalls.clear();
1354                        } else {
1355                            Slog.w(TAG, "Waiting to connect to media container service");
1356                        }
1357                    } else if (mPendingInstalls.size() > 0) {
1358                        HandlerParams params = mPendingInstalls.get(0);
1359                        if (params != null) {
1360                            Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1361                                    System.identityHashCode(params));
1362                            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "startCopy");
1363                            if (params.startCopy()) {
1364                                // We are done...  look for more work or to
1365                                // go idle.
1366                                if (DEBUG_SD_INSTALL) Log.i(TAG,
1367                                        "Checking for more work or unbind...");
1368                                // Delete pending install
1369                                if (mPendingInstalls.size() > 0) {
1370                                    mPendingInstalls.remove(0);
1371                                }
1372                                if (mPendingInstalls.size() == 0) {
1373                                    if (mBound) {
1374                                        if (DEBUG_SD_INSTALL) Log.i(TAG,
1375                                                "Posting delayed MCS_UNBIND");
1376                                        removeMessages(MCS_UNBIND);
1377                                        Message ubmsg = obtainMessage(MCS_UNBIND);
1378                                        // Unbind after a little delay, to avoid
1379                                        // continual thrashing.
1380                                        sendMessageDelayed(ubmsg, 10000);
1381                                    }
1382                                } else {
1383                                    // There are more pending requests in queue.
1384                                    // Just post MCS_BOUND message to trigger processing
1385                                    // of next pending install.
1386                                    if (DEBUG_SD_INSTALL) Log.i(TAG,
1387                                            "Posting MCS_BOUND for next work");
1388                                    mHandler.sendEmptyMessage(MCS_BOUND);
1389                                }
1390                            }
1391                            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
1392                        }
1393                    } else {
1394                        // Should never happen ideally.
1395                        Slog.w(TAG, "Empty queue");
1396                    }
1397                    break;
1398                }
1399                case MCS_RECONNECT: {
1400                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_reconnect");
1401                    if (mPendingInstalls.size() > 0) {
1402                        if (mBound) {
1403                            disconnectService();
1404                        }
1405                        if (!connectToService()) {
1406                            Slog.e(TAG, "Failed to bind to media container service");
1407                            for (HandlerParams params : mPendingInstalls) {
1408                                // Indicate service bind error
1409                                params.serviceError();
1410                                Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1411                                        System.identityHashCode(params));
1412                            }
1413                            mPendingInstalls.clear();
1414                        }
1415                    }
1416                    break;
1417                }
1418                case MCS_UNBIND: {
1419                    // If there is no actual work left, then time to unbind.
1420                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_unbind");
1421
1422                    if (mPendingInstalls.size() == 0 && mPendingVerification.size() == 0) {
1423                        if (mBound) {
1424                            if (DEBUG_INSTALL) Slog.i(TAG, "calling disconnectService()");
1425
1426                            disconnectService();
1427                        }
1428                    } else if (mPendingInstalls.size() > 0) {
1429                        // There are more pending requests in queue.
1430                        // Just post MCS_BOUND message to trigger processing
1431                        // of next pending install.
1432                        mHandler.sendEmptyMessage(MCS_BOUND);
1433                    }
1434
1435                    break;
1436                }
1437                case MCS_GIVE_UP: {
1438                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_giveup too many retries");
1439                    HandlerParams params = mPendingInstalls.remove(0);
1440                    Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1441                            System.identityHashCode(params));
1442                    break;
1443                }
1444                case SEND_PENDING_BROADCAST: {
1445                    String packages[];
1446                    ArrayList<String> components[];
1447                    int size = 0;
1448                    int uids[];
1449                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1450                    synchronized (mPackages) {
1451                        if (mPendingBroadcasts == null) {
1452                            return;
1453                        }
1454                        size = mPendingBroadcasts.size();
1455                        if (size <= 0) {
1456                            // Nothing to be done. Just return
1457                            return;
1458                        }
1459                        packages = new String[size];
1460                        components = new ArrayList[size];
1461                        uids = new int[size];
1462                        int i = 0;  // filling out the above arrays
1463
1464                        for (int n = 0; n < mPendingBroadcasts.userIdCount(); n++) {
1465                            int packageUserId = mPendingBroadcasts.userIdAt(n);
1466                            Iterator<Map.Entry<String, ArrayList<String>>> it
1467                                    = mPendingBroadcasts.packagesForUserId(packageUserId)
1468                                            .entrySet().iterator();
1469                            while (it.hasNext() && i < size) {
1470                                Map.Entry<String, ArrayList<String>> ent = it.next();
1471                                packages[i] = ent.getKey();
1472                                components[i] = ent.getValue();
1473                                PackageSetting ps = mSettings.mPackages.get(ent.getKey());
1474                                uids[i] = (ps != null)
1475                                        ? UserHandle.getUid(packageUserId, ps.appId)
1476                                        : -1;
1477                                i++;
1478                            }
1479                        }
1480                        size = i;
1481                        mPendingBroadcasts.clear();
1482                    }
1483                    // Send broadcasts
1484                    for (int i = 0; i < size; i++) {
1485                        sendPackageChangedBroadcast(packages[i], true, components[i], uids[i]);
1486                    }
1487                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1488                    break;
1489                }
1490                case START_CLEANING_PACKAGE: {
1491                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1492                    final String packageName = (String)msg.obj;
1493                    final int userId = msg.arg1;
1494                    final boolean andCode = msg.arg2 != 0;
1495                    synchronized (mPackages) {
1496                        if (userId == UserHandle.USER_ALL) {
1497                            int[] users = sUserManager.getUserIds();
1498                            for (int user : users) {
1499                                mSettings.addPackageToCleanLPw(
1500                                        new PackageCleanItem(user, packageName, andCode));
1501                            }
1502                        } else {
1503                            mSettings.addPackageToCleanLPw(
1504                                    new PackageCleanItem(userId, packageName, andCode));
1505                        }
1506                    }
1507                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1508                    startCleaningPackages();
1509                } break;
1510                case POST_INSTALL: {
1511                    if (DEBUG_INSTALL) Log.v(TAG, "Handling post-install for " + msg.arg1);
1512
1513                    PostInstallData data = mRunningInstalls.get(msg.arg1);
1514                    final boolean didRestore = (msg.arg2 != 0);
1515                    mRunningInstalls.delete(msg.arg1);
1516
1517                    if (data != null) {
1518                        InstallArgs args = data.args;
1519                        PackageInstalledInfo parentRes = data.res;
1520
1521                        final boolean grantPermissions = (args.installFlags
1522                                & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0;
1523                        final boolean killApp = (args.installFlags
1524                                & PackageManager.INSTALL_DONT_KILL_APP) == 0;
1525                        final String[] grantedPermissions = args.installGrantPermissions;
1526
1527                        // Handle the parent package
1528                        handlePackagePostInstall(parentRes, grantPermissions, killApp,
1529                                grantedPermissions, didRestore, args.installerPackageName,
1530                                args.observer);
1531
1532                        // Handle the child packages
1533                        final int childCount = (parentRes.addedChildPackages != null)
1534                                ? parentRes.addedChildPackages.size() : 0;
1535                        for (int i = 0; i < childCount; i++) {
1536                            PackageInstalledInfo childRes = parentRes.addedChildPackages.valueAt(i);
1537                            handlePackagePostInstall(childRes, grantPermissions, killApp,
1538                                    grantedPermissions, false, args.installerPackageName,
1539                                    args.observer);
1540                        }
1541
1542                        // Log tracing if needed
1543                        if (args.traceMethod != null) {
1544                            Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, args.traceMethod,
1545                                    args.traceCookie);
1546                        }
1547                    } else {
1548                        Slog.e(TAG, "Bogus post-install token " + msg.arg1);
1549                    }
1550
1551                    Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "postInstall", msg.arg1);
1552                } break;
1553                case UPDATED_MEDIA_STATUS: {
1554                    if (DEBUG_SD_INSTALL) Log.i(TAG, "Got message UPDATED_MEDIA_STATUS");
1555                    boolean reportStatus = msg.arg1 == 1;
1556                    boolean doGc = msg.arg2 == 1;
1557                    if (DEBUG_SD_INSTALL) Log.i(TAG, "reportStatus=" + reportStatus + ", doGc = " + doGc);
1558                    if (doGc) {
1559                        // Force a gc to clear up stale containers.
1560                        Runtime.getRuntime().gc();
1561                    }
1562                    if (msg.obj != null) {
1563                        @SuppressWarnings("unchecked")
1564                        Set<AsecInstallArgs> args = (Set<AsecInstallArgs>) msg.obj;
1565                        if (DEBUG_SD_INSTALL) Log.i(TAG, "Unloading all containers");
1566                        // Unload containers
1567                        unloadAllContainers(args);
1568                    }
1569                    if (reportStatus) {
1570                        try {
1571                            if (DEBUG_SD_INSTALL) Log.i(TAG,
1572                                    "Invoking StorageManagerService call back");
1573                            PackageHelper.getStorageManager().finishMediaUpdate();
1574                        } catch (RemoteException e) {
1575                            Log.e(TAG, "StorageManagerService not running?");
1576                        }
1577                    }
1578                } break;
1579                case WRITE_SETTINGS: {
1580                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1581                    synchronized (mPackages) {
1582                        removeMessages(WRITE_SETTINGS);
1583                        removeMessages(WRITE_PACKAGE_RESTRICTIONS);
1584                        mSettings.writeLPr();
1585                        mDirtyUsers.clear();
1586                    }
1587                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1588                } break;
1589                case WRITE_PACKAGE_RESTRICTIONS: {
1590                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1591                    synchronized (mPackages) {
1592                        removeMessages(WRITE_PACKAGE_RESTRICTIONS);
1593                        for (int userId : mDirtyUsers) {
1594                            mSettings.writePackageRestrictionsLPr(userId);
1595                        }
1596                        mDirtyUsers.clear();
1597                    }
1598                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1599                } break;
1600                case WRITE_PACKAGE_LIST: {
1601                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1602                    synchronized (mPackages) {
1603                        removeMessages(WRITE_PACKAGE_LIST);
1604                        mSettings.writePackageListLPr(msg.arg1);
1605                    }
1606                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1607                } break;
1608                case CHECK_PENDING_VERIFICATION: {
1609                    final int verificationId = msg.arg1;
1610                    final PackageVerificationState state = mPendingVerification.get(verificationId);
1611
1612                    if ((state != null) && !state.timeoutExtended()) {
1613                        final InstallArgs args = state.getInstallArgs();
1614                        final Uri originUri = Uri.fromFile(args.origin.resolvedFile);
1615
1616                        Slog.i(TAG, "Verification timed out for " + originUri);
1617                        mPendingVerification.remove(verificationId);
1618
1619                        int ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
1620
1621                        if (getDefaultVerificationResponse() == PackageManager.VERIFICATION_ALLOW) {
1622                            Slog.i(TAG, "Continuing with installation of " + originUri);
1623                            state.setVerifierResponse(Binder.getCallingUid(),
1624                                    PackageManager.VERIFICATION_ALLOW_WITHOUT_SUFFICIENT);
1625                            broadcastPackageVerified(verificationId, originUri,
1626                                    PackageManager.VERIFICATION_ALLOW,
1627                                    state.getInstallArgs().getUser());
1628                            try {
1629                                ret = args.copyApk(mContainerService, true);
1630                            } catch (RemoteException e) {
1631                                Slog.e(TAG, "Could not contact the ContainerService");
1632                            }
1633                        } else {
1634                            broadcastPackageVerified(verificationId, originUri,
1635                                    PackageManager.VERIFICATION_REJECT,
1636                                    state.getInstallArgs().getUser());
1637                        }
1638
1639                        Trace.asyncTraceEnd(
1640                                TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId);
1641
1642                        processPendingInstall(args, ret);
1643                        mHandler.sendEmptyMessage(MCS_UNBIND);
1644                    }
1645                    break;
1646                }
1647                case PACKAGE_VERIFIED: {
1648                    final int verificationId = msg.arg1;
1649
1650                    final PackageVerificationState state = mPendingVerification.get(verificationId);
1651                    if (state == null) {
1652                        Slog.w(TAG, "Invalid verification token " + verificationId + " received");
1653                        break;
1654                    }
1655
1656                    final PackageVerificationResponse response = (PackageVerificationResponse) msg.obj;
1657
1658                    state.setVerifierResponse(response.callerUid, response.code);
1659
1660                    if (state.isVerificationComplete()) {
1661                        mPendingVerification.remove(verificationId);
1662
1663                        final InstallArgs args = state.getInstallArgs();
1664                        final Uri originUri = Uri.fromFile(args.origin.resolvedFile);
1665
1666                        int ret;
1667                        if (state.isInstallAllowed()) {
1668                            ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
1669                            broadcastPackageVerified(verificationId, originUri,
1670                                    response.code, state.getInstallArgs().getUser());
1671                            try {
1672                                ret = args.copyApk(mContainerService, true);
1673                            } catch (RemoteException e) {
1674                                Slog.e(TAG, "Could not contact the ContainerService");
1675                            }
1676                        } else {
1677                            ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
1678                        }
1679
1680                        Trace.asyncTraceEnd(
1681                                TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId);
1682
1683                        processPendingInstall(args, ret);
1684                        mHandler.sendEmptyMessage(MCS_UNBIND);
1685                    }
1686
1687                    break;
1688                }
1689                case START_INTENT_FILTER_VERIFICATIONS: {
1690                    IFVerificationParams params = (IFVerificationParams) msg.obj;
1691                    verifyIntentFiltersIfNeeded(params.userId, params.verifierUid,
1692                            params.replacing, params.pkg);
1693                    break;
1694                }
1695                case INTENT_FILTER_VERIFIED: {
1696                    final int verificationId = msg.arg1;
1697
1698                    final IntentFilterVerificationState state = mIntentFilterVerificationStates.get(
1699                            verificationId);
1700                    if (state == null) {
1701                        Slog.w(TAG, "Invalid IntentFilter verification token "
1702                                + verificationId + " received");
1703                        break;
1704                    }
1705
1706                    final int userId = state.getUserId();
1707
1708                    if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1709                            "Processing IntentFilter verification with token:"
1710                            + verificationId + " and userId:" + userId);
1711
1712                    final IntentFilterVerificationResponse response =
1713                            (IntentFilterVerificationResponse) msg.obj;
1714
1715                    state.setVerifierResponse(response.callerUid, response.code);
1716
1717                    if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1718                            "IntentFilter verification with token:" + verificationId
1719                            + " and userId:" + userId
1720                            + " is settings verifier response with response code:"
1721                            + response.code);
1722
1723                    if (response.code == PackageManager.INTENT_FILTER_VERIFICATION_FAILURE) {
1724                        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Domains failing verification: "
1725                                + response.getFailedDomainsString());
1726                    }
1727
1728                    if (state.isVerificationComplete()) {
1729                        mIntentFilterVerifier.receiveVerificationResponse(verificationId);
1730                    } else {
1731                        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1732                                "IntentFilter verification with token:" + verificationId
1733                                + " was not said to be complete");
1734                    }
1735
1736                    break;
1737                }
1738                case INSTANT_APP_RESOLUTION_PHASE_TWO: {
1739                    EphemeralResolver.doEphemeralResolutionPhaseTwo(mContext,
1740                            mInstantAppResolverConnection,
1741                            (EphemeralRequest) msg.obj,
1742                            mInstantAppInstallerActivity,
1743                            mHandler);
1744                }
1745            }
1746        }
1747    }
1748
1749    private void handlePackagePostInstall(PackageInstalledInfo res, boolean grantPermissions,
1750            boolean killApp, String[] grantedPermissions,
1751            boolean launchedForRestore, String installerPackage,
1752            IPackageInstallObserver2 installObserver) {
1753        if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
1754            // Send the removed broadcasts
1755            if (res.removedInfo != null) {
1756                res.removedInfo.sendPackageRemovedBroadcasts(killApp);
1757            }
1758
1759            // Now that we successfully installed the package, grant runtime
1760            // permissions if requested before broadcasting the install. Also
1761            // for legacy apps in permission review mode we clear the permission
1762            // review flag which is used to emulate runtime permissions for
1763            // legacy apps.
1764            if (grantPermissions) {
1765                grantRequestedRuntimePermissions(res.pkg, res.newUsers, grantedPermissions);
1766            }
1767
1768            final boolean update = res.removedInfo != null
1769                    && res.removedInfo.removedPackage != null;
1770
1771            // If this is the first time we have child packages for a disabled privileged
1772            // app that had no children, we grant requested runtime permissions to the new
1773            // children if the parent on the system image had them already granted.
1774            if (res.pkg.parentPackage != null) {
1775                synchronized (mPackages) {
1776                    grantRuntimePermissionsGrantedToDisabledPrivSysPackageParentLPw(res.pkg);
1777                }
1778            }
1779
1780            synchronized (mPackages) {
1781                mInstantAppRegistry.onPackageInstalledLPw(res.pkg, res.newUsers);
1782            }
1783
1784            final String packageName = res.pkg.applicationInfo.packageName;
1785
1786            // Determine the set of users who are adding this package for
1787            // the first time vs. those who are seeing an update.
1788            int[] firstUsers = EMPTY_INT_ARRAY;
1789            int[] updateUsers = EMPTY_INT_ARRAY;
1790            final boolean allNewUsers = res.origUsers == null || res.origUsers.length == 0;
1791            final PackageSetting ps = (PackageSetting) res.pkg.mExtras;
1792            for (int newUser : res.newUsers) {
1793                if (ps.getInstantApp(newUser)) {
1794                    continue;
1795                }
1796                if (allNewUsers) {
1797                    firstUsers = ArrayUtils.appendInt(firstUsers, newUser);
1798                    continue;
1799                }
1800                boolean isNew = true;
1801                for (int origUser : res.origUsers) {
1802                    if (origUser == newUser) {
1803                        isNew = false;
1804                        break;
1805                    }
1806                }
1807                if (isNew) {
1808                    firstUsers = ArrayUtils.appendInt(firstUsers, newUser);
1809                } else {
1810                    updateUsers = ArrayUtils.appendInt(updateUsers, newUser);
1811                }
1812            }
1813
1814            // Send installed broadcasts if the package is not a static shared lib.
1815            if (res.pkg.staticSharedLibName == null) {
1816                mProcessLoggingHandler.invalidateProcessLoggingBaseApkHash(res.pkg.baseCodePath);
1817
1818                // Send added for users that see the package for the first time
1819                // sendPackageAddedForNewUsers also deals with system apps
1820                int appId = UserHandle.getAppId(res.uid);
1821                boolean isSystem = res.pkg.applicationInfo.isSystemApp();
1822                sendPackageAddedForNewUsers(packageName, isSystem, appId, firstUsers);
1823
1824                // Send added for users that don't see the package for the first time
1825                Bundle extras = new Bundle(1);
1826                extras.putInt(Intent.EXTRA_UID, res.uid);
1827                if (update) {
1828                    extras.putBoolean(Intent.EXTRA_REPLACING, true);
1829                }
1830                sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName,
1831                        extras, 0 /*flags*/, null /*targetPackage*/,
1832                        null /*finishedReceiver*/, updateUsers);
1833
1834                // Send replaced for users that don't see the package for the first time
1835                if (update) {
1836                    sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED,
1837                            packageName, extras, 0 /*flags*/,
1838                            null /*targetPackage*/, null /*finishedReceiver*/,
1839                            updateUsers);
1840                    sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED,
1841                            null /*package*/, null /*extras*/, 0 /*flags*/,
1842                            packageName /*targetPackage*/,
1843                            null /*finishedReceiver*/, updateUsers);
1844                } else if (launchedForRestore && !isSystemApp(res.pkg)) {
1845                    // First-install and we did a restore, so we're responsible for the
1846                    // first-launch broadcast.
1847                    if (DEBUG_BACKUP) {
1848                        Slog.i(TAG, "Post-restore of " + packageName
1849                                + " sending FIRST_LAUNCH in " + Arrays.toString(firstUsers));
1850                    }
1851                    sendFirstLaunchBroadcast(packageName, installerPackage, firstUsers);
1852                }
1853
1854                // Send broadcast package appeared if forward locked/external for all users
1855                // treat asec-hosted packages like removable media on upgrade
1856                if (res.pkg.isForwardLocked() || isExternal(res.pkg)) {
1857                    if (DEBUG_INSTALL) {
1858                        Slog.i(TAG, "upgrading pkg " + res.pkg
1859                                + " is ASEC-hosted -> AVAILABLE");
1860                    }
1861                    final int[] uidArray = new int[]{res.pkg.applicationInfo.uid};
1862                    ArrayList<String> pkgList = new ArrayList<>(1);
1863                    pkgList.add(packageName);
1864                    sendResourcesChangedBroadcast(true, true, pkgList, uidArray, null);
1865                }
1866            }
1867
1868            // Work that needs to happen on first install within each user
1869            if (firstUsers != null && firstUsers.length > 0) {
1870                synchronized (mPackages) {
1871                    for (int userId : firstUsers) {
1872                        // If this app is a browser and it's newly-installed for some
1873                        // users, clear any default-browser state in those users. The
1874                        // app's nature doesn't depend on the user, so we can just check
1875                        // its browser nature in any user and generalize.
1876                        if (packageIsBrowser(packageName, userId)) {
1877                            mSettings.setDefaultBrowserPackageNameLPw(null, userId);
1878                        }
1879
1880                        // We may also need to apply pending (restored) runtime
1881                        // permission grants within these users.
1882                        mSettings.applyPendingPermissionGrantsLPw(packageName, userId);
1883                    }
1884                }
1885            }
1886
1887            // Log current value of "unknown sources" setting
1888            EventLog.writeEvent(EventLogTags.UNKNOWN_SOURCES_ENABLED,
1889                    getUnknownSourcesSettings());
1890
1891            // Force a gc to clear up things
1892            Runtime.getRuntime().gc();
1893
1894            // Remove the replaced package's older resources safely now
1895            // We delete after a gc for applications  on sdcard.
1896            if (res.removedInfo != null && res.removedInfo.args != null) {
1897                synchronized (mInstallLock) {
1898                    res.removedInfo.args.doPostDeleteLI(true);
1899                }
1900            }
1901
1902            // Notify DexManager that the package was installed for new users.
1903            // The updated users should already be indexed and the package code paths
1904            // should not change.
1905            // Don't notify the manager for ephemeral apps as they are not expected to
1906            // survive long enough to benefit of background optimizations.
1907            for (int userId : firstUsers) {
1908                PackageInfo info = getPackageInfo(packageName, /*flags*/ 0, userId);
1909                mDexManager.notifyPackageInstalled(info, userId);
1910            }
1911        }
1912
1913        // If someone is watching installs - notify them
1914        if (installObserver != null) {
1915            try {
1916                Bundle extras = extrasForInstallResult(res);
1917                installObserver.onPackageInstalled(res.name, res.returnCode,
1918                        res.returnMsg, extras);
1919            } catch (RemoteException e) {
1920                Slog.i(TAG, "Observer no longer exists.");
1921            }
1922        }
1923    }
1924
1925    private void grantRuntimePermissionsGrantedToDisabledPrivSysPackageParentLPw(
1926            PackageParser.Package pkg) {
1927        if (pkg.parentPackage == null) {
1928            return;
1929        }
1930        if (pkg.requestedPermissions == null) {
1931            return;
1932        }
1933        final PackageSetting disabledSysParentPs = mSettings
1934                .getDisabledSystemPkgLPr(pkg.parentPackage.packageName);
1935        if (disabledSysParentPs == null || disabledSysParentPs.pkg == null
1936                || !disabledSysParentPs.isPrivileged()
1937                || (disabledSysParentPs.childPackageNames != null
1938                        && !disabledSysParentPs.childPackageNames.isEmpty())) {
1939            return;
1940        }
1941        final int[] allUserIds = sUserManager.getUserIds();
1942        final int permCount = pkg.requestedPermissions.size();
1943        for (int i = 0; i < permCount; i++) {
1944            String permission = pkg.requestedPermissions.get(i);
1945            BasePermission bp = mSettings.mPermissions.get(permission);
1946            if (bp == null || !(bp.isRuntime() || bp.isDevelopment())) {
1947                continue;
1948            }
1949            for (int userId : allUserIds) {
1950                if (disabledSysParentPs.getPermissionsState().hasRuntimePermission(
1951                        permission, userId)) {
1952                    grantRuntimePermission(pkg.packageName, permission, userId);
1953                }
1954            }
1955        }
1956    }
1957
1958    private StorageEventListener mStorageListener = new StorageEventListener() {
1959        @Override
1960        public void onVolumeStateChanged(VolumeInfo vol, int oldState, int newState) {
1961            if (vol.type == VolumeInfo.TYPE_PRIVATE) {
1962                if (vol.state == VolumeInfo.STATE_MOUNTED) {
1963                    final String volumeUuid = vol.getFsUuid();
1964
1965                    // Clean up any users or apps that were removed or recreated
1966                    // while this volume was missing
1967                    sUserManager.reconcileUsers(volumeUuid);
1968                    reconcileApps(volumeUuid);
1969
1970                    // Clean up any install sessions that expired or were
1971                    // cancelled while this volume was missing
1972                    mInstallerService.onPrivateVolumeMounted(volumeUuid);
1973
1974                    loadPrivatePackages(vol);
1975
1976                } else if (vol.state == VolumeInfo.STATE_EJECTING) {
1977                    unloadPrivatePackages(vol);
1978                }
1979            }
1980
1981            if (vol.type == VolumeInfo.TYPE_PUBLIC && vol.isPrimary()) {
1982                if (vol.state == VolumeInfo.STATE_MOUNTED) {
1983                    updateExternalMediaStatus(true, false);
1984                } else if (vol.state == VolumeInfo.STATE_EJECTING) {
1985                    updateExternalMediaStatus(false, false);
1986                }
1987            }
1988        }
1989
1990        @Override
1991        public void onVolumeForgotten(String fsUuid) {
1992            if (TextUtils.isEmpty(fsUuid)) {
1993                Slog.e(TAG, "Forgetting internal storage is probably a mistake; ignoring");
1994                return;
1995            }
1996
1997            // Remove any apps installed on the forgotten volume
1998            synchronized (mPackages) {
1999                final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(fsUuid);
2000                for (PackageSetting ps : packages) {
2001                    Slog.d(TAG, "Destroying " + ps.name + " because volume was forgotten");
2002                    deletePackageVersioned(new VersionedPackage(ps.name,
2003                            PackageManager.VERSION_CODE_HIGHEST),
2004                            new LegacyPackageDeleteObserver(null).getBinder(),
2005                            UserHandle.USER_SYSTEM, PackageManager.DELETE_ALL_USERS);
2006                    // Try very hard to release any references to this package
2007                    // so we don't risk the system server being killed due to
2008                    // open FDs
2009                    AttributeCache.instance().removePackage(ps.name);
2010                }
2011
2012                mSettings.onVolumeForgotten(fsUuid);
2013                mSettings.writeLPr();
2014            }
2015        }
2016    };
2017
2018    private void grantRequestedRuntimePermissions(PackageParser.Package pkg, int[] userIds,
2019            String[] grantedPermissions) {
2020        for (int userId : userIds) {
2021            grantRequestedRuntimePermissionsForUser(pkg, userId, grantedPermissions);
2022        }
2023    }
2024
2025    private void grantRequestedRuntimePermissionsForUser(PackageParser.Package pkg, int userId,
2026            String[] grantedPermissions) {
2027        SettingBase sb = (SettingBase) pkg.mExtras;
2028        if (sb == null) {
2029            return;
2030        }
2031
2032        PermissionsState permissionsState = sb.getPermissionsState();
2033
2034        final int immutableFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED
2035                | PackageManager.FLAG_PERMISSION_POLICY_FIXED;
2036
2037        final boolean supportsRuntimePermissions = pkg.applicationInfo.targetSdkVersion
2038                >= Build.VERSION_CODES.M;
2039
2040        for (String permission : pkg.requestedPermissions) {
2041            final BasePermission bp;
2042            synchronized (mPackages) {
2043                bp = mSettings.mPermissions.get(permission);
2044            }
2045            if (bp != null && (bp.isRuntime() || bp.isDevelopment())
2046                    && (grantedPermissions == null
2047                           || ArrayUtils.contains(grantedPermissions, permission))) {
2048                final int flags = permissionsState.getPermissionFlags(permission, userId);
2049                if (supportsRuntimePermissions) {
2050                    // Installer cannot change immutable permissions.
2051                    if ((flags & immutableFlags) == 0) {
2052                        grantRuntimePermission(pkg.packageName, permission, userId);
2053                    }
2054                } else if (mPermissionReviewRequired) {
2055                    // In permission review mode we clear the review flag when we
2056                    // are asked to install the app with all permissions granted.
2057                    if ((flags & PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED) != 0) {
2058                        updatePermissionFlags(permission, pkg.packageName,
2059                                PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED, 0, userId);
2060                    }
2061                }
2062            }
2063        }
2064    }
2065
2066    Bundle extrasForInstallResult(PackageInstalledInfo res) {
2067        Bundle extras = null;
2068        switch (res.returnCode) {
2069            case PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION: {
2070                extras = new Bundle();
2071                extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PERMISSION,
2072                        res.origPermission);
2073                extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PACKAGE,
2074                        res.origPackage);
2075                break;
2076            }
2077            case PackageManager.INSTALL_SUCCEEDED: {
2078                extras = new Bundle();
2079                extras.putBoolean(Intent.EXTRA_REPLACING,
2080                        res.removedInfo != null && res.removedInfo.removedPackage != null);
2081                break;
2082            }
2083        }
2084        return extras;
2085    }
2086
2087    void scheduleWriteSettingsLocked() {
2088        if (!mHandler.hasMessages(WRITE_SETTINGS)) {
2089            mHandler.sendEmptyMessageDelayed(WRITE_SETTINGS, WRITE_SETTINGS_DELAY);
2090        }
2091    }
2092
2093    void scheduleWritePackageListLocked(int userId) {
2094        if (!mHandler.hasMessages(WRITE_PACKAGE_LIST)) {
2095            Message msg = mHandler.obtainMessage(WRITE_PACKAGE_LIST);
2096            msg.arg1 = userId;
2097            mHandler.sendMessageDelayed(msg, WRITE_SETTINGS_DELAY);
2098        }
2099    }
2100
2101    void scheduleWritePackageRestrictionsLocked(UserHandle user) {
2102        final int userId = user == null ? UserHandle.USER_ALL : user.getIdentifier();
2103        scheduleWritePackageRestrictionsLocked(userId);
2104    }
2105
2106    void scheduleWritePackageRestrictionsLocked(int userId) {
2107        final int[] userIds = (userId == UserHandle.USER_ALL)
2108                ? sUserManager.getUserIds() : new int[]{userId};
2109        for (int nextUserId : userIds) {
2110            if (!sUserManager.exists(nextUserId)) return;
2111            mDirtyUsers.add(nextUserId);
2112            if (!mHandler.hasMessages(WRITE_PACKAGE_RESTRICTIONS)) {
2113                mHandler.sendEmptyMessageDelayed(WRITE_PACKAGE_RESTRICTIONS, WRITE_SETTINGS_DELAY);
2114            }
2115        }
2116    }
2117
2118    public static PackageManagerService main(Context context, Installer installer,
2119            boolean factoryTest, boolean onlyCore) {
2120        // Self-check for initial settings.
2121        PackageManagerServiceCompilerMapping.checkProperties();
2122
2123        PackageManagerService m = new PackageManagerService(context, installer,
2124                factoryTest, onlyCore);
2125        m.enableSystemUserPackages();
2126        ServiceManager.addService("package", m);
2127        return m;
2128    }
2129
2130    private void enableSystemUserPackages() {
2131        if (!UserManager.isSplitSystemUser()) {
2132            return;
2133        }
2134        // For system user, enable apps based on the following conditions:
2135        // - app is whitelisted or belong to one of these groups:
2136        //   -- system app which has no launcher icons
2137        //   -- system app which has INTERACT_ACROSS_USERS permission
2138        //   -- system IME app
2139        // - app is not in the blacklist
2140        AppsQueryHelper queryHelper = new AppsQueryHelper(this);
2141        Set<String> enableApps = new ArraySet<>();
2142        enableApps.addAll(queryHelper.queryApps(AppsQueryHelper.GET_NON_LAUNCHABLE_APPS
2143                | AppsQueryHelper.GET_APPS_WITH_INTERACT_ACROSS_USERS_PERM
2144                | AppsQueryHelper.GET_IMES, /* systemAppsOnly */ true, UserHandle.SYSTEM));
2145        ArraySet<String> wlApps = SystemConfig.getInstance().getSystemUserWhitelistedApps();
2146        enableApps.addAll(wlApps);
2147        enableApps.addAll(queryHelper.queryApps(AppsQueryHelper.GET_REQUIRED_FOR_SYSTEM_USER,
2148                /* systemAppsOnly */ false, UserHandle.SYSTEM));
2149        ArraySet<String> blApps = SystemConfig.getInstance().getSystemUserBlacklistedApps();
2150        enableApps.removeAll(blApps);
2151        Log.i(TAG, "Applications installed for system user: " + enableApps);
2152        List<String> allAps = queryHelper.queryApps(0, /* systemAppsOnly */ false,
2153                UserHandle.SYSTEM);
2154        final int allAppsSize = allAps.size();
2155        synchronized (mPackages) {
2156            for (int i = 0; i < allAppsSize; i++) {
2157                String pName = allAps.get(i);
2158                PackageSetting pkgSetting = mSettings.mPackages.get(pName);
2159                // Should not happen, but we shouldn't be failing if it does
2160                if (pkgSetting == null) {
2161                    continue;
2162                }
2163                boolean install = enableApps.contains(pName);
2164                if (pkgSetting.getInstalled(UserHandle.USER_SYSTEM) != install) {
2165                    Log.i(TAG, (install ? "Installing " : "Uninstalling ") + pName
2166                            + " for system user");
2167                    pkgSetting.setInstalled(install, UserHandle.USER_SYSTEM);
2168                }
2169            }
2170            scheduleWritePackageRestrictionsLocked(UserHandle.USER_SYSTEM);
2171        }
2172    }
2173
2174    private static void getDefaultDisplayMetrics(Context context, DisplayMetrics metrics) {
2175        DisplayManager displayManager = (DisplayManager) context.getSystemService(
2176                Context.DISPLAY_SERVICE);
2177        displayManager.getDisplay(Display.DEFAULT_DISPLAY).getMetrics(metrics);
2178    }
2179
2180    /**
2181     * Requests that files preopted on a secondary system partition be copied to the data partition
2182     * if possible.  Note that the actual copying of the files is accomplished by init for security
2183     * reasons. This simply requests that the copy takes place and awaits confirmation of its
2184     * completion. See platform/system/extras/cppreopt/ for the implementation of the actual copy.
2185     */
2186    private static void requestCopyPreoptedFiles() {
2187        final int WAIT_TIME_MS = 100;
2188        final String CP_PREOPT_PROPERTY = "sys.cppreopt";
2189        if (SystemProperties.getInt("ro.cp_system_other_odex", 0) == 1) {
2190            SystemProperties.set(CP_PREOPT_PROPERTY, "requested");
2191            // We will wait for up to 100 seconds.
2192            final long timeStart = SystemClock.uptimeMillis();
2193            final long timeEnd = timeStart + 100 * 1000;
2194            long timeNow = timeStart;
2195            while (!SystemProperties.get(CP_PREOPT_PROPERTY).equals("finished")) {
2196                try {
2197                    Thread.sleep(WAIT_TIME_MS);
2198                } catch (InterruptedException e) {
2199                    // Do nothing
2200                }
2201                timeNow = SystemClock.uptimeMillis();
2202                if (timeNow > timeEnd) {
2203                    SystemProperties.set(CP_PREOPT_PROPERTY, "timed-out");
2204                    Slog.wtf(TAG, "cppreopt did not finish!");
2205                    break;
2206                }
2207            }
2208
2209            Slog.i(TAG, "cppreopts took " + (timeNow - timeStart) + " ms");
2210        }
2211    }
2212
2213    public PackageManagerService(Context context, Installer installer,
2214            boolean factoryTest, boolean onlyCore) {
2215        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "create package manager");
2216        EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_START,
2217                SystemClock.uptimeMillis());
2218
2219        if (mSdkVersion <= 0) {
2220            Slog.w(TAG, "**** ro.build.version.sdk not set!");
2221        }
2222
2223        mContext = context;
2224
2225        mPermissionReviewRequired = context.getResources().getBoolean(
2226                R.bool.config_permissionReviewRequired);
2227
2228        mFactoryTest = factoryTest;
2229        mOnlyCore = onlyCore;
2230        mMetrics = new DisplayMetrics();
2231        mSettings = new Settings(mPackages);
2232        mSettings.addSharedUserLPw("android.uid.system", Process.SYSTEM_UID,
2233                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2234        mSettings.addSharedUserLPw("android.uid.phone", RADIO_UID,
2235                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2236        mSettings.addSharedUserLPw("android.uid.log", LOG_UID,
2237                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2238        mSettings.addSharedUserLPw("android.uid.nfc", NFC_UID,
2239                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2240        mSettings.addSharedUserLPw("android.uid.bluetooth", BLUETOOTH_UID,
2241                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2242        mSettings.addSharedUserLPw("android.uid.shell", SHELL_UID,
2243                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2244
2245        String separateProcesses = SystemProperties.get("debug.separate_processes");
2246        if (separateProcesses != null && separateProcesses.length() > 0) {
2247            if ("*".equals(separateProcesses)) {
2248                mDefParseFlags = PackageParser.PARSE_IGNORE_PROCESSES;
2249                mSeparateProcesses = null;
2250                Slog.w(TAG, "Running with debug.separate_processes: * (ALL)");
2251            } else {
2252                mDefParseFlags = 0;
2253                mSeparateProcesses = separateProcesses.split(",");
2254                Slog.w(TAG, "Running with debug.separate_processes: "
2255                        + separateProcesses);
2256            }
2257        } else {
2258            mDefParseFlags = 0;
2259            mSeparateProcesses = null;
2260        }
2261
2262        mInstaller = installer;
2263        mPackageDexOptimizer = new PackageDexOptimizer(installer, mInstallLock, context,
2264                "*dexopt*");
2265        mDexManager = new DexManager(this, mPackageDexOptimizer, installer, mInstallLock);
2266        mMoveCallbacks = new MoveCallbacks(FgThread.get().getLooper());
2267
2268        mOnPermissionChangeListeners = new OnPermissionChangeListeners(
2269                FgThread.get().getLooper());
2270
2271        getDefaultDisplayMetrics(context, mMetrics);
2272
2273        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "get system config");
2274        SystemConfig systemConfig = SystemConfig.getInstance();
2275        mGlobalGids = systemConfig.getGlobalGids();
2276        mSystemPermissions = systemConfig.getSystemPermissions();
2277        mAvailableFeatures = systemConfig.getAvailableFeatures();
2278        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
2279
2280        mProtectedPackages = new ProtectedPackages(mContext);
2281
2282        synchronized (mInstallLock) {
2283        // writer
2284        synchronized (mPackages) {
2285            mHandlerThread = new ServiceThread(TAG,
2286                    Process.THREAD_PRIORITY_BACKGROUND, true /*allowIo*/);
2287            mHandlerThread.start();
2288            mHandler = new PackageHandler(mHandlerThread.getLooper());
2289            mProcessLoggingHandler = new ProcessLoggingHandler();
2290            Watchdog.getInstance().addThread(mHandler, WATCHDOG_TIMEOUT);
2291
2292            mDefaultPermissionPolicy = new DefaultPermissionGrantPolicy(this);
2293            mInstantAppRegistry = new InstantAppRegistry(this);
2294
2295            File dataDir = Environment.getDataDirectory();
2296            mAppInstallDir = new File(dataDir, "app");
2297            mAppLib32InstallDir = new File(dataDir, "app-lib");
2298            mAsecInternalPath = new File(dataDir, "app-asec").getPath();
2299            mDrmAppPrivateInstallDir = new File(dataDir, "app-private");
2300            sUserManager = new UserManagerService(context, this,
2301                    new UserDataPreparer(mInstaller, mInstallLock, mContext, mOnlyCore), mPackages);
2302
2303            // Propagate permission configuration in to package manager.
2304            ArrayMap<String, SystemConfig.PermissionEntry> permConfig
2305                    = systemConfig.getPermissions();
2306            for (int i=0; i<permConfig.size(); i++) {
2307                SystemConfig.PermissionEntry perm = permConfig.valueAt(i);
2308                BasePermission bp = mSettings.mPermissions.get(perm.name);
2309                if (bp == null) {
2310                    bp = new BasePermission(perm.name, "android", BasePermission.TYPE_BUILTIN);
2311                    mSettings.mPermissions.put(perm.name, bp);
2312                }
2313                if (perm.gids != null) {
2314                    bp.setGids(perm.gids, perm.perUser);
2315                }
2316            }
2317
2318            ArrayMap<String, String> libConfig = systemConfig.getSharedLibraries();
2319            final int builtInLibCount = libConfig.size();
2320            for (int i = 0; i < builtInLibCount; i++) {
2321                String name = libConfig.keyAt(i);
2322                String path = libConfig.valueAt(i);
2323                addSharedLibraryLPw(path, null, name, SharedLibraryInfo.VERSION_UNDEFINED,
2324                        SharedLibraryInfo.TYPE_BUILTIN, PLATFORM_PACKAGE_NAME, 0);
2325            }
2326
2327            mFoundPolicyFile = SELinuxMMAC.readInstallPolicy();
2328
2329            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "read user settings");
2330            mFirstBoot = !mSettings.readLPw(sUserManager.getUsers(false));
2331            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
2332
2333            // Clean up orphaned packages for which the code path doesn't exist
2334            // and they are an update to a system app - caused by bug/32321269
2335            final int packageSettingCount = mSettings.mPackages.size();
2336            for (int i = packageSettingCount - 1; i >= 0; i--) {
2337                PackageSetting ps = mSettings.mPackages.valueAt(i);
2338                if (!isExternal(ps) && (ps.codePath == null || !ps.codePath.exists())
2339                        && mSettings.getDisabledSystemPkgLPr(ps.name) != null) {
2340                    mSettings.mPackages.removeAt(i);
2341                    mSettings.enableSystemPackageLPw(ps.name);
2342                }
2343            }
2344
2345            if (mFirstBoot) {
2346                requestCopyPreoptedFiles();
2347            }
2348
2349            String customResolverActivity = Resources.getSystem().getString(
2350                    R.string.config_customResolverActivity);
2351            if (TextUtils.isEmpty(customResolverActivity)) {
2352                customResolverActivity = null;
2353            } else {
2354                mCustomResolverComponentName = ComponentName.unflattenFromString(
2355                        customResolverActivity);
2356            }
2357
2358            long startTime = SystemClock.uptimeMillis();
2359
2360            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SYSTEM_SCAN_START,
2361                    startTime);
2362
2363            final String bootClassPath = System.getenv("BOOTCLASSPATH");
2364            final String systemServerClassPath = System.getenv("SYSTEMSERVERCLASSPATH");
2365
2366            if (bootClassPath == null) {
2367                Slog.w(TAG, "No BOOTCLASSPATH found!");
2368            }
2369
2370            if (systemServerClassPath == null) {
2371                Slog.w(TAG, "No SYSTEMSERVERCLASSPATH found!");
2372            }
2373
2374            final List<String> allInstructionSets = InstructionSets.getAllInstructionSets();
2375            final String[] dexCodeInstructionSets =
2376                    getDexCodeInstructionSets(
2377                            allInstructionSets.toArray(new String[allInstructionSets.size()]));
2378
2379            /**
2380             * Ensure all external libraries have had dexopt run on them.
2381             */
2382            if (mSharedLibraries.size() > 0) {
2383                Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt");
2384                // NOTE: For now, we're compiling these system "shared libraries"
2385                // (and framework jars) into all available architectures. It's possible
2386                // to compile them only when we come across an app that uses them (there's
2387                // already logic for that in scanPackageLI) but that adds some complexity.
2388                for (String dexCodeInstructionSet : dexCodeInstructionSets) {
2389                    final int libCount = mSharedLibraries.size();
2390                    for (int i = 0; i < libCount; i++) {
2391                        SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.valueAt(i);
2392                        final int versionCount = versionedLib.size();
2393                        for (int j = 0; j < versionCount; j++) {
2394                            SharedLibraryEntry libEntry = versionedLib.valueAt(j);
2395                            final String libPath = libEntry.path != null
2396                                    ? libEntry.path : libEntry.apk;
2397                            if (libPath == null) {
2398                                continue;
2399                            }
2400                            try {
2401                                // Shared libraries do not have profiles so we perform a full
2402                                // AOT compilation (if needed).
2403                                int dexoptNeeded = DexFile.getDexOptNeeded(
2404                                        libPath, dexCodeInstructionSet,
2405                                        getCompilerFilterForReason(REASON_SHARED_APK),
2406                                        false /* newProfile */);
2407                                if (dexoptNeeded != DexFile.NO_DEXOPT_NEEDED) {
2408                                    mInstaller.dexopt(libPath, Process.SYSTEM_UID, "*",
2409                                            dexCodeInstructionSet, dexoptNeeded, null,
2410                                            DEXOPT_PUBLIC,
2411                                            getCompilerFilterForReason(REASON_SHARED_APK),
2412                                            StorageManager.UUID_PRIVATE_INTERNAL,
2413                                            PackageDexOptimizer.SKIP_SHARED_LIBRARY_CHECK);
2414                                }
2415                            } catch (FileNotFoundException e) {
2416                                Slog.w(TAG, "Library not found: " + libPath);
2417                            } catch (IOException | InstallerException e) {
2418                                Slog.w(TAG, "Cannot dexopt " + libPath + "; is it an APK or JAR? "
2419                                        + e.getMessage());
2420                            }
2421                        }
2422                    }
2423                }
2424                Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
2425            }
2426
2427            File frameworkDir = new File(Environment.getRootDirectory(), "framework");
2428
2429            final VersionInfo ver = mSettings.getInternalVersion();
2430            mIsUpgrade = !Build.FINGERPRINT.equals(ver.fingerprint);
2431
2432            // when upgrading from pre-M, promote system app permissions from install to runtime
2433            mPromoteSystemApps =
2434                    mIsUpgrade && ver.sdkVersion <= Build.VERSION_CODES.LOLLIPOP_MR1;
2435
2436            // When upgrading from pre-N, we need to handle package extraction like first boot,
2437            // as there is no profiling data available.
2438            mIsPreNUpgrade = mIsUpgrade && ver.sdkVersion < Build.VERSION_CODES.N;
2439
2440            mIsPreNMR1Upgrade = mIsUpgrade && ver.sdkVersion < Build.VERSION_CODES.N_MR1;
2441
2442            // save off the names of pre-existing system packages prior to scanning; we don't
2443            // want to automatically grant runtime permissions for new system apps
2444            if (mPromoteSystemApps) {
2445                Iterator<PackageSetting> pkgSettingIter = mSettings.mPackages.values().iterator();
2446                while (pkgSettingIter.hasNext()) {
2447                    PackageSetting ps = pkgSettingIter.next();
2448                    if (isSystemApp(ps)) {
2449                        mExistingSystemPackages.add(ps.name);
2450                    }
2451                }
2452            }
2453
2454            mCacheDir = preparePackageParserCache(mIsUpgrade);
2455
2456            // Set flag to monitor and not change apk file paths when
2457            // scanning install directories.
2458            int scanFlags = SCAN_BOOTING | SCAN_INITIAL;
2459
2460            if (mIsUpgrade || mFirstBoot) {
2461                scanFlags = scanFlags | SCAN_FIRST_BOOT_OR_UPGRADE;
2462            }
2463
2464            // Collect vendor overlay packages. (Do this before scanning any apps.)
2465            // For security and version matching reason, only consider
2466            // overlay packages if they reside in the right directory.
2467            String overlayThemeDir = SystemProperties.get(VENDOR_OVERLAY_THEME_PERSIST_PROPERTY);
2468            if (overlayThemeDir.isEmpty()) {
2469                overlayThemeDir = SystemProperties.get(VENDOR_OVERLAY_THEME_PROPERTY);
2470            }
2471            if (!overlayThemeDir.isEmpty()) {
2472                scanDirTracedLI(new File(VENDOR_OVERLAY_DIR, overlayThemeDir), mDefParseFlags
2473                        | PackageParser.PARSE_IS_SYSTEM
2474                        | PackageParser.PARSE_IS_SYSTEM_DIR
2475                        | PackageParser.PARSE_TRUSTED_OVERLAY, scanFlags | SCAN_TRUSTED_OVERLAY, 0);
2476            }
2477            scanDirTracedLI(new File(VENDOR_OVERLAY_DIR), mDefParseFlags
2478                    | PackageParser.PARSE_IS_SYSTEM
2479                    | PackageParser.PARSE_IS_SYSTEM_DIR
2480                    | PackageParser.PARSE_TRUSTED_OVERLAY, scanFlags | SCAN_TRUSTED_OVERLAY, 0);
2481
2482            // Find base frameworks (resource packages without code).
2483            scanDirTracedLI(frameworkDir, mDefParseFlags
2484                    | PackageParser.PARSE_IS_SYSTEM
2485                    | PackageParser.PARSE_IS_SYSTEM_DIR
2486                    | PackageParser.PARSE_IS_PRIVILEGED,
2487                    scanFlags | SCAN_NO_DEX, 0);
2488
2489            // Collected privileged system packages.
2490            final File privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app");
2491            scanDirTracedLI(privilegedAppDir, mDefParseFlags
2492                    | PackageParser.PARSE_IS_SYSTEM
2493                    | PackageParser.PARSE_IS_SYSTEM_DIR
2494                    | PackageParser.PARSE_IS_PRIVILEGED, scanFlags, 0);
2495
2496            // Collect ordinary system packages.
2497            final File systemAppDir = new File(Environment.getRootDirectory(), "app");
2498            scanDirTracedLI(systemAppDir, mDefParseFlags
2499                    | PackageParser.PARSE_IS_SYSTEM
2500                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
2501
2502            // Collect all vendor packages.
2503            File vendorAppDir = new File("/vendor/app");
2504            try {
2505                vendorAppDir = vendorAppDir.getCanonicalFile();
2506            } catch (IOException e) {
2507                // failed to look up canonical path, continue with original one
2508            }
2509            scanDirTracedLI(vendorAppDir, mDefParseFlags
2510                    | PackageParser.PARSE_IS_SYSTEM
2511                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
2512
2513            // Collect all OEM packages.
2514            final File oemAppDir = new File(Environment.getOemDirectory(), "app");
2515            scanDirTracedLI(oemAppDir, mDefParseFlags
2516                    | PackageParser.PARSE_IS_SYSTEM
2517                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
2518
2519            // Prune any system packages that no longer exist.
2520            final List<String> possiblyDeletedUpdatedSystemApps = new ArrayList<String>();
2521            if (!mOnlyCore) {
2522                Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator();
2523                while (psit.hasNext()) {
2524                    PackageSetting ps = psit.next();
2525
2526                    /*
2527                     * If this is not a system app, it can't be a
2528                     * disable system app.
2529                     */
2530                    if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0) {
2531                        continue;
2532                    }
2533
2534                    /*
2535                     * If the package is scanned, it's not erased.
2536                     */
2537                    final PackageParser.Package scannedPkg = mPackages.get(ps.name);
2538                    if (scannedPkg != null) {
2539                        /*
2540                         * If the system app is both scanned and in the
2541                         * disabled packages list, then it must have been
2542                         * added via OTA. Remove it from the currently
2543                         * scanned package so the previously user-installed
2544                         * application can be scanned.
2545                         */
2546                        if (mSettings.isDisabledSystemPackageLPr(ps.name)) {
2547                            logCriticalInfo(Log.WARN, "Expecting better updated system app for "
2548                                    + ps.name + "; removing system app.  Last known codePath="
2549                                    + ps.codePathString + ", installStatus=" + ps.installStatus
2550                                    + ", versionCode=" + ps.versionCode + "; scanned versionCode="
2551                                    + scannedPkg.mVersionCode);
2552                            removePackageLI(scannedPkg, true);
2553                            mExpectingBetter.put(ps.name, ps.codePath);
2554                        }
2555
2556                        continue;
2557                    }
2558
2559                    if (!mSettings.isDisabledSystemPackageLPr(ps.name)) {
2560                        psit.remove();
2561                        logCriticalInfo(Log.WARN, "System package " + ps.name
2562                                + " no longer exists; it's data will be wiped");
2563                        // Actual deletion of code and data will be handled by later
2564                        // reconciliation step
2565                    } else {
2566                        final PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(ps.name);
2567                        if (disabledPs.codePath == null || !disabledPs.codePath.exists()) {
2568                            possiblyDeletedUpdatedSystemApps.add(ps.name);
2569                        }
2570                    }
2571                }
2572            }
2573
2574            //look for any incomplete package installations
2575            ArrayList<PackageSetting> deletePkgsList = mSettings.getListOfIncompleteInstallPackagesLPr();
2576            for (int i = 0; i < deletePkgsList.size(); i++) {
2577                // Actual deletion of code and data will be handled by later
2578                // reconciliation step
2579                final String packageName = deletePkgsList.get(i).name;
2580                logCriticalInfo(Log.WARN, "Cleaning up incompletely installed app: " + packageName);
2581                synchronized (mPackages) {
2582                    mSettings.removePackageLPw(packageName);
2583                }
2584            }
2585
2586            //delete tmp files
2587            deleteTempPackageFiles();
2588
2589            // Remove any shared userIDs that have no associated packages
2590            mSettings.pruneSharedUsersLPw();
2591
2592            if (!mOnlyCore) {
2593                EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_DATA_SCAN_START,
2594                        SystemClock.uptimeMillis());
2595                scanDirTracedLI(mAppInstallDir, 0, scanFlags | SCAN_REQUIRE_KNOWN, 0);
2596
2597                scanDirTracedLI(mDrmAppPrivateInstallDir, mDefParseFlags
2598                        | PackageParser.PARSE_FORWARD_LOCK,
2599                        scanFlags | SCAN_REQUIRE_KNOWN, 0);
2600
2601                /**
2602                 * Remove disable package settings for any updated system
2603                 * apps that were removed via an OTA. If they're not a
2604                 * previously-updated app, remove them completely.
2605                 * Otherwise, just revoke their system-level permissions.
2606                 */
2607                for (String deletedAppName : possiblyDeletedUpdatedSystemApps) {
2608                    PackageParser.Package deletedPkg = mPackages.get(deletedAppName);
2609                    mSettings.removeDisabledSystemPackageLPw(deletedAppName);
2610
2611                    String msg;
2612                    if (deletedPkg == null) {
2613                        msg = "Updated system package " + deletedAppName
2614                                + " no longer exists; it's data will be wiped";
2615                        // Actual deletion of code and data will be handled by later
2616                        // reconciliation step
2617                    } else {
2618                        msg = "Updated system app + " + deletedAppName
2619                                + " no longer present; removing system privileges for "
2620                                + deletedAppName;
2621
2622                        deletedPkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_SYSTEM;
2623
2624                        PackageSetting deletedPs = mSettings.mPackages.get(deletedAppName);
2625                        deletedPs.pkgFlags &= ~ApplicationInfo.FLAG_SYSTEM;
2626                    }
2627                    logCriticalInfo(Log.WARN, msg);
2628                }
2629
2630                /**
2631                 * Make sure all system apps that we expected to appear on
2632                 * the userdata partition actually showed up. If they never
2633                 * appeared, crawl back and revive the system version.
2634                 */
2635                for (int i = 0; i < mExpectingBetter.size(); i++) {
2636                    final String packageName = mExpectingBetter.keyAt(i);
2637                    if (!mPackages.containsKey(packageName)) {
2638                        final File scanFile = mExpectingBetter.valueAt(i);
2639
2640                        logCriticalInfo(Log.WARN, "Expected better " + packageName
2641                                + " but never showed up; reverting to system");
2642
2643                        int reparseFlags = mDefParseFlags;
2644                        if (FileUtils.contains(privilegedAppDir, scanFile)) {
2645                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2646                                    | PackageParser.PARSE_IS_SYSTEM_DIR
2647                                    | PackageParser.PARSE_IS_PRIVILEGED;
2648                        } else if (FileUtils.contains(systemAppDir, scanFile)) {
2649                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2650                                    | PackageParser.PARSE_IS_SYSTEM_DIR;
2651                        } else if (FileUtils.contains(vendorAppDir, scanFile)) {
2652                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2653                                    | PackageParser.PARSE_IS_SYSTEM_DIR;
2654                        } else if (FileUtils.contains(oemAppDir, scanFile)) {
2655                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2656                                    | PackageParser.PARSE_IS_SYSTEM_DIR;
2657                        } else {
2658                            Slog.e(TAG, "Ignoring unexpected fallback path " + scanFile);
2659                            continue;
2660                        }
2661
2662                        mSettings.enableSystemPackageLPw(packageName);
2663
2664                        try {
2665                            scanPackageTracedLI(scanFile, reparseFlags, scanFlags, 0, null);
2666                        } catch (PackageManagerException e) {
2667                            Slog.e(TAG, "Failed to parse original system package: "
2668                                    + e.getMessage());
2669                        }
2670                    }
2671                }
2672            }
2673            mExpectingBetter.clear();
2674
2675            // Resolve the storage manager.
2676            mStorageManagerPackage = getStorageManagerPackageName();
2677
2678            // Resolve protected action filters. Only the setup wizard is allowed to
2679            // have a high priority filter for these actions.
2680            mSetupWizardPackage = getSetupWizardPackageName();
2681            if (mProtectedFilters.size() > 0) {
2682                if (DEBUG_FILTERS && mSetupWizardPackage == null) {
2683                    Slog.i(TAG, "No setup wizard;"
2684                        + " All protected intents capped to priority 0");
2685                }
2686                for (ActivityIntentInfo filter : mProtectedFilters) {
2687                    if (filter.activity.info.packageName.equals(mSetupWizardPackage)) {
2688                        if (DEBUG_FILTERS) {
2689                            Slog.i(TAG, "Found setup wizard;"
2690                                + " allow priority " + filter.getPriority() + ";"
2691                                + " package: " + filter.activity.info.packageName
2692                                + " activity: " + filter.activity.className
2693                                + " priority: " + filter.getPriority());
2694                        }
2695                        // skip setup wizard; allow it to keep the high priority filter
2696                        continue;
2697                    }
2698                    Slog.w(TAG, "Protected action; cap priority to 0;"
2699                            + " package: " + filter.activity.info.packageName
2700                            + " activity: " + filter.activity.className
2701                            + " origPrio: " + filter.getPriority());
2702                    filter.setPriority(0);
2703                }
2704            }
2705            mDeferProtectedFilters = false;
2706            mProtectedFilters.clear();
2707
2708            // Now that we know all of the shared libraries, update all clients to have
2709            // the correct library paths.
2710            updateAllSharedLibrariesLPw(null);
2711
2712            for (SharedUserSetting setting : mSettings.getAllSharedUsersLPw()) {
2713                // NOTE: We ignore potential failures here during a system scan (like
2714                // the rest of the commands above) because there's precious little we
2715                // can do about it. A settings error is reported, though.
2716                adjustCpuAbisForSharedUserLPw(setting.packages, null /*scannedPackage*/);
2717            }
2718
2719            // Now that we know all the packages we are keeping,
2720            // read and update their last usage times.
2721            mPackageUsage.read(mPackages);
2722            mCompilerStats.read();
2723
2724            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SCAN_END,
2725                    SystemClock.uptimeMillis());
2726            Slog.i(TAG, "Time to scan packages: "
2727                    + ((SystemClock.uptimeMillis()-startTime)/1000f)
2728                    + " seconds");
2729
2730            // If the platform SDK has changed since the last time we booted,
2731            // we need to re-grant app permission to catch any new ones that
2732            // appear.  This is really a hack, and means that apps can in some
2733            // cases get permissions that the user didn't initially explicitly
2734            // allow...  it would be nice to have some better way to handle
2735            // this situation.
2736            int updateFlags = UPDATE_PERMISSIONS_ALL;
2737            if (ver.sdkVersion != mSdkVersion) {
2738                Slog.i(TAG, "Platform changed from " + ver.sdkVersion + " to "
2739                        + mSdkVersion + "; regranting permissions for internal storage");
2740                updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL;
2741            }
2742            updatePermissionsLPw(null, null, StorageManager.UUID_PRIVATE_INTERNAL, updateFlags);
2743            ver.sdkVersion = mSdkVersion;
2744
2745            // If this is the first boot or an update from pre-M, and it is a normal
2746            // boot, then we need to initialize the default preferred apps across
2747            // all defined users.
2748            if (!onlyCore && (mPromoteSystemApps || mFirstBoot)) {
2749                for (UserInfo user : sUserManager.getUsers(true)) {
2750                    mSettings.applyDefaultPreferredAppsLPw(this, user.id);
2751                    applyFactoryDefaultBrowserLPw(user.id);
2752                    primeDomainVerificationsLPw(user.id);
2753                }
2754            }
2755
2756            // Prepare storage for system user really early during boot,
2757            // since core system apps like SettingsProvider and SystemUI
2758            // can't wait for user to start
2759            final int storageFlags;
2760            if (StorageManager.isFileEncryptedNativeOrEmulated()) {
2761                storageFlags = StorageManager.FLAG_STORAGE_DE;
2762            } else {
2763                storageFlags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
2764            }
2765            List<String> deferPackages = reconcileAppsDataLI(StorageManager.UUID_PRIVATE_INTERNAL,
2766                    UserHandle.USER_SYSTEM, storageFlags, true /* migrateAppData */,
2767                    true /* onlyCoreApps */);
2768            mPrepareAppDataFuture = SystemServerInitThreadPool.get().submit(() -> {
2769                if (deferPackages == null || deferPackages.isEmpty()) {
2770                    return;
2771                }
2772                int count = 0;
2773                for (String pkgName : deferPackages) {
2774                    PackageParser.Package pkg = null;
2775                    synchronized (mPackages) {
2776                        PackageSetting ps = mSettings.getPackageLPr(pkgName);
2777                        if (ps != null && ps.getInstalled(UserHandle.USER_SYSTEM)) {
2778                            pkg = ps.pkg;
2779                        }
2780                    }
2781                    if (pkg != null) {
2782                        synchronized (mInstallLock) {
2783                            prepareAppDataAndMigrateLIF(pkg, UserHandle.USER_SYSTEM, storageFlags,
2784                                    true /* maybeMigrateAppData */);
2785                        }
2786                        count++;
2787                    }
2788                }
2789                Slog.i(TAG, "Deferred reconcileAppsData finished " + count + " packages");
2790            }, "prepareAppData");
2791
2792            // If this is first boot after an OTA, and a normal boot, then
2793            // we need to clear code cache directories.
2794            // Note that we do *not* clear the application profiles. These remain valid
2795            // across OTAs and are used to drive profile verification (post OTA) and
2796            // profile compilation (without waiting to collect a fresh set of profiles).
2797            if (mIsUpgrade && !onlyCore) {
2798                Slog.i(TAG, "Build fingerprint changed; clearing code caches");
2799                for (int i = 0; i < mSettings.mPackages.size(); i++) {
2800                    final PackageSetting ps = mSettings.mPackages.valueAt(i);
2801                    if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, ps.volumeUuid)) {
2802                        // No apps are running this early, so no need to freeze
2803                        clearAppDataLIF(ps.pkg, UserHandle.USER_ALL,
2804                                StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE
2805                                        | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
2806                    }
2807                }
2808                ver.fingerprint = Build.FINGERPRINT;
2809            }
2810
2811            checkDefaultBrowser();
2812
2813            // clear only after permissions and other defaults have been updated
2814            mExistingSystemPackages.clear();
2815            mPromoteSystemApps = false;
2816
2817            // All the changes are done during package scanning.
2818            ver.databaseVersion = Settings.CURRENT_DATABASE_VERSION;
2819
2820            // can downgrade to reader
2821            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "write settings");
2822            mSettings.writeLPr();
2823            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
2824
2825            // Perform dexopt on all apps that mark themselves as coreApps. We do this pretty
2826            // early on (before the package manager declares itself as early) because other
2827            // components in the system server might ask for package contexts for these apps.
2828            //
2829            // Note that "onlyCore" in this context means the system is encrypted or encrypting
2830            // (i.e, that the data partition is unavailable).
2831            if ((isFirstBoot() || isUpgrade() || VMRuntime.didPruneDalvikCache()) && !onlyCore) {
2832                long start = System.nanoTime();
2833                List<PackageParser.Package> coreApps = new ArrayList<>();
2834                for (PackageParser.Package pkg : mPackages.values()) {
2835                    if (pkg.coreApp) {
2836                        coreApps.add(pkg);
2837                    }
2838                }
2839
2840                int[] stats = performDexOptUpgrade(coreApps, false,
2841                        getCompilerFilterForReason(REASON_CORE_APP));
2842
2843                final int elapsedTimeSeconds =
2844                        (int) TimeUnit.NANOSECONDS.toSeconds(System.nanoTime() - start);
2845                MetricsLogger.histogram(mContext, "opt_coreapps_time_s", elapsedTimeSeconds);
2846
2847                if (DEBUG_DEXOPT) {
2848                    Slog.i(TAG, "Dex-opt core apps took : " + elapsedTimeSeconds + " seconds (" +
2849                            stats[0] + ", " + stats[1] + ", " + stats[2] + ")");
2850                }
2851
2852
2853                // TODO: Should we log these stats to tron too ?
2854                // MetricsLogger.histogram(mContext, "opt_coreapps_num_dexopted", stats[0]);
2855                // MetricsLogger.histogram(mContext, "opt_coreapps_num_skipped", stats[1]);
2856                // MetricsLogger.histogram(mContext, "opt_coreapps_num_failed", stats[2]);
2857                // MetricsLogger.histogram(mContext, "opt_coreapps_num_total", coreApps.size());
2858            }
2859
2860            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_READY,
2861                    SystemClock.uptimeMillis());
2862
2863            if (!mOnlyCore) {
2864                mRequiredVerifierPackage = getRequiredButNotReallyRequiredVerifierLPr();
2865                mRequiredInstallerPackage = getRequiredInstallerLPr();
2866                mRequiredUninstallerPackage = getRequiredUninstallerLPr();
2867                mIntentFilterVerifierComponent = getIntentFilterVerifierComponentNameLPr();
2868                mIntentFilterVerifier = new IntentVerifierProxy(mContext,
2869                        mIntentFilterVerifierComponent);
2870                mServicesSystemSharedLibraryPackageName = getRequiredSharedLibraryLPr(
2871                        PackageManager.SYSTEM_SHARED_LIBRARY_SERVICES,
2872                        SharedLibraryInfo.VERSION_UNDEFINED);
2873                mSharedSystemSharedLibraryPackageName = getRequiredSharedLibraryLPr(
2874                        PackageManager.SYSTEM_SHARED_LIBRARY_SHARED,
2875                        SharedLibraryInfo.VERSION_UNDEFINED);
2876            } else {
2877                mRequiredVerifierPackage = null;
2878                mRequiredInstallerPackage = null;
2879                mRequiredUninstallerPackage = null;
2880                mIntentFilterVerifierComponent = null;
2881                mIntentFilterVerifier = null;
2882                mServicesSystemSharedLibraryPackageName = null;
2883                mSharedSystemSharedLibraryPackageName = null;
2884            }
2885
2886            mInstallerService = new PackageInstallerService(context, this);
2887
2888            final ComponentName ephemeralResolverComponent = getEphemeralResolverLPr();
2889            if (ephemeralResolverComponent != null) {
2890                if (DEBUG_EPHEMERAL) {
2891                    Slog.i(TAG, "Ephemeral resolver: " + ephemeralResolverComponent);
2892                }
2893                mInstantAppResolverConnection =
2894                        new EphemeralResolverConnection(mContext, ephemeralResolverComponent);
2895            } else {
2896                mInstantAppResolverConnection = null;
2897            }
2898            mInstantAppInstallerComponent = getEphemeralInstallerLPr();
2899            if (mInstantAppInstallerComponent != null) {
2900                if (DEBUG_EPHEMERAL) {
2901                    Slog.i(TAG, "Ephemeral installer: " + mInstantAppInstallerComponent);
2902                }
2903                setUpInstantAppInstallerActivityLP(mInstantAppInstallerComponent);
2904            }
2905
2906            // Read and update the usage of dex files.
2907            // Do this at the end of PM init so that all the packages have their
2908            // data directory reconciled.
2909            // At this point we know the code paths of the packages, so we can validate
2910            // the disk file and build the internal cache.
2911            // The usage file is expected to be small so loading and verifying it
2912            // should take a fairly small time compare to the other activities (e.g. package
2913            // scanning).
2914            final Map<Integer, List<PackageInfo>> userPackages = new HashMap<>();
2915            final int[] currentUserIds = UserManagerService.getInstance().getUserIds();
2916            for (int userId : currentUserIds) {
2917                userPackages.put(userId, getInstalledPackages(/*flags*/ 0, userId).getList());
2918            }
2919            mDexManager.load(userPackages);
2920        } // synchronized (mPackages)
2921        } // synchronized (mInstallLock)
2922
2923        // Now after opening every single application zip, make sure they
2924        // are all flushed.  Not really needed, but keeps things nice and
2925        // tidy.
2926        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "GC");
2927        Runtime.getRuntime().gc();
2928        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
2929
2930        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "loadFallbacks");
2931        FallbackCategoryProvider.loadFallbacks();
2932        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
2933
2934        // The initial scanning above does many calls into installd while
2935        // holding the mPackages lock, but we're mostly interested in yelling
2936        // once we have a booted system.
2937        mInstaller.setWarnIfHeld(mPackages);
2938
2939        // Expose private service for system components to use.
2940        LocalServices.addService(PackageManagerInternal.class, new PackageManagerInternalImpl());
2941        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
2942    }
2943
2944    private static File preparePackageParserCache(boolean isUpgrade) {
2945        if (!DEFAULT_PACKAGE_PARSER_CACHE_ENABLED) {
2946            return null;
2947        }
2948
2949        // Disable package parsing on eng builds to allow for faster incremental development.
2950        if ("eng".equals(Build.TYPE)) {
2951            return null;
2952        }
2953
2954        if (SystemProperties.getBoolean("pm.boot.disable_package_cache", false)) {
2955            Slog.i(TAG, "Disabling package parser cache due to system property.");
2956            return null;
2957        }
2958
2959        // The base directory for the package parser cache lives under /data/system/.
2960        final File cacheBaseDir = FileUtils.createDir(Environment.getDataSystemDirectory(),
2961                "package_cache");
2962        if (cacheBaseDir == null) {
2963            return null;
2964        }
2965
2966        // If this is a system upgrade scenario, delete the contents of the package cache dir.
2967        // This also serves to "GC" unused entries when the package cache version changes (which
2968        // can only happen during upgrades).
2969        if (isUpgrade) {
2970            FileUtils.deleteContents(cacheBaseDir);
2971        }
2972
2973
2974        // Return the versioned package cache directory. This is something like
2975        // "/data/system/package_cache/1"
2976        File cacheDir = FileUtils.createDir(cacheBaseDir, PACKAGE_PARSER_CACHE_VERSION);
2977
2978        // The following is a workaround to aid development on non-numbered userdebug
2979        // builds or cases where "adb sync" is used on userdebug builds. If we detect that
2980        // the system partition is newer.
2981        //
2982        // NOTE: When no BUILD_NUMBER is set by the build system, it defaults to a build
2983        // that starts with "eng." to signify that this is an engineering build and not
2984        // destined for release.
2985        if ("userdebug".equals(Build.TYPE) && Build.VERSION.INCREMENTAL.startsWith("eng.")) {
2986            Slog.w(TAG, "Wiping cache directory because the system partition changed.");
2987
2988            // Heuristic: If the /system directory has been modified recently due to an "adb sync"
2989            // or a regular make, then blow away the cache. Note that mtimes are *NOT* reliable
2990            // in general and should not be used for production changes. In this specific case,
2991            // we know that they will work.
2992            File frameworkDir = new File(Environment.getRootDirectory(), "framework");
2993            if (cacheDir.lastModified() < frameworkDir.lastModified()) {
2994                FileUtils.deleteContents(cacheBaseDir);
2995                cacheDir = FileUtils.createDir(cacheBaseDir, PACKAGE_PARSER_CACHE_VERSION);
2996            }
2997        }
2998
2999        return cacheDir;
3000    }
3001
3002    @Override
3003    public boolean isFirstBoot() {
3004        return mFirstBoot;
3005    }
3006
3007    @Override
3008    public boolean isOnlyCoreApps() {
3009        return mOnlyCore;
3010    }
3011
3012    @Override
3013    public boolean isUpgrade() {
3014        return mIsUpgrade;
3015    }
3016
3017    private @Nullable String getRequiredButNotReallyRequiredVerifierLPr() {
3018        final Intent intent = new Intent(Intent.ACTION_PACKAGE_NEEDS_VERIFICATION);
3019
3020        final List<ResolveInfo> matches = queryIntentReceiversInternal(intent, PACKAGE_MIME_TYPE,
3021                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
3022                UserHandle.USER_SYSTEM);
3023        if (matches.size() == 1) {
3024            return matches.get(0).getComponentInfo().packageName;
3025        } else if (matches.size() == 0) {
3026            Log.e(TAG, "There should probably be a verifier, but, none were found");
3027            return null;
3028        }
3029        throw new RuntimeException("There must be exactly one verifier; found " + matches);
3030    }
3031
3032    private @NonNull String getRequiredSharedLibraryLPr(String name, int version) {
3033        synchronized (mPackages) {
3034            SharedLibraryEntry libraryEntry = getSharedLibraryEntryLPr(name, version);
3035            if (libraryEntry == null) {
3036                throw new IllegalStateException("Missing required shared library:" + name);
3037            }
3038            return libraryEntry.apk;
3039        }
3040    }
3041
3042    private @NonNull String getRequiredInstallerLPr() {
3043        final Intent intent = new Intent(Intent.ACTION_INSTALL_PACKAGE);
3044        intent.addCategory(Intent.CATEGORY_DEFAULT);
3045        intent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE);
3046
3047        final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, PACKAGE_MIME_TYPE,
3048                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
3049                UserHandle.USER_SYSTEM);
3050        if (matches.size() == 1) {
3051            ResolveInfo resolveInfo = matches.get(0);
3052            if (!resolveInfo.activityInfo.applicationInfo.isPrivilegedApp()) {
3053                throw new RuntimeException("The installer must be a privileged app");
3054            }
3055            return matches.get(0).getComponentInfo().packageName;
3056        } else {
3057            throw new RuntimeException("There must be exactly one installer; found " + matches);
3058        }
3059    }
3060
3061    private @NonNull String getRequiredUninstallerLPr() {
3062        final Intent intent = new Intent(Intent.ACTION_UNINSTALL_PACKAGE);
3063        intent.addCategory(Intent.CATEGORY_DEFAULT);
3064        intent.setData(Uri.fromParts(PACKAGE_SCHEME, "foo.bar", null));
3065
3066        final ResolveInfo resolveInfo = resolveIntent(intent, null,
3067                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
3068                UserHandle.USER_SYSTEM);
3069        if (resolveInfo == null ||
3070                mResolveActivity.name.equals(resolveInfo.getComponentInfo().name)) {
3071            throw new RuntimeException("There must be exactly one uninstaller; found "
3072                    + resolveInfo);
3073        }
3074        return resolveInfo.getComponentInfo().packageName;
3075    }
3076
3077    private @NonNull ComponentName getIntentFilterVerifierComponentNameLPr() {
3078        final Intent intent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION);
3079
3080        final List<ResolveInfo> matches = queryIntentReceiversInternal(intent, PACKAGE_MIME_TYPE,
3081                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
3082                UserHandle.USER_SYSTEM);
3083        ResolveInfo best = null;
3084        final int N = matches.size();
3085        for (int i = 0; i < N; i++) {
3086            final ResolveInfo cur = matches.get(i);
3087            final String packageName = cur.getComponentInfo().packageName;
3088            if (checkPermission(android.Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT,
3089                    packageName, UserHandle.USER_SYSTEM) != PackageManager.PERMISSION_GRANTED) {
3090                continue;
3091            }
3092
3093            if (best == null || cur.priority > best.priority) {
3094                best = cur;
3095            }
3096        }
3097
3098        if (best != null) {
3099            return best.getComponentInfo().getComponentName();
3100        } else {
3101            throw new RuntimeException("There must be at least one intent filter verifier");
3102        }
3103    }
3104
3105    private @Nullable ComponentName getEphemeralResolverLPr() {
3106        final String[] packageArray =
3107                mContext.getResources().getStringArray(R.array.config_ephemeralResolverPackage);
3108        if (packageArray.length == 0 && !Build.IS_DEBUGGABLE) {
3109            if (DEBUG_EPHEMERAL) {
3110                Slog.d(TAG, "Ephemeral resolver NOT found; empty package list");
3111            }
3112            return null;
3113        }
3114
3115        final int resolveFlags =
3116                MATCH_DIRECT_BOOT_AWARE
3117                | MATCH_DIRECT_BOOT_UNAWARE
3118                | (!Build.IS_DEBUGGABLE ? MATCH_SYSTEM_ONLY : 0);
3119        final Intent resolverIntent = new Intent(Intent.ACTION_RESOLVE_EPHEMERAL_PACKAGE);
3120        final List<ResolveInfo> resolvers = queryIntentServicesInternal(resolverIntent, null,
3121                resolveFlags, UserHandle.USER_SYSTEM);
3122
3123        final int N = resolvers.size();
3124        if (N == 0) {
3125            if (DEBUG_EPHEMERAL) {
3126                Slog.d(TAG, "Ephemeral resolver NOT found; no matching intent filters");
3127            }
3128            return null;
3129        }
3130
3131        final Set<String> possiblePackages = new ArraySet<>(Arrays.asList(packageArray));
3132        for (int i = 0; i < N; i++) {
3133            final ResolveInfo info = resolvers.get(i);
3134
3135            if (info.serviceInfo == null) {
3136                continue;
3137            }
3138
3139            final String packageName = info.serviceInfo.packageName;
3140            if (!possiblePackages.contains(packageName) && !Build.IS_DEBUGGABLE) {
3141                if (DEBUG_EPHEMERAL) {
3142                    Slog.d(TAG, "Ephemeral resolver not in allowed package list;"
3143                            + " pkg: " + packageName + ", info:" + info);
3144                }
3145                continue;
3146            }
3147
3148            if (DEBUG_EPHEMERAL) {
3149                Slog.v(TAG, "Ephemeral resolver found;"
3150                        + " pkg: " + packageName + ", info:" + info);
3151            }
3152            return new ComponentName(packageName, info.serviceInfo.name);
3153        }
3154        if (DEBUG_EPHEMERAL) {
3155            Slog.v(TAG, "Ephemeral resolver NOT found");
3156        }
3157        return null;
3158    }
3159
3160    private @Nullable ComponentName getEphemeralInstallerLPr() {
3161        final Intent intent = new Intent(Intent.ACTION_INSTALL_EPHEMERAL_PACKAGE);
3162        intent.addCategory(Intent.CATEGORY_DEFAULT);
3163        intent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE);
3164
3165        final int resolveFlags =
3166                MATCH_DIRECT_BOOT_AWARE
3167                | MATCH_DIRECT_BOOT_UNAWARE
3168                | (!Build.IS_DEBUGGABLE ? MATCH_SYSTEM_ONLY : 0);
3169        final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, PACKAGE_MIME_TYPE,
3170                resolveFlags, UserHandle.USER_SYSTEM);
3171        Iterator<ResolveInfo> iter = matches.iterator();
3172        while (iter.hasNext()) {
3173            final ResolveInfo rInfo = iter.next();
3174            final PackageSetting ps = mSettings.mPackages.get(rInfo.activityInfo.packageName);
3175            if (ps != null) {
3176                final PermissionsState permissionsState = ps.getPermissionsState();
3177                if (permissionsState.hasPermission(Manifest.permission.INSTALL_PACKAGES, 0)) {
3178                    continue;
3179                }
3180            }
3181            iter.remove();
3182        }
3183        if (matches.size() == 0) {
3184            return null;
3185        } else if (matches.size() == 1) {
3186            return matches.get(0).getComponentInfo().getComponentName();
3187        } else {
3188            throw new RuntimeException(
3189                    "There must be at most one ephemeral installer; found " + matches);
3190        }
3191    }
3192
3193    private void primeDomainVerificationsLPw(int userId) {
3194        if (DEBUG_DOMAIN_VERIFICATION) {
3195            Slog.d(TAG, "Priming domain verifications in user " + userId);
3196        }
3197
3198        SystemConfig systemConfig = SystemConfig.getInstance();
3199        ArraySet<String> packages = systemConfig.getLinkedApps();
3200
3201        for (String packageName : packages) {
3202            PackageParser.Package pkg = mPackages.get(packageName);
3203            if (pkg != null) {
3204                if (!pkg.isSystemApp()) {
3205                    Slog.w(TAG, "Non-system app '" + packageName + "' in sysconfig <app-link>");
3206                    continue;
3207                }
3208
3209                ArraySet<String> domains = null;
3210                for (PackageParser.Activity a : pkg.activities) {
3211                    for (ActivityIntentInfo filter : a.intents) {
3212                        if (hasValidDomains(filter)) {
3213                            if (domains == null) {
3214                                domains = new ArraySet<String>();
3215                            }
3216                            domains.addAll(filter.getHostsList());
3217                        }
3218                    }
3219                }
3220
3221                if (domains != null && domains.size() > 0) {
3222                    if (DEBUG_DOMAIN_VERIFICATION) {
3223                        Slog.v(TAG, "      + " + packageName);
3224                    }
3225                    // 'Undefined' in the global IntentFilterVerificationInfo, i.e. the usual
3226                    // state w.r.t. the formal app-linkage "no verification attempted" state;
3227                    // and then 'always' in the per-user state actually used for intent resolution.
3228                    final IntentFilterVerificationInfo ivi;
3229                    ivi = mSettings.createIntentFilterVerificationIfNeededLPw(packageName, domains);
3230                    ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED);
3231                    mSettings.updateIntentFilterVerificationStatusLPw(packageName,
3232                            INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS, userId);
3233                } else {
3234                    Slog.w(TAG, "Sysconfig <app-link> package '" + packageName
3235                            + "' does not handle web links");
3236                }
3237            } else {
3238                Slog.w(TAG, "Unknown package " + packageName + " in sysconfig <app-link>");
3239            }
3240        }
3241
3242        scheduleWritePackageRestrictionsLocked(userId);
3243        scheduleWriteSettingsLocked();
3244    }
3245
3246    private void applyFactoryDefaultBrowserLPw(int userId) {
3247        // The default browser app's package name is stored in a string resource,
3248        // with a product-specific overlay used for vendor customization.
3249        String browserPkg = mContext.getResources().getString(
3250                com.android.internal.R.string.default_browser);
3251        if (!TextUtils.isEmpty(browserPkg)) {
3252            // non-empty string => required to be a known package
3253            PackageSetting ps = mSettings.mPackages.get(browserPkg);
3254            if (ps == null) {
3255                Slog.e(TAG, "Product default browser app does not exist: " + browserPkg);
3256                browserPkg = null;
3257            } else {
3258                mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId);
3259            }
3260        }
3261
3262        // Nothing valid explicitly set? Make the factory-installed browser the explicit
3263        // default.  If there's more than one, just leave everything alone.
3264        if (browserPkg == null) {
3265            calculateDefaultBrowserLPw(userId);
3266        }
3267    }
3268
3269    private void calculateDefaultBrowserLPw(int userId) {
3270        List<String> allBrowsers = resolveAllBrowserApps(userId);
3271        final String browserPkg = (allBrowsers.size() == 1) ? allBrowsers.get(0) : null;
3272        mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId);
3273    }
3274
3275    private List<String> resolveAllBrowserApps(int userId) {
3276        // Resolve the canonical browser intent and check that the handleAllWebDataURI boolean is set
3277        List<ResolveInfo> list = queryIntentActivitiesInternal(sBrowserIntent, null,
3278                PackageManager.MATCH_ALL, userId);
3279
3280        final int count = list.size();
3281        List<String> result = new ArrayList<String>(count);
3282        for (int i=0; i<count; i++) {
3283            ResolveInfo info = list.get(i);
3284            if (info.activityInfo == null
3285                    || !info.handleAllWebDataURI
3286                    || (info.activityInfo.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) == 0
3287                    || result.contains(info.activityInfo.packageName)) {
3288                continue;
3289            }
3290            result.add(info.activityInfo.packageName);
3291        }
3292
3293        return result;
3294    }
3295
3296    private boolean packageIsBrowser(String packageName, int userId) {
3297        List<ResolveInfo> list = queryIntentActivitiesInternal(sBrowserIntent, null,
3298                PackageManager.MATCH_ALL, userId);
3299        final int N = list.size();
3300        for (int i = 0; i < N; i++) {
3301            ResolveInfo info = list.get(i);
3302            if (packageName.equals(info.activityInfo.packageName)) {
3303                return true;
3304            }
3305        }
3306        return false;
3307    }
3308
3309    private void checkDefaultBrowser() {
3310        final int myUserId = UserHandle.myUserId();
3311        final String packageName = getDefaultBrowserPackageName(myUserId);
3312        if (packageName != null) {
3313            PackageInfo info = getPackageInfo(packageName, 0, myUserId);
3314            if (info == null) {
3315                Slog.w(TAG, "Default browser no longer installed: " + packageName);
3316                synchronized (mPackages) {
3317                    applyFactoryDefaultBrowserLPw(myUserId);    // leaves ambiguous when > 1
3318                }
3319            }
3320        }
3321    }
3322
3323    @Override
3324    public boolean onTransact(int code, Parcel data, Parcel reply, int flags)
3325            throws RemoteException {
3326        try {
3327            return super.onTransact(code, data, reply, flags);
3328        } catch (RuntimeException e) {
3329            if (!(e instanceof SecurityException) && !(e instanceof IllegalArgumentException)) {
3330                Slog.wtf(TAG, "Package Manager Crash", e);
3331            }
3332            throw e;
3333        }
3334    }
3335
3336    static int[] appendInts(int[] cur, int[] add) {
3337        if (add == null) return cur;
3338        if (cur == null) return add;
3339        final int N = add.length;
3340        for (int i=0; i<N; i++) {
3341            cur = appendInt(cur, add[i]);
3342        }
3343        return cur;
3344    }
3345
3346    private PackageInfo generatePackageInfo(PackageSetting ps, int flags, int userId) {
3347        if (!sUserManager.exists(userId)) return null;
3348        if (ps == null) {
3349            return null;
3350        }
3351        final PackageParser.Package p = ps.pkg;
3352        if (p == null) {
3353            return null;
3354        }
3355        // Filter out ephemeral app metadata:
3356        //   * The system/shell/root can see metadata for any app
3357        //   * An installed app can see metadata for 1) other installed apps
3358        //     and 2) ephemeral apps that have explicitly interacted with it
3359        //   * Ephemeral apps can only see their own metadata
3360        //   * Holding a signature permission allows seeing instant apps
3361        final int callingAppId = UserHandle.getAppId(Binder.getCallingUid());
3362        if (callingAppId != Process.SYSTEM_UID
3363                && callingAppId != Process.SHELL_UID
3364                && callingAppId != Process.ROOT_UID
3365                && checkUidPermission(Manifest.permission.ACCESS_INSTANT_APPS,
3366                        Binder.getCallingUid()) != PackageManager.PERMISSION_GRANTED) {
3367            final String instantAppPackageName = getInstantAppPackageName(Binder.getCallingUid());
3368            if (instantAppPackageName != null) {
3369                // ephemeral apps can only get information on themselves
3370                if (!instantAppPackageName.equals(p.packageName)) {
3371                    return null;
3372                }
3373            } else {
3374                if (ps.getInstantApp(userId)) {
3375                    // only get access to the ephemeral app if we've been granted access
3376                    if (!mInstantAppRegistry.isInstantAccessGranted(
3377                            userId, callingAppId, ps.appId)) {
3378                        return null;
3379                    }
3380                }
3381            }
3382        }
3383
3384        final PermissionsState permissionsState = ps.getPermissionsState();
3385
3386        // Compute GIDs only if requested
3387        final int[] gids = (flags & PackageManager.GET_GIDS) == 0
3388                ? EMPTY_INT_ARRAY : permissionsState.computeGids(userId);
3389        // Compute granted permissions only if package has requested permissions
3390        final Set<String> permissions = ArrayUtils.isEmpty(p.requestedPermissions)
3391                ? Collections.<String>emptySet() : permissionsState.getPermissions(userId);
3392        final PackageUserState state = ps.readUserState(userId);
3393
3394        if ((flags & MATCH_UNINSTALLED_PACKAGES) != 0
3395                && ps.isSystem()) {
3396            flags |= MATCH_ANY_USER;
3397        }
3398
3399        PackageInfo packageInfo = PackageParser.generatePackageInfo(p, gids, flags,
3400                ps.firstInstallTime, ps.lastUpdateTime, permissions, state, userId);
3401
3402        if (packageInfo == null) {
3403            return null;
3404        }
3405
3406        packageInfo.packageName = packageInfo.applicationInfo.packageName =
3407                resolveExternalPackageNameLPr(p);
3408
3409        return packageInfo;
3410    }
3411
3412    @Override
3413    public void checkPackageStartable(String packageName, int userId) {
3414        final boolean userKeyUnlocked = StorageManager.isUserKeyUnlocked(userId);
3415
3416        synchronized (mPackages) {
3417            final PackageSetting ps = mSettings.mPackages.get(packageName);
3418            if (ps == null) {
3419                throw new SecurityException("Package " + packageName + " was not found!");
3420            }
3421
3422            if (!ps.getInstalled(userId)) {
3423                throw new SecurityException(
3424                        "Package " + packageName + " was not installed for user " + userId + "!");
3425            }
3426
3427            if (mSafeMode && !ps.isSystem()) {
3428                throw new SecurityException("Package " + packageName + " not a system app!");
3429            }
3430
3431            if (mFrozenPackages.contains(packageName)) {
3432                throw new SecurityException("Package " + packageName + " is currently frozen!");
3433            }
3434
3435            if (!userKeyUnlocked && !(ps.pkg.applicationInfo.isDirectBootAware()
3436                    || ps.pkg.applicationInfo.isPartiallyDirectBootAware())) {
3437                throw new SecurityException("Package " + packageName + " is not encryption aware!");
3438            }
3439        }
3440    }
3441
3442    @Override
3443    public boolean isPackageAvailable(String packageName, int userId) {
3444        if (!sUserManager.exists(userId)) return false;
3445        enforceCrossUserPermission(Binder.getCallingUid(), userId,
3446                false /* requireFullPermission */, false /* checkShell */, "is package available");
3447        synchronized (mPackages) {
3448            PackageParser.Package p = mPackages.get(packageName);
3449            if (p != null) {
3450                final PackageSetting ps = (PackageSetting) p.mExtras;
3451                if (ps != null) {
3452                    final PackageUserState state = ps.readUserState(userId);
3453                    if (state != null) {
3454                        return PackageParser.isAvailable(state);
3455                    }
3456                }
3457            }
3458        }
3459        return false;
3460    }
3461
3462    @Override
3463    public PackageInfo getPackageInfo(String packageName, int flags, int userId) {
3464        return getPackageInfoInternal(packageName, PackageManager.VERSION_CODE_HIGHEST,
3465                flags, userId);
3466    }
3467
3468    @Override
3469    public PackageInfo getPackageInfoVersioned(VersionedPackage versionedPackage,
3470            int flags, int userId) {
3471        return getPackageInfoInternal(versionedPackage.getPackageName(),
3472                // TODO: We will change version code to long, so in the new API it is long
3473                (int) versionedPackage.getVersionCode(), flags, userId);
3474    }
3475
3476    private PackageInfo getPackageInfoInternal(String packageName, int versionCode,
3477            int flags, int userId) {
3478        if (!sUserManager.exists(userId)) return null;
3479        flags = updateFlagsForPackage(flags, userId, packageName);
3480        enforceCrossUserPermission(Binder.getCallingUid(), userId,
3481                false /* requireFullPermission */, false /* checkShell */, "get package info");
3482
3483        // reader
3484        synchronized (mPackages) {
3485            // Normalize package name to handle renamed packages and static libs
3486            packageName = resolveInternalPackageNameLPr(packageName, versionCode);
3487
3488            final boolean matchFactoryOnly = (flags & MATCH_FACTORY_ONLY) != 0;
3489            if (matchFactoryOnly) {
3490                final PackageSetting ps = mSettings.getDisabledSystemPkgLPr(packageName);
3491                if (ps != null) {
3492                    if (filterSharedLibPackageLPr(ps, Binder.getCallingUid(), userId)) {
3493                        return null;
3494                    }
3495                    return generatePackageInfo(ps, flags, userId);
3496                }
3497            }
3498
3499            PackageParser.Package p = mPackages.get(packageName);
3500            if (matchFactoryOnly && p != null && !isSystemApp(p)) {
3501                return null;
3502            }
3503            if (DEBUG_PACKAGE_INFO)
3504                Log.v(TAG, "getPackageInfo " + packageName + ": " + p);
3505            if (p != null) {
3506                if (filterSharedLibPackageLPr((PackageSetting) p.mExtras,
3507                        Binder.getCallingUid(), userId)) {
3508                    return null;
3509                }
3510                return generatePackageInfo((PackageSetting)p.mExtras, flags, userId);
3511            }
3512            if (!matchFactoryOnly && (flags & MATCH_KNOWN_PACKAGES) != 0) {
3513                final PackageSetting ps = mSettings.mPackages.get(packageName);
3514                if (filterSharedLibPackageLPr(ps, Binder.getCallingUid(), userId)) {
3515                    return null;
3516                }
3517                return generatePackageInfo(ps, flags, userId);
3518            }
3519        }
3520        return null;
3521    }
3522
3523
3524    private boolean filterSharedLibPackageLPr(@Nullable PackageSetting ps, int uid, int userId) {
3525        // System/shell/root get to see all static libs
3526        final int appId = UserHandle.getAppId(uid);
3527        if (appId == Process.SYSTEM_UID || appId == Process.SHELL_UID
3528                || appId == Process.ROOT_UID) {
3529            return false;
3530        }
3531
3532        // No package means no static lib as it is always on internal storage
3533        if (ps == null || ps.pkg == null || !ps.pkg.applicationInfo.isStaticSharedLibrary()) {
3534            return false;
3535        }
3536
3537        final SharedLibraryEntry libEntry = getSharedLibraryEntryLPr(ps.pkg.staticSharedLibName,
3538                ps.pkg.staticSharedLibVersion);
3539        if (libEntry == null) {
3540            return false;
3541        }
3542
3543        final int resolvedUid = UserHandle.getUid(userId, UserHandle.getAppId(uid));
3544        final String[] uidPackageNames = getPackagesForUid(resolvedUid);
3545        if (uidPackageNames == null) {
3546            return true;
3547        }
3548
3549        for (String uidPackageName : uidPackageNames) {
3550            if (ps.name.equals(uidPackageName)) {
3551                return false;
3552            }
3553            PackageSetting uidPs = mSettings.getPackageLPr(uidPackageName);
3554            if (uidPs != null) {
3555                final int index = ArrayUtils.indexOf(uidPs.usesStaticLibraries,
3556                        libEntry.info.getName());
3557                if (index < 0) {
3558                    continue;
3559                }
3560                if (uidPs.pkg.usesStaticLibrariesVersions[index] == libEntry.info.getVersion()) {
3561                    return false;
3562                }
3563            }
3564        }
3565        return true;
3566    }
3567
3568    @Override
3569    public String[] currentToCanonicalPackageNames(String[] names) {
3570        String[] out = new String[names.length];
3571        // reader
3572        synchronized (mPackages) {
3573            for (int i=names.length-1; i>=0; i--) {
3574                PackageSetting ps = mSettings.mPackages.get(names[i]);
3575                out[i] = ps != null && ps.realName != null ? ps.realName : names[i];
3576            }
3577        }
3578        return out;
3579    }
3580
3581    @Override
3582    public String[] canonicalToCurrentPackageNames(String[] names) {
3583        String[] out = new String[names.length];
3584        // reader
3585        synchronized (mPackages) {
3586            for (int i=names.length-1; i>=0; i--) {
3587                String cur = mSettings.getRenamedPackageLPr(names[i]);
3588                out[i] = cur != null ? cur : names[i];
3589            }
3590        }
3591        return out;
3592    }
3593
3594    @Override
3595    public int getPackageUid(String packageName, int flags, int userId) {
3596        if (!sUserManager.exists(userId)) return -1;
3597        flags = updateFlagsForPackage(flags, userId, packageName);
3598        enforceCrossUserPermission(Binder.getCallingUid(), userId,
3599                false /* requireFullPermission */, false /* checkShell */, "get package uid");
3600
3601        // reader
3602        synchronized (mPackages) {
3603            final PackageParser.Package p = mPackages.get(packageName);
3604            if (p != null && p.isMatch(flags)) {
3605                return UserHandle.getUid(userId, p.applicationInfo.uid);
3606            }
3607            if ((flags & MATCH_KNOWN_PACKAGES) != 0) {
3608                final PackageSetting ps = mSettings.mPackages.get(packageName);
3609                if (ps != null && ps.isMatch(flags)) {
3610                    return UserHandle.getUid(userId, ps.appId);
3611                }
3612            }
3613        }
3614
3615        return -1;
3616    }
3617
3618    @Override
3619    public int[] getPackageGids(String packageName, int flags, int userId) {
3620        if (!sUserManager.exists(userId)) return null;
3621        flags = updateFlagsForPackage(flags, userId, packageName);
3622        enforceCrossUserPermission(Binder.getCallingUid(), userId,
3623                false /* requireFullPermission */, false /* checkShell */,
3624                "getPackageGids");
3625
3626        // reader
3627        synchronized (mPackages) {
3628            final PackageParser.Package p = mPackages.get(packageName);
3629            if (p != null && p.isMatch(flags)) {
3630                PackageSetting ps = (PackageSetting) p.mExtras;
3631                // TODO: Shouldn't this be checking for package installed state for userId and
3632                // return null?
3633                return ps.getPermissionsState().computeGids(userId);
3634            }
3635            if ((flags & MATCH_KNOWN_PACKAGES) != 0) {
3636                final PackageSetting ps = mSettings.mPackages.get(packageName);
3637                if (ps != null && ps.isMatch(flags)) {
3638                    return ps.getPermissionsState().computeGids(userId);
3639                }
3640            }
3641        }
3642
3643        return null;
3644    }
3645
3646    static PermissionInfo generatePermissionInfo(BasePermission bp, int flags) {
3647        if (bp.perm != null) {
3648            return PackageParser.generatePermissionInfo(bp.perm, flags);
3649        }
3650        PermissionInfo pi = new PermissionInfo();
3651        pi.name = bp.name;
3652        pi.packageName = bp.sourcePackage;
3653        pi.nonLocalizedLabel = bp.name;
3654        pi.protectionLevel = bp.protectionLevel;
3655        return pi;
3656    }
3657
3658    @Override
3659    public PermissionInfo getPermissionInfo(String name, int flags) {
3660        // reader
3661        synchronized (mPackages) {
3662            final BasePermission p = mSettings.mPermissions.get(name);
3663            if (p != null) {
3664                return generatePermissionInfo(p, flags);
3665            }
3666            return null;
3667        }
3668    }
3669
3670    @Override
3671    public @Nullable ParceledListSlice<PermissionInfo> queryPermissionsByGroup(String group,
3672            int flags) {
3673        // reader
3674        synchronized (mPackages) {
3675            if (group != null && !mPermissionGroups.containsKey(group)) {
3676                // This is thrown as NameNotFoundException
3677                return null;
3678            }
3679
3680            ArrayList<PermissionInfo> out = new ArrayList<PermissionInfo>(10);
3681            for (BasePermission p : mSettings.mPermissions.values()) {
3682                if (group == null) {
3683                    if (p.perm == null || p.perm.info.group == null) {
3684                        out.add(generatePermissionInfo(p, flags));
3685                    }
3686                } else {
3687                    if (p.perm != null && group.equals(p.perm.info.group)) {
3688                        out.add(PackageParser.generatePermissionInfo(p.perm, flags));
3689                    }
3690                }
3691            }
3692            return new ParceledListSlice<>(out);
3693        }
3694    }
3695
3696    @Override
3697    public PermissionGroupInfo getPermissionGroupInfo(String name, int flags) {
3698        // reader
3699        synchronized (mPackages) {
3700            return PackageParser.generatePermissionGroupInfo(
3701                    mPermissionGroups.get(name), flags);
3702        }
3703    }
3704
3705    @Override
3706    public @NonNull ParceledListSlice<PermissionGroupInfo> getAllPermissionGroups(int flags) {
3707        // reader
3708        synchronized (mPackages) {
3709            final int N = mPermissionGroups.size();
3710            ArrayList<PermissionGroupInfo> out
3711                    = new ArrayList<PermissionGroupInfo>(N);
3712            for (PackageParser.PermissionGroup pg : mPermissionGroups.values()) {
3713                out.add(PackageParser.generatePermissionGroupInfo(pg, flags));
3714            }
3715            return new ParceledListSlice<>(out);
3716        }
3717    }
3718
3719    private ApplicationInfo generateApplicationInfoFromSettingsLPw(String packageName, int flags,
3720            int uid, int userId) {
3721        if (!sUserManager.exists(userId)) return null;
3722        PackageSetting ps = mSettings.mPackages.get(packageName);
3723        if (ps != null) {
3724            if (filterSharedLibPackageLPr(ps, uid, userId)) {
3725                return null;
3726            }
3727            if (ps.pkg == null) {
3728                final PackageInfo pInfo = generatePackageInfo(ps, flags, userId);
3729                if (pInfo != null) {
3730                    return pInfo.applicationInfo;
3731                }
3732                return null;
3733            }
3734            ApplicationInfo ai = PackageParser.generateApplicationInfo(ps.pkg, flags,
3735                    ps.readUserState(userId), userId);
3736            if (ai != null) {
3737                ai.packageName = resolveExternalPackageNameLPr(ps.pkg);
3738            }
3739            return ai;
3740        }
3741        return null;
3742    }
3743
3744    @Override
3745    public ApplicationInfo getApplicationInfo(String packageName, int flags, int userId) {
3746        if (!sUserManager.exists(userId)) return null;
3747        flags = updateFlagsForApplication(flags, userId, packageName);
3748        enforceCrossUserPermission(Binder.getCallingUid(), userId,
3749                false /* requireFullPermission */, false /* checkShell */, "get application info");
3750
3751        // writer
3752        synchronized (mPackages) {
3753            // Normalize package name to handle renamed packages and static libs
3754            packageName = resolveInternalPackageNameLPr(packageName,
3755                    PackageManager.VERSION_CODE_HIGHEST);
3756
3757            PackageParser.Package p = mPackages.get(packageName);
3758            if (DEBUG_PACKAGE_INFO) Log.v(
3759                    TAG, "getApplicationInfo " + packageName
3760                    + ": " + p);
3761            if (p != null) {
3762                PackageSetting ps = mSettings.mPackages.get(packageName);
3763                if (ps == null) return null;
3764                if (filterSharedLibPackageLPr(ps, Binder.getCallingUid(), userId)) {
3765                    return null;
3766                }
3767                // Note: isEnabledLP() does not apply here - always return info
3768                ApplicationInfo ai = PackageParser.generateApplicationInfo(
3769                        p, flags, ps.readUserState(userId), userId);
3770                if (ai != null) {
3771                    ai.packageName = resolveExternalPackageNameLPr(p);
3772                }
3773                return ai;
3774            }
3775            if ("android".equals(packageName)||"system".equals(packageName)) {
3776                return mAndroidApplication;
3777            }
3778            if ((flags & MATCH_KNOWN_PACKAGES) != 0) {
3779                // Already generates the external package name
3780                return generateApplicationInfoFromSettingsLPw(packageName,
3781                        Binder.getCallingUid(), flags, userId);
3782            }
3783        }
3784        return null;
3785    }
3786
3787    private String normalizePackageNameLPr(String packageName) {
3788        String normalizedPackageName = mSettings.getRenamedPackageLPr(packageName);
3789        return normalizedPackageName != null ? normalizedPackageName : packageName;
3790    }
3791
3792    @Override
3793    public void freeStorageAndNotify(final String volumeUuid, final long freeStorageSize,
3794            final IPackageDataObserver observer) {
3795        mContext.enforceCallingOrSelfPermission(
3796                android.Manifest.permission.CLEAR_APP_CACHE, null);
3797        mHandler.post(() -> {
3798            boolean success = false;
3799            try {
3800                freeStorage(volumeUuid, freeStorageSize, 0);
3801                success = true;
3802            } catch (IOException e) {
3803                Slog.w(TAG, e);
3804            }
3805            if (observer != null) {
3806                try {
3807                    observer.onRemoveCompleted(null, success);
3808                } catch (RemoteException e) {
3809                    Slog.w(TAG, e);
3810                }
3811            }
3812        });
3813    }
3814
3815    @Override
3816    public void freeStorage(final String volumeUuid, final long freeStorageSize,
3817            final IntentSender pi) {
3818        mContext.enforceCallingOrSelfPermission(
3819                android.Manifest.permission.CLEAR_APP_CACHE, TAG);
3820        mHandler.post(() -> {
3821            boolean success = false;
3822            try {
3823                freeStorage(volumeUuid, freeStorageSize, 0);
3824                success = true;
3825            } catch (IOException e) {
3826                Slog.w(TAG, e);
3827            }
3828            if (pi != null) {
3829                try {
3830                    pi.sendIntent(null, success ? 1 : 0, null, null, null);
3831                } catch (SendIntentException e) {
3832                    Slog.w(TAG, e);
3833                }
3834            }
3835        });
3836    }
3837
3838    /**
3839     * Blocking call to clear various types of cached data across the system
3840     * until the requested bytes are available.
3841     */
3842    public void freeStorage(String volumeUuid, long bytes, int storageFlags) throws IOException {
3843        final StorageManager storage = mContext.getSystemService(StorageManager.class);
3844        final File file = storage.findPathForUuid(volumeUuid);
3845
3846        if (ENABLE_FREE_CACHE_V2) {
3847            final boolean aggressive = (storageFlags
3848                    & StorageManager.FLAG_ALLOCATE_AGGRESSIVE) != 0;
3849
3850            // 1. Pre-flight to determine if we have any chance to succeed
3851            // 2. Consider preloaded data (after 1w honeymoon, unless aggressive)
3852
3853            // 3. Consider parsed APK data (aggressive only)
3854            if (aggressive) {
3855                FileUtils.deleteContents(mCacheDir);
3856            }
3857            if (file.getUsableSpace() >= bytes) return;
3858
3859            // 4. Consider cached app data (above quotas)
3860            try {
3861                mInstaller.freeCache(volumeUuid, bytes, Installer.FLAG_FREE_CACHE_V2);
3862            } catch (InstallerException ignored) {
3863            }
3864            if (file.getUsableSpace() >= bytes) return;
3865
3866            // 5. Consider shared libraries with refcount=0 and age>2h
3867            // 6. Consider dexopt output (aggressive only)
3868            // 7. Consider ephemeral apps not used in last week
3869
3870            // 8. Consider cached app data (below quotas)
3871            try {
3872                mInstaller.freeCache(volumeUuid, bytes, Installer.FLAG_FREE_CACHE_V2
3873                        | Installer.FLAG_FREE_CACHE_V2_DEFY_QUOTA);
3874            } catch (InstallerException ignored) {
3875            }
3876            if (file.getUsableSpace() >= bytes) return;
3877
3878            // 9. Consider DropBox entries
3879            // 10. Consider ephemeral cookies
3880
3881        } else {
3882            try {
3883                mInstaller.freeCache(volumeUuid, bytes, 0);
3884            } catch (InstallerException ignored) {
3885            }
3886            if (file.getUsableSpace() >= bytes) return;
3887        }
3888
3889        throw new IOException("Failed to free " + bytes + " on storage device at " + file);
3890    }
3891
3892    /**
3893     * Update given flags based on encryption status of current user.
3894     */
3895    private int updateFlags(int flags, int userId) {
3896        if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE
3897                | PackageManager.MATCH_DIRECT_BOOT_AWARE)) != 0) {
3898            // Caller expressed an explicit opinion about what encryption
3899            // aware/unaware components they want to see, so fall through and
3900            // give them what they want
3901        } else {
3902            // Caller expressed no opinion, so match based on user state
3903            if (getUserManagerInternal().isUserUnlockingOrUnlocked(userId)) {
3904                flags |= PackageManager.MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE;
3905            } else {
3906                flags |= PackageManager.MATCH_DIRECT_BOOT_AWARE;
3907            }
3908        }
3909        return flags;
3910    }
3911
3912    private UserManagerInternal getUserManagerInternal() {
3913        if (mUserManagerInternal == null) {
3914            mUserManagerInternal = LocalServices.getService(UserManagerInternal.class);
3915        }
3916        return mUserManagerInternal;
3917    }
3918
3919    private DeviceIdleController.LocalService getDeviceIdleController() {
3920        if (mDeviceIdleController == null) {
3921            mDeviceIdleController =
3922                    LocalServices.getService(DeviceIdleController.LocalService.class);
3923        }
3924        return mDeviceIdleController;
3925    }
3926
3927    /**
3928     * Update given flags when being used to request {@link PackageInfo}.
3929     */
3930    private int updateFlagsForPackage(int flags, int userId, Object cookie) {
3931        final boolean isCallerSystemUser = UserHandle.getCallingUserId() == UserHandle.USER_SYSTEM;
3932        boolean triaged = true;
3933        if ((flags & (PackageManager.GET_ACTIVITIES | PackageManager.GET_RECEIVERS
3934                | PackageManager.GET_SERVICES | PackageManager.GET_PROVIDERS)) != 0) {
3935            // Caller is asking for component details, so they'd better be
3936            // asking for specific encryption matching behavior, or be triaged
3937            if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE
3938                    | PackageManager.MATCH_DIRECT_BOOT_AWARE
3939                    | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) {
3940                triaged = false;
3941            }
3942        }
3943        if ((flags & (PackageManager.MATCH_UNINSTALLED_PACKAGES
3944                | PackageManager.MATCH_SYSTEM_ONLY
3945                | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) {
3946            triaged = false;
3947        }
3948        if ((flags & PackageManager.MATCH_ANY_USER) != 0) {
3949            enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false,
3950                    "MATCH_ANY_USER flag requires INTERACT_ACROSS_USERS permission at "
3951                    + Debug.getCallers(5));
3952        } else if ((flags & PackageManager.MATCH_UNINSTALLED_PACKAGES) != 0 && isCallerSystemUser
3953                && sUserManager.hasManagedProfile(UserHandle.USER_SYSTEM)) {
3954            // If the caller wants all packages and has a restricted profile associated with it,
3955            // then match all users. This is to make sure that launchers that need to access work
3956            // profile apps don't start breaking. TODO: Remove this hack when launchers stop using
3957            // MATCH_UNINSTALLED_PACKAGES to query apps in other profiles. b/31000380
3958            flags |= PackageManager.MATCH_ANY_USER;
3959        }
3960        if (DEBUG_TRIAGED_MISSING && (Binder.getCallingUid() == Process.SYSTEM_UID) && !triaged) {
3961            Log.w(TAG, "Caller hasn't been triaged for missing apps; they asked about " + cookie
3962                    + " with flags 0x" + Integer.toHexString(flags), new Throwable());
3963        }
3964        return updateFlags(flags, userId);
3965    }
3966
3967    /**
3968     * Update given flags when being used to request {@link ApplicationInfo}.
3969     */
3970    private int updateFlagsForApplication(int flags, int userId, Object cookie) {
3971        return updateFlagsForPackage(flags, userId, cookie);
3972    }
3973
3974    /**
3975     * Update given flags when being used to request {@link ComponentInfo}.
3976     */
3977    private int updateFlagsForComponent(int flags, int userId, Object cookie) {
3978        if (cookie instanceof Intent) {
3979            if ((((Intent) cookie).getFlags() & Intent.FLAG_DEBUG_TRIAGED_MISSING) != 0) {
3980                flags |= PackageManager.MATCH_DEBUG_TRIAGED_MISSING;
3981            }
3982        }
3983
3984        boolean triaged = true;
3985        // Caller is asking for component details, so they'd better be
3986        // asking for specific encryption matching behavior, or be triaged
3987        if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE
3988                | PackageManager.MATCH_DIRECT_BOOT_AWARE
3989                | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) {
3990            triaged = false;
3991        }
3992        if (DEBUG_TRIAGED_MISSING && (Binder.getCallingUid() == Process.SYSTEM_UID) && !triaged) {
3993            Log.w(TAG, "Caller hasn't been triaged for missing apps; they asked about " + cookie
3994                    + " with flags 0x" + Integer.toHexString(flags), new Throwable());
3995        }
3996
3997        return updateFlags(flags, userId);
3998    }
3999
4000    /**
4001     * Update given intent when being used to request {@link ResolveInfo}.
4002     */
4003    private Intent updateIntentForResolve(Intent intent) {
4004        if (intent.getSelector() != null) {
4005            intent = intent.getSelector();
4006        }
4007        if (DEBUG_PREFERRED) {
4008            intent.addFlags(Intent.FLAG_DEBUG_LOG_RESOLUTION);
4009        }
4010        return intent;
4011    }
4012
4013    /**
4014     * Update given flags when being used to request {@link ResolveInfo}.
4015     */
4016    int updateFlagsForResolve(int flags, int userId, Object cookie) {
4017        // Safe mode means we shouldn't match any third-party components
4018        if (mSafeMode) {
4019            flags |= PackageManager.MATCH_SYSTEM_ONLY;
4020        }
4021        final int callingUid = Binder.getCallingUid();
4022        if (getInstantAppPackageName(callingUid) != null) {
4023            // But, ephemeral apps see both ephemeral and exposed, non-ephemeral components
4024            flags |= PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY;
4025            flags |= PackageManager.MATCH_INSTANT;
4026        } else {
4027            // Otherwise, prevent leaking ephemeral components
4028            flags &= ~PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY;
4029            if (callingUid != Process.SYSTEM_UID
4030                    && callingUid != Process.SHELL_UID
4031                    && callingUid != 0) {
4032                // Unless called from the system process
4033                flags &= ~PackageManager.MATCH_INSTANT;
4034            }
4035        }
4036        return updateFlagsForComponent(flags, userId, cookie);
4037    }
4038
4039    @Override
4040    public ActivityInfo getActivityInfo(ComponentName component, int flags, int userId) {
4041        if (!sUserManager.exists(userId)) return null;
4042        flags = updateFlagsForComponent(flags, userId, component);
4043        enforceCrossUserPermission(Binder.getCallingUid(), userId,
4044                false /* requireFullPermission */, false /* checkShell */, "get activity info");
4045        synchronized (mPackages) {
4046            PackageParser.Activity a = mActivities.mActivities.get(component);
4047
4048            if (DEBUG_PACKAGE_INFO) Log.v(TAG, "getActivityInfo " + component + ": " + a);
4049            if (a != null && mSettings.isEnabledAndMatchLPr(a.info, flags, userId)) {
4050                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
4051                if (ps == null) return null;
4052                return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId),
4053                        userId);
4054            }
4055            if (mResolveComponentName.equals(component)) {
4056                return PackageParser.generateActivityInfo(mResolveActivity, flags,
4057                        new PackageUserState(), userId);
4058            }
4059        }
4060        return null;
4061    }
4062
4063    @Override
4064    public boolean activitySupportsIntent(ComponentName component, Intent intent,
4065            String resolvedType) {
4066        synchronized (mPackages) {
4067            if (component.equals(mResolveComponentName)) {
4068                // The resolver supports EVERYTHING!
4069                return true;
4070            }
4071            PackageParser.Activity a = mActivities.mActivities.get(component);
4072            if (a == null) {
4073                return false;
4074            }
4075            for (int i=0; i<a.intents.size(); i++) {
4076                if (a.intents.get(i).match(intent.getAction(), resolvedType, intent.getScheme(),
4077                        intent.getData(), intent.getCategories(), TAG) >= 0) {
4078                    return true;
4079                }
4080            }
4081            return false;
4082        }
4083    }
4084
4085    @Override
4086    public ActivityInfo getReceiverInfo(ComponentName component, int flags, int userId) {
4087        if (!sUserManager.exists(userId)) return null;
4088        flags = updateFlagsForComponent(flags, userId, component);
4089        enforceCrossUserPermission(Binder.getCallingUid(), userId,
4090                false /* requireFullPermission */, false /* checkShell */, "get receiver info");
4091        synchronized (mPackages) {
4092            PackageParser.Activity a = mReceivers.mActivities.get(component);
4093            if (DEBUG_PACKAGE_INFO) Log.v(
4094                TAG, "getReceiverInfo " + component + ": " + a);
4095            if (a != null && mSettings.isEnabledAndMatchLPr(a.info, flags, userId)) {
4096                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
4097                if (ps == null) return null;
4098                return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId),
4099                        userId);
4100            }
4101        }
4102        return null;
4103    }
4104
4105    @Override
4106    public ParceledListSlice<SharedLibraryInfo> getSharedLibraries(int flags, int userId) {
4107        if (!sUserManager.exists(userId)) return null;
4108        Preconditions.checkArgumentNonnegative(userId, "userId must be >= 0");
4109
4110        flags = updateFlagsForPackage(flags, userId, null);
4111
4112        final boolean canSeeStaticLibraries =
4113                mContext.checkCallingOrSelfPermission(INSTALL_PACKAGES)
4114                        == PERMISSION_GRANTED
4115                || mContext.checkCallingOrSelfPermission(DELETE_PACKAGES)
4116                        == PERMISSION_GRANTED
4117                || mContext.checkCallingOrSelfPermission(REQUEST_INSTALL_PACKAGES)
4118                        == PERMISSION_GRANTED
4119                || mContext.checkCallingOrSelfPermission(REQUEST_DELETE_PACKAGES)
4120                        == PERMISSION_GRANTED;
4121
4122        synchronized (mPackages) {
4123            List<SharedLibraryInfo> result = null;
4124
4125            final int libCount = mSharedLibraries.size();
4126            for (int i = 0; i < libCount; i++) {
4127                SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.valueAt(i);
4128                if (versionedLib == null) {
4129                    continue;
4130                }
4131
4132                final int versionCount = versionedLib.size();
4133                for (int j = 0; j < versionCount; j++) {
4134                    SharedLibraryInfo libInfo = versionedLib.valueAt(j).info;
4135                    if (!canSeeStaticLibraries && libInfo.isStatic()) {
4136                        break;
4137                    }
4138                    final long identity = Binder.clearCallingIdentity();
4139                    try {
4140                        // TODO: We will change version code to long, so in the new API it is long
4141                        PackageInfo packageInfo = getPackageInfoVersioned(
4142                                libInfo.getDeclaringPackage(), flags, userId);
4143                        if (packageInfo == null) {
4144                            continue;
4145                        }
4146                    } finally {
4147                        Binder.restoreCallingIdentity(identity);
4148                    }
4149
4150                    SharedLibraryInfo resLibInfo = new SharedLibraryInfo(libInfo.getName(),
4151                            libInfo.getVersion(), libInfo.getType(), libInfo.getDeclaringPackage(),
4152                            getPackagesUsingSharedLibraryLPr(libInfo, flags, userId));
4153
4154                    if (result == null) {
4155                        result = new ArrayList<>();
4156                    }
4157                    result.add(resLibInfo);
4158                }
4159            }
4160
4161            return result != null ? new ParceledListSlice<>(result) : null;
4162        }
4163    }
4164
4165    private List<VersionedPackage> getPackagesUsingSharedLibraryLPr(
4166            SharedLibraryInfo libInfo, int flags, int userId) {
4167        List<VersionedPackage> versionedPackages = null;
4168        final int packageCount = mSettings.mPackages.size();
4169        for (int i = 0; i < packageCount; i++) {
4170            PackageSetting ps = mSettings.mPackages.valueAt(i);
4171
4172            if (ps == null) {
4173                continue;
4174            }
4175
4176            if (!ps.getUserState().get(userId).isAvailable(flags)) {
4177                continue;
4178            }
4179
4180            final String libName = libInfo.getName();
4181            if (libInfo.isStatic()) {
4182                final int libIdx = ArrayUtils.indexOf(ps.usesStaticLibraries, libName);
4183                if (libIdx < 0) {
4184                    continue;
4185                }
4186                if (ps.usesStaticLibrariesVersions[libIdx] != libInfo.getVersion()) {
4187                    continue;
4188                }
4189                if (versionedPackages == null) {
4190                    versionedPackages = new ArrayList<>();
4191                }
4192                // If the dependent is a static shared lib, use the public package name
4193                String dependentPackageName = ps.name;
4194                if (ps.pkg != null && ps.pkg.applicationInfo.isStaticSharedLibrary()) {
4195                    dependentPackageName = ps.pkg.manifestPackageName;
4196                }
4197                versionedPackages.add(new VersionedPackage(dependentPackageName, ps.versionCode));
4198            } else if (ps.pkg != null) {
4199                if (ArrayUtils.contains(ps.pkg.usesLibraries, libName)
4200                        || ArrayUtils.contains(ps.pkg.usesOptionalLibraries, libName)) {
4201                    if (versionedPackages == null) {
4202                        versionedPackages = new ArrayList<>();
4203                    }
4204                    versionedPackages.add(new VersionedPackage(ps.name, ps.versionCode));
4205                }
4206            }
4207        }
4208
4209        return versionedPackages;
4210    }
4211
4212    @Override
4213    public ServiceInfo getServiceInfo(ComponentName component, int flags, int userId) {
4214        if (!sUserManager.exists(userId)) return null;
4215        flags = updateFlagsForComponent(flags, userId, component);
4216        enforceCrossUserPermission(Binder.getCallingUid(), userId,
4217                false /* requireFullPermission */, false /* checkShell */, "get service info");
4218        synchronized (mPackages) {
4219            PackageParser.Service s = mServices.mServices.get(component);
4220            if (DEBUG_PACKAGE_INFO) Log.v(
4221                TAG, "getServiceInfo " + component + ": " + s);
4222            if (s != null && mSettings.isEnabledAndMatchLPr(s.info, flags, userId)) {
4223                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
4224                if (ps == null) return null;
4225                return PackageParser.generateServiceInfo(s, flags, ps.readUserState(userId),
4226                        userId);
4227            }
4228        }
4229        return null;
4230    }
4231
4232    @Override
4233    public ProviderInfo getProviderInfo(ComponentName component, int flags, int userId) {
4234        if (!sUserManager.exists(userId)) return null;
4235        flags = updateFlagsForComponent(flags, userId, component);
4236        enforceCrossUserPermission(Binder.getCallingUid(), userId,
4237                false /* requireFullPermission */, false /* checkShell */, "get provider info");
4238        synchronized (mPackages) {
4239            PackageParser.Provider p = mProviders.mProviders.get(component);
4240            if (DEBUG_PACKAGE_INFO) Log.v(
4241                TAG, "getProviderInfo " + component + ": " + p);
4242            if (p != null && mSettings.isEnabledAndMatchLPr(p.info, flags, userId)) {
4243                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
4244                if (ps == null) return null;
4245                return PackageParser.generateProviderInfo(p, flags, ps.readUserState(userId),
4246                        userId);
4247            }
4248        }
4249        return null;
4250    }
4251
4252    @Override
4253    public String[] getSystemSharedLibraryNames() {
4254        synchronized (mPackages) {
4255            Set<String> libs = null;
4256            final int libCount = mSharedLibraries.size();
4257            for (int i = 0; i < libCount; i++) {
4258                SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.valueAt(i);
4259                if (versionedLib == null) {
4260                    continue;
4261                }
4262                final int versionCount = versionedLib.size();
4263                for (int j = 0; j < versionCount; j++) {
4264                    SharedLibraryEntry libEntry = versionedLib.valueAt(j);
4265                    if (!libEntry.info.isStatic()) {
4266                        if (libs == null) {
4267                            libs = new ArraySet<>();
4268                        }
4269                        libs.add(libEntry.info.getName());
4270                        break;
4271                    }
4272                    PackageSetting ps = mSettings.getPackageLPr(libEntry.apk);
4273                    if (ps != null && !filterSharedLibPackageLPr(ps, Binder.getCallingUid(),
4274                            UserHandle.getUserId(Binder.getCallingUid()))) {
4275                        if (libs == null) {
4276                            libs = new ArraySet<>();
4277                        }
4278                        libs.add(libEntry.info.getName());
4279                        break;
4280                    }
4281                }
4282            }
4283
4284            if (libs != null) {
4285                String[] libsArray = new String[libs.size()];
4286                libs.toArray(libsArray);
4287                return libsArray;
4288            }
4289
4290            return null;
4291        }
4292    }
4293
4294    @Override
4295    public @NonNull String getServicesSystemSharedLibraryPackageName() {
4296        synchronized (mPackages) {
4297            return mServicesSystemSharedLibraryPackageName;
4298        }
4299    }
4300
4301    @Override
4302    public @NonNull String getSharedSystemSharedLibraryPackageName() {
4303        synchronized (mPackages) {
4304            return mSharedSystemSharedLibraryPackageName;
4305        }
4306    }
4307
4308    private void updateSequenceNumberLP(String packageName, int[] userList) {
4309        for (int i = userList.length - 1; i >= 0; --i) {
4310            final int userId = userList[i];
4311            SparseArray<String> changedPackages = mChangedPackages.get(userId);
4312            if (changedPackages == null) {
4313                changedPackages = new SparseArray<>();
4314                mChangedPackages.put(userId, changedPackages);
4315            }
4316            Map<String, Integer> sequenceNumbers = mChangedPackagesSequenceNumbers.get(userId);
4317            if (sequenceNumbers == null) {
4318                sequenceNumbers = new HashMap<>();
4319                mChangedPackagesSequenceNumbers.put(userId, sequenceNumbers);
4320            }
4321            final Integer sequenceNumber = sequenceNumbers.get(packageName);
4322            if (sequenceNumber != null) {
4323                changedPackages.remove(sequenceNumber);
4324            }
4325            changedPackages.put(mChangedPackagesSequenceNumber, packageName);
4326            sequenceNumbers.put(packageName, mChangedPackagesSequenceNumber);
4327        }
4328        mChangedPackagesSequenceNumber++;
4329    }
4330
4331    @Override
4332    public ChangedPackages getChangedPackages(int sequenceNumber, int userId) {
4333        synchronized (mPackages) {
4334            if (sequenceNumber >= mChangedPackagesSequenceNumber) {
4335                return null;
4336            }
4337            final SparseArray<String> changedPackages = mChangedPackages.get(userId);
4338            if (changedPackages == null) {
4339                return null;
4340            }
4341            final List<String> packageNames =
4342                    new ArrayList<>(mChangedPackagesSequenceNumber - sequenceNumber);
4343            for (int i = sequenceNumber; i < mChangedPackagesSequenceNumber; i++) {
4344                final String packageName = changedPackages.get(i);
4345                if (packageName != null) {
4346                    packageNames.add(packageName);
4347                }
4348            }
4349            return packageNames.isEmpty()
4350                    ? null : new ChangedPackages(mChangedPackagesSequenceNumber, packageNames);
4351        }
4352    }
4353
4354    @Override
4355    public @NonNull ParceledListSlice<FeatureInfo> getSystemAvailableFeatures() {
4356        ArrayList<FeatureInfo> res;
4357        synchronized (mAvailableFeatures) {
4358            res = new ArrayList<>(mAvailableFeatures.size() + 1);
4359            res.addAll(mAvailableFeatures.values());
4360        }
4361        final FeatureInfo fi = new FeatureInfo();
4362        fi.reqGlEsVersion = SystemProperties.getInt("ro.opengles.version",
4363                FeatureInfo.GL_ES_VERSION_UNDEFINED);
4364        res.add(fi);
4365
4366        return new ParceledListSlice<>(res);
4367    }
4368
4369    @Override
4370    public boolean hasSystemFeature(String name, int version) {
4371        synchronized (mAvailableFeatures) {
4372            final FeatureInfo feat = mAvailableFeatures.get(name);
4373            if (feat == null) {
4374                return false;
4375            } else {
4376                return feat.version >= version;
4377            }
4378        }
4379    }
4380
4381    @Override
4382    public int checkPermission(String permName, String pkgName, int userId) {
4383        if (!sUserManager.exists(userId)) {
4384            return PackageManager.PERMISSION_DENIED;
4385        }
4386
4387        synchronized (mPackages) {
4388            final PackageParser.Package p = mPackages.get(pkgName);
4389            if (p != null && p.mExtras != null) {
4390                final PackageSetting ps = (PackageSetting) p.mExtras;
4391                final PermissionsState permissionsState = ps.getPermissionsState();
4392                if (permissionsState.hasPermission(permName, userId)) {
4393                    return PackageManager.PERMISSION_GRANTED;
4394                }
4395                // Special case: ACCESS_FINE_LOCATION permission includes ACCESS_COARSE_LOCATION
4396                if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && permissionsState
4397                        .hasPermission(Manifest.permission.ACCESS_FINE_LOCATION, userId)) {
4398                    return PackageManager.PERMISSION_GRANTED;
4399                }
4400            }
4401        }
4402
4403        return PackageManager.PERMISSION_DENIED;
4404    }
4405
4406    @Override
4407    public int checkUidPermission(String permName, int uid) {
4408        final int userId = UserHandle.getUserId(uid);
4409
4410        if (!sUserManager.exists(userId)) {
4411            return PackageManager.PERMISSION_DENIED;
4412        }
4413
4414        synchronized (mPackages) {
4415            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
4416            if (obj != null) {
4417                final SettingBase ps = (SettingBase) obj;
4418                final PermissionsState permissionsState = ps.getPermissionsState();
4419                if (permissionsState.hasPermission(permName, userId)) {
4420                    return PackageManager.PERMISSION_GRANTED;
4421                }
4422                // Special case: ACCESS_FINE_LOCATION permission includes ACCESS_COARSE_LOCATION
4423                if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && permissionsState
4424                        .hasPermission(Manifest.permission.ACCESS_FINE_LOCATION, userId)) {
4425                    return PackageManager.PERMISSION_GRANTED;
4426                }
4427            } else {
4428                ArraySet<String> perms = mSystemPermissions.get(uid);
4429                if (perms != null) {
4430                    if (perms.contains(permName)) {
4431                        return PackageManager.PERMISSION_GRANTED;
4432                    }
4433                    if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && perms
4434                            .contains(Manifest.permission.ACCESS_FINE_LOCATION)) {
4435                        return PackageManager.PERMISSION_GRANTED;
4436                    }
4437                }
4438            }
4439        }
4440
4441        return PackageManager.PERMISSION_DENIED;
4442    }
4443
4444    @Override
4445    public boolean isPermissionRevokedByPolicy(String permission, String packageName, int userId) {
4446        if (UserHandle.getCallingUserId() != userId) {
4447            mContext.enforceCallingPermission(
4448                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
4449                    "isPermissionRevokedByPolicy for user " + userId);
4450        }
4451
4452        if (checkPermission(permission, packageName, userId)
4453                == PackageManager.PERMISSION_GRANTED) {
4454            return false;
4455        }
4456
4457        final long identity = Binder.clearCallingIdentity();
4458        try {
4459            final int flags = getPermissionFlags(permission, packageName, userId);
4460            return (flags & PackageManager.FLAG_PERMISSION_POLICY_FIXED) != 0;
4461        } finally {
4462            Binder.restoreCallingIdentity(identity);
4463        }
4464    }
4465
4466    @Override
4467    public String getPermissionControllerPackageName() {
4468        synchronized (mPackages) {
4469            return mRequiredInstallerPackage;
4470        }
4471    }
4472
4473    /**
4474     * Checks if the request is from the system or an app that has INTERACT_ACROSS_USERS
4475     * or INTERACT_ACROSS_USERS_FULL permissions, if the userid is not for the caller.
4476     * @param checkShell whether to prevent shell from access if there's a debugging restriction
4477     * @param message the message to log on security exception
4478     */
4479    void enforceCrossUserPermission(int callingUid, int userId, boolean requireFullPermission,
4480            boolean checkShell, String message) {
4481        if (userId < 0) {
4482            throw new IllegalArgumentException("Invalid userId " + userId);
4483        }
4484        if (checkShell) {
4485            enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, userId);
4486        }
4487        if (userId == UserHandle.getUserId(callingUid)) return;
4488        if (callingUid != Process.SYSTEM_UID && callingUid != 0) {
4489            if (requireFullPermission) {
4490                mContext.enforceCallingOrSelfPermission(
4491                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message);
4492            } else {
4493                try {
4494                    mContext.enforceCallingOrSelfPermission(
4495                            android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message);
4496                } catch (SecurityException se) {
4497                    mContext.enforceCallingOrSelfPermission(
4498                            android.Manifest.permission.INTERACT_ACROSS_USERS, message);
4499                }
4500            }
4501        }
4502    }
4503
4504    void enforceShellRestriction(String restriction, int callingUid, int userHandle) {
4505        if (callingUid == Process.SHELL_UID) {
4506            if (userHandle >= 0
4507                    && sUserManager.hasUserRestriction(restriction, userHandle)) {
4508                throw new SecurityException("Shell does not have permission to access user "
4509                        + userHandle);
4510            } else if (userHandle < 0) {
4511                Slog.e(TAG, "Unable to check shell permission for user " + userHandle + "\n\t"
4512                        + Debug.getCallers(3));
4513            }
4514        }
4515    }
4516
4517    private BasePermission findPermissionTreeLP(String permName) {
4518        for(BasePermission bp : mSettings.mPermissionTrees.values()) {
4519            if (permName.startsWith(bp.name) &&
4520                    permName.length() > bp.name.length() &&
4521                    permName.charAt(bp.name.length()) == '.') {
4522                return bp;
4523            }
4524        }
4525        return null;
4526    }
4527
4528    private BasePermission checkPermissionTreeLP(String permName) {
4529        if (permName != null) {
4530            BasePermission bp = findPermissionTreeLP(permName);
4531            if (bp != null) {
4532                if (bp.uid == UserHandle.getAppId(Binder.getCallingUid())) {
4533                    return bp;
4534                }
4535                throw new SecurityException("Calling uid "
4536                        + Binder.getCallingUid()
4537                        + " is not allowed to add to permission tree "
4538                        + bp.name + " owned by uid " + bp.uid);
4539            }
4540        }
4541        throw new SecurityException("No permission tree found for " + permName);
4542    }
4543
4544    static boolean compareStrings(CharSequence s1, CharSequence s2) {
4545        if (s1 == null) {
4546            return s2 == null;
4547        }
4548        if (s2 == null) {
4549            return false;
4550        }
4551        if (s1.getClass() != s2.getClass()) {
4552            return false;
4553        }
4554        return s1.equals(s2);
4555    }
4556
4557    static boolean comparePermissionInfos(PermissionInfo pi1, PermissionInfo pi2) {
4558        if (pi1.icon != pi2.icon) return false;
4559        if (pi1.logo != pi2.logo) return false;
4560        if (pi1.protectionLevel != pi2.protectionLevel) return false;
4561        if (!compareStrings(pi1.name, pi2.name)) return false;
4562        if (!compareStrings(pi1.nonLocalizedLabel, pi2.nonLocalizedLabel)) return false;
4563        // We'll take care of setting this one.
4564        if (!compareStrings(pi1.packageName, pi2.packageName)) return false;
4565        // These are not currently stored in settings.
4566        //if (!compareStrings(pi1.group, pi2.group)) return false;
4567        //if (!compareStrings(pi1.nonLocalizedDescription, pi2.nonLocalizedDescription)) return false;
4568        //if (pi1.labelRes != pi2.labelRes) return false;
4569        //if (pi1.descriptionRes != pi2.descriptionRes) return false;
4570        return true;
4571    }
4572
4573    int permissionInfoFootprint(PermissionInfo info) {
4574        int size = info.name.length();
4575        if (info.nonLocalizedLabel != null) size += info.nonLocalizedLabel.length();
4576        if (info.nonLocalizedDescription != null) size += info.nonLocalizedDescription.length();
4577        return size;
4578    }
4579
4580    int calculateCurrentPermissionFootprintLocked(BasePermission tree) {
4581        int size = 0;
4582        for (BasePermission perm : mSettings.mPermissions.values()) {
4583            if (perm.uid == tree.uid) {
4584                size += perm.name.length() + permissionInfoFootprint(perm.perm.info);
4585            }
4586        }
4587        return size;
4588    }
4589
4590    void enforcePermissionCapLocked(PermissionInfo info, BasePermission tree) {
4591        // We calculate the max size of permissions defined by this uid and throw
4592        // if that plus the size of 'info' would exceed our stated maximum.
4593        if (tree.uid != Process.SYSTEM_UID) {
4594            final int curTreeSize = calculateCurrentPermissionFootprintLocked(tree);
4595            if (curTreeSize + permissionInfoFootprint(info) > MAX_PERMISSION_TREE_FOOTPRINT) {
4596                throw new SecurityException("Permission tree size cap exceeded");
4597            }
4598        }
4599    }
4600
4601    boolean addPermissionLocked(PermissionInfo info, boolean async) {
4602        if (info.labelRes == 0 && info.nonLocalizedLabel == null) {
4603            throw new SecurityException("Label must be specified in permission");
4604        }
4605        BasePermission tree = checkPermissionTreeLP(info.name);
4606        BasePermission bp = mSettings.mPermissions.get(info.name);
4607        boolean added = bp == null;
4608        boolean changed = true;
4609        int fixedLevel = PermissionInfo.fixProtectionLevel(info.protectionLevel);
4610        if (added) {
4611            enforcePermissionCapLocked(info, tree);
4612            bp = new BasePermission(info.name, tree.sourcePackage,
4613                    BasePermission.TYPE_DYNAMIC);
4614        } else if (bp.type != BasePermission.TYPE_DYNAMIC) {
4615            throw new SecurityException(
4616                    "Not allowed to modify non-dynamic permission "
4617                    + info.name);
4618        } else {
4619            if (bp.protectionLevel == fixedLevel
4620                    && bp.perm.owner.equals(tree.perm.owner)
4621                    && bp.uid == tree.uid
4622                    && comparePermissionInfos(bp.perm.info, info)) {
4623                changed = false;
4624            }
4625        }
4626        bp.protectionLevel = fixedLevel;
4627        info = new PermissionInfo(info);
4628        info.protectionLevel = fixedLevel;
4629        bp.perm = new PackageParser.Permission(tree.perm.owner, info);
4630        bp.perm.info.packageName = tree.perm.info.packageName;
4631        bp.uid = tree.uid;
4632        if (added) {
4633            mSettings.mPermissions.put(info.name, bp);
4634        }
4635        if (changed) {
4636            if (!async) {
4637                mSettings.writeLPr();
4638            } else {
4639                scheduleWriteSettingsLocked();
4640            }
4641        }
4642        return added;
4643    }
4644
4645    @Override
4646    public boolean addPermission(PermissionInfo info) {
4647        synchronized (mPackages) {
4648            return addPermissionLocked(info, false);
4649        }
4650    }
4651
4652    @Override
4653    public boolean addPermissionAsync(PermissionInfo info) {
4654        synchronized (mPackages) {
4655            return addPermissionLocked(info, true);
4656        }
4657    }
4658
4659    @Override
4660    public void removePermission(String name) {
4661        synchronized (mPackages) {
4662            checkPermissionTreeLP(name);
4663            BasePermission bp = mSettings.mPermissions.get(name);
4664            if (bp != null) {
4665                if (bp.type != BasePermission.TYPE_DYNAMIC) {
4666                    throw new SecurityException(
4667                            "Not allowed to modify non-dynamic permission "
4668                            + name);
4669                }
4670                mSettings.mPermissions.remove(name);
4671                mSettings.writeLPr();
4672            }
4673        }
4674    }
4675
4676    private static void enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(PackageParser.Package pkg,
4677            BasePermission bp) {
4678        int index = pkg.requestedPermissions.indexOf(bp.name);
4679        if (index == -1) {
4680            throw new SecurityException("Package " + pkg.packageName
4681                    + " has not requested permission " + bp.name);
4682        }
4683        if (!bp.isRuntime() && !bp.isDevelopment()) {
4684            throw new SecurityException("Permission " + bp.name
4685                    + " is not a changeable permission type");
4686        }
4687    }
4688
4689    @Override
4690    public void grantRuntimePermission(String packageName, String name, final int userId) {
4691        grantRuntimePermission(packageName, name, userId, false /* Only if not fixed by policy */);
4692    }
4693
4694    private void grantRuntimePermission(String packageName, String name, final int userId,
4695            boolean overridePolicy) {
4696        if (!sUserManager.exists(userId)) {
4697            Log.e(TAG, "No such user:" + userId);
4698            return;
4699        }
4700
4701        mContext.enforceCallingOrSelfPermission(
4702                android.Manifest.permission.GRANT_RUNTIME_PERMISSIONS,
4703                "grantRuntimePermission");
4704
4705        enforceCrossUserPermission(Binder.getCallingUid(), userId,
4706                true /* requireFullPermission */, true /* checkShell */,
4707                "grantRuntimePermission");
4708
4709        final int uid;
4710        final SettingBase sb;
4711
4712        synchronized (mPackages) {
4713            final PackageParser.Package pkg = mPackages.get(packageName);
4714            if (pkg == null) {
4715                throw new IllegalArgumentException("Unknown package: " + packageName);
4716            }
4717
4718            final BasePermission bp = mSettings.mPermissions.get(name);
4719            if (bp == null) {
4720                throw new IllegalArgumentException("Unknown permission: " + name);
4721            }
4722
4723            enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(pkg, bp);
4724
4725            // If a permission review is required for legacy apps we represent
4726            // their permissions as always granted runtime ones since we need
4727            // to keep the review required permission flag per user while an
4728            // install permission's state is shared across all users.
4729            if (mPermissionReviewRequired
4730                    && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M
4731                    && bp.isRuntime()) {
4732                return;
4733            }
4734
4735            uid = UserHandle.getUid(userId, pkg.applicationInfo.uid);
4736            sb = (SettingBase) pkg.mExtras;
4737            if (sb == null) {
4738                throw new IllegalArgumentException("Unknown package: " + packageName);
4739            }
4740
4741            final PermissionsState permissionsState = sb.getPermissionsState();
4742
4743            final int flags = permissionsState.getPermissionFlags(name, userId);
4744            if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) {
4745                throw new SecurityException("Cannot grant system fixed permission "
4746                        + name + " for package " + packageName);
4747            }
4748            if (!overridePolicy && (flags & PackageManager.FLAG_PERMISSION_POLICY_FIXED) != 0) {
4749                throw new SecurityException("Cannot grant policy fixed permission "
4750                        + name + " for package " + packageName);
4751            }
4752
4753            if (bp.isDevelopment()) {
4754                // Development permissions must be handled specially, since they are not
4755                // normal runtime permissions.  For now they apply to all users.
4756                if (permissionsState.grantInstallPermission(bp) !=
4757                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
4758                    scheduleWriteSettingsLocked();
4759                }
4760                return;
4761            }
4762
4763            final PackageSetting ps = mSettings.mPackages.get(packageName);
4764            if (ps.getInstantApp(userId) && !bp.isInstant()) {
4765                throw new SecurityException("Cannot grant non-ephemeral permission"
4766                        + name + " for package " + packageName);
4767            }
4768
4769            if (pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) {
4770                Slog.w(TAG, "Cannot grant runtime permission to a legacy app");
4771                return;
4772            }
4773
4774            final int result = permissionsState.grantRuntimePermission(bp, userId);
4775            switch (result) {
4776                case PermissionsState.PERMISSION_OPERATION_FAILURE: {
4777                    return;
4778                }
4779
4780                case PermissionsState.PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: {
4781                    final int appId = UserHandle.getAppId(pkg.applicationInfo.uid);
4782                    mHandler.post(new Runnable() {
4783                        @Override
4784                        public void run() {
4785                            killUid(appId, userId, KILL_APP_REASON_GIDS_CHANGED);
4786                        }
4787                    });
4788                }
4789                break;
4790            }
4791
4792            if (bp.isRuntime()) {
4793                logPermissionGranted(mContext, name, packageName);
4794            }
4795
4796            mOnPermissionChangeListeners.onPermissionsChanged(uid);
4797
4798            // Not critical if that is lost - app has to request again.
4799            mSettings.writeRuntimePermissionsForUserLPr(userId, false);
4800        }
4801
4802        // Only need to do this if user is initialized. Otherwise it's a new user
4803        // and there are no processes running as the user yet and there's no need
4804        // to make an expensive call to remount processes for the changed permissions.
4805        if (READ_EXTERNAL_STORAGE.equals(name)
4806                || WRITE_EXTERNAL_STORAGE.equals(name)) {
4807            final long token = Binder.clearCallingIdentity();
4808            try {
4809                if (sUserManager.isInitialized(userId)) {
4810                    StorageManagerInternal storageManagerInternal = LocalServices.getService(
4811                            StorageManagerInternal.class);
4812                    storageManagerInternal.onExternalStoragePolicyChanged(uid, packageName);
4813                }
4814            } finally {
4815                Binder.restoreCallingIdentity(token);
4816            }
4817        }
4818    }
4819
4820    @Override
4821    public void revokeRuntimePermission(String packageName, String name, int userId) {
4822        revokeRuntimePermission(packageName, name, userId, false /* Only if not fixed by policy */);
4823    }
4824
4825    private void revokeRuntimePermission(String packageName, String name, int userId,
4826            boolean overridePolicy) {
4827        if (!sUserManager.exists(userId)) {
4828            Log.e(TAG, "No such user:" + userId);
4829            return;
4830        }
4831
4832        mContext.enforceCallingOrSelfPermission(
4833                android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS,
4834                "revokeRuntimePermission");
4835
4836        enforceCrossUserPermission(Binder.getCallingUid(), userId,
4837                true /* requireFullPermission */, true /* checkShell */,
4838                "revokeRuntimePermission");
4839
4840        final int appId;
4841
4842        synchronized (mPackages) {
4843            final PackageParser.Package pkg = mPackages.get(packageName);
4844            if (pkg == null) {
4845                throw new IllegalArgumentException("Unknown package: " + packageName);
4846            }
4847
4848            final BasePermission bp = mSettings.mPermissions.get(name);
4849            if (bp == null) {
4850                throw new IllegalArgumentException("Unknown permission: " + name);
4851            }
4852
4853            enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(pkg, bp);
4854
4855            // If a permission review is required for legacy apps we represent
4856            // their permissions as always granted runtime ones since we need
4857            // to keep the review required permission flag per user while an
4858            // install permission's state is shared across all users.
4859            if (mPermissionReviewRequired
4860                    && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M
4861                    && bp.isRuntime()) {
4862                return;
4863            }
4864
4865            SettingBase sb = (SettingBase) pkg.mExtras;
4866            if (sb == null) {
4867                throw new IllegalArgumentException("Unknown package: " + packageName);
4868            }
4869
4870            final PermissionsState permissionsState = sb.getPermissionsState();
4871
4872            final int flags = permissionsState.getPermissionFlags(name, userId);
4873            if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) {
4874                throw new SecurityException("Cannot revoke system fixed permission "
4875                        + name + " for package " + packageName);
4876            }
4877            if (!overridePolicy && (flags & PackageManager.FLAG_PERMISSION_POLICY_FIXED) != 0) {
4878                throw new SecurityException("Cannot revoke policy fixed permission "
4879                        + name + " for package " + packageName);
4880            }
4881
4882            if (bp.isDevelopment()) {
4883                // Development permissions must be handled specially, since they are not
4884                // normal runtime permissions.  For now they apply to all users.
4885                if (permissionsState.revokeInstallPermission(bp) !=
4886                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
4887                    scheduleWriteSettingsLocked();
4888                }
4889                return;
4890            }
4891
4892            if (permissionsState.revokeRuntimePermission(bp, userId) ==
4893                    PermissionsState.PERMISSION_OPERATION_FAILURE) {
4894                return;
4895            }
4896
4897            if (bp.isRuntime()) {
4898                logPermissionRevoked(mContext, name, packageName);
4899            }
4900
4901            mOnPermissionChangeListeners.onPermissionsChanged(pkg.applicationInfo.uid);
4902
4903            // Critical, after this call app should never have the permission.
4904            mSettings.writeRuntimePermissionsForUserLPr(userId, true);
4905
4906            appId = UserHandle.getAppId(pkg.applicationInfo.uid);
4907        }
4908
4909        killUid(appId, userId, KILL_APP_REASON_PERMISSIONS_REVOKED);
4910    }
4911
4912    /**
4913     * Get the first event id for the permission.
4914     *
4915     * <p>There are four events for each permission: <ul>
4916     *     <li>Request permission: first id + 0</li>
4917     *     <li>Grant permission: first id + 1</li>
4918     *     <li>Request for permission denied: first id + 2</li>
4919     *     <li>Revoke permission: first id + 3</li>
4920     * </ul></p>
4921     *
4922     * @param name name of the permission
4923     *
4924     * @return The first event id for the permission
4925     */
4926    private static int getBaseEventId(@NonNull String name) {
4927        int eventIdIndex = ALL_DANGEROUS_PERMISSIONS.indexOf(name);
4928
4929        if (eventIdIndex == -1) {
4930            if (AppOpsManager.permissionToOpCode(name) == AppOpsManager.OP_NONE
4931                    || "user".equals(Build.TYPE)) {
4932                Log.i(TAG, "Unknown permission " + name);
4933
4934                return MetricsEvent.ACTION_PERMISSION_REQUEST_UNKNOWN;
4935            } else {
4936                // Most likely #ALL_DANGEROUS_PERMISSIONS needs to be updated.
4937                //
4938                // Also update
4939                // - EventLogger#ALL_DANGEROUS_PERMISSIONS
4940                // - metrics_constants.proto
4941                throw new IllegalStateException("Unknown permission " + name);
4942            }
4943        }
4944
4945        return MetricsEvent.ACTION_PERMISSION_REQUEST_READ_CALENDAR + eventIdIndex * 4;
4946    }
4947
4948    /**
4949     * Log that a permission was revoked.
4950     *
4951     * @param context Context of the caller
4952     * @param name name of the permission
4953     * @param packageName package permission if for
4954     */
4955    private static void logPermissionRevoked(@NonNull Context context, @NonNull String name,
4956            @NonNull String packageName) {
4957        MetricsLogger.action(context, getBaseEventId(name) + 3, packageName);
4958    }
4959
4960    /**
4961     * Log that a permission request was granted.
4962     *
4963     * @param context Context of the caller
4964     * @param name name of the permission
4965     * @param packageName package permission if for
4966     */
4967    private static void logPermissionGranted(@NonNull Context context, @NonNull String name,
4968            @NonNull String packageName) {
4969        MetricsLogger.action(context, getBaseEventId(name) + 1, packageName);
4970    }
4971
4972    @Override
4973    public void resetRuntimePermissions() {
4974        mContext.enforceCallingOrSelfPermission(
4975                android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS,
4976                "revokeRuntimePermission");
4977
4978        int callingUid = Binder.getCallingUid();
4979        if (callingUid != Process.SYSTEM_UID && callingUid != 0) {
4980            mContext.enforceCallingOrSelfPermission(
4981                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
4982                    "resetRuntimePermissions");
4983        }
4984
4985        synchronized (mPackages) {
4986            updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL);
4987            for (int userId : UserManagerService.getInstance().getUserIds()) {
4988                final int packageCount = mPackages.size();
4989                for (int i = 0; i < packageCount; i++) {
4990                    PackageParser.Package pkg = mPackages.valueAt(i);
4991                    if (!(pkg.mExtras instanceof PackageSetting)) {
4992                        continue;
4993                    }
4994                    PackageSetting ps = (PackageSetting) pkg.mExtras;
4995                    resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
4996                }
4997            }
4998        }
4999    }
5000
5001    @Override
5002    public int getPermissionFlags(String name, String packageName, int userId) {
5003        if (!sUserManager.exists(userId)) {
5004            return 0;
5005        }
5006
5007        enforceGrantRevokeRuntimePermissionPermissions("getPermissionFlags");
5008
5009        enforceCrossUserPermission(Binder.getCallingUid(), userId,
5010                true /* requireFullPermission */, false /* checkShell */,
5011                "getPermissionFlags");
5012
5013        synchronized (mPackages) {
5014            final PackageParser.Package pkg = mPackages.get(packageName);
5015            if (pkg == null) {
5016                return 0;
5017            }
5018
5019            final BasePermission bp = mSettings.mPermissions.get(name);
5020            if (bp == null) {
5021                return 0;
5022            }
5023
5024            SettingBase sb = (SettingBase) pkg.mExtras;
5025            if (sb == null) {
5026                return 0;
5027            }
5028
5029            PermissionsState permissionsState = sb.getPermissionsState();
5030            return permissionsState.getPermissionFlags(name, userId);
5031        }
5032    }
5033
5034    @Override
5035    public void updatePermissionFlags(String name, String packageName, int flagMask,
5036            int flagValues, int userId) {
5037        if (!sUserManager.exists(userId)) {
5038            return;
5039        }
5040
5041        enforceGrantRevokeRuntimePermissionPermissions("updatePermissionFlags");
5042
5043        enforceCrossUserPermission(Binder.getCallingUid(), userId,
5044                true /* requireFullPermission */, true /* checkShell */,
5045                "updatePermissionFlags");
5046
5047        // Only the system can change these flags and nothing else.
5048        if (getCallingUid() != Process.SYSTEM_UID) {
5049            flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
5050            flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
5051            flagMask &= ~PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT;
5052            flagValues &= ~PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT;
5053            flagValues &= ~PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED;
5054        }
5055
5056        synchronized (mPackages) {
5057            final PackageParser.Package pkg = mPackages.get(packageName);
5058            if (pkg == null) {
5059                throw new IllegalArgumentException("Unknown package: " + packageName);
5060            }
5061
5062            final BasePermission bp = mSettings.mPermissions.get(name);
5063            if (bp == null) {
5064                throw new IllegalArgumentException("Unknown permission: " + name);
5065            }
5066
5067            SettingBase sb = (SettingBase) pkg.mExtras;
5068            if (sb == null) {
5069                throw new IllegalArgumentException("Unknown package: " + packageName);
5070            }
5071
5072            PermissionsState permissionsState = sb.getPermissionsState();
5073
5074            boolean hadState = permissionsState.getRuntimePermissionState(name, userId) != null;
5075
5076            if (permissionsState.updatePermissionFlags(bp, userId, flagMask, flagValues)) {
5077                // Install and runtime permissions are stored in different places,
5078                // so figure out what permission changed and persist the change.
5079                if (permissionsState.getInstallPermissionState(name) != null) {
5080                    scheduleWriteSettingsLocked();
5081                } else if (permissionsState.getRuntimePermissionState(name, userId) != null
5082                        || hadState) {
5083                    mSettings.writeRuntimePermissionsForUserLPr(userId, false);
5084                }
5085            }
5086        }
5087    }
5088
5089    /**
5090     * Update the permission flags for all packages and runtime permissions of a user in order
5091     * to allow device or profile owner to remove POLICY_FIXED.
5092     */
5093    @Override
5094    public void updatePermissionFlagsForAllApps(int flagMask, int flagValues, int userId) {
5095        if (!sUserManager.exists(userId)) {
5096            return;
5097        }
5098
5099        enforceGrantRevokeRuntimePermissionPermissions("updatePermissionFlagsForAllApps");
5100
5101        enforceCrossUserPermission(Binder.getCallingUid(), userId,
5102                true /* requireFullPermission */, true /* checkShell */,
5103                "updatePermissionFlagsForAllApps");
5104
5105        // Only the system can change system fixed flags.
5106        if (getCallingUid() != Process.SYSTEM_UID) {
5107            flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
5108            flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
5109        }
5110
5111        synchronized (mPackages) {
5112            boolean changed = false;
5113            final int packageCount = mPackages.size();
5114            for (int pkgIndex = 0; pkgIndex < packageCount; pkgIndex++) {
5115                final PackageParser.Package pkg = mPackages.valueAt(pkgIndex);
5116                SettingBase sb = (SettingBase) pkg.mExtras;
5117                if (sb == null) {
5118                    continue;
5119                }
5120                PermissionsState permissionsState = sb.getPermissionsState();
5121                changed |= permissionsState.updatePermissionFlagsForAllPermissions(
5122                        userId, flagMask, flagValues);
5123            }
5124            if (changed) {
5125                mSettings.writeRuntimePermissionsForUserLPr(userId, false);
5126            }
5127        }
5128    }
5129
5130    private void enforceGrantRevokeRuntimePermissionPermissions(String message) {
5131        if (mContext.checkCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS)
5132                != PackageManager.PERMISSION_GRANTED
5133            && mContext.checkCallingOrSelfPermission(Manifest.permission.REVOKE_RUNTIME_PERMISSIONS)
5134                != PackageManager.PERMISSION_GRANTED) {
5135            throw new SecurityException(message + " requires "
5136                    + Manifest.permission.GRANT_RUNTIME_PERMISSIONS + " or "
5137                    + Manifest.permission.REVOKE_RUNTIME_PERMISSIONS);
5138        }
5139    }
5140
5141    @Override
5142    public boolean shouldShowRequestPermissionRationale(String permissionName,
5143            String packageName, int userId) {
5144        if (UserHandle.getCallingUserId() != userId) {
5145            mContext.enforceCallingPermission(
5146                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
5147                    "canShowRequestPermissionRationale for user " + userId);
5148        }
5149
5150        final int uid = getPackageUid(packageName, MATCH_DEBUG_TRIAGED_MISSING, userId);
5151        if (UserHandle.getAppId(getCallingUid()) != UserHandle.getAppId(uid)) {
5152            return false;
5153        }
5154
5155        if (checkPermission(permissionName, packageName, userId)
5156                == PackageManager.PERMISSION_GRANTED) {
5157            return false;
5158        }
5159
5160        final int flags;
5161
5162        final long identity = Binder.clearCallingIdentity();
5163        try {
5164            flags = getPermissionFlags(permissionName,
5165                    packageName, userId);
5166        } finally {
5167            Binder.restoreCallingIdentity(identity);
5168        }
5169
5170        final int fixedFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED
5171                | PackageManager.FLAG_PERMISSION_POLICY_FIXED
5172                | PackageManager.FLAG_PERMISSION_USER_FIXED;
5173
5174        if ((flags & fixedFlags) != 0) {
5175            return false;
5176        }
5177
5178        return (flags & PackageManager.FLAG_PERMISSION_USER_SET) != 0;
5179    }
5180
5181    @Override
5182    public void addOnPermissionsChangeListener(IOnPermissionsChangeListener listener) {
5183        mContext.enforceCallingOrSelfPermission(
5184                Manifest.permission.OBSERVE_GRANT_REVOKE_PERMISSIONS,
5185                "addOnPermissionsChangeListener");
5186
5187        synchronized (mPackages) {
5188            mOnPermissionChangeListeners.addListenerLocked(listener);
5189        }
5190    }
5191
5192    @Override
5193    public void removeOnPermissionsChangeListener(IOnPermissionsChangeListener listener) {
5194        synchronized (mPackages) {
5195            mOnPermissionChangeListeners.removeListenerLocked(listener);
5196        }
5197    }
5198
5199    @Override
5200    public boolean isProtectedBroadcast(String actionName) {
5201        synchronized (mPackages) {
5202            if (mProtectedBroadcasts.contains(actionName)) {
5203                return true;
5204            } else if (actionName != null) {
5205                // TODO: remove these terrible hacks
5206                if (actionName.startsWith("android.net.netmon.lingerExpired")
5207                        || actionName.startsWith("com.android.server.sip.SipWakeupTimer")
5208                        || actionName.startsWith("com.android.internal.telephony.data-reconnect")
5209                        || actionName.startsWith("android.net.netmon.launchCaptivePortalApp")) {
5210                    return true;
5211                }
5212            }
5213        }
5214        return false;
5215    }
5216
5217    @Override
5218    public int checkSignatures(String pkg1, String pkg2) {
5219        synchronized (mPackages) {
5220            final PackageParser.Package p1 = mPackages.get(pkg1);
5221            final PackageParser.Package p2 = mPackages.get(pkg2);
5222            if (p1 == null || p1.mExtras == null
5223                    || p2 == null || p2.mExtras == null) {
5224                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5225            }
5226            return compareSignatures(p1.mSignatures, p2.mSignatures);
5227        }
5228    }
5229
5230    @Override
5231    public int checkUidSignatures(int uid1, int uid2) {
5232        // Map to base uids.
5233        uid1 = UserHandle.getAppId(uid1);
5234        uid2 = UserHandle.getAppId(uid2);
5235        // reader
5236        synchronized (mPackages) {
5237            Signature[] s1;
5238            Signature[] s2;
5239            Object obj = mSettings.getUserIdLPr(uid1);
5240            if (obj != null) {
5241                if (obj instanceof SharedUserSetting) {
5242                    s1 = ((SharedUserSetting)obj).signatures.mSignatures;
5243                } else if (obj instanceof PackageSetting) {
5244                    s1 = ((PackageSetting)obj).signatures.mSignatures;
5245                } else {
5246                    return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5247                }
5248            } else {
5249                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5250            }
5251            obj = mSettings.getUserIdLPr(uid2);
5252            if (obj != null) {
5253                if (obj instanceof SharedUserSetting) {
5254                    s2 = ((SharedUserSetting)obj).signatures.mSignatures;
5255                } else if (obj instanceof PackageSetting) {
5256                    s2 = ((PackageSetting)obj).signatures.mSignatures;
5257                } else {
5258                    return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5259                }
5260            } else {
5261                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5262            }
5263            return compareSignatures(s1, s2);
5264        }
5265    }
5266
5267    /**
5268     * This method should typically only be used when granting or revoking
5269     * permissions, since the app may immediately restart after this call.
5270     * <p>
5271     * If you're doing surgery on app code/data, use {@link PackageFreezer} to
5272     * guard your work against the app being relaunched.
5273     */
5274    private void killUid(int appId, int userId, String reason) {
5275        final long identity = Binder.clearCallingIdentity();
5276        try {
5277            IActivityManager am = ActivityManager.getService();
5278            if (am != null) {
5279                try {
5280                    am.killUid(appId, userId, reason);
5281                } catch (RemoteException e) {
5282                    /* ignore - same process */
5283                }
5284            }
5285        } finally {
5286            Binder.restoreCallingIdentity(identity);
5287        }
5288    }
5289
5290    /**
5291     * Compares two sets of signatures. Returns:
5292     * <br />
5293     * {@link PackageManager#SIGNATURE_NEITHER_SIGNED}: if both signature sets are null,
5294     * <br />
5295     * {@link PackageManager#SIGNATURE_FIRST_NOT_SIGNED}: if the first signature set is null,
5296     * <br />
5297     * {@link PackageManager#SIGNATURE_SECOND_NOT_SIGNED}: if the second signature set is null,
5298     * <br />
5299     * {@link PackageManager#SIGNATURE_MATCH}: if the two signature sets are identical,
5300     * <br />
5301     * {@link PackageManager#SIGNATURE_NO_MATCH}: if the two signature sets differ.
5302     */
5303    static int compareSignatures(Signature[] s1, Signature[] s2) {
5304        if (s1 == null) {
5305            return s2 == null
5306                    ? PackageManager.SIGNATURE_NEITHER_SIGNED
5307                    : PackageManager.SIGNATURE_FIRST_NOT_SIGNED;
5308        }
5309
5310        if (s2 == null) {
5311            return PackageManager.SIGNATURE_SECOND_NOT_SIGNED;
5312        }
5313
5314        if (s1.length != s2.length) {
5315            return PackageManager.SIGNATURE_NO_MATCH;
5316        }
5317
5318        // Since both signature sets are of size 1, we can compare without HashSets.
5319        if (s1.length == 1) {
5320            return s1[0].equals(s2[0]) ?
5321                    PackageManager.SIGNATURE_MATCH :
5322                    PackageManager.SIGNATURE_NO_MATCH;
5323        }
5324
5325        ArraySet<Signature> set1 = new ArraySet<Signature>();
5326        for (Signature sig : s1) {
5327            set1.add(sig);
5328        }
5329        ArraySet<Signature> set2 = new ArraySet<Signature>();
5330        for (Signature sig : s2) {
5331            set2.add(sig);
5332        }
5333        // Make sure s2 contains all signatures in s1.
5334        if (set1.equals(set2)) {
5335            return PackageManager.SIGNATURE_MATCH;
5336        }
5337        return PackageManager.SIGNATURE_NO_MATCH;
5338    }
5339
5340    /**
5341     * If the database version for this type of package (internal storage or
5342     * external storage) is less than the version where package signatures
5343     * were updated, return true.
5344     */
5345    private boolean isCompatSignatureUpdateNeeded(PackageParser.Package scannedPkg) {
5346        final VersionInfo ver = getSettingsVersionForPackage(scannedPkg);
5347        return ver.databaseVersion < DatabaseVersion.SIGNATURE_END_ENTITY;
5348    }
5349
5350    /**
5351     * Used for backward compatibility to make sure any packages with
5352     * certificate chains get upgraded to the new style. {@code existingSigs}
5353     * will be in the old format (since they were stored on disk from before the
5354     * system upgrade) and {@code scannedSigs} will be in the newer format.
5355     */
5356    private int compareSignaturesCompat(PackageSignatures existingSigs,
5357            PackageParser.Package scannedPkg) {
5358        if (!isCompatSignatureUpdateNeeded(scannedPkg)) {
5359            return PackageManager.SIGNATURE_NO_MATCH;
5360        }
5361
5362        ArraySet<Signature> existingSet = new ArraySet<Signature>();
5363        for (Signature sig : existingSigs.mSignatures) {
5364            existingSet.add(sig);
5365        }
5366        ArraySet<Signature> scannedCompatSet = new ArraySet<Signature>();
5367        for (Signature sig : scannedPkg.mSignatures) {
5368            try {
5369                Signature[] chainSignatures = sig.getChainSignatures();
5370                for (Signature chainSig : chainSignatures) {
5371                    scannedCompatSet.add(chainSig);
5372                }
5373            } catch (CertificateEncodingException e) {
5374                scannedCompatSet.add(sig);
5375            }
5376        }
5377        /*
5378         * Make sure the expanded scanned set contains all signatures in the
5379         * existing one.
5380         */
5381        if (scannedCompatSet.equals(existingSet)) {
5382            // Migrate the old signatures to the new scheme.
5383            existingSigs.assignSignatures(scannedPkg.mSignatures);
5384            // The new KeySets will be re-added later in the scanning process.
5385            synchronized (mPackages) {
5386                mSettings.mKeySetManagerService.removeAppKeySetDataLPw(scannedPkg.packageName);
5387            }
5388            return PackageManager.SIGNATURE_MATCH;
5389        }
5390        return PackageManager.SIGNATURE_NO_MATCH;
5391    }
5392
5393    private boolean isRecoverSignatureUpdateNeeded(PackageParser.Package scannedPkg) {
5394        final VersionInfo ver = getSettingsVersionForPackage(scannedPkg);
5395        return ver.databaseVersion < DatabaseVersion.SIGNATURE_MALFORMED_RECOVER;
5396    }
5397
5398    private int compareSignaturesRecover(PackageSignatures existingSigs,
5399            PackageParser.Package scannedPkg) {
5400        if (!isRecoverSignatureUpdateNeeded(scannedPkg)) {
5401            return PackageManager.SIGNATURE_NO_MATCH;
5402        }
5403
5404        String msg = null;
5405        try {
5406            if (Signature.areEffectiveMatch(existingSigs.mSignatures, scannedPkg.mSignatures)) {
5407                logCriticalInfo(Log.INFO, "Recovered effectively matching certificates for "
5408                        + scannedPkg.packageName);
5409                return PackageManager.SIGNATURE_MATCH;
5410            }
5411        } catch (CertificateException e) {
5412            msg = e.getMessage();
5413        }
5414
5415        logCriticalInfo(Log.INFO,
5416                "Failed to recover certificates for " + scannedPkg.packageName + ": " + msg);
5417        return PackageManager.SIGNATURE_NO_MATCH;
5418    }
5419
5420    @Override
5421    public List<String> getAllPackages() {
5422        synchronized (mPackages) {
5423            return new ArrayList<String>(mPackages.keySet());
5424        }
5425    }
5426
5427    @Override
5428    public String[] getPackagesForUid(int uid) {
5429        final int userId = UserHandle.getUserId(uid);
5430        uid = UserHandle.getAppId(uid);
5431        // reader
5432        synchronized (mPackages) {
5433            Object obj = mSettings.getUserIdLPr(uid);
5434            if (obj instanceof SharedUserSetting) {
5435                final SharedUserSetting sus = (SharedUserSetting) obj;
5436                final int N = sus.packages.size();
5437                String[] res = new String[N];
5438                final Iterator<PackageSetting> it = sus.packages.iterator();
5439                int i = 0;
5440                while (it.hasNext()) {
5441                    PackageSetting ps = it.next();
5442                    if (ps.getInstalled(userId)) {
5443                        res[i++] = ps.name;
5444                    } else {
5445                        res = ArrayUtils.removeElement(String.class, res, res[i]);
5446                    }
5447                }
5448                return res;
5449            } else if (obj instanceof PackageSetting) {
5450                final PackageSetting ps = (PackageSetting) obj;
5451                if (ps.getInstalled(userId)) {
5452                    return new String[]{ps.name};
5453                }
5454            }
5455        }
5456        return null;
5457    }
5458
5459    @Override
5460    public String getNameForUid(int uid) {
5461        // reader
5462        synchronized (mPackages) {
5463            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
5464            if (obj instanceof SharedUserSetting) {
5465                final SharedUserSetting sus = (SharedUserSetting) obj;
5466                return sus.name + ":" + sus.userId;
5467            } else if (obj instanceof PackageSetting) {
5468                final PackageSetting ps = (PackageSetting) obj;
5469                return ps.name;
5470            }
5471        }
5472        return null;
5473    }
5474
5475    @Override
5476    public int getUidForSharedUser(String sharedUserName) {
5477        if(sharedUserName == null) {
5478            return -1;
5479        }
5480        // reader
5481        synchronized (mPackages) {
5482            SharedUserSetting suid;
5483            try {
5484                suid = mSettings.getSharedUserLPw(sharedUserName, 0, 0, false);
5485                if (suid != null) {
5486                    return suid.userId;
5487                }
5488            } catch (PackageManagerException ignore) {
5489                // can't happen, but, still need to catch it
5490            }
5491            return -1;
5492        }
5493    }
5494
5495    @Override
5496    public int getFlagsForUid(int uid) {
5497        synchronized (mPackages) {
5498            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
5499            if (obj instanceof SharedUserSetting) {
5500                final SharedUserSetting sus = (SharedUserSetting) obj;
5501                return sus.pkgFlags;
5502            } else if (obj instanceof PackageSetting) {
5503                final PackageSetting ps = (PackageSetting) obj;
5504                return ps.pkgFlags;
5505            }
5506        }
5507        return 0;
5508    }
5509
5510    @Override
5511    public int getPrivateFlagsForUid(int uid) {
5512        synchronized (mPackages) {
5513            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
5514            if (obj instanceof SharedUserSetting) {
5515                final SharedUserSetting sus = (SharedUserSetting) obj;
5516                return sus.pkgPrivateFlags;
5517            } else if (obj instanceof PackageSetting) {
5518                final PackageSetting ps = (PackageSetting) obj;
5519                return ps.pkgPrivateFlags;
5520            }
5521        }
5522        return 0;
5523    }
5524
5525    @Override
5526    public boolean isUidPrivileged(int uid) {
5527        uid = UserHandle.getAppId(uid);
5528        // reader
5529        synchronized (mPackages) {
5530            Object obj = mSettings.getUserIdLPr(uid);
5531            if (obj instanceof SharedUserSetting) {
5532                final SharedUserSetting sus = (SharedUserSetting) obj;
5533                final Iterator<PackageSetting> it = sus.packages.iterator();
5534                while (it.hasNext()) {
5535                    if (it.next().isPrivileged()) {
5536                        return true;
5537                    }
5538                }
5539            } else if (obj instanceof PackageSetting) {
5540                final PackageSetting ps = (PackageSetting) obj;
5541                return ps.isPrivileged();
5542            }
5543        }
5544        return false;
5545    }
5546
5547    @Override
5548    public String[] getAppOpPermissionPackages(String permissionName) {
5549        synchronized (mPackages) {
5550            ArraySet<String> pkgs = mAppOpPermissionPackages.get(permissionName);
5551            if (pkgs == null) {
5552                return null;
5553            }
5554            return pkgs.toArray(new String[pkgs.size()]);
5555        }
5556    }
5557
5558    @Override
5559    public ResolveInfo resolveIntent(Intent intent, String resolvedType,
5560            int flags, int userId) {
5561        try {
5562            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "resolveIntent");
5563
5564            if (!sUserManager.exists(userId)) return null;
5565            flags = updateFlagsForResolve(flags, userId, intent);
5566            enforceCrossUserPermission(Binder.getCallingUid(), userId,
5567                    false /*requireFullPermission*/, false /*checkShell*/, "resolve intent");
5568
5569            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "queryIntentActivities");
5570            final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType,
5571                    flags, userId);
5572            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
5573
5574            final ResolveInfo bestChoice =
5575                    chooseBestActivity(intent, resolvedType, flags, query, userId);
5576            return bestChoice;
5577        } finally {
5578            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
5579        }
5580    }
5581
5582    @Override
5583    public ResolveInfo findPersistentPreferredActivity(Intent intent, int userId) {
5584        if (!UserHandle.isSameApp(Binder.getCallingUid(), Process.SYSTEM_UID)) {
5585            throw new SecurityException(
5586                    "findPersistentPreferredActivity can only be run by the system");
5587        }
5588        if (!sUserManager.exists(userId)) {
5589            return null;
5590        }
5591        intent = updateIntentForResolve(intent);
5592        final String resolvedType = intent.resolveTypeIfNeeded(mContext.getContentResolver());
5593        final int flags = updateFlagsForResolve(0, userId, intent);
5594        final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags,
5595                userId);
5596        synchronized (mPackages) {
5597            return findPersistentPreferredActivityLP(intent, resolvedType, flags, query, false,
5598                    userId);
5599        }
5600    }
5601
5602    @Override
5603    public void setLastChosenActivity(Intent intent, String resolvedType, int flags,
5604            IntentFilter filter, int match, ComponentName activity) {
5605        final int userId = UserHandle.getCallingUserId();
5606        if (DEBUG_PREFERRED) {
5607            Log.v(TAG, "setLastChosenActivity intent=" + intent
5608                + " resolvedType=" + resolvedType
5609                + " flags=" + flags
5610                + " filter=" + filter
5611                + " match=" + match
5612                + " activity=" + activity);
5613            filter.dump(new PrintStreamPrinter(System.out), "    ");
5614        }
5615        intent.setComponent(null);
5616        final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags,
5617                userId);
5618        // Find any earlier preferred or last chosen entries and nuke them
5619        findPreferredActivity(intent, resolvedType,
5620                flags, query, 0, false, true, false, userId);
5621        // Add the new activity as the last chosen for this filter
5622        addPreferredActivityInternal(filter, match, null, activity, false, userId,
5623                "Setting last chosen");
5624    }
5625
5626    @Override
5627    public ResolveInfo getLastChosenActivity(Intent intent, String resolvedType, int flags) {
5628        final int userId = UserHandle.getCallingUserId();
5629        if (DEBUG_PREFERRED) Log.v(TAG, "Querying last chosen activity for " + intent);
5630        final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags,
5631                userId);
5632        return findPreferredActivity(intent, resolvedType, flags, query, 0,
5633                false, false, false, userId);
5634    }
5635
5636    /**
5637     * Returns whether or not instant apps have been disabled remotely.
5638     * <p><em>IMPORTANT</em> This should not be called with the package manager lock
5639     * held. Otherwise we run the risk of deadlock.
5640     */
5641    private boolean isEphemeralDisabled() {
5642        // ephemeral apps have been disabled across the board
5643        if (DISABLE_EPHEMERAL_APPS) {
5644            return true;
5645        }
5646        // system isn't up yet; can't read settings, so, assume no ephemeral apps
5647        if (!mSystemReady) {
5648            return true;
5649        }
5650        // we can't get a content resolver until the system is ready; these checks must happen last
5651        final ContentResolver resolver = mContext.getContentResolver();
5652        if (Global.getInt(resolver, Global.ENABLE_EPHEMERAL_FEATURE, 1) == 0) {
5653            return true;
5654        }
5655        return Secure.getInt(resolver, Secure.WEB_ACTION_ENABLED, 1) == 0;
5656    }
5657
5658    private boolean isEphemeralAllowed(
5659            Intent intent, List<ResolveInfo> resolvedActivities, int userId,
5660            boolean skipPackageCheck) {
5661        final int callingUser = UserHandle.getCallingUserId();
5662        if (callingUser != UserHandle.USER_SYSTEM) {
5663            return false;
5664        }
5665        if (mInstantAppResolverConnection == null) {
5666            return false;
5667        }
5668        if (mInstantAppInstallerComponent == null) {
5669            return false;
5670        }
5671        if (intent.getComponent() != null) {
5672            return false;
5673        }
5674        if ((intent.getFlags() & Intent.FLAG_IGNORE_EPHEMERAL) != 0) {
5675            return false;
5676        }
5677        if (!skipPackageCheck && intent.getPackage() != null) {
5678            return false;
5679        }
5680        final boolean isWebUri = hasWebURI(intent);
5681        if (!isWebUri || intent.getData().getHost() == null) {
5682            return false;
5683        }
5684        // Deny ephemeral apps if the user chose _ALWAYS or _ALWAYS_ASK for intent resolution.
5685        // Or if there's already an ephemeral app installed that handles the action
5686        synchronized (mPackages) {
5687            final int count = (resolvedActivities == null ? 0 : resolvedActivities.size());
5688            for (int n = 0; n < count; n++) {
5689                ResolveInfo info = resolvedActivities.get(n);
5690                String packageName = info.activityInfo.packageName;
5691                PackageSetting ps = mSettings.mPackages.get(packageName);
5692                if (ps != null) {
5693                    // Try to get the status from User settings first
5694                    long packedStatus = getDomainVerificationStatusLPr(ps, userId);
5695                    int status = (int) (packedStatus >> 32);
5696                    if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS
5697                            || status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) {
5698                        if (DEBUG_EPHEMERAL) {
5699                            Slog.v(TAG, "DENY ephemeral apps;"
5700                                + " pkg: " + packageName + ", status: " + status);
5701                        }
5702                        return false;
5703                    }
5704                    if (ps.getInstantApp(userId)) {
5705                        return false;
5706                    }
5707                }
5708            }
5709        }
5710        // We've exhausted all ways to deny ephemeral application; let the system look for them.
5711        return true;
5712    }
5713
5714    private void requestInstantAppResolutionPhaseTwo(AuxiliaryResolveInfo responseObj,
5715            Intent origIntent, String resolvedType, String callingPackage,
5716            int userId) {
5717        final Message msg = mHandler.obtainMessage(INSTANT_APP_RESOLUTION_PHASE_TWO,
5718                new EphemeralRequest(responseObj, origIntent, resolvedType,
5719                        callingPackage, userId));
5720        mHandler.sendMessage(msg);
5721    }
5722
5723    private ResolveInfo chooseBestActivity(Intent intent, String resolvedType,
5724            int flags, List<ResolveInfo> query, int userId) {
5725        if (query != null) {
5726            final int N = query.size();
5727            if (N == 1) {
5728                return query.get(0);
5729            } else if (N > 1) {
5730                final boolean debug = ((intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0);
5731                // If there is more than one activity with the same priority,
5732                // then let the user decide between them.
5733                ResolveInfo r0 = query.get(0);
5734                ResolveInfo r1 = query.get(1);
5735                if (DEBUG_INTENT_MATCHING || debug) {
5736                    Slog.v(TAG, r0.activityInfo.name + "=" + r0.priority + " vs "
5737                            + r1.activityInfo.name + "=" + r1.priority);
5738                }
5739                // If the first activity has a higher priority, or a different
5740                // default, then it is always desirable to pick it.
5741                if (r0.priority != r1.priority
5742                        || r0.preferredOrder != r1.preferredOrder
5743                        || r0.isDefault != r1.isDefault) {
5744                    return query.get(0);
5745                }
5746                // If we have saved a preference for a preferred activity for
5747                // this Intent, use that.
5748                ResolveInfo ri = findPreferredActivity(intent, resolvedType,
5749                        flags, query, r0.priority, true, false, debug, userId);
5750                if (ri != null) {
5751                    return ri;
5752                }
5753                ri = new ResolveInfo(mResolveInfo);
5754                ri.activityInfo = new ActivityInfo(ri.activityInfo);
5755                ri.activityInfo.labelRes = ResolverActivity.getLabelRes(intent.getAction());
5756                // If all of the options come from the same package, show the application's
5757                // label and icon instead of the generic resolver's.
5758                // Some calls like Intent.resolveActivityInfo query the ResolveInfo from here
5759                // and then throw away the ResolveInfo itself, meaning that the caller loses
5760                // the resolvePackageName. Therefore the activityInfo.labelRes above provides
5761                // a fallback for this case; we only set the target package's resources on
5762                // the ResolveInfo, not the ActivityInfo.
5763                final String intentPackage = intent.getPackage();
5764                if (!TextUtils.isEmpty(intentPackage) && allHavePackage(query, intentPackage)) {
5765                    final ApplicationInfo appi = query.get(0).activityInfo.applicationInfo;
5766                    ri.resolvePackageName = intentPackage;
5767                    if (userNeedsBadging(userId)) {
5768                        ri.noResourceId = true;
5769                    } else {
5770                        ri.icon = appi.icon;
5771                    }
5772                    ri.iconResourceId = appi.icon;
5773                    ri.labelRes = appi.labelRes;
5774                }
5775                ri.activityInfo.applicationInfo = new ApplicationInfo(
5776                        ri.activityInfo.applicationInfo);
5777                if (userId != 0) {
5778                    ri.activityInfo.applicationInfo.uid = UserHandle.getUid(userId,
5779                            UserHandle.getAppId(ri.activityInfo.applicationInfo.uid));
5780                }
5781                // Make sure that the resolver is displayable in car mode
5782                if (ri.activityInfo.metaData == null) ri.activityInfo.metaData = new Bundle();
5783                ri.activityInfo.metaData.putBoolean(Intent.METADATA_DOCK_HOME, true);
5784                return ri;
5785            }
5786        }
5787        return null;
5788    }
5789
5790    /**
5791     * Return true if the given list is not empty and all of its contents have
5792     * an activityInfo with the given package name.
5793     */
5794    private boolean allHavePackage(List<ResolveInfo> list, String packageName) {
5795        if (ArrayUtils.isEmpty(list)) {
5796            return false;
5797        }
5798        for (int i = 0, N = list.size(); i < N; i++) {
5799            final ResolveInfo ri = list.get(i);
5800            final ActivityInfo ai = ri != null ? ri.activityInfo : null;
5801            if (ai == null || !packageName.equals(ai.packageName)) {
5802                return false;
5803            }
5804        }
5805        return true;
5806    }
5807
5808    private ResolveInfo findPersistentPreferredActivityLP(Intent intent, String resolvedType,
5809            int flags, List<ResolveInfo> query, boolean debug, int userId) {
5810        final int N = query.size();
5811        PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities
5812                .get(userId);
5813        // Get the list of persistent preferred activities that handle the intent
5814        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for presistent preferred activities...");
5815        List<PersistentPreferredActivity> pprefs = ppir != null
5816                ? ppir.queryIntent(intent, resolvedType,
5817                        (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0,
5818                        userId)
5819                : null;
5820        if (pprefs != null && pprefs.size() > 0) {
5821            final int M = pprefs.size();
5822            for (int i=0; i<M; i++) {
5823                final PersistentPreferredActivity ppa = pprefs.get(i);
5824                if (DEBUG_PREFERRED || debug) {
5825                    Slog.v(TAG, "Checking PersistentPreferredActivity ds="
5826                            + (ppa.countDataSchemes() > 0 ? ppa.getDataScheme(0) : "<none>")
5827                            + "\n  component=" + ppa.mComponent);
5828                    ppa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
5829                }
5830                final ActivityInfo ai = getActivityInfo(ppa.mComponent,
5831                        flags | MATCH_DISABLED_COMPONENTS, userId);
5832                if (DEBUG_PREFERRED || debug) {
5833                    Slog.v(TAG, "Found persistent preferred activity:");
5834                    if (ai != null) {
5835                        ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
5836                    } else {
5837                        Slog.v(TAG, "  null");
5838                    }
5839                }
5840                if (ai == null) {
5841                    // This previously registered persistent preferred activity
5842                    // component is no longer known. Ignore it and do NOT remove it.
5843                    continue;
5844                }
5845                for (int j=0; j<N; j++) {
5846                    final ResolveInfo ri = query.get(j);
5847                    if (!ri.activityInfo.applicationInfo.packageName
5848                            .equals(ai.applicationInfo.packageName)) {
5849                        continue;
5850                    }
5851                    if (!ri.activityInfo.name.equals(ai.name)) {
5852                        continue;
5853                    }
5854                    //  Found a persistent preference that can handle the intent.
5855                    if (DEBUG_PREFERRED || debug) {
5856                        Slog.v(TAG, "Returning persistent preferred activity: " +
5857                                ri.activityInfo.packageName + "/" + ri.activityInfo.name);
5858                    }
5859                    return ri;
5860                }
5861            }
5862        }
5863        return null;
5864    }
5865
5866    // TODO: handle preferred activities missing while user has amnesia
5867    ResolveInfo findPreferredActivity(Intent intent, String resolvedType, int flags,
5868            List<ResolveInfo> query, int priority, boolean always,
5869            boolean removeMatches, boolean debug, int userId) {
5870        if (!sUserManager.exists(userId)) return null;
5871        flags = updateFlagsForResolve(flags, userId, intent);
5872        intent = updateIntentForResolve(intent);
5873        // writer
5874        synchronized (mPackages) {
5875            // Try to find a matching persistent preferred activity.
5876            ResolveInfo pri = findPersistentPreferredActivityLP(intent, resolvedType, flags, query,
5877                    debug, userId);
5878
5879            // If a persistent preferred activity matched, use it.
5880            if (pri != null) {
5881                return pri;
5882            }
5883
5884            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
5885            // Get the list of preferred activities that handle the intent
5886            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for preferred activities...");
5887            List<PreferredActivity> prefs = pir != null
5888                    ? pir.queryIntent(intent, resolvedType,
5889                            (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0,
5890                            userId)
5891                    : null;
5892            if (prefs != null && prefs.size() > 0) {
5893                boolean changed = false;
5894                try {
5895                    // First figure out how good the original match set is.
5896                    // We will only allow preferred activities that came
5897                    // from the same match quality.
5898                    int match = 0;
5899
5900                    if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Figuring out best match...");
5901
5902                    final int N = query.size();
5903                    for (int j=0; j<N; j++) {
5904                        final ResolveInfo ri = query.get(j);
5905                        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Match for " + ri.activityInfo
5906                                + ": 0x" + Integer.toHexString(match));
5907                        if (ri.match > match) {
5908                            match = ri.match;
5909                        }
5910                    }
5911
5912                    if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Best match: 0x"
5913                            + Integer.toHexString(match));
5914
5915                    match &= IntentFilter.MATCH_CATEGORY_MASK;
5916                    final int M = prefs.size();
5917                    for (int i=0; i<M; i++) {
5918                        final PreferredActivity pa = prefs.get(i);
5919                        if (DEBUG_PREFERRED || debug) {
5920                            Slog.v(TAG, "Checking PreferredActivity ds="
5921                                    + (pa.countDataSchemes() > 0 ? pa.getDataScheme(0) : "<none>")
5922                                    + "\n  component=" + pa.mPref.mComponent);
5923                            pa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
5924                        }
5925                        if (pa.mPref.mMatch != match) {
5926                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping bad match "
5927                                    + Integer.toHexString(pa.mPref.mMatch));
5928                            continue;
5929                        }
5930                        // If it's not an "always" type preferred activity and that's what we're
5931                        // looking for, skip it.
5932                        if (always && !pa.mPref.mAlways) {
5933                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping mAlways=false entry");
5934                            continue;
5935                        }
5936                        final ActivityInfo ai = getActivityInfo(
5937                                pa.mPref.mComponent, flags | MATCH_DISABLED_COMPONENTS
5938                                        | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
5939                                userId);
5940                        if (DEBUG_PREFERRED || debug) {
5941                            Slog.v(TAG, "Found preferred activity:");
5942                            if (ai != null) {
5943                                ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
5944                            } else {
5945                                Slog.v(TAG, "  null");
5946                            }
5947                        }
5948                        if (ai == null) {
5949                            // This previously registered preferred activity
5950                            // component is no longer known.  Most likely an update
5951                            // to the app was installed and in the new version this
5952                            // component no longer exists.  Clean it up by removing
5953                            // it from the preferred activities list, and skip it.
5954                            Slog.w(TAG, "Removing dangling preferred activity: "
5955                                    + pa.mPref.mComponent);
5956                            pir.removeFilter(pa);
5957                            changed = true;
5958                            continue;
5959                        }
5960                        for (int j=0; j<N; j++) {
5961                            final ResolveInfo ri = query.get(j);
5962                            if (!ri.activityInfo.applicationInfo.packageName
5963                                    .equals(ai.applicationInfo.packageName)) {
5964                                continue;
5965                            }
5966                            if (!ri.activityInfo.name.equals(ai.name)) {
5967                                continue;
5968                            }
5969
5970                            if (removeMatches) {
5971                                pir.removeFilter(pa);
5972                                changed = true;
5973                                if (DEBUG_PREFERRED) {
5974                                    Slog.v(TAG, "Removing match " + pa.mPref.mComponent);
5975                                }
5976                                break;
5977                            }
5978
5979                            // Okay we found a previously set preferred or last chosen app.
5980                            // If the result set is different from when this
5981                            // was created, we need to clear it and re-ask the
5982                            // user their preference, if we're looking for an "always" type entry.
5983                            if (always && !pa.mPref.sameSet(query)) {
5984                                Slog.i(TAG, "Result set changed, dropping preferred activity for "
5985                                        + intent + " type " + resolvedType);
5986                                if (DEBUG_PREFERRED) {
5987                                    Slog.v(TAG, "Removing preferred activity since set changed "
5988                                            + pa.mPref.mComponent);
5989                                }
5990                                pir.removeFilter(pa);
5991                                // Re-add the filter as a "last chosen" entry (!always)
5992                                PreferredActivity lastChosen = new PreferredActivity(
5993                                        pa, pa.mPref.mMatch, null, pa.mPref.mComponent, false);
5994                                pir.addFilter(lastChosen);
5995                                changed = true;
5996                                return null;
5997                            }
5998
5999                            // Yay! Either the set matched or we're looking for the last chosen
6000                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Returning preferred activity: "
6001                                    + ri.activityInfo.packageName + "/" + ri.activityInfo.name);
6002                            return ri;
6003                        }
6004                    }
6005                } finally {
6006                    if (changed) {
6007                        if (DEBUG_PREFERRED) {
6008                            Slog.v(TAG, "Preferred activity bookkeeping changed; writing restrictions");
6009                        }
6010                        scheduleWritePackageRestrictionsLocked(userId);
6011                    }
6012                }
6013            }
6014        }
6015        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "No preferred activity to return");
6016        return null;
6017    }
6018
6019    /*
6020     * Returns if intent can be forwarded from the sourceUserId to the targetUserId
6021     */
6022    @Override
6023    public boolean canForwardTo(Intent intent, String resolvedType, int sourceUserId,
6024            int targetUserId) {
6025        mContext.enforceCallingOrSelfPermission(
6026                android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
6027        List<CrossProfileIntentFilter> matches =
6028                getMatchingCrossProfileIntentFilters(intent, resolvedType, sourceUserId);
6029        if (matches != null) {
6030            int size = matches.size();
6031            for (int i = 0; i < size; i++) {
6032                if (matches.get(i).getTargetUserId() == targetUserId) return true;
6033            }
6034        }
6035        if (hasWebURI(intent)) {
6036            // cross-profile app linking works only towards the parent.
6037            final UserInfo parent = getProfileParent(sourceUserId);
6038            synchronized(mPackages) {
6039                int flags = updateFlagsForResolve(0, parent.id, intent);
6040                CrossProfileDomainInfo xpDomainInfo = getCrossProfileDomainPreferredLpr(
6041                        intent, resolvedType, flags, sourceUserId, parent.id);
6042                return xpDomainInfo != null;
6043            }
6044        }
6045        return false;
6046    }
6047
6048    private UserInfo getProfileParent(int userId) {
6049        final long identity = Binder.clearCallingIdentity();
6050        try {
6051            return sUserManager.getProfileParent(userId);
6052        } finally {
6053            Binder.restoreCallingIdentity(identity);
6054        }
6055    }
6056
6057    private List<CrossProfileIntentFilter> getMatchingCrossProfileIntentFilters(Intent intent,
6058            String resolvedType, int userId) {
6059        CrossProfileIntentResolver resolver = mSettings.mCrossProfileIntentResolvers.get(userId);
6060        if (resolver != null) {
6061            return resolver.queryIntent(intent, resolvedType, false /*defaultOnly*/, userId);
6062        }
6063        return null;
6064    }
6065
6066    @Override
6067    public @NonNull ParceledListSlice<ResolveInfo> queryIntentActivities(Intent intent,
6068            String resolvedType, int flags, int userId) {
6069        try {
6070            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "queryIntentActivities");
6071
6072            return new ParceledListSlice<>(
6073                    queryIntentActivitiesInternal(intent, resolvedType, flags, userId));
6074        } finally {
6075            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
6076        }
6077    }
6078
6079    /**
6080     * Returns the package name of the calling Uid if it's an instant app. If it isn't
6081     * instant, returns {@code null}.
6082     */
6083    private String getInstantAppPackageName(int callingUid) {
6084        final int appId = UserHandle.getAppId(callingUid);
6085        synchronized (mPackages) {
6086            final Object obj = mSettings.getUserIdLPr(appId);
6087            if (obj instanceof PackageSetting) {
6088                final PackageSetting ps = (PackageSetting) obj;
6089                final boolean isInstantApp = ps.getInstantApp(UserHandle.getUserId(callingUid));
6090                return isInstantApp ? ps.pkg.packageName : null;
6091            }
6092        }
6093        return null;
6094    }
6095
6096    private @NonNull List<ResolveInfo> queryIntentActivitiesInternal(Intent intent,
6097            String resolvedType, int flags, int userId) {
6098        if (!sUserManager.exists(userId)) return Collections.emptyList();
6099        final String instantAppPkgName = getInstantAppPackageName(Binder.getCallingUid());
6100        flags = updateFlagsForResolve(flags, userId, intent);
6101        enforceCrossUserPermission(Binder.getCallingUid(), userId,
6102                false /* requireFullPermission */, false /* checkShell */,
6103                "query intent activities");
6104        ComponentName comp = intent.getComponent();
6105        if (comp == null) {
6106            if (intent.getSelector() != null) {
6107                intent = intent.getSelector();
6108                comp = intent.getComponent();
6109            }
6110        }
6111
6112        if (comp != null) {
6113            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
6114            final ActivityInfo ai = getActivityInfo(comp, flags, userId);
6115            if (ai != null) {
6116                // When specifying an explicit component, we prevent the activity from being
6117                // used when either 1) the calling package is normal and the activity is within
6118                // an ephemeral application or 2) the calling package is ephemeral and the
6119                // activity is not visible to ephemeral applications.
6120                final boolean matchInstantApp =
6121                        (flags & PackageManager.MATCH_INSTANT) != 0;
6122                final boolean matchVisibleToInstantAppOnly =
6123                        (flags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
6124                final boolean isCallerInstantApp =
6125                        instantAppPkgName != null;
6126                final boolean isTargetSameInstantApp =
6127                        comp.getPackageName().equals(instantAppPkgName);
6128                final boolean isTargetInstantApp =
6129                        (ai.applicationInfo.privateFlags
6130                                & ApplicationInfo.PRIVATE_FLAG_INSTANT) != 0;
6131                final boolean isTargetHiddenFromInstantApp =
6132                        (ai.flags & ActivityInfo.FLAG_VISIBLE_TO_EPHEMERAL) == 0;
6133                final boolean blockResolution =
6134                        !isTargetSameInstantApp
6135                        && ((!matchInstantApp && !isCallerInstantApp && isTargetInstantApp)
6136                                || (matchVisibleToInstantAppOnly && isCallerInstantApp
6137                                        && isTargetHiddenFromInstantApp));
6138                if (!blockResolution) {
6139                    final ResolveInfo ri = new ResolveInfo();
6140                    ri.activityInfo = ai;
6141                    list.add(ri);
6142                }
6143            }
6144            return applyPostResolutionFilter(list, instantAppPkgName);
6145        }
6146
6147        // reader
6148        boolean sortResult = false;
6149        boolean addEphemeral = false;
6150        List<ResolveInfo> result;
6151        final String pkgName = intent.getPackage();
6152        final boolean ephemeralDisabled = isEphemeralDisabled();
6153        synchronized (mPackages) {
6154            if (pkgName == null) {
6155                List<CrossProfileIntentFilter> matchingFilters =
6156                        getMatchingCrossProfileIntentFilters(intent, resolvedType, userId);
6157                // Check for results that need to skip the current profile.
6158                ResolveInfo xpResolveInfo  = querySkipCurrentProfileIntents(matchingFilters, intent,
6159                        resolvedType, flags, userId);
6160                if (xpResolveInfo != null) {
6161                    List<ResolveInfo> xpResult = new ArrayList<ResolveInfo>(1);
6162                    xpResult.add(xpResolveInfo);
6163                    return applyPostResolutionFilter(
6164                            filterIfNotSystemUser(xpResult, userId), instantAppPkgName);
6165                }
6166
6167                // Check for results in the current profile.
6168                result = filterIfNotSystemUser(mActivities.queryIntent(
6169                        intent, resolvedType, flags, userId), userId);
6170                addEphemeral = !ephemeralDisabled
6171                        && isEphemeralAllowed(intent, result, userId, false /*skipPackageCheck*/);
6172
6173                // Check for cross profile results.
6174                boolean hasNonNegativePriorityResult = hasNonNegativePriority(result);
6175                xpResolveInfo = queryCrossProfileIntents(
6176                        matchingFilters, intent, resolvedType, flags, userId,
6177                        hasNonNegativePriorityResult);
6178                if (xpResolveInfo != null && isUserEnabled(xpResolveInfo.targetUserId)) {
6179                    boolean isVisibleToUser = filterIfNotSystemUser(
6180                            Collections.singletonList(xpResolveInfo), userId).size() > 0;
6181                    if (isVisibleToUser) {
6182                        result.add(xpResolveInfo);
6183                        sortResult = true;
6184                    }
6185                }
6186                if (hasWebURI(intent)) {
6187                    CrossProfileDomainInfo xpDomainInfo = null;
6188                    final UserInfo parent = getProfileParent(userId);
6189                    if (parent != null) {
6190                        xpDomainInfo = getCrossProfileDomainPreferredLpr(intent, resolvedType,
6191                                flags, userId, parent.id);
6192                    }
6193                    if (xpDomainInfo != null) {
6194                        if (xpResolveInfo != null) {
6195                            // If we didn't remove it, the cross-profile ResolveInfo would be twice
6196                            // in the result.
6197                            result.remove(xpResolveInfo);
6198                        }
6199                        if (result.size() == 0 && !addEphemeral) {
6200                            // No result in current profile, but found candidate in parent user.
6201                            // And we are not going to add emphemeral app, so we can return the
6202                            // result straight away.
6203                            result.add(xpDomainInfo.resolveInfo);
6204                            return applyPostResolutionFilter(result, instantAppPkgName);
6205                        }
6206                    } else if (result.size() <= 1 && !addEphemeral) {
6207                        // No result in parent user and <= 1 result in current profile, and we
6208                        // are not going to add emphemeral app, so we can return the result without
6209                        // further processing.
6210                        return applyPostResolutionFilter(result, instantAppPkgName);
6211                    }
6212                    // We have more than one candidate (combining results from current and parent
6213                    // profile), so we need filtering and sorting.
6214                    result = filterCandidatesWithDomainPreferredActivitiesLPr(
6215                            intent, flags, result, xpDomainInfo, userId);
6216                    sortResult = true;
6217                }
6218            } else {
6219                final PackageParser.Package pkg = mPackages.get(pkgName);
6220                if (pkg != null) {
6221                    result = applyPostResolutionFilter(filterIfNotSystemUser(
6222                            mActivities.queryIntentForPackage(
6223                                    intent, resolvedType, flags, pkg.activities, userId),
6224                            userId), instantAppPkgName);
6225                } else {
6226                    // the caller wants to resolve for a particular package; however, there
6227                    // were no installed results, so, try to find an ephemeral result
6228                    addEphemeral =  !ephemeralDisabled
6229                            && isEphemeralAllowed(
6230                                    intent, null /*result*/, userId, true /*skipPackageCheck*/);
6231                    result = new ArrayList<ResolveInfo>();
6232                }
6233            }
6234        }
6235        if (addEphemeral) {
6236            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "resolveEphemeral");
6237            final EphemeralRequest requestObject = new EphemeralRequest(
6238                    null /*responseObj*/, intent /*origIntent*/, resolvedType,
6239                    null /*callingPackage*/, userId);
6240            final AuxiliaryResolveInfo auxiliaryResponse =
6241                    EphemeralResolver.doEphemeralResolutionPhaseOne(
6242                            mContext, mInstantAppResolverConnection, requestObject);
6243            if (auxiliaryResponse != null) {
6244                if (DEBUG_EPHEMERAL) {
6245                    Slog.v(TAG, "Adding ephemeral installer to the ResolveInfo list");
6246                }
6247                final ResolveInfo ephemeralInstaller = new ResolveInfo(mInstantAppInstallerInfo);
6248                ephemeralInstaller.auxiliaryInfo = auxiliaryResponse;
6249                // make sure this resolver is the default
6250                ephemeralInstaller.isDefault = true;
6251                ephemeralInstaller.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART
6252                        | IntentFilter.MATCH_ADJUSTMENT_NORMAL;
6253                // add a non-generic filter
6254                ephemeralInstaller.filter = new IntentFilter(intent.getAction());
6255                ephemeralInstaller.filter.addDataPath(
6256                        intent.getData().getPath(), PatternMatcher.PATTERN_LITERAL);
6257                result.add(ephemeralInstaller);
6258            }
6259            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
6260        }
6261        if (sortResult) {
6262            Collections.sort(result, mResolvePrioritySorter);
6263        }
6264        return applyPostResolutionFilter(result, instantAppPkgName);
6265    }
6266
6267    private static class CrossProfileDomainInfo {
6268        /* ResolveInfo for IntentForwarderActivity to send the intent to the other profile */
6269        ResolveInfo resolveInfo;
6270        /* Best domain verification status of the activities found in the other profile */
6271        int bestDomainVerificationStatus;
6272    }
6273
6274    private CrossProfileDomainInfo getCrossProfileDomainPreferredLpr(Intent intent,
6275            String resolvedType, int flags, int sourceUserId, int parentUserId) {
6276        if (!sUserManager.hasUserRestriction(UserManager.ALLOW_PARENT_PROFILE_APP_LINKING,
6277                sourceUserId)) {
6278            return null;
6279        }
6280        List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent,
6281                resolvedType, flags, parentUserId);
6282
6283        if (resultTargetUser == null || resultTargetUser.isEmpty()) {
6284            return null;
6285        }
6286        CrossProfileDomainInfo result = null;
6287        int size = resultTargetUser.size();
6288        for (int i = 0; i < size; i++) {
6289            ResolveInfo riTargetUser = resultTargetUser.get(i);
6290            // Intent filter verification is only for filters that specify a host. So don't return
6291            // those that handle all web uris.
6292            if (riTargetUser.handleAllWebDataURI) {
6293                continue;
6294            }
6295            String packageName = riTargetUser.activityInfo.packageName;
6296            PackageSetting ps = mSettings.mPackages.get(packageName);
6297            if (ps == null) {
6298                continue;
6299            }
6300            long verificationState = getDomainVerificationStatusLPr(ps, parentUserId);
6301            int status = (int)(verificationState >> 32);
6302            if (result == null) {
6303                result = new CrossProfileDomainInfo();
6304                result.resolveInfo = createForwardingResolveInfoUnchecked(new IntentFilter(),
6305                        sourceUserId, parentUserId);
6306                result.bestDomainVerificationStatus = status;
6307            } else {
6308                result.bestDomainVerificationStatus = bestDomainVerificationStatus(status,
6309                        result.bestDomainVerificationStatus);
6310            }
6311        }
6312        // Don't consider matches with status NEVER across profiles.
6313        if (result != null && result.bestDomainVerificationStatus
6314                == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
6315            return null;
6316        }
6317        return result;
6318    }
6319
6320    /**
6321     * Verification statuses are ordered from the worse to the best, except for
6322     * INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER, which is the worse.
6323     */
6324    private int bestDomainVerificationStatus(int status1, int status2) {
6325        if (status1 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
6326            return status2;
6327        }
6328        if (status2 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
6329            return status1;
6330        }
6331        return (int) MathUtils.max(status1, status2);
6332    }
6333
6334    private boolean isUserEnabled(int userId) {
6335        long callingId = Binder.clearCallingIdentity();
6336        try {
6337            UserInfo userInfo = sUserManager.getUserInfo(userId);
6338            return userInfo != null && userInfo.isEnabled();
6339        } finally {
6340            Binder.restoreCallingIdentity(callingId);
6341        }
6342    }
6343
6344    /**
6345     * Filter out activities with systemUserOnly flag set, when current user is not System.
6346     *
6347     * @return filtered list
6348     */
6349    private List<ResolveInfo> filterIfNotSystemUser(List<ResolveInfo> resolveInfos, int userId) {
6350        if (userId == UserHandle.USER_SYSTEM) {
6351            return resolveInfos;
6352        }
6353        for (int i = resolveInfos.size() - 1; i >= 0; i--) {
6354            ResolveInfo info = resolveInfos.get(i);
6355            if ((info.activityInfo.flags & ActivityInfo.FLAG_SYSTEM_USER_ONLY) != 0) {
6356                resolveInfos.remove(i);
6357            }
6358        }
6359        return resolveInfos;
6360    }
6361
6362    /**
6363     * Filters out ephemeral activities.
6364     * <p>When resolving for an ephemeral app, only activities that 1) are defined in the
6365     * ephemeral app or 2) marked with {@code visibleToEphemeral} are returned.
6366     *
6367     * @param resolveInfos The pre-filtered list of resolved activities
6368     * @param ephemeralPkgName The ephemeral package name. If {@code null}, no filtering
6369     *          is performed.
6370     * @return A filtered list of resolved activities.
6371     */
6372    private List<ResolveInfo> applyPostResolutionFilter(List<ResolveInfo> resolveInfos,
6373            String ephemeralPkgName) {
6374        // TODO: When adding on-demand split support for non-instant apps, remove this check
6375        // and always apply post filtering
6376        if (ephemeralPkgName == null) {
6377            return resolveInfos;
6378        }
6379        for (int i = resolveInfos.size() - 1; i >= 0; i--) {
6380            final ResolveInfo info = resolveInfos.get(i);
6381            final boolean isEphemeralApp = info.activityInfo.applicationInfo.isInstantApp();
6382            // allow activities that are defined in the provided package
6383            if (isEphemeralApp && ephemeralPkgName.equals(info.activityInfo.packageName)) {
6384                if (info.activityInfo.splitName != null
6385                        && !ArrayUtils.contains(info.activityInfo.applicationInfo.splitNames,
6386                                info.activityInfo.splitName)) {
6387                    // requested activity is defined in a split that hasn't been installed yet.
6388                    // add the installer to the resolve list
6389                    if (DEBUG_EPHEMERAL) {
6390                        Slog.v(TAG, "Adding ephemeral installer to the ResolveInfo list");
6391                    }
6392                    final ResolveInfo installerInfo = new ResolveInfo(mInstantAppInstallerInfo);
6393                    installerInfo.auxiliaryInfo = new AuxiliaryResolveInfo(
6394                            info.activityInfo.packageName, info.activityInfo.splitName,
6395                            info.activityInfo.applicationInfo.versionCode);
6396                    // make sure this resolver is the default
6397                    installerInfo.isDefault = true;
6398                    installerInfo.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART
6399                            | IntentFilter.MATCH_ADJUSTMENT_NORMAL;
6400                    // add a non-generic filter
6401                    installerInfo.filter = new IntentFilter();
6402                    // load resources from the correct package
6403                    installerInfo.resolvePackageName = info.getComponentInfo().packageName;
6404                    resolveInfos.set(i, installerInfo);
6405                }
6406                continue;
6407            }
6408            // allow activities that have been explicitly exposed to ephemeral apps
6409            if (!isEphemeralApp
6410                    && ((info.activityInfo.flags & ActivityInfo.FLAG_VISIBLE_TO_EPHEMERAL) != 0)) {
6411                continue;
6412            }
6413            resolveInfos.remove(i);
6414        }
6415        return resolveInfos;
6416    }
6417
6418    /**
6419     * @param resolveInfos list of resolve infos in descending priority order
6420     * @return if the list contains a resolve info with non-negative priority
6421     */
6422    private boolean hasNonNegativePriority(List<ResolveInfo> resolveInfos) {
6423        return resolveInfos.size() > 0 && resolveInfos.get(0).priority >= 0;
6424    }
6425
6426    private static boolean hasWebURI(Intent intent) {
6427        if (intent.getData() == null) {
6428            return false;
6429        }
6430        final String scheme = intent.getScheme();
6431        if (TextUtils.isEmpty(scheme)) {
6432            return false;
6433        }
6434        return scheme.equals(IntentFilter.SCHEME_HTTP) || scheme.equals(IntentFilter.SCHEME_HTTPS);
6435    }
6436
6437    private List<ResolveInfo> filterCandidatesWithDomainPreferredActivitiesLPr(Intent intent,
6438            int matchFlags, List<ResolveInfo> candidates, CrossProfileDomainInfo xpDomainInfo,
6439            int userId) {
6440        final boolean debug = (intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0;
6441
6442        if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) {
6443            Slog.v(TAG, "Filtering results with preferred activities. Candidates count: " +
6444                    candidates.size());
6445        }
6446
6447        ArrayList<ResolveInfo> result = new ArrayList<ResolveInfo>();
6448        ArrayList<ResolveInfo> alwaysList = new ArrayList<ResolveInfo>();
6449        ArrayList<ResolveInfo> undefinedList = new ArrayList<ResolveInfo>();
6450        ArrayList<ResolveInfo> alwaysAskList = new ArrayList<ResolveInfo>();
6451        ArrayList<ResolveInfo> neverList = new ArrayList<ResolveInfo>();
6452        ArrayList<ResolveInfo> matchAllList = new ArrayList<ResolveInfo>();
6453
6454        synchronized (mPackages) {
6455            final int count = candidates.size();
6456            // First, try to use linked apps. Partition the candidates into four lists:
6457            // one for the final results, one for the "do not use ever", one for "undefined status"
6458            // and finally one for "browser app type".
6459            for (int n=0; n<count; n++) {
6460                ResolveInfo info = candidates.get(n);
6461                String packageName = info.activityInfo.packageName;
6462                PackageSetting ps = mSettings.mPackages.get(packageName);
6463                if (ps != null) {
6464                    // Add to the special match all list (Browser use case)
6465                    if (info.handleAllWebDataURI) {
6466                        matchAllList.add(info);
6467                        continue;
6468                    }
6469                    // Try to get the status from User settings first
6470                    long packedStatus = getDomainVerificationStatusLPr(ps, userId);
6471                    int status = (int)(packedStatus >> 32);
6472                    int linkGeneration = (int)(packedStatus & 0xFFFFFFFF);
6473                    if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS) {
6474                        if (DEBUG_DOMAIN_VERIFICATION || debug) {
6475                            Slog.i(TAG, "  + always: " + info.activityInfo.packageName
6476                                    + " : linkgen=" + linkGeneration);
6477                        }
6478                        // Use link-enabled generation as preferredOrder, i.e.
6479                        // prefer newly-enabled over earlier-enabled.
6480                        info.preferredOrder = linkGeneration;
6481                        alwaysList.add(info);
6482                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
6483                        if (DEBUG_DOMAIN_VERIFICATION || debug) {
6484                            Slog.i(TAG, "  + never: " + info.activityInfo.packageName);
6485                        }
6486                        neverList.add(info);
6487                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) {
6488                        if (DEBUG_DOMAIN_VERIFICATION || debug) {
6489                            Slog.i(TAG, "  + always-ask: " + info.activityInfo.packageName);
6490                        }
6491                        alwaysAskList.add(info);
6492                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED ||
6493                            status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK) {
6494                        if (DEBUG_DOMAIN_VERIFICATION || debug) {
6495                            Slog.i(TAG, "  + ask: " + info.activityInfo.packageName);
6496                        }
6497                        undefinedList.add(info);
6498                    }
6499                }
6500            }
6501
6502            // We'll want to include browser possibilities in a few cases
6503            boolean includeBrowser = false;
6504
6505            // First try to add the "always" resolution(s) for the current user, if any
6506            if (alwaysList.size() > 0) {
6507                result.addAll(alwaysList);
6508            } else {
6509                // Add all undefined apps as we want them to appear in the disambiguation dialog.
6510                result.addAll(undefinedList);
6511                // Maybe add one for the other profile.
6512                if (xpDomainInfo != null && (
6513                        xpDomainInfo.bestDomainVerificationStatus
6514                        != INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER)) {
6515                    result.add(xpDomainInfo.resolveInfo);
6516                }
6517                includeBrowser = true;
6518            }
6519
6520            // The presence of any 'always ask' alternatives means we'll also offer browsers.
6521            // If there were 'always' entries their preferred order has been set, so we also
6522            // back that off to make the alternatives equivalent
6523            if (alwaysAskList.size() > 0) {
6524                for (ResolveInfo i : result) {
6525                    i.preferredOrder = 0;
6526                }
6527                result.addAll(alwaysAskList);
6528                includeBrowser = true;
6529            }
6530
6531            if (includeBrowser) {
6532                // Also add browsers (all of them or only the default one)
6533                if (DEBUG_DOMAIN_VERIFICATION) {
6534                    Slog.v(TAG, "   ...including browsers in candidate set");
6535                }
6536                if ((matchFlags & MATCH_ALL) != 0) {
6537                    result.addAll(matchAllList);
6538                } else {
6539                    // Browser/generic handling case.  If there's a default browser, go straight
6540                    // to that (but only if there is no other higher-priority match).
6541                    final String defaultBrowserPackageName = getDefaultBrowserPackageName(userId);
6542                    int maxMatchPrio = 0;
6543                    ResolveInfo defaultBrowserMatch = null;
6544                    final int numCandidates = matchAllList.size();
6545                    for (int n = 0; n < numCandidates; n++) {
6546                        ResolveInfo info = matchAllList.get(n);
6547                        // track the highest overall match priority...
6548                        if (info.priority > maxMatchPrio) {
6549                            maxMatchPrio = info.priority;
6550                        }
6551                        // ...and the highest-priority default browser match
6552                        if (info.activityInfo.packageName.equals(defaultBrowserPackageName)) {
6553                            if (defaultBrowserMatch == null
6554                                    || (defaultBrowserMatch.priority < info.priority)) {
6555                                if (debug) {
6556                                    Slog.v(TAG, "Considering default browser match " + info);
6557                                }
6558                                defaultBrowserMatch = info;
6559                            }
6560                        }
6561                    }
6562                    if (defaultBrowserMatch != null
6563                            && defaultBrowserMatch.priority >= maxMatchPrio
6564                            && !TextUtils.isEmpty(defaultBrowserPackageName))
6565                    {
6566                        if (debug) {
6567                            Slog.v(TAG, "Default browser match " + defaultBrowserMatch);
6568                        }
6569                        result.add(defaultBrowserMatch);
6570                    } else {
6571                        result.addAll(matchAllList);
6572                    }
6573                }
6574
6575                // If there is nothing selected, add all candidates and remove the ones that the user
6576                // has explicitly put into the INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER state
6577                if (result.size() == 0) {
6578                    result.addAll(candidates);
6579                    result.removeAll(neverList);
6580                }
6581            }
6582        }
6583        if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) {
6584            Slog.v(TAG, "Filtered results with preferred activities. New candidates count: " +
6585                    result.size());
6586            for (ResolveInfo info : result) {
6587                Slog.v(TAG, "  + " + info.activityInfo);
6588            }
6589        }
6590        return result;
6591    }
6592
6593    // Returns a packed value as a long:
6594    //
6595    // high 'int'-sized word: link status: undefined/ask/never/always.
6596    // low 'int'-sized word: relative priority among 'always' results.
6597    private long getDomainVerificationStatusLPr(PackageSetting ps, int userId) {
6598        long result = ps.getDomainVerificationStatusForUser(userId);
6599        // if none available, get the master status
6600        if (result >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) {
6601            if (ps.getIntentFilterVerificationInfo() != null) {
6602                result = ((long)ps.getIntentFilterVerificationInfo().getStatus()) << 32;
6603            }
6604        }
6605        return result;
6606    }
6607
6608    private ResolveInfo querySkipCurrentProfileIntents(
6609            List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType,
6610            int flags, int sourceUserId) {
6611        if (matchingFilters != null) {
6612            int size = matchingFilters.size();
6613            for (int i = 0; i < size; i ++) {
6614                CrossProfileIntentFilter filter = matchingFilters.get(i);
6615                if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0) {
6616                    // Checking if there are activities in the target user that can handle the
6617                    // intent.
6618                    ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent,
6619                            resolvedType, flags, sourceUserId);
6620                    if (resolveInfo != null) {
6621                        return resolveInfo;
6622                    }
6623                }
6624            }
6625        }
6626        return null;
6627    }
6628
6629    // Return matching ResolveInfo in target user if any.
6630    private ResolveInfo queryCrossProfileIntents(
6631            List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType,
6632            int flags, int sourceUserId, boolean matchInCurrentProfile) {
6633        if (matchingFilters != null) {
6634            // Two {@link CrossProfileIntentFilter}s can have the same targetUserId and
6635            // match the same intent. For performance reasons, it is better not to
6636            // run queryIntent twice for the same userId
6637            SparseBooleanArray alreadyTriedUserIds = new SparseBooleanArray();
6638            int size = matchingFilters.size();
6639            for (int i = 0; i < size; i++) {
6640                CrossProfileIntentFilter filter = matchingFilters.get(i);
6641                int targetUserId = filter.getTargetUserId();
6642                boolean skipCurrentProfile =
6643                        (filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0;
6644                boolean skipCurrentProfileIfNoMatchFound =
6645                        (filter.getFlags() & PackageManager.ONLY_IF_NO_MATCH_FOUND) != 0;
6646                if (!skipCurrentProfile && !alreadyTriedUserIds.get(targetUserId)
6647                        && (!skipCurrentProfileIfNoMatchFound || !matchInCurrentProfile)) {
6648                    // Checking if there are activities in the target user that can handle the
6649                    // intent.
6650                    ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent,
6651                            resolvedType, flags, sourceUserId);
6652                    if (resolveInfo != null) return resolveInfo;
6653                    alreadyTriedUserIds.put(targetUserId, true);
6654                }
6655            }
6656        }
6657        return null;
6658    }
6659
6660    /**
6661     * If the filter's target user can handle the intent and is enabled: returns a ResolveInfo that
6662     * will forward the intent to the filter's target user.
6663     * Otherwise, returns null.
6664     */
6665    private ResolveInfo createForwardingResolveInfo(CrossProfileIntentFilter filter, Intent intent,
6666            String resolvedType, int flags, int sourceUserId) {
6667        int targetUserId = filter.getTargetUserId();
6668        List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent,
6669                resolvedType, flags, targetUserId);
6670        if (resultTargetUser != null && isUserEnabled(targetUserId)) {
6671            // If all the matches in the target profile are suspended, return null.
6672            for (int i = resultTargetUser.size() - 1; i >= 0; i--) {
6673                if ((resultTargetUser.get(i).activityInfo.applicationInfo.flags
6674                        & ApplicationInfo.FLAG_SUSPENDED) == 0) {
6675                    return createForwardingResolveInfoUnchecked(filter, sourceUserId,
6676                            targetUserId);
6677                }
6678            }
6679        }
6680        return null;
6681    }
6682
6683    private ResolveInfo createForwardingResolveInfoUnchecked(IntentFilter filter,
6684            int sourceUserId, int targetUserId) {
6685        ResolveInfo forwardingResolveInfo = new ResolveInfo();
6686        long ident = Binder.clearCallingIdentity();
6687        boolean targetIsProfile;
6688        try {
6689            targetIsProfile = sUserManager.getUserInfo(targetUserId).isManagedProfile();
6690        } finally {
6691            Binder.restoreCallingIdentity(ident);
6692        }
6693        String className;
6694        if (targetIsProfile) {
6695            className = FORWARD_INTENT_TO_MANAGED_PROFILE;
6696        } else {
6697            className = FORWARD_INTENT_TO_PARENT;
6698        }
6699        ComponentName forwardingActivityComponentName = new ComponentName(
6700                mAndroidApplication.packageName, className);
6701        ActivityInfo forwardingActivityInfo = getActivityInfo(forwardingActivityComponentName, 0,
6702                sourceUserId);
6703        if (!targetIsProfile) {
6704            forwardingActivityInfo.showUserIcon = targetUserId;
6705            forwardingResolveInfo.noResourceId = true;
6706        }
6707        forwardingResolveInfo.activityInfo = forwardingActivityInfo;
6708        forwardingResolveInfo.priority = 0;
6709        forwardingResolveInfo.preferredOrder = 0;
6710        forwardingResolveInfo.match = 0;
6711        forwardingResolveInfo.isDefault = true;
6712        forwardingResolveInfo.filter = filter;
6713        forwardingResolveInfo.targetUserId = targetUserId;
6714        return forwardingResolveInfo;
6715    }
6716
6717    @Override
6718    public @NonNull ParceledListSlice<ResolveInfo> queryIntentActivityOptions(ComponentName caller,
6719            Intent[] specifics, String[] specificTypes, Intent intent,
6720            String resolvedType, int flags, int userId) {
6721        return new ParceledListSlice<>(queryIntentActivityOptionsInternal(caller, specifics,
6722                specificTypes, intent, resolvedType, flags, userId));
6723    }
6724
6725    private @NonNull List<ResolveInfo> queryIntentActivityOptionsInternal(ComponentName caller,
6726            Intent[] specifics, String[] specificTypes, Intent intent,
6727            String resolvedType, int flags, int userId) {
6728        if (!sUserManager.exists(userId)) return Collections.emptyList();
6729        flags = updateFlagsForResolve(flags, userId, intent);
6730        enforceCrossUserPermission(Binder.getCallingUid(), userId,
6731                false /* requireFullPermission */, false /* checkShell */,
6732                "query intent activity options");
6733        final String resultsAction = intent.getAction();
6734
6735        final List<ResolveInfo> results = queryIntentActivitiesInternal(intent, resolvedType, flags
6736                | PackageManager.GET_RESOLVED_FILTER, userId);
6737
6738        if (DEBUG_INTENT_MATCHING) {
6739            Log.v(TAG, "Query " + intent + ": " + results);
6740        }
6741
6742        int specificsPos = 0;
6743        int N;
6744
6745        // todo: note that the algorithm used here is O(N^2).  This
6746        // isn't a problem in our current environment, but if we start running
6747        // into situations where we have more than 5 or 10 matches then this
6748        // should probably be changed to something smarter...
6749
6750        // First we go through and resolve each of the specific items
6751        // that were supplied, taking care of removing any corresponding
6752        // duplicate items in the generic resolve list.
6753        if (specifics != null) {
6754            for (int i=0; i<specifics.length; i++) {
6755                final Intent sintent = specifics[i];
6756                if (sintent == null) {
6757                    continue;
6758                }
6759
6760                if (DEBUG_INTENT_MATCHING) {
6761                    Log.v(TAG, "Specific #" + i + ": " + sintent);
6762                }
6763
6764                String action = sintent.getAction();
6765                if (resultsAction != null && resultsAction.equals(action)) {
6766                    // If this action was explicitly requested, then don't
6767                    // remove things that have it.
6768                    action = null;
6769                }
6770
6771                ResolveInfo ri = null;
6772                ActivityInfo ai = null;
6773
6774                ComponentName comp = sintent.getComponent();
6775                if (comp == null) {
6776                    ri = resolveIntent(
6777                        sintent,
6778                        specificTypes != null ? specificTypes[i] : null,
6779                            flags, userId);
6780                    if (ri == null) {
6781                        continue;
6782                    }
6783                    if (ri == mResolveInfo) {
6784                        // ACK!  Must do something better with this.
6785                    }
6786                    ai = ri.activityInfo;
6787                    comp = new ComponentName(ai.applicationInfo.packageName,
6788                            ai.name);
6789                } else {
6790                    ai = getActivityInfo(comp, flags, userId);
6791                    if (ai == null) {
6792                        continue;
6793                    }
6794                }
6795
6796                // Look for any generic query activities that are duplicates
6797                // of this specific one, and remove them from the results.
6798                if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Specific #" + i + ": " + ai);
6799                N = results.size();
6800                int j;
6801                for (j=specificsPos; j<N; j++) {
6802                    ResolveInfo sri = results.get(j);
6803                    if ((sri.activityInfo.name.equals(comp.getClassName())
6804                            && sri.activityInfo.applicationInfo.packageName.equals(
6805                                    comp.getPackageName()))
6806                        || (action != null && sri.filter.matchAction(action))) {
6807                        results.remove(j);
6808                        if (DEBUG_INTENT_MATCHING) Log.v(
6809                            TAG, "Removing duplicate item from " + j
6810                            + " due to specific " + specificsPos);
6811                        if (ri == null) {
6812                            ri = sri;
6813                        }
6814                        j--;
6815                        N--;
6816                    }
6817                }
6818
6819                // Add this specific item to its proper place.
6820                if (ri == null) {
6821                    ri = new ResolveInfo();
6822                    ri.activityInfo = ai;
6823                }
6824                results.add(specificsPos, ri);
6825                ri.specificIndex = i;
6826                specificsPos++;
6827            }
6828        }
6829
6830        // Now we go through the remaining generic results and remove any
6831        // duplicate actions that are found here.
6832        N = results.size();
6833        for (int i=specificsPos; i<N-1; i++) {
6834            final ResolveInfo rii = results.get(i);
6835            if (rii.filter == null) {
6836                continue;
6837            }
6838
6839            // Iterate over all of the actions of this result's intent
6840            // filter...  typically this should be just one.
6841            final Iterator<String> it = rii.filter.actionsIterator();
6842            if (it == null) {
6843                continue;
6844            }
6845            while (it.hasNext()) {
6846                final String action = it.next();
6847                if (resultsAction != null && resultsAction.equals(action)) {
6848                    // If this action was explicitly requested, then don't
6849                    // remove things that have it.
6850                    continue;
6851                }
6852                for (int j=i+1; j<N; j++) {
6853                    final ResolveInfo rij = results.get(j);
6854                    if (rij.filter != null && rij.filter.hasAction(action)) {
6855                        results.remove(j);
6856                        if (DEBUG_INTENT_MATCHING) Log.v(
6857                            TAG, "Removing duplicate item from " + j
6858                            + " due to action " + action + " at " + i);
6859                        j--;
6860                        N--;
6861                    }
6862                }
6863            }
6864
6865            // If the caller didn't request filter information, drop it now
6866            // so we don't have to marshall/unmarshall it.
6867            if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
6868                rii.filter = null;
6869            }
6870        }
6871
6872        // Filter out the caller activity if so requested.
6873        if (caller != null) {
6874            N = results.size();
6875            for (int i=0; i<N; i++) {
6876                ActivityInfo ainfo = results.get(i).activityInfo;
6877                if (caller.getPackageName().equals(ainfo.applicationInfo.packageName)
6878                        && caller.getClassName().equals(ainfo.name)) {
6879                    results.remove(i);
6880                    break;
6881                }
6882            }
6883        }
6884
6885        // If the caller didn't request filter information,
6886        // drop them now so we don't have to
6887        // marshall/unmarshall it.
6888        if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
6889            N = results.size();
6890            for (int i=0; i<N; i++) {
6891                results.get(i).filter = null;
6892            }
6893        }
6894
6895        if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Result: " + results);
6896        return results;
6897    }
6898
6899    @Override
6900    public @NonNull ParceledListSlice<ResolveInfo> queryIntentReceivers(Intent intent,
6901            String resolvedType, int flags, int userId) {
6902        return new ParceledListSlice<>(
6903                queryIntentReceiversInternal(intent, resolvedType, flags, userId));
6904    }
6905
6906    private @NonNull List<ResolveInfo> queryIntentReceiversInternal(Intent intent,
6907            String resolvedType, int flags, int userId) {
6908        if (!sUserManager.exists(userId)) return Collections.emptyList();
6909        flags = updateFlagsForResolve(flags, userId, intent);
6910        ComponentName comp = intent.getComponent();
6911        if (comp == null) {
6912            if (intent.getSelector() != null) {
6913                intent = intent.getSelector();
6914                comp = intent.getComponent();
6915            }
6916        }
6917        if (comp != null) {
6918            List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
6919            ActivityInfo ai = getReceiverInfo(comp, flags, userId);
6920            if (ai != null) {
6921                ResolveInfo ri = new ResolveInfo();
6922                ri.activityInfo = ai;
6923                list.add(ri);
6924            }
6925            return list;
6926        }
6927
6928        // reader
6929        synchronized (mPackages) {
6930            String pkgName = intent.getPackage();
6931            if (pkgName == null) {
6932                return mReceivers.queryIntent(intent, resolvedType, flags, userId);
6933            }
6934            final PackageParser.Package pkg = mPackages.get(pkgName);
6935            if (pkg != null) {
6936                return mReceivers.queryIntentForPackage(intent, resolvedType, flags, pkg.receivers,
6937                        userId);
6938            }
6939            return Collections.emptyList();
6940        }
6941    }
6942
6943    @Override
6944    public ResolveInfo resolveService(Intent intent, String resolvedType, int flags, int userId) {
6945        if (!sUserManager.exists(userId)) return null;
6946        flags = updateFlagsForResolve(flags, userId, intent);
6947        List<ResolveInfo> query = queryIntentServicesInternal(intent, resolvedType, flags, userId);
6948        if (query != null) {
6949            if (query.size() >= 1) {
6950                // If there is more than one service with the same priority,
6951                // just arbitrarily pick the first one.
6952                return query.get(0);
6953            }
6954        }
6955        return null;
6956    }
6957
6958    @Override
6959    public @NonNull ParceledListSlice<ResolveInfo> queryIntentServices(Intent intent,
6960            String resolvedType, int flags, int userId) {
6961        return new ParceledListSlice<>(
6962                queryIntentServicesInternal(intent, resolvedType, flags, userId));
6963    }
6964
6965    private @NonNull List<ResolveInfo> queryIntentServicesInternal(Intent intent,
6966            String resolvedType, int flags, int userId) {
6967        if (!sUserManager.exists(userId)) return Collections.emptyList();
6968        flags = updateFlagsForResolve(flags, userId, intent);
6969        ComponentName comp = intent.getComponent();
6970        if (comp == null) {
6971            if (intent.getSelector() != null) {
6972                intent = intent.getSelector();
6973                comp = intent.getComponent();
6974            }
6975        }
6976        if (comp != null) {
6977            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
6978            final ServiceInfo si = getServiceInfo(comp, flags, userId);
6979            if (si != null) {
6980                final ResolveInfo ri = new ResolveInfo();
6981                ri.serviceInfo = si;
6982                list.add(ri);
6983            }
6984            return list;
6985        }
6986
6987        // reader
6988        synchronized (mPackages) {
6989            String pkgName = intent.getPackage();
6990            if (pkgName == null) {
6991                return mServices.queryIntent(intent, resolvedType, flags, userId);
6992            }
6993            final PackageParser.Package pkg = mPackages.get(pkgName);
6994            if (pkg != null) {
6995                return mServices.queryIntentForPackage(intent, resolvedType, flags, pkg.services,
6996                        userId);
6997            }
6998            return Collections.emptyList();
6999        }
7000    }
7001
7002    @Override
7003    public @NonNull ParceledListSlice<ResolveInfo> queryIntentContentProviders(Intent intent,
7004            String resolvedType, int flags, int userId) {
7005        return new ParceledListSlice<>(
7006                queryIntentContentProvidersInternal(intent, resolvedType, flags, userId));
7007    }
7008
7009    private @NonNull List<ResolveInfo> queryIntentContentProvidersInternal(
7010            Intent intent, String resolvedType, int flags, int userId) {
7011        if (!sUserManager.exists(userId)) return Collections.emptyList();
7012        flags = updateFlagsForResolve(flags, userId, intent);
7013        ComponentName comp = intent.getComponent();
7014        if (comp == null) {
7015            if (intent.getSelector() != null) {
7016                intent = intent.getSelector();
7017                comp = intent.getComponent();
7018            }
7019        }
7020        if (comp != null) {
7021            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
7022            final ProviderInfo pi = getProviderInfo(comp, flags, userId);
7023            if (pi != null) {
7024                final ResolveInfo ri = new ResolveInfo();
7025                ri.providerInfo = pi;
7026                list.add(ri);
7027            }
7028            return list;
7029        }
7030
7031        // reader
7032        synchronized (mPackages) {
7033            String pkgName = intent.getPackage();
7034            if (pkgName == null) {
7035                return mProviders.queryIntent(intent, resolvedType, flags, userId);
7036            }
7037            final PackageParser.Package pkg = mPackages.get(pkgName);
7038            if (pkg != null) {
7039                return mProviders.queryIntentForPackage(
7040                        intent, resolvedType, flags, pkg.providers, userId);
7041            }
7042            return Collections.emptyList();
7043        }
7044    }
7045
7046    @Override
7047    public ParceledListSlice<PackageInfo> getInstalledPackages(int flags, int userId) {
7048        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
7049        flags = updateFlagsForPackage(flags, userId, null);
7050        final boolean listUninstalled = (flags & MATCH_KNOWN_PACKAGES) != 0;
7051        enforceCrossUserPermission(Binder.getCallingUid(), userId,
7052                true /* requireFullPermission */, false /* checkShell */,
7053                "get installed packages");
7054
7055        // writer
7056        synchronized (mPackages) {
7057            ArrayList<PackageInfo> list;
7058            if (listUninstalled) {
7059                list = new ArrayList<>(mSettings.mPackages.size());
7060                for (PackageSetting ps : mSettings.mPackages.values()) {
7061                    if (filterSharedLibPackageLPr(ps, Binder.getCallingUid(), userId)) {
7062                        continue;
7063                    }
7064                    final PackageInfo pi = generatePackageInfo(ps, flags, userId);
7065                    if (pi != null) {
7066                        list.add(pi);
7067                    }
7068                }
7069            } else {
7070                list = new ArrayList<>(mPackages.size());
7071                for (PackageParser.Package p : mPackages.values()) {
7072                    if (filterSharedLibPackageLPr((PackageSetting) p.mExtras,
7073                            Binder.getCallingUid(), userId)) {
7074                        continue;
7075                    }
7076                    final PackageInfo pi = generatePackageInfo((PackageSetting)
7077                            p.mExtras, flags, userId);
7078                    if (pi != null) {
7079                        list.add(pi);
7080                    }
7081                }
7082            }
7083
7084            return new ParceledListSlice<>(list);
7085        }
7086    }
7087
7088    private void addPackageHoldingPermissions(ArrayList<PackageInfo> list, PackageSetting ps,
7089            String[] permissions, boolean[] tmp, int flags, int userId) {
7090        int numMatch = 0;
7091        final PermissionsState permissionsState = ps.getPermissionsState();
7092        for (int i=0; i<permissions.length; i++) {
7093            final String permission = permissions[i];
7094            if (permissionsState.hasPermission(permission, userId)) {
7095                tmp[i] = true;
7096                numMatch++;
7097            } else {
7098                tmp[i] = false;
7099            }
7100        }
7101        if (numMatch == 0) {
7102            return;
7103        }
7104        final PackageInfo pi = generatePackageInfo(ps, flags, userId);
7105
7106        // The above might return null in cases of uninstalled apps or install-state
7107        // skew across users/profiles.
7108        if (pi != null) {
7109            if ((flags&PackageManager.GET_PERMISSIONS) == 0) {
7110                if (numMatch == permissions.length) {
7111                    pi.requestedPermissions = permissions;
7112                } else {
7113                    pi.requestedPermissions = new String[numMatch];
7114                    numMatch = 0;
7115                    for (int i=0; i<permissions.length; i++) {
7116                        if (tmp[i]) {
7117                            pi.requestedPermissions[numMatch] = permissions[i];
7118                            numMatch++;
7119                        }
7120                    }
7121                }
7122            }
7123            list.add(pi);
7124        }
7125    }
7126
7127    @Override
7128    public ParceledListSlice<PackageInfo> getPackagesHoldingPermissions(
7129            String[] permissions, int flags, int userId) {
7130        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
7131        flags = updateFlagsForPackage(flags, userId, permissions);
7132        enforceCrossUserPermission(Binder.getCallingUid(), userId,
7133                true /* requireFullPermission */, false /* checkShell */,
7134                "get packages holding permissions");
7135        final boolean listUninstalled = (flags & MATCH_KNOWN_PACKAGES) != 0;
7136
7137        // writer
7138        synchronized (mPackages) {
7139            ArrayList<PackageInfo> list = new ArrayList<PackageInfo>();
7140            boolean[] tmpBools = new boolean[permissions.length];
7141            if (listUninstalled) {
7142                for (PackageSetting ps : mSettings.mPackages.values()) {
7143                    addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags,
7144                            userId);
7145                }
7146            } else {
7147                for (PackageParser.Package pkg : mPackages.values()) {
7148                    PackageSetting ps = (PackageSetting)pkg.mExtras;
7149                    if (ps != null) {
7150                        addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags,
7151                                userId);
7152                    }
7153                }
7154            }
7155
7156            return new ParceledListSlice<PackageInfo>(list);
7157        }
7158    }
7159
7160    @Override
7161    public ParceledListSlice<ApplicationInfo> getInstalledApplications(int flags, int userId) {
7162        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
7163        flags = updateFlagsForApplication(flags, userId, null);
7164        final boolean listUninstalled = (flags & MATCH_KNOWN_PACKAGES) != 0;
7165
7166        // writer
7167        synchronized (mPackages) {
7168            ArrayList<ApplicationInfo> list;
7169            if (listUninstalled) {
7170                list = new ArrayList<>(mSettings.mPackages.size());
7171                for (PackageSetting ps : mSettings.mPackages.values()) {
7172                    ApplicationInfo ai;
7173                    int effectiveFlags = flags;
7174                    if (ps.isSystem()) {
7175                        effectiveFlags |= PackageManager.MATCH_ANY_USER;
7176                    }
7177                    if (ps.pkg != null) {
7178                        if (filterSharedLibPackageLPr(ps, Binder.getCallingUid(), userId)) {
7179                            continue;
7180                        }
7181                        ai = PackageParser.generateApplicationInfo(ps.pkg, effectiveFlags,
7182                                ps.readUserState(userId), userId);
7183                        if (ai != null) {
7184                            ai.packageName = resolveExternalPackageNameLPr(ps.pkg);
7185                        }
7186                    } else {
7187                        // Shared lib filtering done in generateApplicationInfoFromSettingsLPw
7188                        // and already converts to externally visible package name
7189                        ai = generateApplicationInfoFromSettingsLPw(ps.name,
7190                                Binder.getCallingUid(), effectiveFlags, userId);
7191                    }
7192                    if (ai != null) {
7193                        list.add(ai);
7194                    }
7195                }
7196            } else {
7197                list = new ArrayList<>(mPackages.size());
7198                for (PackageParser.Package p : mPackages.values()) {
7199                    if (p.mExtras != null) {
7200                        PackageSetting ps = (PackageSetting) p.mExtras;
7201                        if (filterSharedLibPackageLPr(ps, Binder.getCallingUid(), userId)) {
7202                            continue;
7203                        }
7204                        ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags,
7205                                ps.readUserState(userId), userId);
7206                        if (ai != null) {
7207                            ai.packageName = resolveExternalPackageNameLPr(p);
7208                            list.add(ai);
7209                        }
7210                    }
7211                }
7212            }
7213
7214            return new ParceledListSlice<>(list);
7215        }
7216    }
7217
7218    @Override
7219    public ParceledListSlice<InstantAppInfo> getInstantApps(int userId) {
7220        if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) {
7221            return null;
7222        }
7223
7224        mContext.enforceCallingOrSelfPermission(Manifest.permission.ACCESS_INSTANT_APPS,
7225                "getEphemeralApplications");
7226        enforceCrossUserPermission(Binder.getCallingUid(), userId,
7227                true /* requireFullPermission */, false /* checkShell */,
7228                "getEphemeralApplications");
7229        synchronized (mPackages) {
7230            List<InstantAppInfo> instantApps = mInstantAppRegistry
7231                    .getInstantAppsLPr(userId);
7232            if (instantApps != null) {
7233                return new ParceledListSlice<>(instantApps);
7234            }
7235        }
7236        return null;
7237    }
7238
7239    @Override
7240    public boolean isInstantApp(String packageName, int userId) {
7241        enforceCrossUserPermission(Binder.getCallingUid(), userId,
7242                true /* requireFullPermission */, false /* checkShell */,
7243                "isInstantApp");
7244        if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) {
7245            return false;
7246        }
7247
7248        if (!isCallerSameApp(packageName)) {
7249            return false;
7250        }
7251        synchronized (mPackages) {
7252            final PackageSetting ps = mSettings.mPackages.get(packageName);
7253            if (ps != null) {
7254                return ps.getInstantApp(userId);
7255            }
7256        }
7257        return false;
7258    }
7259
7260    @Override
7261    public byte[] getInstantAppCookie(String packageName, int userId) {
7262        if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) {
7263            return null;
7264        }
7265
7266        enforceCrossUserPermission(Binder.getCallingUid(), userId,
7267                true /* requireFullPermission */, false /* checkShell */,
7268                "getInstantAppCookie");
7269        if (!isCallerSameApp(packageName)) {
7270            return null;
7271        }
7272        synchronized (mPackages) {
7273            return mInstantAppRegistry.getInstantAppCookieLPw(
7274                    packageName, userId);
7275        }
7276    }
7277
7278    @Override
7279    public boolean setInstantAppCookie(String packageName, byte[] cookie, int userId) {
7280        if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) {
7281            return true;
7282        }
7283
7284        enforceCrossUserPermission(Binder.getCallingUid(), userId,
7285                true /* requireFullPermission */, true /* checkShell */,
7286                "setInstantAppCookie");
7287        if (!isCallerSameApp(packageName)) {
7288            return false;
7289        }
7290        synchronized (mPackages) {
7291            return mInstantAppRegistry.setInstantAppCookieLPw(
7292                    packageName, cookie, userId);
7293        }
7294    }
7295
7296    @Override
7297    public Bitmap getInstantAppIcon(String packageName, int userId) {
7298        if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) {
7299            return null;
7300        }
7301
7302        mContext.enforceCallingOrSelfPermission(Manifest.permission.ACCESS_INSTANT_APPS,
7303                "getInstantAppIcon");
7304
7305        enforceCrossUserPermission(Binder.getCallingUid(), userId,
7306                true /* requireFullPermission */, false /* checkShell */,
7307                "getInstantAppIcon");
7308
7309        synchronized (mPackages) {
7310            return mInstantAppRegistry.getInstantAppIconLPw(
7311                    packageName, userId);
7312        }
7313    }
7314
7315    private boolean isCallerSameApp(String packageName) {
7316        PackageParser.Package pkg = mPackages.get(packageName);
7317        return pkg != null
7318                && UserHandle.getAppId(Binder.getCallingUid()) == pkg.applicationInfo.uid;
7319    }
7320
7321    @Override
7322    public @NonNull ParceledListSlice<ApplicationInfo> getPersistentApplications(int flags) {
7323        return new ParceledListSlice<>(getPersistentApplicationsInternal(flags));
7324    }
7325
7326    private @NonNull List<ApplicationInfo> getPersistentApplicationsInternal(int flags) {
7327        final ArrayList<ApplicationInfo> finalList = new ArrayList<ApplicationInfo>();
7328
7329        // reader
7330        synchronized (mPackages) {
7331            final Iterator<PackageParser.Package> i = mPackages.values().iterator();
7332            final int userId = UserHandle.getCallingUserId();
7333            while (i.hasNext()) {
7334                final PackageParser.Package p = i.next();
7335                if (p.applicationInfo == null) continue;
7336
7337                final boolean matchesUnaware = ((flags & MATCH_DIRECT_BOOT_UNAWARE) != 0)
7338                        && !p.applicationInfo.isDirectBootAware();
7339                final boolean matchesAware = ((flags & MATCH_DIRECT_BOOT_AWARE) != 0)
7340                        && p.applicationInfo.isDirectBootAware();
7341
7342                if ((p.applicationInfo.flags & ApplicationInfo.FLAG_PERSISTENT) != 0
7343                        && (!mSafeMode || isSystemApp(p))
7344                        && (matchesUnaware || matchesAware)) {
7345                    PackageSetting ps = mSettings.mPackages.get(p.packageName);
7346                    if (ps != null) {
7347                        ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags,
7348                                ps.readUserState(userId), userId);
7349                        if (ai != null) {
7350                            finalList.add(ai);
7351                        }
7352                    }
7353                }
7354            }
7355        }
7356
7357        return finalList;
7358    }
7359
7360    @Override
7361    public ProviderInfo resolveContentProvider(String name, int flags, int userId) {
7362        if (!sUserManager.exists(userId)) return null;
7363        flags = updateFlagsForComponent(flags, userId, name);
7364        // reader
7365        synchronized (mPackages) {
7366            final PackageParser.Provider provider = mProvidersByAuthority.get(name);
7367            PackageSetting ps = provider != null
7368                    ? mSettings.mPackages.get(provider.owner.packageName)
7369                    : null;
7370            return ps != null
7371                    && mSettings.isEnabledAndMatchLPr(provider.info, flags, userId)
7372                    ? PackageParser.generateProviderInfo(provider, flags,
7373                            ps.readUserState(userId), userId)
7374                    : null;
7375        }
7376    }
7377
7378    /**
7379     * @deprecated
7380     */
7381    @Deprecated
7382    public void querySyncProviders(List<String> outNames, List<ProviderInfo> outInfo) {
7383        // reader
7384        synchronized (mPackages) {
7385            final Iterator<Map.Entry<String, PackageParser.Provider>> i = mProvidersByAuthority
7386                    .entrySet().iterator();
7387            final int userId = UserHandle.getCallingUserId();
7388            while (i.hasNext()) {
7389                Map.Entry<String, PackageParser.Provider> entry = i.next();
7390                PackageParser.Provider p = entry.getValue();
7391                PackageSetting ps = mSettings.mPackages.get(p.owner.packageName);
7392
7393                if (ps != null && p.syncable
7394                        && (!mSafeMode || (p.info.applicationInfo.flags
7395                                &ApplicationInfo.FLAG_SYSTEM) != 0)) {
7396                    ProviderInfo info = PackageParser.generateProviderInfo(p, 0,
7397                            ps.readUserState(userId), userId);
7398                    if (info != null) {
7399                        outNames.add(entry.getKey());
7400                        outInfo.add(info);
7401                    }
7402                }
7403            }
7404        }
7405    }
7406
7407    @Override
7408    public @NonNull ParceledListSlice<ProviderInfo> queryContentProviders(String processName,
7409            int uid, int flags) {
7410        final int userId = processName != null ? UserHandle.getUserId(uid)
7411                : UserHandle.getCallingUserId();
7412        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
7413        flags = updateFlagsForComponent(flags, userId, processName);
7414
7415        ArrayList<ProviderInfo> finalList = null;
7416        // reader
7417        synchronized (mPackages) {
7418            final Iterator<PackageParser.Provider> i = mProviders.mProviders.values().iterator();
7419            while (i.hasNext()) {
7420                final PackageParser.Provider p = i.next();
7421                PackageSetting ps = mSettings.mPackages.get(p.owner.packageName);
7422                if (ps != null && p.info.authority != null
7423                        && (processName == null
7424                                || (p.info.processName.equals(processName)
7425                                        && UserHandle.isSameApp(p.info.applicationInfo.uid, uid)))
7426                        && mSettings.isEnabledAndMatchLPr(p.info, flags, userId)) {
7427                    if (finalList == null) {
7428                        finalList = new ArrayList<ProviderInfo>(3);
7429                    }
7430                    ProviderInfo info = PackageParser.generateProviderInfo(p, flags,
7431                            ps.readUserState(userId), userId);
7432                    if (info != null) {
7433                        finalList.add(info);
7434                    }
7435                }
7436            }
7437        }
7438
7439        if (finalList != null) {
7440            Collections.sort(finalList, mProviderInitOrderSorter);
7441            return new ParceledListSlice<ProviderInfo>(finalList);
7442        }
7443
7444        return ParceledListSlice.emptyList();
7445    }
7446
7447    @Override
7448    public InstrumentationInfo getInstrumentationInfo(ComponentName name, int flags) {
7449        // reader
7450        synchronized (mPackages) {
7451            final PackageParser.Instrumentation i = mInstrumentation.get(name);
7452            return PackageParser.generateInstrumentationInfo(i, flags);
7453        }
7454    }
7455
7456    @Override
7457    public @NonNull ParceledListSlice<InstrumentationInfo> queryInstrumentation(
7458            String targetPackage, int flags) {
7459        return new ParceledListSlice<>(queryInstrumentationInternal(targetPackage, flags));
7460    }
7461
7462    private @NonNull List<InstrumentationInfo> queryInstrumentationInternal(String targetPackage,
7463            int flags) {
7464        ArrayList<InstrumentationInfo> finalList = new ArrayList<InstrumentationInfo>();
7465
7466        // reader
7467        synchronized (mPackages) {
7468            final Iterator<PackageParser.Instrumentation> i = mInstrumentation.values().iterator();
7469            while (i.hasNext()) {
7470                final PackageParser.Instrumentation p = i.next();
7471                if (targetPackage == null
7472                        || targetPackage.equals(p.info.targetPackage)) {
7473                    InstrumentationInfo ii = PackageParser.generateInstrumentationInfo(p,
7474                            flags);
7475                    if (ii != null) {
7476                        finalList.add(ii);
7477                    }
7478                }
7479            }
7480        }
7481
7482        return finalList;
7483    }
7484
7485    private void createIdmapsForPackageLI(PackageParser.Package pkg) {
7486        ArrayMap<String, PackageParser.Package> overlays = mOverlays.get(pkg.packageName);
7487        if (overlays == null) {
7488            Slog.w(TAG, "Unable to create idmap for " + pkg.packageName + ": no overlay packages");
7489            return;
7490        }
7491        for (PackageParser.Package opkg : overlays.values()) {
7492            // Not much to do if idmap fails: we already logged the error
7493            // and we certainly don't want to abort installation of pkg simply
7494            // because an overlay didn't fit properly. For these reasons,
7495            // ignore the return value of createIdmapForPackagePairLI.
7496            createIdmapForPackagePairLI(pkg, opkg);
7497        }
7498    }
7499
7500    private boolean createIdmapForPackagePairLI(PackageParser.Package pkg,
7501            PackageParser.Package opkg) {
7502        if (!opkg.mTrustedOverlay) {
7503            Slog.w(TAG, "Skipping target and overlay pair " + pkg.baseCodePath + " and " +
7504                    opkg.baseCodePath + ": overlay not trusted");
7505            return false;
7506        }
7507        ArrayMap<String, PackageParser.Package> overlaySet = mOverlays.get(pkg.packageName);
7508        if (overlaySet == null) {
7509            Slog.e(TAG, "was about to create idmap for " + pkg.baseCodePath + " and " +
7510                    opkg.baseCodePath + " but target package has no known overlays");
7511            return false;
7512        }
7513        final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid);
7514        // TODO: generate idmap for split APKs
7515        try {
7516            mInstaller.idmap(pkg.baseCodePath, opkg.baseCodePath, sharedGid);
7517        } catch (InstallerException e) {
7518            Slog.e(TAG, "Failed to generate idmap for " + pkg.baseCodePath + " and "
7519                    + opkg.baseCodePath);
7520            return false;
7521        }
7522        PackageParser.Package[] overlayArray =
7523            overlaySet.values().toArray(new PackageParser.Package[0]);
7524        Comparator<PackageParser.Package> cmp = new Comparator<PackageParser.Package>() {
7525            public int compare(PackageParser.Package p1, PackageParser.Package p2) {
7526                return p1.mOverlayPriority - p2.mOverlayPriority;
7527            }
7528        };
7529        Arrays.sort(overlayArray, cmp);
7530
7531        pkg.applicationInfo.resourceDirs = new String[overlayArray.length];
7532        int i = 0;
7533        for (PackageParser.Package p : overlayArray) {
7534            pkg.applicationInfo.resourceDirs[i++] = p.baseCodePath;
7535        }
7536        return true;
7537    }
7538
7539    private void scanDirTracedLI(File dir, final int parseFlags, int scanFlags, long currentTime) {
7540        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanDir [" + dir.getAbsolutePath() + "]");
7541        try {
7542            scanDirLI(dir, parseFlags, scanFlags, currentTime);
7543        } finally {
7544            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
7545        }
7546    }
7547
7548    private void scanDirLI(File dir, int parseFlags, int scanFlags, long currentTime) {
7549        final File[] files = dir.listFiles();
7550        if (ArrayUtils.isEmpty(files)) {
7551            Log.d(TAG, "No files in app dir " + dir);
7552            return;
7553        }
7554
7555        if (DEBUG_PACKAGE_SCANNING) {
7556            Log.d(TAG, "Scanning app dir " + dir + " scanFlags=" + scanFlags
7557                    + " flags=0x" + Integer.toHexString(parseFlags));
7558        }
7559        ParallelPackageParser parallelPackageParser = new ParallelPackageParser(
7560                mSeparateProcesses, mOnlyCore, mMetrics, mCacheDir);
7561
7562        // Submit files for parsing in parallel
7563        int fileCount = 0;
7564        for (File file : files) {
7565            final boolean isPackage = (isApkFile(file) || file.isDirectory())
7566                    && !PackageInstallerService.isStageName(file.getName());
7567            if (!isPackage) {
7568                // Ignore entries which are not packages
7569                continue;
7570            }
7571            parallelPackageParser.submit(file, parseFlags);
7572            fileCount++;
7573        }
7574
7575        // Process results one by one
7576        for (; fileCount > 0; fileCount--) {
7577            ParallelPackageParser.ParseResult parseResult = parallelPackageParser.take();
7578            Throwable throwable = parseResult.throwable;
7579            int errorCode = PackageManager.INSTALL_SUCCEEDED;
7580
7581            if (throwable == null) {
7582                // Static shared libraries have synthetic package names
7583                if (parseResult.pkg.applicationInfo.isStaticSharedLibrary()) {
7584                    renameStaticSharedLibraryPackage(parseResult.pkg);
7585                }
7586                try {
7587                    if (errorCode == PackageManager.INSTALL_SUCCEEDED) {
7588                        scanPackageLI(parseResult.pkg, parseResult.scanFile, parseFlags, scanFlags,
7589                                currentTime, null);
7590                    }
7591                } catch (PackageManagerException e) {
7592                    errorCode = e.error;
7593                    Slog.w(TAG, "Failed to scan " + parseResult.scanFile + ": " + e.getMessage());
7594                }
7595            } else if (throwable instanceof PackageParser.PackageParserException) {
7596                PackageParser.PackageParserException e = (PackageParser.PackageParserException)
7597                        throwable;
7598                errorCode = e.error;
7599                Slog.w(TAG, "Failed to parse " + parseResult.scanFile + ": " + e.getMessage());
7600            } else {
7601                throw new IllegalStateException("Unexpected exception occurred while parsing "
7602                        + parseResult.scanFile, throwable);
7603            }
7604
7605            // Delete invalid userdata apps
7606            if ((parseFlags & PackageParser.PARSE_IS_SYSTEM) == 0 &&
7607                    errorCode == PackageManager.INSTALL_FAILED_INVALID_APK) {
7608                logCriticalInfo(Log.WARN,
7609                        "Deleting invalid package at " + parseResult.scanFile);
7610                removeCodePathLI(parseResult.scanFile);
7611            }
7612        }
7613        parallelPackageParser.close();
7614    }
7615
7616    private static File getSettingsProblemFile() {
7617        File dataDir = Environment.getDataDirectory();
7618        File systemDir = new File(dataDir, "system");
7619        File fname = new File(systemDir, "uiderrors.txt");
7620        return fname;
7621    }
7622
7623    static void reportSettingsProblem(int priority, String msg) {
7624        logCriticalInfo(priority, msg);
7625    }
7626
7627    static void logCriticalInfo(int priority, String msg) {
7628        Slog.println(priority, TAG, msg);
7629        EventLogTags.writePmCriticalInfo(msg);
7630        try {
7631            File fname = getSettingsProblemFile();
7632            FileOutputStream out = new FileOutputStream(fname, true);
7633            PrintWriter pw = new FastPrintWriter(out);
7634            SimpleDateFormat formatter = new SimpleDateFormat();
7635            String dateString = formatter.format(new Date(System.currentTimeMillis()));
7636            pw.println(dateString + ": " + msg);
7637            pw.close();
7638            FileUtils.setPermissions(
7639                    fname.toString(),
7640                    FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IROTH,
7641                    -1, -1);
7642        } catch (java.io.IOException e) {
7643        }
7644    }
7645
7646    private long getLastModifiedTime(PackageParser.Package pkg, File srcFile) {
7647        if (srcFile.isDirectory()) {
7648            final File baseFile = new File(pkg.baseCodePath);
7649            long maxModifiedTime = baseFile.lastModified();
7650            if (pkg.splitCodePaths != null) {
7651                for (int i = pkg.splitCodePaths.length - 1; i >=0; --i) {
7652                    final File splitFile = new File(pkg.splitCodePaths[i]);
7653                    maxModifiedTime = Math.max(maxModifiedTime, splitFile.lastModified());
7654                }
7655            }
7656            return maxModifiedTime;
7657        }
7658        return srcFile.lastModified();
7659    }
7660
7661    private void collectCertificatesLI(PackageSetting ps, PackageParser.Package pkg, File srcFile,
7662            final int policyFlags) throws PackageManagerException {
7663        // When upgrading from pre-N MR1, verify the package time stamp using the package
7664        // directory and not the APK file.
7665        final long lastModifiedTime = mIsPreNMR1Upgrade
7666                ? new File(pkg.codePath).lastModified() : getLastModifiedTime(pkg, srcFile);
7667        if (ps != null
7668                && ps.codePath.equals(srcFile)
7669                && ps.timeStamp == lastModifiedTime
7670                && !isCompatSignatureUpdateNeeded(pkg)
7671                && !isRecoverSignatureUpdateNeeded(pkg)) {
7672            long mSigningKeySetId = ps.keySetData.getProperSigningKeySet();
7673            KeySetManagerService ksms = mSettings.mKeySetManagerService;
7674            ArraySet<PublicKey> signingKs;
7675            synchronized (mPackages) {
7676                signingKs = ksms.getPublicKeysFromKeySetLPr(mSigningKeySetId);
7677            }
7678            if (ps.signatures.mSignatures != null
7679                    && ps.signatures.mSignatures.length != 0
7680                    && signingKs != null) {
7681                // Optimization: reuse the existing cached certificates
7682                // if the package appears to be unchanged.
7683                pkg.mSignatures = ps.signatures.mSignatures;
7684                pkg.mSigningKeys = signingKs;
7685                return;
7686            }
7687
7688            Slog.w(TAG, "PackageSetting for " + ps.name
7689                    + " is missing signatures.  Collecting certs again to recover them.");
7690        } else {
7691            Slog.i(TAG, srcFile.toString() + " changed; collecting certs");
7692        }
7693
7694        try {
7695            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "collectCertificates");
7696            PackageParser.collectCertificates(pkg, policyFlags);
7697        } catch (PackageParserException e) {
7698            throw PackageManagerException.from(e);
7699        } finally {
7700            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
7701        }
7702    }
7703
7704    /**
7705     *  Traces a package scan.
7706     *  @see #scanPackageLI(File, int, int, long, UserHandle)
7707     */
7708    private PackageParser.Package scanPackageTracedLI(File scanFile, final int parseFlags,
7709            int scanFlags, long currentTime, UserHandle user) throws PackageManagerException {
7710        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage [" + scanFile.toString() + "]");
7711        try {
7712            return scanPackageLI(scanFile, parseFlags, scanFlags, currentTime, user);
7713        } finally {
7714            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
7715        }
7716    }
7717
7718    /**
7719     *  Scans a package and returns the newly parsed package.
7720     *  Returns {@code null} in case of errors and the error code is stored in mLastScanError
7721     */
7722    private PackageParser.Package scanPackageLI(File scanFile, int parseFlags, int scanFlags,
7723            long currentTime, UserHandle user) throws PackageManagerException {
7724        if (DEBUG_INSTALL) Slog.d(TAG, "Parsing: " + scanFile);
7725        PackageParser pp = new PackageParser();
7726        pp.setSeparateProcesses(mSeparateProcesses);
7727        pp.setOnlyCoreApps(mOnlyCore);
7728        pp.setDisplayMetrics(mMetrics);
7729
7730        if ((scanFlags & SCAN_TRUSTED_OVERLAY) != 0) {
7731            parseFlags |= PackageParser.PARSE_TRUSTED_OVERLAY;
7732        }
7733
7734        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "parsePackage");
7735        final PackageParser.Package pkg;
7736        try {
7737            pkg = pp.parsePackage(scanFile, parseFlags);
7738        } catch (PackageParserException e) {
7739            throw PackageManagerException.from(e);
7740        } finally {
7741            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
7742        }
7743
7744        // Static shared libraries have synthetic package names
7745        if (pkg.applicationInfo.isStaticSharedLibrary()) {
7746            renameStaticSharedLibraryPackage(pkg);
7747        }
7748
7749        return scanPackageLI(pkg, scanFile, parseFlags, scanFlags, currentTime, user);
7750    }
7751
7752    /**
7753     *  Scans a package and returns the newly parsed package.
7754     *  @throws PackageManagerException on a parse error.
7755     */
7756    private PackageParser.Package scanPackageLI(PackageParser.Package pkg, File scanFile,
7757            final int policyFlags, int scanFlags, long currentTime, @Nullable UserHandle user)
7758            throws PackageManagerException {
7759        // If the package has children and this is the first dive in the function
7760        // we scan the package with the SCAN_CHECK_ONLY flag set to see whether all
7761        // packages (parent and children) would be successfully scanned before the
7762        // actual scan since scanning mutates internal state and we want to atomically
7763        // install the package and its children.
7764        if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
7765            if (pkg.childPackages != null && pkg.childPackages.size() > 0) {
7766                scanFlags |= SCAN_CHECK_ONLY;
7767            }
7768        } else {
7769            scanFlags &= ~SCAN_CHECK_ONLY;
7770        }
7771
7772        // Scan the parent
7773        PackageParser.Package scannedPkg = scanPackageInternalLI(pkg, scanFile, policyFlags,
7774                scanFlags, currentTime, user);
7775
7776        // Scan the children
7777        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
7778        for (int i = 0; i < childCount; i++) {
7779            PackageParser.Package childPackage = pkg.childPackages.get(i);
7780            scanPackageInternalLI(childPackage, scanFile, policyFlags, scanFlags,
7781                    currentTime, user);
7782        }
7783
7784
7785        if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
7786            return scanPackageLI(pkg, scanFile, policyFlags, scanFlags, currentTime, user);
7787        }
7788
7789        return scannedPkg;
7790    }
7791
7792    /**
7793     *  Scans a package and returns the newly parsed package.
7794     *  @throws PackageManagerException on a parse error.
7795     */
7796    private PackageParser.Package scanPackageInternalLI(PackageParser.Package pkg, File scanFile,
7797            int policyFlags, int scanFlags, long currentTime, @Nullable UserHandle user)
7798            throws PackageManagerException {
7799        PackageSetting ps = null;
7800        PackageSetting updatedPkg;
7801        // reader
7802        synchronized (mPackages) {
7803            // Look to see if we already know about this package.
7804            String oldName = mSettings.getRenamedPackageLPr(pkg.packageName);
7805            if (pkg.mOriginalPackages != null && pkg.mOriginalPackages.contains(oldName)) {
7806                // This package has been renamed to its original name.  Let's
7807                // use that.
7808                ps = mSettings.getPackageLPr(oldName);
7809            }
7810            // If there was no original package, see one for the real package name.
7811            if (ps == null) {
7812                ps = mSettings.getPackageLPr(pkg.packageName);
7813            }
7814            // Check to see if this package could be hiding/updating a system
7815            // package.  Must look for it either under the original or real
7816            // package name depending on our state.
7817            updatedPkg = mSettings.getDisabledSystemPkgLPr(ps != null ? ps.name : pkg.packageName);
7818            if (DEBUG_INSTALL && updatedPkg != null) Slog.d(TAG, "updatedPkg = " + updatedPkg);
7819
7820            // If this is a package we don't know about on the system partition, we
7821            // may need to remove disabled child packages on the system partition
7822            // or may need to not add child packages if the parent apk is updated
7823            // on the data partition and no longer defines this child package.
7824            if ((policyFlags & PackageParser.PARSE_IS_SYSTEM) != 0) {
7825                // If this is a parent package for an updated system app and this system
7826                // app got an OTA update which no longer defines some of the child packages
7827                // we have to prune them from the disabled system packages.
7828                PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(pkg.packageName);
7829                if (disabledPs != null) {
7830                    final int scannedChildCount = (pkg.childPackages != null)
7831                            ? pkg.childPackages.size() : 0;
7832                    final int disabledChildCount = disabledPs.childPackageNames != null
7833                            ? disabledPs.childPackageNames.size() : 0;
7834                    for (int i = 0; i < disabledChildCount; i++) {
7835                        String disabledChildPackageName = disabledPs.childPackageNames.get(i);
7836                        boolean disabledPackageAvailable = false;
7837                        for (int j = 0; j < scannedChildCount; j++) {
7838                            PackageParser.Package childPkg = pkg.childPackages.get(j);
7839                            if (childPkg.packageName.equals(disabledChildPackageName)) {
7840                                disabledPackageAvailable = true;
7841                                break;
7842                            }
7843                         }
7844                         if (!disabledPackageAvailable) {
7845                             mSettings.removeDisabledSystemPackageLPw(disabledChildPackageName);
7846                         }
7847                    }
7848                }
7849            }
7850        }
7851
7852        boolean updatedPkgBetter = false;
7853        // First check if this is a system package that may involve an update
7854        if (updatedPkg != null && (policyFlags & PackageParser.PARSE_IS_SYSTEM) != 0) {
7855            // If new package is not located in "/system/priv-app" (e.g. due to an OTA),
7856            // it needs to drop FLAG_PRIVILEGED.
7857            if (locationIsPrivileged(scanFile)) {
7858                updatedPkg.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
7859            } else {
7860                updatedPkg.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
7861            }
7862
7863            if (ps != null && !ps.codePath.equals(scanFile)) {
7864                // The path has changed from what was last scanned...  check the
7865                // version of the new path against what we have stored to determine
7866                // what to do.
7867                if (DEBUG_INSTALL) Slog.d(TAG, "Path changing from " + ps.codePath);
7868                if (pkg.mVersionCode <= ps.versionCode) {
7869                    // The system package has been updated and the code path does not match
7870                    // Ignore entry. Skip it.
7871                    if (DEBUG_INSTALL) Slog.i(TAG, "Package " + ps.name + " at " + scanFile
7872                            + " ignored: updated version " + ps.versionCode
7873                            + " better than this " + pkg.mVersionCode);
7874                    if (!updatedPkg.codePath.equals(scanFile)) {
7875                        Slog.w(PackageManagerService.TAG, "Code path for hidden system pkg "
7876                                + ps.name + " changing from " + updatedPkg.codePathString
7877                                + " to " + scanFile);
7878                        updatedPkg.codePath = scanFile;
7879                        updatedPkg.codePathString = scanFile.toString();
7880                        updatedPkg.resourcePath = scanFile;
7881                        updatedPkg.resourcePathString = scanFile.toString();
7882                    }
7883                    updatedPkg.pkg = pkg;
7884                    updatedPkg.versionCode = pkg.mVersionCode;
7885
7886                    // Update the disabled system child packages to point to the package too.
7887                    final int childCount = updatedPkg.childPackageNames != null
7888                            ? updatedPkg.childPackageNames.size() : 0;
7889                    for (int i = 0; i < childCount; i++) {
7890                        String childPackageName = updatedPkg.childPackageNames.get(i);
7891                        PackageSetting updatedChildPkg = mSettings.getDisabledSystemPkgLPr(
7892                                childPackageName);
7893                        if (updatedChildPkg != null) {
7894                            updatedChildPkg.pkg = pkg;
7895                            updatedChildPkg.versionCode = pkg.mVersionCode;
7896                        }
7897                    }
7898
7899                    throw new PackageManagerException(Log.WARN, "Package " + ps.name + " at "
7900                            + scanFile + " ignored: updated version " + ps.versionCode
7901                            + " better than this " + pkg.mVersionCode);
7902                } else {
7903                    // The current app on the system partition is better than
7904                    // what we have updated to on the data partition; switch
7905                    // back to the system partition version.
7906                    // At this point, its safely assumed that package installation for
7907                    // apps in system partition will go through. If not there won't be a working
7908                    // version of the app
7909                    // writer
7910                    synchronized (mPackages) {
7911                        // Just remove the loaded entries from package lists.
7912                        mPackages.remove(ps.name);
7913                    }
7914
7915                    logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile
7916                            + " reverting from " + ps.codePathString
7917                            + ": new version " + pkg.mVersionCode
7918                            + " better than installed " + ps.versionCode);
7919
7920                    InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
7921                            ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
7922                    synchronized (mInstallLock) {
7923                        args.cleanUpResourcesLI();
7924                    }
7925                    synchronized (mPackages) {
7926                        mSettings.enableSystemPackageLPw(ps.name);
7927                    }
7928                    updatedPkgBetter = true;
7929                }
7930            }
7931        }
7932
7933        if (updatedPkg != null) {
7934            // An updated system app will not have the PARSE_IS_SYSTEM flag set
7935            // initially
7936            policyFlags |= PackageParser.PARSE_IS_SYSTEM;
7937
7938            // An updated privileged app will not have the PARSE_IS_PRIVILEGED
7939            // flag set initially
7940            if ((updatedPkg.pkgPrivateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0) {
7941                policyFlags |= PackageParser.PARSE_IS_PRIVILEGED;
7942            }
7943        }
7944
7945        // Verify certificates against what was last scanned
7946        collectCertificatesLI(ps, pkg, scanFile, policyFlags);
7947
7948        /*
7949         * A new system app appeared, but we already had a non-system one of the
7950         * same name installed earlier.
7951         */
7952        boolean shouldHideSystemApp = false;
7953        if (updatedPkg == null && ps != null
7954                && (policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0 && !isSystemApp(ps)) {
7955            /*
7956             * Check to make sure the signatures match first. If they don't,
7957             * wipe the installed application and its data.
7958             */
7959            if (compareSignatures(ps.signatures.mSignatures, pkg.mSignatures)
7960                    != PackageManager.SIGNATURE_MATCH) {
7961                logCriticalInfo(Log.WARN, "Package " + ps.name + " appeared on system, but"
7962                        + " signatures don't match existing userdata copy; removing");
7963                try (PackageFreezer freezer = freezePackage(pkg.packageName,
7964                        "scanPackageInternalLI")) {
7965                    deletePackageLIF(pkg.packageName, null, true, null, 0, null, false, null);
7966                }
7967                ps = null;
7968            } else {
7969                /*
7970                 * If the newly-added system app is an older version than the
7971                 * already installed version, hide it. It will be scanned later
7972                 * and re-added like an update.
7973                 */
7974                if (pkg.mVersionCode <= ps.versionCode) {
7975                    shouldHideSystemApp = true;
7976                    logCriticalInfo(Log.INFO, "Package " + ps.name + " appeared at " + scanFile
7977                            + " but new version " + pkg.mVersionCode + " better than installed "
7978                            + ps.versionCode + "; hiding system");
7979                } else {
7980                    /*
7981                     * The newly found system app is a newer version that the
7982                     * one previously installed. Simply remove the
7983                     * already-installed application and replace it with our own
7984                     * while keeping the application data.
7985                     */
7986                    logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile
7987                            + " reverting from " + ps.codePathString + ": new version "
7988                            + pkg.mVersionCode + " better than installed " + ps.versionCode);
7989                    InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
7990                            ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
7991                    synchronized (mInstallLock) {
7992                        args.cleanUpResourcesLI();
7993                    }
7994                }
7995            }
7996        }
7997
7998        // The apk is forward locked (not public) if its code and resources
7999        // are kept in different files. (except for app in either system or
8000        // vendor path).
8001        // TODO grab this value from PackageSettings
8002        if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
8003            if (ps != null && !ps.codePath.equals(ps.resourcePath)) {
8004                policyFlags |= PackageParser.PARSE_FORWARD_LOCK;
8005            }
8006        }
8007
8008        // TODO: extend to support forward-locked splits
8009        String resourcePath = null;
8010        String baseResourcePath = null;
8011        if ((policyFlags & PackageParser.PARSE_FORWARD_LOCK) != 0 && !updatedPkgBetter) {
8012            if (ps != null && ps.resourcePathString != null) {
8013                resourcePath = ps.resourcePathString;
8014                baseResourcePath = ps.resourcePathString;
8015            } else {
8016                // Should not happen at all. Just log an error.
8017                Slog.e(TAG, "Resource path not set for package " + pkg.packageName);
8018            }
8019        } else {
8020            resourcePath = pkg.codePath;
8021            baseResourcePath = pkg.baseCodePath;
8022        }
8023
8024        // Set application objects path explicitly.
8025        pkg.setApplicationVolumeUuid(pkg.volumeUuid);
8026        pkg.setApplicationInfoCodePath(pkg.codePath);
8027        pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
8028        pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
8029        pkg.setApplicationInfoResourcePath(resourcePath);
8030        pkg.setApplicationInfoBaseResourcePath(baseResourcePath);
8031        pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
8032
8033        final int userId = ((user == null) ? 0 : user.getIdentifier());
8034        if (ps != null && ps.getInstantApp(userId)) {
8035            scanFlags |= SCAN_AS_INSTANT_APP;
8036        }
8037
8038        // Note that we invoke the following method only if we are about to unpack an application
8039        PackageParser.Package scannedPkg = scanPackageLI(pkg, policyFlags, scanFlags
8040                | SCAN_UPDATE_SIGNATURE, currentTime, user);
8041
8042        /*
8043         * If the system app should be overridden by a previously installed
8044         * data, hide the system app now and let the /data/app scan pick it up
8045         * again.
8046         */
8047        if (shouldHideSystemApp) {
8048            synchronized (mPackages) {
8049                mSettings.disableSystemPackageLPw(pkg.packageName, true);
8050            }
8051        }
8052
8053        return scannedPkg;
8054    }
8055
8056    private void renameStaticSharedLibraryPackage(PackageParser.Package pkg) {
8057        // Derive the new package synthetic package name
8058        pkg.setPackageName(pkg.packageName + STATIC_SHARED_LIB_DELIMITER
8059                + pkg.staticSharedLibVersion);
8060    }
8061
8062    private static String fixProcessName(String defProcessName,
8063            String processName) {
8064        if (processName == null) {
8065            return defProcessName;
8066        }
8067        return processName;
8068    }
8069
8070    private void verifySignaturesLP(PackageSetting pkgSetting, PackageParser.Package pkg)
8071            throws PackageManagerException {
8072        if (pkgSetting.signatures.mSignatures != null) {
8073            // Already existing package. Make sure signatures match
8074            boolean match = compareSignatures(pkgSetting.signatures.mSignatures, pkg.mSignatures)
8075                    == PackageManager.SIGNATURE_MATCH;
8076            if (!match) {
8077                match = compareSignaturesCompat(pkgSetting.signatures, pkg)
8078                        == PackageManager.SIGNATURE_MATCH;
8079            }
8080            if (!match) {
8081                match = compareSignaturesRecover(pkgSetting.signatures, pkg)
8082                        == PackageManager.SIGNATURE_MATCH;
8083            }
8084            if (!match) {
8085                throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package "
8086                        + pkg.packageName + " signatures do not match the "
8087                        + "previously installed version; ignoring!");
8088            }
8089        }
8090
8091        // Check for shared user signatures
8092        if (pkgSetting.sharedUser != null && pkgSetting.sharedUser.signatures.mSignatures != null) {
8093            // Already existing package. Make sure signatures match
8094            boolean match = compareSignatures(pkgSetting.sharedUser.signatures.mSignatures,
8095                    pkg.mSignatures) == PackageManager.SIGNATURE_MATCH;
8096            if (!match) {
8097                match = compareSignaturesCompat(pkgSetting.sharedUser.signatures, pkg)
8098                        == PackageManager.SIGNATURE_MATCH;
8099            }
8100            if (!match) {
8101                match = compareSignaturesRecover(pkgSetting.sharedUser.signatures, pkg)
8102                        == PackageManager.SIGNATURE_MATCH;
8103            }
8104            if (!match) {
8105                throw new PackageManagerException(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE,
8106                        "Package " + pkg.packageName
8107                        + " has no signatures that match those in shared user "
8108                        + pkgSetting.sharedUser.name + "; ignoring!");
8109            }
8110        }
8111    }
8112
8113    /**
8114     * Enforces that only the system UID or root's UID can call a method exposed
8115     * via Binder.
8116     *
8117     * @param message used as message if SecurityException is thrown
8118     * @throws SecurityException if the caller is not system or root
8119     */
8120    private static final void enforceSystemOrRoot(String message) {
8121        final int uid = Binder.getCallingUid();
8122        if (uid != Process.SYSTEM_UID && uid != 0) {
8123            throw new SecurityException(message);
8124        }
8125    }
8126
8127    @Override
8128    public void performFstrimIfNeeded() {
8129        enforceSystemOrRoot("Only the system can request fstrim");
8130
8131        // Before everything else, see whether we need to fstrim.
8132        try {
8133            IStorageManager sm = PackageHelper.getStorageManager();
8134            if (sm != null) {
8135                boolean doTrim = false;
8136                final long interval = android.provider.Settings.Global.getLong(
8137                        mContext.getContentResolver(),
8138                        android.provider.Settings.Global.FSTRIM_MANDATORY_INTERVAL,
8139                        DEFAULT_MANDATORY_FSTRIM_INTERVAL);
8140                if (interval > 0) {
8141                    final long timeSinceLast = System.currentTimeMillis() - sm.lastMaintenance();
8142                    if (timeSinceLast > interval) {
8143                        doTrim = true;
8144                        Slog.w(TAG, "No disk maintenance in " + timeSinceLast
8145                                + "; running immediately");
8146                    }
8147                }
8148                if (doTrim) {
8149                    final boolean dexOptDialogShown;
8150                    synchronized (mPackages) {
8151                        dexOptDialogShown = mDexOptDialogShown;
8152                    }
8153                    if (!isFirstBoot() && dexOptDialogShown) {
8154                        try {
8155                            ActivityManager.getService().showBootMessage(
8156                                    mContext.getResources().getString(
8157                                            R.string.android_upgrading_fstrim), true);
8158                        } catch (RemoteException e) {
8159                        }
8160                    }
8161                    sm.runMaintenance();
8162                }
8163            } else {
8164                Slog.e(TAG, "storageManager service unavailable!");
8165            }
8166        } catch (RemoteException e) {
8167            // Can't happen; StorageManagerService is local
8168        }
8169    }
8170
8171    @Override
8172    public void updatePackagesIfNeeded() {
8173        enforceSystemOrRoot("Only the system can request package update");
8174
8175        // We need to re-extract after an OTA.
8176        boolean causeUpgrade = isUpgrade();
8177
8178        // First boot or factory reset.
8179        // Note: we also handle devices that are upgrading to N right now as if it is their
8180        //       first boot, as they do not have profile data.
8181        boolean causeFirstBoot = isFirstBoot() || mIsPreNUpgrade;
8182
8183        // We need to re-extract after a pruned cache, as AoT-ed files will be out of date.
8184        boolean causePrunedCache = VMRuntime.didPruneDalvikCache();
8185
8186        if (!causeUpgrade && !causeFirstBoot && !causePrunedCache) {
8187            return;
8188        }
8189
8190        List<PackageParser.Package> pkgs;
8191        synchronized (mPackages) {
8192            pkgs = PackageManagerServiceUtils.getPackagesForDexopt(mPackages.values(), this);
8193        }
8194
8195        final long startTime = System.nanoTime();
8196        final int[] stats = performDexOptUpgrade(pkgs, mIsPreNUpgrade /* showDialog */,
8197                    getCompilerFilterForReason(causeFirstBoot ? REASON_FIRST_BOOT : REASON_BOOT));
8198
8199        final int elapsedTimeSeconds =
8200                (int) TimeUnit.NANOSECONDS.toSeconds(System.nanoTime() - startTime);
8201
8202        MetricsLogger.histogram(mContext, "opt_dialog_num_dexopted", stats[0]);
8203        MetricsLogger.histogram(mContext, "opt_dialog_num_skipped", stats[1]);
8204        MetricsLogger.histogram(mContext, "opt_dialog_num_failed", stats[2]);
8205        MetricsLogger.histogram(mContext, "opt_dialog_num_total", getOptimizablePackages().size());
8206        MetricsLogger.histogram(mContext, "opt_dialog_time_s", elapsedTimeSeconds);
8207    }
8208
8209    /**
8210     * Performs dexopt on the set of packages in {@code packages} and returns an int array
8211     * containing statistics about the invocation. The array consists of three elements,
8212     * which are (in order) {@code numberOfPackagesOptimized}, {@code numberOfPackagesSkipped}
8213     * and {@code numberOfPackagesFailed}.
8214     */
8215    private int[] performDexOptUpgrade(List<PackageParser.Package> pkgs, boolean showDialog,
8216            String compilerFilter) {
8217
8218        int numberOfPackagesVisited = 0;
8219        int numberOfPackagesOptimized = 0;
8220        int numberOfPackagesSkipped = 0;
8221        int numberOfPackagesFailed = 0;
8222        final int numberOfPackagesToDexopt = pkgs.size();
8223
8224        for (PackageParser.Package pkg : pkgs) {
8225            numberOfPackagesVisited++;
8226
8227            if (!PackageDexOptimizer.canOptimizePackage(pkg)) {
8228                if (DEBUG_DEXOPT) {
8229                    Log.i(TAG, "Skipping update of of non-optimizable app " + pkg.packageName);
8230                }
8231                numberOfPackagesSkipped++;
8232                continue;
8233            }
8234
8235            if (DEBUG_DEXOPT) {
8236                Log.i(TAG, "Updating app " + numberOfPackagesVisited + " of " +
8237                        numberOfPackagesToDexopt + ": " + pkg.packageName);
8238            }
8239
8240            if (showDialog) {
8241                try {
8242                    ActivityManager.getService().showBootMessage(
8243                            mContext.getResources().getString(R.string.android_upgrading_apk,
8244                                    numberOfPackagesVisited, numberOfPackagesToDexopt), true);
8245                } catch (RemoteException e) {
8246                }
8247                synchronized (mPackages) {
8248                    mDexOptDialogShown = true;
8249                }
8250            }
8251
8252            // If the OTA updates a system app which was previously preopted to a non-preopted state
8253            // the app might end up being verified at runtime. That's because by default the apps
8254            // are verify-profile but for preopted apps there's no profile.
8255            // Do a hacky check to ensure that if we have no profiles (a reasonable indication
8256            // that before the OTA the app was preopted) the app gets compiled with a non-profile
8257            // filter (by default interpret-only).
8258            // Note that at this stage unused apps are already filtered.
8259            if (isSystemApp(pkg) &&
8260                    DexFile.isProfileGuidedCompilerFilter(compilerFilter) &&
8261                    !Environment.getReferenceProfile(pkg.packageName).exists()) {
8262                compilerFilter = getNonProfileGuidedCompilerFilter(compilerFilter);
8263            }
8264
8265            // checkProfiles is false to avoid merging profiles during boot which
8266            // might interfere with background compilation (b/28612421).
8267            // Unfortunately this will also means that "pm.dexopt.boot=speed-profile" will
8268            // behave differently than "pm.dexopt.bg-dexopt=speed-profile" but that's a
8269            // trade-off worth doing to save boot time work.
8270            int dexOptStatus = performDexOptTraced(pkg.packageName,
8271                    false /* checkProfiles */,
8272                    compilerFilter,
8273                    false /* force */);
8274            switch (dexOptStatus) {
8275                case PackageDexOptimizer.DEX_OPT_PERFORMED:
8276                    numberOfPackagesOptimized++;
8277                    break;
8278                case PackageDexOptimizer.DEX_OPT_SKIPPED:
8279                    numberOfPackagesSkipped++;
8280                    break;
8281                case PackageDexOptimizer.DEX_OPT_FAILED:
8282                    numberOfPackagesFailed++;
8283                    break;
8284                default:
8285                    Log.e(TAG, "Unexpected dexopt return code " + dexOptStatus);
8286                    break;
8287            }
8288        }
8289
8290        return new int[] { numberOfPackagesOptimized, numberOfPackagesSkipped,
8291                numberOfPackagesFailed };
8292    }
8293
8294    @Override
8295    public void notifyPackageUse(String packageName, int reason) {
8296        synchronized (mPackages) {
8297            PackageParser.Package p = mPackages.get(packageName);
8298            if (p == null) {
8299                return;
8300            }
8301            p.mLastPackageUsageTimeInMills[reason] = System.currentTimeMillis();
8302        }
8303    }
8304
8305    @Override
8306    public void notifyDexLoad(String loadingPackageName, List<String> dexPaths, String loaderIsa) {
8307        int userId = UserHandle.getCallingUserId();
8308        ApplicationInfo ai = getApplicationInfo(loadingPackageName, /*flags*/ 0, userId);
8309        if (ai == null) {
8310            Slog.w(TAG, "Loading a package that does not exist for the calling user. package="
8311                + loadingPackageName + ", user=" + userId);
8312            return;
8313        }
8314        mDexManager.notifyDexLoad(ai, dexPaths, loaderIsa, userId);
8315    }
8316
8317    // TODO: this is not used nor needed. Delete it.
8318    @Override
8319    public boolean performDexOptIfNeeded(String packageName) {
8320        int dexOptStatus = performDexOptTraced(packageName,
8321                false /* checkProfiles */, getFullCompilerFilter(), false /* force */);
8322        return dexOptStatus != PackageDexOptimizer.DEX_OPT_FAILED;
8323    }
8324
8325    @Override
8326    public boolean performDexOpt(String packageName,
8327            boolean checkProfiles, int compileReason, boolean force) {
8328        int dexOptStatus = performDexOptTraced(packageName, checkProfiles,
8329                getCompilerFilterForReason(compileReason), force);
8330        return dexOptStatus != PackageDexOptimizer.DEX_OPT_FAILED;
8331    }
8332
8333    @Override
8334    public boolean performDexOptMode(String packageName,
8335            boolean checkProfiles, String targetCompilerFilter, boolean force) {
8336        int dexOptStatus = performDexOptTraced(packageName, checkProfiles,
8337                targetCompilerFilter, force);
8338        return dexOptStatus != PackageDexOptimizer.DEX_OPT_FAILED;
8339    }
8340
8341    private int performDexOptTraced(String packageName,
8342                boolean checkProfiles, String targetCompilerFilter, boolean force) {
8343        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt");
8344        try {
8345            return performDexOptInternal(packageName, checkProfiles,
8346                    targetCompilerFilter, force);
8347        } finally {
8348            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
8349        }
8350    }
8351
8352    // Run dexopt on a given package. Returns true if dexopt did not fail, i.e.
8353    // if the package can now be considered up to date for the given filter.
8354    private int performDexOptInternal(String packageName,
8355                boolean checkProfiles, String targetCompilerFilter, boolean force) {
8356        PackageParser.Package p;
8357        synchronized (mPackages) {
8358            p = mPackages.get(packageName);
8359            if (p == null) {
8360                // Package could not be found. Report failure.
8361                return PackageDexOptimizer.DEX_OPT_FAILED;
8362            }
8363            mPackageUsage.maybeWriteAsync(mPackages);
8364            mCompilerStats.maybeWriteAsync();
8365        }
8366        long callingId = Binder.clearCallingIdentity();
8367        try {
8368            synchronized (mInstallLock) {
8369                return performDexOptInternalWithDependenciesLI(p, checkProfiles,
8370                        targetCompilerFilter, force);
8371            }
8372        } finally {
8373            Binder.restoreCallingIdentity(callingId);
8374        }
8375    }
8376
8377    public ArraySet<String> getOptimizablePackages() {
8378        ArraySet<String> pkgs = new ArraySet<String>();
8379        synchronized (mPackages) {
8380            for (PackageParser.Package p : mPackages.values()) {
8381                if (PackageDexOptimizer.canOptimizePackage(p)) {
8382                    pkgs.add(p.packageName);
8383                }
8384            }
8385        }
8386        return pkgs;
8387    }
8388
8389    private int performDexOptInternalWithDependenciesLI(PackageParser.Package p,
8390            boolean checkProfiles, String targetCompilerFilter,
8391            boolean force) {
8392        // Select the dex optimizer based on the force parameter.
8393        // Note: The force option is rarely used (cmdline input for testing, mostly), so it's OK to
8394        //       allocate an object here.
8395        PackageDexOptimizer pdo = force
8396                ? new PackageDexOptimizer.ForcedUpdatePackageDexOptimizer(mPackageDexOptimizer)
8397                : mPackageDexOptimizer;
8398
8399        // Optimize all dependencies first. Note: we ignore the return value and march on
8400        // on errors.
8401        Collection<PackageParser.Package> deps = findSharedNonSystemLibraries(p);
8402        final String[] instructionSets = getAppDexInstructionSets(p.applicationInfo);
8403        if (!deps.isEmpty()) {
8404            for (PackageParser.Package depPackage : deps) {
8405                // TODO: Analyze and investigate if we (should) profile libraries.
8406                // Currently this will do a full compilation of the library by default.
8407                pdo.performDexOpt(depPackage, null /* sharedLibraries */, instructionSets,
8408                        false /* checkProfiles */,
8409                        getCompilerFilterForReason(REASON_NON_SYSTEM_LIBRARY),
8410                        getOrCreateCompilerPackageStats(depPackage));
8411            }
8412        }
8413        return pdo.performDexOpt(p, p.usesLibraryFiles, instructionSets, checkProfiles,
8414                targetCompilerFilter, getOrCreateCompilerPackageStats(p));
8415    }
8416
8417    // Performs dexopt on the used secondary dex files belonging to the given package.
8418    // Returns true if all dex files were process successfully (which could mean either dexopt or
8419    // skip). Returns false if any of the files caused errors.
8420    @Override
8421    public boolean performDexOptSecondary(String packageName, String compilerFilter,
8422            boolean force) {
8423        return mDexManager.dexoptSecondaryDex(packageName, compilerFilter, force);
8424    }
8425
8426    /**
8427     * Reconcile the information we have about the secondary dex files belonging to
8428     * {@code packagName} and the actual dex files. For all dex files that were
8429     * deleted, update the internal records and delete the generated oat files.
8430     */
8431    @Override
8432    public void reconcileSecondaryDexFiles(String packageName) {
8433        mDexManager.reconcileSecondaryDexFiles(packageName);
8434    }
8435
8436    // TODO(calin): this is only needed for BackgroundDexOptService. Find a cleaner way to inject
8437    // a reference there.
8438    /*package*/ DexManager getDexManager() {
8439        return mDexManager;
8440    }
8441
8442    /**
8443     * Execute the background dexopt job immediately.
8444     */
8445    @Override
8446    public boolean runBackgroundDexoptJob() {
8447        return BackgroundDexOptService.runIdleOptimizationsNow(this, mContext);
8448    }
8449
8450    List<PackageParser.Package> findSharedNonSystemLibraries(PackageParser.Package p) {
8451        if (p.usesLibraries != null || p.usesOptionalLibraries != null
8452                || p.usesStaticLibraries != null) {
8453            ArrayList<PackageParser.Package> retValue = new ArrayList<>();
8454            Set<String> collectedNames = new HashSet<>();
8455            findSharedNonSystemLibrariesRecursive(p, retValue, collectedNames);
8456
8457            retValue.remove(p);
8458
8459            return retValue;
8460        } else {
8461            return Collections.emptyList();
8462        }
8463    }
8464
8465    private void findSharedNonSystemLibrariesRecursive(PackageParser.Package p,
8466            ArrayList<PackageParser.Package> collected, Set<String> collectedNames) {
8467        if (!collectedNames.contains(p.packageName)) {
8468            collectedNames.add(p.packageName);
8469            collected.add(p);
8470
8471            if (p.usesLibraries != null) {
8472                findSharedNonSystemLibrariesRecursive(p.usesLibraries,
8473                        null, collected, collectedNames);
8474            }
8475            if (p.usesOptionalLibraries != null) {
8476                findSharedNonSystemLibrariesRecursive(p.usesOptionalLibraries,
8477                        null, collected, collectedNames);
8478            }
8479            if (p.usesStaticLibraries != null) {
8480                findSharedNonSystemLibrariesRecursive(p.usesStaticLibraries,
8481                        p.usesStaticLibrariesVersions, collected, collectedNames);
8482            }
8483        }
8484    }
8485
8486    private void findSharedNonSystemLibrariesRecursive(ArrayList<String> libs, int[] versions,
8487            ArrayList<PackageParser.Package> collected, Set<String> collectedNames) {
8488        final int libNameCount = libs.size();
8489        for (int i = 0; i < libNameCount; i++) {
8490            String libName = libs.get(i);
8491            int version = (versions != null && versions.length == libNameCount)
8492                    ? versions[i] : PackageManager.VERSION_CODE_HIGHEST;
8493            PackageParser.Package libPkg = findSharedNonSystemLibrary(libName, version);
8494            if (libPkg != null) {
8495                findSharedNonSystemLibrariesRecursive(libPkg, collected, collectedNames);
8496            }
8497        }
8498    }
8499
8500    private PackageParser.Package findSharedNonSystemLibrary(String name, int version) {
8501        synchronized (mPackages) {
8502            SharedLibraryEntry libEntry = getSharedLibraryEntryLPr(name, version);
8503            if (libEntry != null) {
8504                return mPackages.get(libEntry.apk);
8505            }
8506            return null;
8507        }
8508    }
8509
8510    private SharedLibraryEntry getSharedLibraryEntryLPr(String name, int version) {
8511        SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(name);
8512        if (versionedLib == null) {
8513            return null;
8514        }
8515        return versionedLib.get(version);
8516    }
8517
8518    private SharedLibraryEntry getLatestSharedLibraVersionLPr(PackageParser.Package pkg) {
8519        SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(
8520                pkg.staticSharedLibName);
8521        if (versionedLib == null) {
8522            return null;
8523        }
8524        int previousLibVersion = -1;
8525        final int versionCount = versionedLib.size();
8526        for (int i = 0; i < versionCount; i++) {
8527            final int libVersion = versionedLib.keyAt(i);
8528            if (libVersion < pkg.staticSharedLibVersion) {
8529                previousLibVersion = Math.max(previousLibVersion, libVersion);
8530            }
8531        }
8532        if (previousLibVersion >= 0) {
8533            return versionedLib.get(previousLibVersion);
8534        }
8535        return null;
8536    }
8537
8538    public void shutdown() {
8539        mPackageUsage.writeNow(mPackages);
8540        mCompilerStats.writeNow();
8541    }
8542
8543    @Override
8544    public void dumpProfiles(String packageName) {
8545        PackageParser.Package pkg;
8546        synchronized (mPackages) {
8547            pkg = mPackages.get(packageName);
8548            if (pkg == null) {
8549                throw new IllegalArgumentException("Unknown package: " + packageName);
8550            }
8551        }
8552        /* Only the shell, root, or the app user should be able to dump profiles. */
8553        int callingUid = Binder.getCallingUid();
8554        if (callingUid != Process.SHELL_UID &&
8555            callingUid != Process.ROOT_UID &&
8556            callingUid != pkg.applicationInfo.uid) {
8557            throw new SecurityException("dumpProfiles");
8558        }
8559
8560        synchronized (mInstallLock) {
8561            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dump profiles");
8562            final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid);
8563            try {
8564                List<String> allCodePaths = pkg.getAllCodePathsExcludingResourceOnly();
8565                String codePaths = TextUtils.join(";", allCodePaths);
8566                mInstaller.dumpProfiles(sharedGid, packageName, codePaths);
8567            } catch (InstallerException e) {
8568                Slog.w(TAG, "Failed to dump profiles", e);
8569            }
8570            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
8571        }
8572    }
8573
8574    @Override
8575    public void forceDexOpt(String packageName) {
8576        enforceSystemOrRoot("forceDexOpt");
8577
8578        PackageParser.Package pkg;
8579        synchronized (mPackages) {
8580            pkg = mPackages.get(packageName);
8581            if (pkg == null) {
8582                throw new IllegalArgumentException("Unknown package: " + packageName);
8583            }
8584        }
8585
8586        synchronized (mInstallLock) {
8587            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt");
8588
8589            // Whoever is calling forceDexOpt wants a fully compiled package.
8590            // Don't use profiles since that may cause compilation to be skipped.
8591            final int res = performDexOptInternalWithDependenciesLI(pkg,
8592                    false /* checkProfiles */, getCompilerFilterForReason(REASON_FORCED_DEXOPT),
8593                    true /* force */);
8594
8595            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
8596            if (res != PackageDexOptimizer.DEX_OPT_PERFORMED) {
8597                throw new IllegalStateException("Failed to dexopt: " + res);
8598            }
8599        }
8600    }
8601
8602    private boolean verifyPackageUpdateLPr(PackageSetting oldPkg, PackageParser.Package newPkg) {
8603        if ((oldPkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) {
8604            Slog.w(TAG, "Unable to update from " + oldPkg.name
8605                    + " to " + newPkg.packageName
8606                    + ": old package not in system partition");
8607            return false;
8608        } else if (mPackages.get(oldPkg.name) != null) {
8609            Slog.w(TAG, "Unable to update from " + oldPkg.name
8610                    + " to " + newPkg.packageName
8611                    + ": old package still exists");
8612            return false;
8613        }
8614        return true;
8615    }
8616
8617    void removeCodePathLI(File codePath) {
8618        if (codePath.isDirectory()) {
8619            try {
8620                mInstaller.rmPackageDir(codePath.getAbsolutePath());
8621            } catch (InstallerException e) {
8622                Slog.w(TAG, "Failed to remove code path", e);
8623            }
8624        } else {
8625            codePath.delete();
8626        }
8627    }
8628
8629    private int[] resolveUserIds(int userId) {
8630        return (userId == UserHandle.USER_ALL) ? sUserManager.getUserIds() : new int[] { userId };
8631    }
8632
8633    private void clearAppDataLIF(PackageParser.Package pkg, int userId, int flags) {
8634        if (pkg == null) {
8635            Slog.wtf(TAG, "Package was null!", new Throwable());
8636            return;
8637        }
8638        clearAppDataLeafLIF(pkg, userId, flags);
8639        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
8640        for (int i = 0; i < childCount; i++) {
8641            clearAppDataLeafLIF(pkg.childPackages.get(i), userId, flags);
8642        }
8643    }
8644
8645    private void clearAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) {
8646        final PackageSetting ps;
8647        synchronized (mPackages) {
8648            ps = mSettings.mPackages.get(pkg.packageName);
8649        }
8650        for (int realUserId : resolveUserIds(userId)) {
8651            final long ceDataInode = (ps != null) ? ps.getCeDataInode(realUserId) : 0;
8652            try {
8653                mInstaller.clearAppData(pkg.volumeUuid, pkg.packageName, realUserId, flags,
8654                        ceDataInode);
8655            } catch (InstallerException e) {
8656                Slog.w(TAG, String.valueOf(e));
8657            }
8658        }
8659    }
8660
8661    private void destroyAppDataLIF(PackageParser.Package pkg, int userId, int flags) {
8662        if (pkg == null) {
8663            Slog.wtf(TAG, "Package was null!", new Throwable());
8664            return;
8665        }
8666        destroyAppDataLeafLIF(pkg, userId, flags);
8667        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
8668        for (int i = 0; i < childCount; i++) {
8669            destroyAppDataLeafLIF(pkg.childPackages.get(i), userId, flags);
8670        }
8671    }
8672
8673    private void destroyAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) {
8674        final PackageSetting ps;
8675        synchronized (mPackages) {
8676            ps = mSettings.mPackages.get(pkg.packageName);
8677        }
8678        for (int realUserId : resolveUserIds(userId)) {
8679            final long ceDataInode = (ps != null) ? ps.getCeDataInode(realUserId) : 0;
8680            try {
8681                mInstaller.destroyAppData(pkg.volumeUuid, pkg.packageName, realUserId, flags,
8682                        ceDataInode);
8683            } catch (InstallerException e) {
8684                Slog.w(TAG, String.valueOf(e));
8685            }
8686        }
8687    }
8688
8689    private void destroyAppProfilesLIF(PackageParser.Package pkg, int userId) {
8690        if (pkg == null) {
8691            Slog.wtf(TAG, "Package was null!", new Throwable());
8692            return;
8693        }
8694        destroyAppProfilesLeafLIF(pkg);
8695        destroyAppReferenceProfileLeafLIF(pkg, userId, true /* removeBaseMarker */);
8696        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
8697        for (int i = 0; i < childCount; i++) {
8698            destroyAppProfilesLeafLIF(pkg.childPackages.get(i));
8699            destroyAppReferenceProfileLeafLIF(pkg.childPackages.get(i), userId,
8700                    true /* removeBaseMarker */);
8701        }
8702    }
8703
8704    private void destroyAppReferenceProfileLeafLIF(PackageParser.Package pkg, int userId,
8705            boolean removeBaseMarker) {
8706        if (pkg.isForwardLocked()) {
8707            return;
8708        }
8709
8710        for (String path : pkg.getAllCodePathsExcludingResourceOnly()) {
8711            try {
8712                path = PackageManagerServiceUtils.realpath(new File(path));
8713            } catch (IOException e) {
8714                // TODO: Should we return early here ?
8715                Slog.w(TAG, "Failed to get canonical path", e);
8716                continue;
8717            }
8718
8719            final String useMarker = path.replace('/', '@');
8720            for (int realUserId : resolveUserIds(userId)) {
8721                File profileDir = Environment.getDataProfilesDeForeignDexDirectory(realUserId);
8722                if (removeBaseMarker) {
8723                    File foreignUseMark = new File(profileDir, useMarker);
8724                    if (foreignUseMark.exists()) {
8725                        if (!foreignUseMark.delete()) {
8726                            Slog.w(TAG, "Unable to delete foreign user mark for package: "
8727                                    + pkg.packageName);
8728                        }
8729                    }
8730                }
8731
8732                File[] markers = profileDir.listFiles();
8733                if (markers != null) {
8734                    final String searchString = "@" + pkg.packageName + "@";
8735                    // We also delete all markers that contain the package name we're
8736                    // uninstalling. These are associated with secondary dex-files belonging
8737                    // to the package. Reconstructing the path of these dex files is messy
8738                    // in general.
8739                    for (File marker : markers) {
8740                        if (marker.getName().indexOf(searchString) > 0) {
8741                            if (!marker.delete()) {
8742                                Slog.w(TAG, "Unable to delete foreign user mark for package: "
8743                                    + pkg.packageName);
8744                            }
8745                        }
8746                    }
8747                }
8748            }
8749        }
8750    }
8751
8752    private void destroyAppProfilesLeafLIF(PackageParser.Package pkg) {
8753        try {
8754            mInstaller.destroyAppProfiles(pkg.packageName);
8755        } catch (InstallerException e) {
8756            Slog.w(TAG, String.valueOf(e));
8757        }
8758    }
8759
8760    private void clearAppProfilesLIF(PackageParser.Package pkg, int userId) {
8761        if (pkg == null) {
8762            Slog.wtf(TAG, "Package was null!", new Throwable());
8763            return;
8764        }
8765        clearAppProfilesLeafLIF(pkg);
8766        // We don't remove the base foreign use marker when clearing profiles because
8767        // we will rename it when the app is updated. Unlike the actual profile contents,
8768        // the foreign use marker is good across installs.
8769        destroyAppReferenceProfileLeafLIF(pkg, userId, false /* removeBaseMarker */);
8770        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
8771        for (int i = 0; i < childCount; i++) {
8772            clearAppProfilesLeafLIF(pkg.childPackages.get(i));
8773        }
8774    }
8775
8776    private void clearAppProfilesLeafLIF(PackageParser.Package pkg) {
8777        try {
8778            mInstaller.clearAppProfiles(pkg.packageName);
8779        } catch (InstallerException e) {
8780            Slog.w(TAG, String.valueOf(e));
8781        }
8782    }
8783
8784    private void setInstallAndUpdateTime(PackageParser.Package pkg, long firstInstallTime,
8785            long lastUpdateTime) {
8786        // Set parent install/update time
8787        PackageSetting ps = (PackageSetting) pkg.mExtras;
8788        if (ps != null) {
8789            ps.firstInstallTime = firstInstallTime;
8790            ps.lastUpdateTime = lastUpdateTime;
8791        }
8792        // Set children install/update time
8793        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
8794        for (int i = 0; i < childCount; i++) {
8795            PackageParser.Package childPkg = pkg.childPackages.get(i);
8796            ps = (PackageSetting) childPkg.mExtras;
8797            if (ps != null) {
8798                ps.firstInstallTime = firstInstallTime;
8799                ps.lastUpdateTime = lastUpdateTime;
8800            }
8801        }
8802    }
8803
8804    private void addSharedLibraryLPr(ArraySet<String> usesLibraryFiles, SharedLibraryEntry file,
8805            PackageParser.Package changingLib) {
8806        if (file.path != null) {
8807            usesLibraryFiles.add(file.path);
8808            return;
8809        }
8810        PackageParser.Package p = mPackages.get(file.apk);
8811        if (changingLib != null && changingLib.packageName.equals(file.apk)) {
8812            // If we are doing this while in the middle of updating a library apk,
8813            // then we need to make sure to use that new apk for determining the
8814            // dependencies here.  (We haven't yet finished committing the new apk
8815            // to the package manager state.)
8816            if (p == null || p.packageName.equals(changingLib.packageName)) {
8817                p = changingLib;
8818            }
8819        }
8820        if (p != null) {
8821            usesLibraryFiles.addAll(p.getAllCodePaths());
8822        }
8823    }
8824
8825    private void updateSharedLibrariesLPr(PackageParser.Package pkg,
8826            PackageParser.Package changingLib) throws PackageManagerException {
8827        if (pkg == null) {
8828            return;
8829        }
8830        ArraySet<String> usesLibraryFiles = null;
8831        if (pkg.usesLibraries != null) {
8832            usesLibraryFiles = addSharedLibrariesLPw(pkg.usesLibraries,
8833                    null, null, pkg.packageName, changingLib, true, null);
8834        }
8835        if (pkg.usesStaticLibraries != null) {
8836            usesLibraryFiles = addSharedLibrariesLPw(pkg.usesStaticLibraries,
8837                    pkg.usesStaticLibrariesVersions, pkg.usesStaticLibrariesCertDigests,
8838                    pkg.packageName, changingLib, true, usesLibraryFiles);
8839        }
8840        if (pkg.usesOptionalLibraries != null) {
8841            usesLibraryFiles = addSharedLibrariesLPw(pkg.usesOptionalLibraries,
8842                    null, null, pkg.packageName, changingLib, false, usesLibraryFiles);
8843        }
8844        if (!ArrayUtils.isEmpty(usesLibraryFiles)) {
8845            pkg.usesLibraryFiles = usesLibraryFiles.toArray(new String[usesLibraryFiles.size()]);
8846        } else {
8847            pkg.usesLibraryFiles = null;
8848        }
8849    }
8850
8851    private ArraySet<String> addSharedLibrariesLPw(@NonNull List<String> requestedLibraries,
8852            @Nullable int[] requiredVersions, @Nullable String[] requiredCertDigests,
8853            @NonNull String packageName, @Nullable PackageParser.Package changingLib,
8854            boolean required, @Nullable ArraySet<String> outUsedLibraries)
8855            throws PackageManagerException {
8856        final int libCount = requestedLibraries.size();
8857        for (int i = 0; i < libCount; i++) {
8858            final String libName = requestedLibraries.get(i);
8859            final int libVersion = requiredVersions != null ? requiredVersions[i]
8860                    : SharedLibraryInfo.VERSION_UNDEFINED;
8861            final SharedLibraryEntry libEntry = getSharedLibraryEntryLPr(libName, libVersion);
8862            if (libEntry == null) {
8863                if (required) {
8864                    throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY,
8865                            "Package " + packageName + " requires unavailable shared library "
8866                                    + libName + "; failing!");
8867                } else {
8868                    Slog.w(TAG, "Package " + packageName
8869                            + " desires unavailable shared library "
8870                            + libName + "; ignoring!");
8871                }
8872            } else {
8873                if (requiredVersions != null && requiredCertDigests != null) {
8874                    if (libEntry.info.getVersion() != requiredVersions[i]) {
8875                        throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY,
8876                            "Package " + packageName + " requires unavailable static shared"
8877                                    + " library " + libName + " version "
8878                                    + libEntry.info.getVersion() + "; failing!");
8879                    }
8880
8881                    PackageParser.Package libPkg = mPackages.get(libEntry.apk);
8882                    if (libPkg == null) {
8883                        throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY,
8884                                "Package " + packageName + " requires unavailable static shared"
8885                                        + " library; failing!");
8886                    }
8887
8888                    String expectedCertDigest = requiredCertDigests[i];
8889                    String libCertDigest = PackageUtils.computeCertSha256Digest(
8890                                libPkg.mSignatures[0]);
8891                    if (!libCertDigest.equalsIgnoreCase(expectedCertDigest)) {
8892                        throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY,
8893                                "Package " + packageName + " requires differently signed" +
8894                                        " static shared library; failing!");
8895                    }
8896                }
8897
8898                if (outUsedLibraries == null) {
8899                    outUsedLibraries = new ArraySet<>();
8900                }
8901                addSharedLibraryLPr(outUsedLibraries, libEntry, changingLib);
8902            }
8903        }
8904        return outUsedLibraries;
8905    }
8906
8907    private static boolean hasString(List<String> list, List<String> which) {
8908        if (list == null) {
8909            return false;
8910        }
8911        for (int i=list.size()-1; i>=0; i--) {
8912            for (int j=which.size()-1; j>=0; j--) {
8913                if (which.get(j).equals(list.get(i))) {
8914                    return true;
8915                }
8916            }
8917        }
8918        return false;
8919    }
8920
8921    private ArrayList<PackageParser.Package> updateAllSharedLibrariesLPw(
8922            PackageParser.Package changingPkg) {
8923        ArrayList<PackageParser.Package> res = null;
8924        for (PackageParser.Package pkg : mPackages.values()) {
8925            if (changingPkg != null
8926                    && !hasString(pkg.usesLibraries, changingPkg.libraryNames)
8927                    && !hasString(pkg.usesOptionalLibraries, changingPkg.libraryNames)
8928                    && !ArrayUtils.contains(pkg.usesStaticLibraries,
8929                            changingPkg.staticSharedLibName)) {
8930                return null;
8931            }
8932            if (res == null) {
8933                res = new ArrayList<>();
8934            }
8935            res.add(pkg);
8936            try {
8937                updateSharedLibrariesLPr(pkg, changingPkg);
8938            } catch (PackageManagerException e) {
8939                // If a system app update or an app and a required lib missing we
8940                // delete the package and for updated system apps keep the data as
8941                // it is better for the user to reinstall than to be in an limbo
8942                // state. Also libs disappearing under an app should never happen
8943                // - just in case.
8944                if (!pkg.isSystemApp() || pkg.isUpdatedSystemApp()) {
8945                    final int flags = pkg.isUpdatedSystemApp()
8946                            ? PackageManager.DELETE_KEEP_DATA : 0;
8947                    deletePackageLIF(pkg.packageName, null, true, sUserManager.getUserIds(),
8948                            flags , null, true, null);
8949                }
8950                Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
8951            }
8952        }
8953        return res;
8954    }
8955
8956    /**
8957     * Derive the value of the {@code cpuAbiOverride} based on the provided
8958     * value and an optional stored value from the package settings.
8959     */
8960    private static String deriveAbiOverride(String abiOverride, PackageSetting settings) {
8961        String cpuAbiOverride = null;
8962
8963        if (NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(abiOverride)) {
8964            cpuAbiOverride = null;
8965        } else if (abiOverride != null) {
8966            cpuAbiOverride = abiOverride;
8967        } else if (settings != null) {
8968            cpuAbiOverride = settings.cpuAbiOverrideString;
8969        }
8970
8971        return cpuAbiOverride;
8972    }
8973
8974    private PackageParser.Package scanPackageTracedLI(PackageParser.Package pkg,
8975            final int policyFlags, int scanFlags, long currentTime, @Nullable UserHandle user)
8976                    throws PackageManagerException {
8977        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage");
8978        // If the package has children and this is the first dive in the function
8979        // we recursively scan the package with the SCAN_CHECK_ONLY flag set to see
8980        // whether all packages (parent and children) would be successfully scanned
8981        // before the actual scan since scanning mutates internal state and we want
8982        // to atomically install the package and its children.
8983        if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
8984            if (pkg.childPackages != null && pkg.childPackages.size() > 0) {
8985                scanFlags |= SCAN_CHECK_ONLY;
8986            }
8987        } else {
8988            scanFlags &= ~SCAN_CHECK_ONLY;
8989        }
8990
8991        final PackageParser.Package scannedPkg;
8992        try {
8993            // Scan the parent
8994            scannedPkg = scanPackageLI(pkg, policyFlags, scanFlags, currentTime, user);
8995            // Scan the children
8996            final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
8997            for (int i = 0; i < childCount; i++) {
8998                PackageParser.Package childPkg = pkg.childPackages.get(i);
8999                scanPackageLI(childPkg, policyFlags,
9000                        scanFlags, currentTime, user);
9001            }
9002        } finally {
9003            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
9004        }
9005
9006        if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
9007            return scanPackageTracedLI(pkg, policyFlags, scanFlags, currentTime, user);
9008        }
9009
9010        return scannedPkg;
9011    }
9012
9013    private PackageParser.Package scanPackageLI(PackageParser.Package pkg, final int policyFlags,
9014            int scanFlags, long currentTime, @Nullable UserHandle user)
9015                    throws PackageManagerException {
9016        boolean success = false;
9017        try {
9018            final PackageParser.Package res = scanPackageDirtyLI(pkg, policyFlags, scanFlags,
9019                    currentTime, user);
9020            success = true;
9021            return res;
9022        } finally {
9023            if (!success && (scanFlags & SCAN_DELETE_DATA_ON_FAILURES) != 0) {
9024                // DELETE_DATA_ON_FAILURES is only used by frozen paths
9025                destroyAppDataLIF(pkg, UserHandle.USER_ALL,
9026                        StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
9027                destroyAppProfilesLIF(pkg, UserHandle.USER_ALL);
9028            }
9029        }
9030    }
9031
9032    /**
9033     * Returns {@code true} if the given file contains code. Otherwise {@code false}.
9034     */
9035    private static boolean apkHasCode(String fileName) {
9036        StrictJarFile jarFile = null;
9037        try {
9038            jarFile = new StrictJarFile(fileName,
9039                    false /*verify*/, false /*signatureSchemeRollbackProtectionsEnforced*/);
9040            return jarFile.findEntry("classes.dex") != null;
9041        } catch (IOException ignore) {
9042        } finally {
9043            try {
9044                if (jarFile != null) {
9045                    jarFile.close();
9046                }
9047            } catch (IOException ignore) {}
9048        }
9049        return false;
9050    }
9051
9052    /**
9053     * Enforces code policy for the package. This ensures that if an APK has
9054     * declared hasCode="true" in its manifest that the APK actually contains
9055     * code.
9056     *
9057     * @throws PackageManagerException If bytecode could not be found when it should exist
9058     */
9059    private static void assertCodePolicy(PackageParser.Package pkg)
9060            throws PackageManagerException {
9061        final boolean shouldHaveCode =
9062                (pkg.applicationInfo.flags & ApplicationInfo.FLAG_HAS_CODE) != 0;
9063        if (shouldHaveCode && !apkHasCode(pkg.baseCodePath)) {
9064            throw new PackageManagerException(INSTALL_FAILED_INVALID_APK,
9065                    "Package " + pkg.baseCodePath + " code is missing");
9066        }
9067
9068        if (!ArrayUtils.isEmpty(pkg.splitCodePaths)) {
9069            for (int i = 0; i < pkg.splitCodePaths.length; i++) {
9070                final boolean splitShouldHaveCode =
9071                        (pkg.splitFlags[i] & ApplicationInfo.FLAG_HAS_CODE) != 0;
9072                if (splitShouldHaveCode && !apkHasCode(pkg.splitCodePaths[i])) {
9073                    throw new PackageManagerException(INSTALL_FAILED_INVALID_APK,
9074                            "Package " + pkg.splitCodePaths[i] + " code is missing");
9075                }
9076            }
9077        }
9078    }
9079
9080    private PackageParser.Package scanPackageDirtyLI(PackageParser.Package pkg,
9081            final int policyFlags, final int scanFlags, long currentTime, @Nullable UserHandle user)
9082                    throws PackageManagerException {
9083        if (DEBUG_PACKAGE_SCANNING) {
9084            if ((policyFlags & PackageParser.PARSE_CHATTY) != 0)
9085                Log.d(TAG, "Scanning package " + pkg.packageName);
9086        }
9087
9088        applyPolicy(pkg, policyFlags);
9089
9090        assertPackageIsValid(pkg, policyFlags, scanFlags);
9091
9092        // Initialize package source and resource directories
9093        final File scanFile = new File(pkg.codePath);
9094        final File destCodeFile = new File(pkg.applicationInfo.getCodePath());
9095        final File destResourceFile = new File(pkg.applicationInfo.getResourcePath());
9096
9097        SharedUserSetting suid = null;
9098        PackageSetting pkgSetting = null;
9099
9100        // Getting the package setting may have a side-effect, so if we
9101        // are only checking if scan would succeed, stash a copy of the
9102        // old setting to restore at the end.
9103        PackageSetting nonMutatedPs = null;
9104
9105        // We keep references to the derived CPU Abis from settings in oder to reuse
9106        // them in the case where we're not upgrading or booting for the first time.
9107        String primaryCpuAbiFromSettings = null;
9108        String secondaryCpuAbiFromSettings = null;
9109
9110        // writer
9111        synchronized (mPackages) {
9112            if (pkg.mSharedUserId != null) {
9113                // SIDE EFFECTS; may potentially allocate a new shared user
9114                suid = mSettings.getSharedUserLPw(
9115                        pkg.mSharedUserId, 0 /*pkgFlags*/, 0 /*pkgPrivateFlags*/, true /*create*/);
9116                if (DEBUG_PACKAGE_SCANNING) {
9117                    if ((policyFlags & PackageParser.PARSE_CHATTY) != 0)
9118                        Log.d(TAG, "Shared UserID " + pkg.mSharedUserId + " (uid=" + suid.userId
9119                                + "): packages=" + suid.packages);
9120                }
9121            }
9122
9123            // Check if we are renaming from an original package name.
9124            PackageSetting origPackage = null;
9125            String realName = null;
9126            if (pkg.mOriginalPackages != null) {
9127                // This package may need to be renamed to a previously
9128                // installed name.  Let's check on that...
9129                final String renamed = mSettings.getRenamedPackageLPr(pkg.mRealPackage);
9130                if (pkg.mOriginalPackages.contains(renamed)) {
9131                    // This package had originally been installed as the
9132                    // original name, and we have already taken care of
9133                    // transitioning to the new one.  Just update the new
9134                    // one to continue using the old name.
9135                    realName = pkg.mRealPackage;
9136                    if (!pkg.packageName.equals(renamed)) {
9137                        // Callers into this function may have already taken
9138                        // care of renaming the package; only do it here if
9139                        // it is not already done.
9140                        pkg.setPackageName(renamed);
9141                    }
9142                } else {
9143                    for (int i=pkg.mOriginalPackages.size()-1; i>=0; i--) {
9144                        if ((origPackage = mSettings.getPackageLPr(
9145                                pkg.mOriginalPackages.get(i))) != null) {
9146                            // We do have the package already installed under its
9147                            // original name...  should we use it?
9148                            if (!verifyPackageUpdateLPr(origPackage, pkg)) {
9149                                // New package is not compatible with original.
9150                                origPackage = null;
9151                                continue;
9152                            } else if (origPackage.sharedUser != null) {
9153                                // Make sure uid is compatible between packages.
9154                                if (!origPackage.sharedUser.name.equals(pkg.mSharedUserId)) {
9155                                    Slog.w(TAG, "Unable to migrate data from " + origPackage.name
9156                                            + " to " + pkg.packageName + ": old uid "
9157                                            + origPackage.sharedUser.name
9158                                            + " differs from " + pkg.mSharedUserId);
9159                                    origPackage = null;
9160                                    continue;
9161                                }
9162                                // TODO: Add case when shared user id is added [b/28144775]
9163                            } else {
9164                                if (DEBUG_UPGRADE) Log.v(TAG, "Renaming new package "
9165                                        + pkg.packageName + " to old name " + origPackage.name);
9166                            }
9167                            break;
9168                        }
9169                    }
9170                }
9171            }
9172
9173            if (mTransferedPackages.contains(pkg.packageName)) {
9174                Slog.w(TAG, "Package " + pkg.packageName
9175                        + " was transferred to another, but its .apk remains");
9176            }
9177
9178            // See comments in nonMutatedPs declaration
9179            if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
9180                PackageSetting foundPs = mSettings.getPackageLPr(pkg.packageName);
9181                if (foundPs != null) {
9182                    nonMutatedPs = new PackageSetting(foundPs);
9183                }
9184            }
9185
9186            if ((scanFlags & SCAN_FIRST_BOOT_OR_UPGRADE) == 0) {
9187                PackageSetting foundPs = mSettings.getPackageLPr(pkg.packageName);
9188                if (foundPs != null) {
9189                    primaryCpuAbiFromSettings = foundPs.primaryCpuAbiString;
9190                    secondaryCpuAbiFromSettings = foundPs.secondaryCpuAbiString;
9191                }
9192            }
9193
9194            pkgSetting = mSettings.getPackageLPr(pkg.packageName);
9195            if (pkgSetting != null && pkgSetting.sharedUser != suid) {
9196                PackageManagerService.reportSettingsProblem(Log.WARN,
9197                        "Package " + pkg.packageName + " shared user changed from "
9198                                + (pkgSetting.sharedUser != null
9199                                        ? pkgSetting.sharedUser.name : "<nothing>")
9200                                + " to "
9201                                + (suid != null ? suid.name : "<nothing>")
9202                                + "; replacing with new");
9203                pkgSetting = null;
9204            }
9205            final PackageSetting oldPkgSetting =
9206                    pkgSetting == null ? null : new PackageSetting(pkgSetting);
9207            final PackageSetting disabledPkgSetting =
9208                    mSettings.getDisabledSystemPkgLPr(pkg.packageName);
9209
9210            String[] usesStaticLibraries = null;
9211            if (pkg.usesStaticLibraries != null) {
9212                usesStaticLibraries = new String[pkg.usesStaticLibraries.size()];
9213                pkg.usesStaticLibraries.toArray(usesStaticLibraries);
9214            }
9215
9216            if (pkgSetting == null) {
9217                final String parentPackageName = (pkg.parentPackage != null)
9218                        ? pkg.parentPackage.packageName : null;
9219                final boolean instantApp = (scanFlags & SCAN_AS_INSTANT_APP) != 0;
9220                // REMOVE SharedUserSetting from method; update in a separate call
9221                pkgSetting = Settings.createNewSetting(pkg.packageName, origPackage,
9222                        disabledPkgSetting, realName, suid, destCodeFile, destResourceFile,
9223                        pkg.applicationInfo.nativeLibraryRootDir, pkg.applicationInfo.primaryCpuAbi,
9224                        pkg.applicationInfo.secondaryCpuAbi, pkg.mVersionCode,
9225                        pkg.applicationInfo.flags, pkg.applicationInfo.privateFlags, user,
9226                        true /*allowInstall*/, instantApp, parentPackageName,
9227                        pkg.getChildPackageNames(), UserManagerService.getInstance(),
9228                        usesStaticLibraries, pkg.usesStaticLibrariesVersions);
9229                // SIDE EFFECTS; updates system state; move elsewhere
9230                if (origPackage != null) {
9231                    mSettings.addRenamedPackageLPw(pkg.packageName, origPackage.name);
9232                }
9233                mSettings.addUserToSettingLPw(pkgSetting);
9234            } else {
9235                // REMOVE SharedUserSetting from method; update in a separate call.
9236                //
9237                // TODO(narayan): This update is bogus. nativeLibraryDir & primaryCpuAbi,
9238                // secondaryCpuAbi are not known at this point so we always update them
9239                // to null here, only to reset them at a later point.
9240                Settings.updatePackageSetting(pkgSetting, disabledPkgSetting, suid, destCodeFile,
9241                        pkg.applicationInfo.nativeLibraryDir, pkg.applicationInfo.primaryCpuAbi,
9242                        pkg.applicationInfo.secondaryCpuAbi, pkg.applicationInfo.flags,
9243                        pkg.applicationInfo.privateFlags, pkg.getChildPackageNames(),
9244                        UserManagerService.getInstance(), usesStaticLibraries,
9245                        pkg.usesStaticLibrariesVersions);
9246            }
9247            // SIDE EFFECTS; persists system state to files on disk; move elsewhere
9248            mSettings.writeUserRestrictionsLPw(pkgSetting, oldPkgSetting);
9249
9250            // SIDE EFFECTS; modifies system state; move elsewhere
9251            if (pkgSetting.origPackage != null) {
9252                // If we are first transitioning from an original package,
9253                // fix up the new package's name now.  We need to do this after
9254                // looking up the package under its new name, so getPackageLP
9255                // can take care of fiddling things correctly.
9256                pkg.setPackageName(origPackage.name);
9257
9258                // File a report about this.
9259                String msg = "New package " + pkgSetting.realName
9260                        + " renamed to replace old package " + pkgSetting.name;
9261                reportSettingsProblem(Log.WARN, msg);
9262
9263                // Make a note of it.
9264                if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
9265                    mTransferedPackages.add(origPackage.name);
9266                }
9267
9268                // No longer need to retain this.
9269                pkgSetting.origPackage = null;
9270            }
9271
9272            // SIDE EFFECTS; modifies system state; move elsewhere
9273            if ((scanFlags & SCAN_CHECK_ONLY) == 0 && realName != null) {
9274                // Make a note of it.
9275                mTransferedPackages.add(pkg.packageName);
9276            }
9277
9278            if (mSettings.isDisabledSystemPackageLPr(pkg.packageName)) {
9279                pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
9280            }
9281
9282            if ((scanFlags & SCAN_BOOTING) == 0
9283                    && (policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
9284                // Check all shared libraries and map to their actual file path.
9285                // We only do this here for apps not on a system dir, because those
9286                // are the only ones that can fail an install due to this.  We
9287                // will take care of the system apps by updating all of their
9288                // library paths after the scan is done. Also during the initial
9289                // scan don't update any libs as we do this wholesale after all
9290                // apps are scanned to avoid dependency based scanning.
9291                updateSharedLibrariesLPr(pkg, null);
9292            }
9293
9294            if (mFoundPolicyFile) {
9295                SELinuxMMAC.assignSeInfoValue(pkg);
9296            }
9297            pkg.applicationInfo.uid = pkgSetting.appId;
9298            pkg.mExtras = pkgSetting;
9299
9300
9301            // Static shared libs have same package with different versions where
9302            // we internally use a synthetic package name to allow multiple versions
9303            // of the same package, therefore we need to compare signatures against
9304            // the package setting for the latest library version.
9305            PackageSetting signatureCheckPs = pkgSetting;
9306            if (pkg.applicationInfo.isStaticSharedLibrary()) {
9307                SharedLibraryEntry libraryEntry = getLatestSharedLibraVersionLPr(pkg);
9308                if (libraryEntry != null) {
9309                    signatureCheckPs = mSettings.getPackageLPr(libraryEntry.apk);
9310                }
9311            }
9312
9313            if (shouldCheckUpgradeKeySetLP(signatureCheckPs, scanFlags)) {
9314                if (checkUpgradeKeySetLP(signatureCheckPs, pkg)) {
9315                    // We just determined the app is signed correctly, so bring
9316                    // over the latest parsed certs.
9317                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
9318                } else {
9319                    if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
9320                        throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
9321                                "Package " + pkg.packageName + " upgrade keys do not match the "
9322                                + "previously installed version");
9323                    } else {
9324                        pkgSetting.signatures.mSignatures = pkg.mSignatures;
9325                        String msg = "System package " + pkg.packageName
9326                                + " signature changed; retaining data.";
9327                        reportSettingsProblem(Log.WARN, msg);
9328                    }
9329                }
9330            } else {
9331                try {
9332                    // SIDE EFFECTS; compareSignaturesCompat() changes KeysetManagerService
9333                    verifySignaturesLP(signatureCheckPs, pkg);
9334                    // We just determined the app is signed correctly, so bring
9335                    // over the latest parsed certs.
9336                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
9337                } catch (PackageManagerException e) {
9338                    if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
9339                        throw e;
9340                    }
9341                    // The signature has changed, but this package is in the system
9342                    // image...  let's recover!
9343                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
9344                    // However...  if this package is part of a shared user, but it
9345                    // doesn't match the signature of the shared user, let's fail.
9346                    // What this means is that you can't change the signatures
9347                    // associated with an overall shared user, which doesn't seem all
9348                    // that unreasonable.
9349                    if (signatureCheckPs.sharedUser != null) {
9350                        if (compareSignatures(signatureCheckPs.sharedUser.signatures.mSignatures,
9351                                pkg.mSignatures) != PackageManager.SIGNATURE_MATCH) {
9352                            throw new PackageManagerException(
9353                                    INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES,
9354                                    "Signature mismatch for shared user: "
9355                                            + pkgSetting.sharedUser);
9356                        }
9357                    }
9358                    // File a report about this.
9359                    String msg = "System package " + pkg.packageName
9360                            + " signature changed; retaining data.";
9361                    reportSettingsProblem(Log.WARN, msg);
9362                }
9363            }
9364
9365            if ((scanFlags & SCAN_CHECK_ONLY) == 0 && pkg.mAdoptPermissions != null) {
9366                // This package wants to adopt ownership of permissions from
9367                // another package.
9368                for (int i = pkg.mAdoptPermissions.size() - 1; i >= 0; i--) {
9369                    final String origName = pkg.mAdoptPermissions.get(i);
9370                    final PackageSetting orig = mSettings.getPackageLPr(origName);
9371                    if (orig != null) {
9372                        if (verifyPackageUpdateLPr(orig, pkg)) {
9373                            Slog.i(TAG, "Adopting permissions from " + origName + " to "
9374                                    + pkg.packageName);
9375                            // SIDE EFFECTS; updates permissions system state; move elsewhere
9376                            mSettings.transferPermissionsLPw(origName, pkg.packageName);
9377                        }
9378                    }
9379                }
9380            }
9381        }
9382
9383        pkg.applicationInfo.processName = fixProcessName(
9384                pkg.applicationInfo.packageName,
9385                pkg.applicationInfo.processName);
9386
9387        if (pkg != mPlatformPackage) {
9388            // Get all of our default paths setup
9389            pkg.applicationInfo.initForUser(UserHandle.USER_SYSTEM);
9390        }
9391
9392        final String cpuAbiOverride = deriveAbiOverride(pkg.cpuAbiOverride, pkgSetting);
9393
9394        if ((scanFlags & SCAN_NEW_INSTALL) == 0) {
9395            if ((scanFlags & SCAN_FIRST_BOOT_OR_UPGRADE) != 0) {
9396                Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "derivePackageAbi");
9397                derivePackageAbi(
9398                        pkg, scanFile, cpuAbiOverride, true /*extractLibs*/, mAppLib32InstallDir);
9399                Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
9400
9401                // Some system apps still use directory structure for native libraries
9402                // in which case we might end up not detecting abi solely based on apk
9403                // structure. Try to detect abi based on directory structure.
9404                if (isSystemApp(pkg) && !pkg.isUpdatedSystemApp() &&
9405                        pkg.applicationInfo.primaryCpuAbi == null) {
9406                    setBundledAppAbisAndRoots(pkg, pkgSetting);
9407                    setNativeLibraryPaths(pkg, mAppLib32InstallDir);
9408                }
9409            } else {
9410                // This is not a first boot or an upgrade, don't bother deriving the
9411                // ABI during the scan. Instead, trust the value that was stored in the
9412                // package setting.
9413                pkg.applicationInfo.primaryCpuAbi = primaryCpuAbiFromSettings;
9414                pkg.applicationInfo.secondaryCpuAbi = secondaryCpuAbiFromSettings;
9415
9416                setNativeLibraryPaths(pkg, mAppLib32InstallDir);
9417
9418                if (DEBUG_ABI_SELECTION) {
9419                    Slog.i(TAG, "Using ABIS and native lib paths from settings : " +
9420                        pkg.packageName + " " + pkg.applicationInfo.primaryCpuAbi + ", " +
9421                        pkg.applicationInfo.secondaryCpuAbi);
9422                }
9423            }
9424        } else {
9425            if ((scanFlags & SCAN_MOVE) != 0) {
9426                // We haven't run dex-opt for this move (since we've moved the compiled output too)
9427                // but we already have this packages package info in the PackageSetting. We just
9428                // use that and derive the native library path based on the new codepath.
9429                pkg.applicationInfo.primaryCpuAbi = pkgSetting.primaryCpuAbiString;
9430                pkg.applicationInfo.secondaryCpuAbi = pkgSetting.secondaryCpuAbiString;
9431            }
9432
9433            // Set native library paths again. For moves, the path will be updated based on the
9434            // ABIs we've determined above. For non-moves, the path will be updated based on the
9435            // ABIs we determined during compilation, but the path will depend on the final
9436            // package path (after the rename away from the stage path).
9437            setNativeLibraryPaths(pkg, mAppLib32InstallDir);
9438        }
9439
9440        // This is a special case for the "system" package, where the ABI is
9441        // dictated by the zygote configuration (and init.rc). We should keep track
9442        // of this ABI so that we can deal with "normal" applications that run under
9443        // the same UID correctly.
9444        if (mPlatformPackage == pkg) {
9445            pkg.applicationInfo.primaryCpuAbi = VMRuntime.getRuntime().is64Bit() ?
9446                    Build.SUPPORTED_64_BIT_ABIS[0] : Build.SUPPORTED_32_BIT_ABIS[0];
9447        }
9448
9449        // If there's a mismatch between the abi-override in the package setting
9450        // and the abiOverride specified for the install. Warn about this because we
9451        // would've already compiled the app without taking the package setting into
9452        // account.
9453        if ((scanFlags & SCAN_NO_DEX) == 0 && (scanFlags & SCAN_NEW_INSTALL) != 0) {
9454            if (cpuAbiOverride == null && pkgSetting.cpuAbiOverrideString != null) {
9455                Slog.w(TAG, "Ignoring persisted ABI override " + cpuAbiOverride +
9456                        " for package " + pkg.packageName);
9457            }
9458        }
9459
9460        pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi;
9461        pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi;
9462        pkgSetting.cpuAbiOverrideString = cpuAbiOverride;
9463
9464        // Copy the derived override back to the parsed package, so that we can
9465        // update the package settings accordingly.
9466        pkg.cpuAbiOverride = cpuAbiOverride;
9467
9468        if (DEBUG_ABI_SELECTION) {
9469            Slog.d(TAG, "Resolved nativeLibraryRoot for " + pkg.applicationInfo.packageName
9470                    + " to root=" + pkg.applicationInfo.nativeLibraryRootDir + ", isa="
9471                    + pkg.applicationInfo.nativeLibraryRootRequiresIsa);
9472        }
9473
9474        // Push the derived path down into PackageSettings so we know what to
9475        // clean up at uninstall time.
9476        pkgSetting.legacyNativeLibraryPathString = pkg.applicationInfo.nativeLibraryRootDir;
9477
9478        if (DEBUG_ABI_SELECTION) {
9479            Log.d(TAG, "Abis for package[" + pkg.packageName + "] are" +
9480                    " primary=" + pkg.applicationInfo.primaryCpuAbi +
9481                    " secondary=" + pkg.applicationInfo.secondaryCpuAbi);
9482        }
9483
9484        // SIDE EFFECTS; removes DEX files from disk; move elsewhere
9485        if ((scanFlags & SCAN_BOOTING) == 0 && pkgSetting.sharedUser != null) {
9486            // We don't do this here during boot because we can do it all
9487            // at once after scanning all existing packages.
9488            //
9489            // We also do this *before* we perform dexopt on this package, so that
9490            // we can avoid redundant dexopts, and also to make sure we've got the
9491            // code and package path correct.
9492            adjustCpuAbisForSharedUserLPw(pkgSetting.sharedUser.packages, pkg);
9493        }
9494
9495        if (mFactoryTest && pkg.requestedPermissions.contains(
9496                android.Manifest.permission.FACTORY_TEST)) {
9497            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_FACTORY_TEST;
9498        }
9499
9500        if (isSystemApp(pkg)) {
9501            pkgSetting.isOrphaned = true;
9502        }
9503
9504        // Take care of first install / last update times.
9505        final long scanFileTime = getLastModifiedTime(pkg, scanFile);
9506        if (currentTime != 0) {
9507            if (pkgSetting.firstInstallTime == 0) {
9508                pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = currentTime;
9509            } else if ((scanFlags & SCAN_UPDATE_TIME) != 0) {
9510                pkgSetting.lastUpdateTime = currentTime;
9511            }
9512        } else if (pkgSetting.firstInstallTime == 0) {
9513            // We need *something*.  Take time time stamp of the file.
9514            pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = scanFileTime;
9515        } else if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0) {
9516            if (scanFileTime != pkgSetting.timeStamp) {
9517                // A package on the system image has changed; consider this
9518                // to be an update.
9519                pkgSetting.lastUpdateTime = scanFileTime;
9520            }
9521        }
9522        pkgSetting.setTimeStamp(scanFileTime);
9523
9524        if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
9525            if (nonMutatedPs != null) {
9526                synchronized (mPackages) {
9527                    mSettings.mPackages.put(nonMutatedPs.name, nonMutatedPs);
9528                }
9529            }
9530        } else {
9531            final int userId = user == null ? 0 : user.getIdentifier();
9532            // Modify state for the given package setting
9533            commitPackageSettings(pkg, pkgSetting, user, scanFlags,
9534                    (policyFlags & PackageParser.PARSE_CHATTY) != 0 /*chatty*/);
9535            if (pkgSetting.getInstantApp(userId)) {
9536                mInstantAppRegistry.addInstantAppLPw(userId, pkgSetting.appId);
9537            }
9538        }
9539        return pkg;
9540    }
9541
9542    /**
9543     * Applies policy to the parsed package based upon the given policy flags.
9544     * Ensures the package is in a good state.
9545     * <p>
9546     * Implementation detail: This method must NOT have any side effect. It would
9547     * ideally be static, but, it requires locks to read system state.
9548     */
9549    private void applyPolicy(PackageParser.Package pkg, int policyFlags) {
9550        if ((policyFlags&PackageParser.PARSE_IS_SYSTEM) != 0) {
9551            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_SYSTEM;
9552            if (pkg.applicationInfo.isDirectBootAware()) {
9553                // we're direct boot aware; set for all components
9554                for (PackageParser.Service s : pkg.services) {
9555                    s.info.encryptionAware = s.info.directBootAware = true;
9556                }
9557                for (PackageParser.Provider p : pkg.providers) {
9558                    p.info.encryptionAware = p.info.directBootAware = true;
9559                }
9560                for (PackageParser.Activity a : pkg.activities) {
9561                    a.info.encryptionAware = a.info.directBootAware = true;
9562                }
9563                for (PackageParser.Activity r : pkg.receivers) {
9564                    r.info.encryptionAware = r.info.directBootAware = true;
9565                }
9566            }
9567        } else {
9568            // Only allow system apps to be flagged as core apps.
9569            pkg.coreApp = false;
9570            // clear flags not applicable to regular apps
9571            pkg.applicationInfo.privateFlags &=
9572                    ~ApplicationInfo.PRIVATE_FLAG_DEFAULT_TO_DEVICE_PROTECTED_STORAGE;
9573            pkg.applicationInfo.privateFlags &=
9574                    ~ApplicationInfo.PRIVATE_FLAG_DIRECT_BOOT_AWARE;
9575        }
9576        pkg.mTrustedOverlay = (policyFlags&PackageParser.PARSE_TRUSTED_OVERLAY) != 0;
9577
9578        if ((policyFlags&PackageParser.PARSE_IS_PRIVILEGED) != 0) {
9579            pkg.applicationInfo.privateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
9580        }
9581
9582        if (!isSystemApp(pkg)) {
9583            // Only system apps can use these features.
9584            pkg.mOriginalPackages = null;
9585            pkg.mRealPackage = null;
9586            pkg.mAdoptPermissions = null;
9587        }
9588    }
9589
9590    /**
9591     * Asserts the parsed package is valid according to the given policy. If the
9592     * package is invalid, for whatever reason, throws {@link PackgeManagerException}.
9593     * <p>
9594     * Implementation detail: This method must NOT have any side effects. It would
9595     * ideally be static, but, it requires locks to read system state.
9596     *
9597     * @throws PackageManagerException If the package fails any of the validation checks
9598     */
9599    private void assertPackageIsValid(PackageParser.Package pkg, int policyFlags, int scanFlags)
9600            throws PackageManagerException {
9601        if ((policyFlags & PackageParser.PARSE_ENFORCE_CODE) != 0) {
9602            assertCodePolicy(pkg);
9603        }
9604
9605        if (pkg.applicationInfo.getCodePath() == null ||
9606                pkg.applicationInfo.getResourcePath() == null) {
9607            // Bail out. The resource and code paths haven't been set.
9608            throw new PackageManagerException(INSTALL_FAILED_INVALID_APK,
9609                    "Code and resource paths haven't been set correctly");
9610        }
9611
9612        // Make sure we're not adding any bogus keyset info
9613        KeySetManagerService ksms = mSettings.mKeySetManagerService;
9614        ksms.assertScannedPackageValid(pkg);
9615
9616        synchronized (mPackages) {
9617            // The special "android" package can only be defined once
9618            if (pkg.packageName.equals("android")) {
9619                if (mAndroidApplication != null) {
9620                    Slog.w(TAG, "*************************************************");
9621                    Slog.w(TAG, "Core android package being redefined.  Skipping.");
9622                    Slog.w(TAG, " codePath=" + pkg.codePath);
9623                    Slog.w(TAG, "*************************************************");
9624                    throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE,
9625                            "Core android package being redefined.  Skipping.");
9626                }
9627            }
9628
9629            // A package name must be unique; don't allow duplicates
9630            if (mPackages.containsKey(pkg.packageName)) {
9631                throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE,
9632                        "Application package " + pkg.packageName
9633                        + " already installed.  Skipping duplicate.");
9634            }
9635
9636            if (pkg.applicationInfo.isStaticSharedLibrary()) {
9637                // Static libs have a synthetic package name containing the version
9638                // but we still want the base name to be unique.
9639                if (mPackages.containsKey(pkg.manifestPackageName)) {
9640                    throw new PackageManagerException(
9641                            "Duplicate static shared lib provider package");
9642                }
9643
9644                // Static shared libraries should have at least O target SDK
9645                if (pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.O) {
9646                    throw new PackageManagerException(
9647                            "Packages declaring static-shared libs must target O SDK or higher");
9648                }
9649
9650                // Package declaring static a shared lib cannot be instant apps
9651                if ((scanFlags & SCAN_AS_INSTANT_APP) != 0) {
9652                    throw new PackageManagerException(
9653                            "Packages declaring static-shared libs cannot be instant apps");
9654                }
9655
9656                // Package declaring static a shared lib cannot be renamed since the package
9657                // name is synthetic and apps can't code around package manager internals.
9658                if (!ArrayUtils.isEmpty(pkg.mOriginalPackages)) {
9659                    throw new PackageManagerException(
9660                            "Packages declaring static-shared libs cannot be renamed");
9661                }
9662
9663                // Package declaring static a shared lib cannot declare child packages
9664                if (!ArrayUtils.isEmpty(pkg.childPackages)) {
9665                    throw new PackageManagerException(
9666                            "Packages declaring static-shared libs cannot have child packages");
9667                }
9668
9669                // Package declaring static a shared lib cannot declare dynamic libs
9670                if (!ArrayUtils.isEmpty(pkg.libraryNames)) {
9671                    throw new PackageManagerException(
9672                            "Packages declaring static-shared libs cannot declare dynamic libs");
9673                }
9674
9675                // Package declaring static a shared lib cannot declare shared users
9676                if (pkg.mSharedUserId != null) {
9677                    throw new PackageManagerException(
9678                            "Packages declaring static-shared libs cannot declare shared users");
9679                }
9680
9681                // Static shared libs cannot declare activities
9682                if (!pkg.activities.isEmpty()) {
9683                    throw new PackageManagerException(
9684                            "Static shared libs cannot declare activities");
9685                }
9686
9687                // Static shared libs cannot declare services
9688                if (!pkg.services.isEmpty()) {
9689                    throw new PackageManagerException(
9690                            "Static shared libs cannot declare services");
9691                }
9692
9693                // Static shared libs cannot declare providers
9694                if (!pkg.providers.isEmpty()) {
9695                    throw new PackageManagerException(
9696                            "Static shared libs cannot declare content providers");
9697                }
9698
9699                // Static shared libs cannot declare receivers
9700                if (!pkg.receivers.isEmpty()) {
9701                    throw new PackageManagerException(
9702                            "Static shared libs cannot declare broadcast receivers");
9703                }
9704
9705                // Static shared libs cannot declare permission groups
9706                if (!pkg.permissionGroups.isEmpty()) {
9707                    throw new PackageManagerException(
9708                            "Static shared libs cannot declare permission groups");
9709                }
9710
9711                // Static shared libs cannot declare permissions
9712                if (!pkg.permissions.isEmpty()) {
9713                    throw new PackageManagerException(
9714                            "Static shared libs cannot declare permissions");
9715                }
9716
9717                // Static shared libs cannot declare protected broadcasts
9718                if (pkg.protectedBroadcasts != null) {
9719                    throw new PackageManagerException(
9720                            "Static shared libs cannot declare protected broadcasts");
9721                }
9722
9723                // Static shared libs cannot be overlay targets
9724                if (pkg.mOverlayTarget != null) {
9725                    throw new PackageManagerException(
9726                            "Static shared libs cannot be overlay targets");
9727                }
9728
9729                // The version codes must be ordered as lib versions
9730                int minVersionCode = Integer.MIN_VALUE;
9731                int maxVersionCode = Integer.MAX_VALUE;
9732
9733                SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(
9734                        pkg.staticSharedLibName);
9735                if (versionedLib != null) {
9736                    final int versionCount = versionedLib.size();
9737                    for (int i = 0; i < versionCount; i++) {
9738                        SharedLibraryInfo libInfo = versionedLib.valueAt(i).info;
9739                        // TODO: We will change version code to long, so in the new API it is long
9740                        final int libVersionCode = (int) libInfo.getDeclaringPackage()
9741                                .getVersionCode();
9742                        if (libInfo.getVersion() <  pkg.staticSharedLibVersion) {
9743                            minVersionCode = Math.max(minVersionCode, libVersionCode + 1);
9744                        } else if (libInfo.getVersion() >  pkg.staticSharedLibVersion) {
9745                            maxVersionCode = Math.min(maxVersionCode, libVersionCode - 1);
9746                        } else {
9747                            minVersionCode = maxVersionCode = libVersionCode;
9748                            break;
9749                        }
9750                    }
9751                }
9752                if (pkg.mVersionCode < minVersionCode || pkg.mVersionCode > maxVersionCode) {
9753                    throw new PackageManagerException("Static shared"
9754                            + " lib version codes must be ordered as lib versions");
9755                }
9756            }
9757
9758            // Only privileged apps and updated privileged apps can add child packages.
9759            if (pkg.childPackages != null && !pkg.childPackages.isEmpty()) {
9760                if ((policyFlags & PARSE_IS_PRIVILEGED) == 0) {
9761                    throw new PackageManagerException("Only privileged apps can add child "
9762                            + "packages. Ignoring package " + pkg.packageName);
9763                }
9764                final int childCount = pkg.childPackages.size();
9765                for (int i = 0; i < childCount; i++) {
9766                    PackageParser.Package childPkg = pkg.childPackages.get(i);
9767                    if (mSettings.hasOtherDisabledSystemPkgWithChildLPr(pkg.packageName,
9768                            childPkg.packageName)) {
9769                        throw new PackageManagerException("Can't override child of "
9770                                + "another disabled app. Ignoring package " + pkg.packageName);
9771                    }
9772                }
9773            }
9774
9775            // If we're only installing presumed-existing packages, require that the
9776            // scanned APK is both already known and at the path previously established
9777            // for it.  Previously unknown packages we pick up normally, but if we have an
9778            // a priori expectation about this package's install presence, enforce it.
9779            // With a singular exception for new system packages. When an OTA contains
9780            // a new system package, we allow the codepath to change from a system location
9781            // to the user-installed location. If we don't allow this change, any newer,
9782            // user-installed version of the application will be ignored.
9783            if ((scanFlags & SCAN_REQUIRE_KNOWN) != 0) {
9784                if (mExpectingBetter.containsKey(pkg.packageName)) {
9785                    logCriticalInfo(Log.WARN,
9786                            "Relax SCAN_REQUIRE_KNOWN requirement for package " + pkg.packageName);
9787                } else {
9788                    PackageSetting known = mSettings.getPackageLPr(pkg.packageName);
9789                    if (known != null) {
9790                        if (DEBUG_PACKAGE_SCANNING) {
9791                            Log.d(TAG, "Examining " + pkg.codePath
9792                                    + " and requiring known paths " + known.codePathString
9793                                    + " & " + known.resourcePathString);
9794                        }
9795                        if (!pkg.applicationInfo.getCodePath().equals(known.codePathString)
9796                                || !pkg.applicationInfo.getResourcePath().equals(
9797                                        known.resourcePathString)) {
9798                            throw new PackageManagerException(INSTALL_FAILED_PACKAGE_CHANGED,
9799                                    "Application package " + pkg.packageName
9800                                    + " found at " + pkg.applicationInfo.getCodePath()
9801                                    + " but expected at " + known.codePathString
9802                                    + "; ignoring.");
9803                        }
9804                    }
9805                }
9806            }
9807
9808            // Verify that this new package doesn't have any content providers
9809            // that conflict with existing packages.  Only do this if the
9810            // package isn't already installed, since we don't want to break
9811            // things that are installed.
9812            if ((scanFlags & SCAN_NEW_INSTALL) != 0) {
9813                final int N = pkg.providers.size();
9814                int i;
9815                for (i=0; i<N; i++) {
9816                    PackageParser.Provider p = pkg.providers.get(i);
9817                    if (p.info.authority != null) {
9818                        String names[] = p.info.authority.split(";");
9819                        for (int j = 0; j < names.length; j++) {
9820                            if (mProvidersByAuthority.containsKey(names[j])) {
9821                                PackageParser.Provider other = mProvidersByAuthority.get(names[j]);
9822                                final String otherPackageName =
9823                                        ((other != null && other.getComponentName() != null) ?
9824                                                other.getComponentName().getPackageName() : "?");
9825                                throw new PackageManagerException(
9826                                        INSTALL_FAILED_CONFLICTING_PROVIDER,
9827                                        "Can't install because provider name " + names[j]
9828                                                + " (in package " + pkg.applicationInfo.packageName
9829                                                + ") is already used by " + otherPackageName);
9830                            }
9831                        }
9832                    }
9833                }
9834            }
9835        }
9836    }
9837
9838    private boolean addSharedLibraryLPw(String path, String apk, String name, int version,
9839            int type, String declaringPackageName, int declaringVersionCode) {
9840        SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(name);
9841        if (versionedLib == null) {
9842            versionedLib = new SparseArray<>();
9843            mSharedLibraries.put(name, versionedLib);
9844            if (type == SharedLibraryInfo.TYPE_STATIC) {
9845                mStaticLibsByDeclaringPackage.put(declaringPackageName, versionedLib);
9846            }
9847        } else if (versionedLib.indexOfKey(version) >= 0) {
9848            return false;
9849        }
9850        SharedLibraryEntry libEntry = new SharedLibraryEntry(path, apk, name,
9851                version, type, declaringPackageName, declaringVersionCode);
9852        versionedLib.put(version, libEntry);
9853        return true;
9854    }
9855
9856    private boolean removeSharedLibraryLPw(String name, int version) {
9857        SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(name);
9858        if (versionedLib == null) {
9859            return false;
9860        }
9861        final int libIdx = versionedLib.indexOfKey(version);
9862        if (libIdx < 0) {
9863            return false;
9864        }
9865        SharedLibraryEntry libEntry = versionedLib.valueAt(libIdx);
9866        versionedLib.remove(version);
9867        if (versionedLib.size() <= 0) {
9868            mSharedLibraries.remove(name);
9869            if (libEntry.info.getType() == SharedLibraryInfo.TYPE_STATIC) {
9870                mStaticLibsByDeclaringPackage.remove(libEntry.info.getDeclaringPackage()
9871                        .getPackageName());
9872            }
9873        }
9874        return true;
9875    }
9876
9877    /**
9878     * Adds a scanned package to the system. When this method is finished, the package will
9879     * be available for query, resolution, etc...
9880     */
9881    private void commitPackageSettings(PackageParser.Package pkg, PackageSetting pkgSetting,
9882            UserHandle user, int scanFlags, boolean chatty) throws PackageManagerException {
9883        final String pkgName = pkg.packageName;
9884        if (mCustomResolverComponentName != null &&
9885                mCustomResolverComponentName.getPackageName().equals(pkg.packageName)) {
9886            setUpCustomResolverActivity(pkg);
9887        }
9888
9889        if (pkg.packageName.equals("android")) {
9890            synchronized (mPackages) {
9891                if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
9892                    // Set up information for our fall-back user intent resolution activity.
9893                    mPlatformPackage = pkg;
9894                    pkg.mVersionCode = mSdkVersion;
9895                    mAndroidApplication = pkg.applicationInfo;
9896                    if (!mResolverReplaced) {
9897                        mResolveActivity.applicationInfo = mAndroidApplication;
9898                        mResolveActivity.name = ResolverActivity.class.getName();
9899                        mResolveActivity.packageName = mAndroidApplication.packageName;
9900                        mResolveActivity.processName = "system:ui";
9901                        mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
9902                        mResolveActivity.documentLaunchMode = ActivityInfo.DOCUMENT_LAUNCH_NEVER;
9903                        mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS;
9904                        mResolveActivity.theme = R.style.Theme_Material_Dialog_Alert;
9905                        mResolveActivity.exported = true;
9906                        mResolveActivity.enabled = true;
9907                        mResolveActivity.resizeMode = ActivityInfo.RESIZE_MODE_RESIZEABLE;
9908                        mResolveActivity.configChanges = ActivityInfo.CONFIG_SCREEN_SIZE
9909                                | ActivityInfo.CONFIG_SMALLEST_SCREEN_SIZE
9910                                | ActivityInfo.CONFIG_SCREEN_LAYOUT
9911                                | ActivityInfo.CONFIG_ORIENTATION
9912                                | ActivityInfo.CONFIG_KEYBOARD
9913                                | ActivityInfo.CONFIG_KEYBOARD_HIDDEN;
9914                        mResolveInfo.activityInfo = mResolveActivity;
9915                        mResolveInfo.priority = 0;
9916                        mResolveInfo.preferredOrder = 0;
9917                        mResolveInfo.match = 0;
9918                        mResolveComponentName = new ComponentName(
9919                                mAndroidApplication.packageName, mResolveActivity.name);
9920                    }
9921                }
9922            }
9923        }
9924
9925        ArrayList<PackageParser.Package> clientLibPkgs = null;
9926        // writer
9927        synchronized (mPackages) {
9928            boolean hasStaticSharedLibs = false;
9929
9930            // Any app can add new static shared libraries
9931            if (pkg.staticSharedLibName != null) {
9932                // Static shared libs don't allow renaming as they have synthetic package
9933                // names to allow install of multiple versions, so use name from manifest.
9934                if (addSharedLibraryLPw(null, pkg.packageName, pkg.staticSharedLibName,
9935                        pkg.staticSharedLibVersion, SharedLibraryInfo.TYPE_STATIC,
9936                        pkg.manifestPackageName, pkg.mVersionCode)) {
9937                    hasStaticSharedLibs = true;
9938                } else {
9939                    Slog.w(TAG, "Package " + pkg.packageName + " library "
9940                                + pkg.staticSharedLibName + " already exists; skipping");
9941                }
9942                // Static shared libs cannot be updated once installed since they
9943                // use synthetic package name which includes the version code, so
9944                // not need to update other packages's shared lib dependencies.
9945            }
9946
9947            if (!hasStaticSharedLibs
9948                    && (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
9949                // Only system apps can add new dynamic shared libraries.
9950                if (pkg.libraryNames != null) {
9951                    for (int i = 0; i < pkg.libraryNames.size(); i++) {
9952                        String name = pkg.libraryNames.get(i);
9953                        boolean allowed = false;
9954                        if (pkg.isUpdatedSystemApp()) {
9955                            // New library entries can only be added through the
9956                            // system image.  This is important to get rid of a lot
9957                            // of nasty edge cases: for example if we allowed a non-
9958                            // system update of the app to add a library, then uninstalling
9959                            // the update would make the library go away, and assumptions
9960                            // we made such as through app install filtering would now
9961                            // have allowed apps on the device which aren't compatible
9962                            // with it.  Better to just have the restriction here, be
9963                            // conservative, and create many fewer cases that can negatively
9964                            // impact the user experience.
9965                            final PackageSetting sysPs = mSettings
9966                                    .getDisabledSystemPkgLPr(pkg.packageName);
9967                            if (sysPs.pkg != null && sysPs.pkg.libraryNames != null) {
9968                                for (int j = 0; j < sysPs.pkg.libraryNames.size(); j++) {
9969                                    if (name.equals(sysPs.pkg.libraryNames.get(j))) {
9970                                        allowed = true;
9971                                        break;
9972                                    }
9973                                }
9974                            }
9975                        } else {
9976                            allowed = true;
9977                        }
9978                        if (allowed) {
9979                            if (!addSharedLibraryLPw(null, pkg.packageName, name,
9980                                    SharedLibraryInfo.VERSION_UNDEFINED,
9981                                    SharedLibraryInfo.TYPE_DYNAMIC,
9982                                    pkg.packageName, pkg.mVersionCode)) {
9983                                Slog.w(TAG, "Package " + pkg.packageName + " library "
9984                                        + name + " already exists; skipping");
9985                            }
9986                        } else {
9987                            Slog.w(TAG, "Package " + pkg.packageName + " declares lib "
9988                                    + name + " that is not declared on system image; skipping");
9989                        }
9990                    }
9991
9992                    if ((scanFlags & SCAN_BOOTING) == 0) {
9993                        // If we are not booting, we need to update any applications
9994                        // that are clients of our shared library.  If we are booting,
9995                        // this will all be done once the scan is complete.
9996                        clientLibPkgs = updateAllSharedLibrariesLPw(pkg);
9997                    }
9998                }
9999            }
10000        }
10001
10002        if ((scanFlags & SCAN_BOOTING) != 0) {
10003            // No apps can run during boot scan, so they don't need to be frozen
10004        } else if ((scanFlags & SCAN_DONT_KILL_APP) != 0) {
10005            // Caller asked to not kill app, so it's probably not frozen
10006        } else if ((scanFlags & SCAN_IGNORE_FROZEN) != 0) {
10007            // Caller asked us to ignore frozen check for some reason; they
10008            // probably didn't know the package name
10009        } else {
10010            // We're doing major surgery on this package, so it better be frozen
10011            // right now to keep it from launching
10012            checkPackageFrozen(pkgName);
10013        }
10014
10015        // Also need to kill any apps that are dependent on the library.
10016        if (clientLibPkgs != null) {
10017            for (int i=0; i<clientLibPkgs.size(); i++) {
10018                PackageParser.Package clientPkg = clientLibPkgs.get(i);
10019                killApplication(clientPkg.applicationInfo.packageName,
10020                        clientPkg.applicationInfo.uid, "update lib");
10021            }
10022        }
10023
10024        // writer
10025        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings");
10026
10027        boolean createIdmapFailed = false;
10028        synchronized (mPackages) {
10029            // We don't expect installation to fail beyond this point
10030
10031            if (pkgSetting.pkg != null) {
10032                // Note that |user| might be null during the initial boot scan. If a codePath
10033                // for an app has changed during a boot scan, it's due to an app update that's
10034                // part of the system partition and marker changes must be applied to all users.
10035                final int userId = ((user != null) ? user : UserHandle.ALL).getIdentifier();
10036                final int[] userIds = resolveUserIds(userId);
10037                maybeRenameForeignDexMarkers(pkgSetting.pkg, pkg, userIds);
10038            }
10039
10040            // Add the new setting to mSettings
10041            mSettings.insertPackageSettingLPw(pkgSetting, pkg);
10042            // Add the new setting to mPackages
10043            mPackages.put(pkg.applicationInfo.packageName, pkg);
10044            // Make sure we don't accidentally delete its data.
10045            final Iterator<PackageCleanItem> iter = mSettings.mPackagesToBeCleaned.iterator();
10046            while (iter.hasNext()) {
10047                PackageCleanItem item = iter.next();
10048                if (pkgName.equals(item.packageName)) {
10049                    iter.remove();
10050                }
10051            }
10052
10053            // Add the package's KeySets to the global KeySetManagerService
10054            KeySetManagerService ksms = mSettings.mKeySetManagerService;
10055            ksms.addScannedPackageLPw(pkg);
10056
10057            int N = pkg.providers.size();
10058            StringBuilder r = null;
10059            int i;
10060            for (i=0; i<N; i++) {
10061                PackageParser.Provider p = pkg.providers.get(i);
10062                p.info.processName = fixProcessName(pkg.applicationInfo.processName,
10063                        p.info.processName);
10064                mProviders.addProvider(p);
10065                p.syncable = p.info.isSyncable;
10066                if (p.info.authority != null) {
10067                    String names[] = p.info.authority.split(";");
10068                    p.info.authority = null;
10069                    for (int j = 0; j < names.length; j++) {
10070                        if (j == 1 && p.syncable) {
10071                            // We only want the first authority for a provider to possibly be
10072                            // syncable, so if we already added this provider using a different
10073                            // authority clear the syncable flag. We copy the provider before
10074                            // changing it because the mProviders object contains a reference
10075                            // to a provider that we don't want to change.
10076                            // Only do this for the second authority since the resulting provider
10077                            // object can be the same for all future authorities for this provider.
10078                            p = new PackageParser.Provider(p);
10079                            p.syncable = false;
10080                        }
10081                        if (!mProvidersByAuthority.containsKey(names[j])) {
10082                            mProvidersByAuthority.put(names[j], p);
10083                            if (p.info.authority == null) {
10084                                p.info.authority = names[j];
10085                            } else {
10086                                p.info.authority = p.info.authority + ";" + names[j];
10087                            }
10088                            if (DEBUG_PACKAGE_SCANNING) {
10089                                if (chatty)
10090                                    Log.d(TAG, "Registered content provider: " + names[j]
10091                                            + ", className = " + p.info.name + ", isSyncable = "
10092                                            + p.info.isSyncable);
10093                            }
10094                        } else {
10095                            PackageParser.Provider other = mProvidersByAuthority.get(names[j]);
10096                            Slog.w(TAG, "Skipping provider name " + names[j] +
10097                                    " (in package " + pkg.applicationInfo.packageName +
10098                                    "): name already used by "
10099                                    + ((other != null && other.getComponentName() != null)
10100                                            ? other.getComponentName().getPackageName() : "?"));
10101                        }
10102                    }
10103                }
10104                if (chatty) {
10105                    if (r == null) {
10106                        r = new StringBuilder(256);
10107                    } else {
10108                        r.append(' ');
10109                    }
10110                    r.append(p.info.name);
10111                }
10112            }
10113            if (r != null) {
10114                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Providers: " + r);
10115            }
10116
10117            N = pkg.services.size();
10118            r = null;
10119            for (i=0; i<N; i++) {
10120                PackageParser.Service s = pkg.services.get(i);
10121                s.info.processName = fixProcessName(pkg.applicationInfo.processName,
10122                        s.info.processName);
10123                mServices.addService(s);
10124                if (chatty) {
10125                    if (r == null) {
10126                        r = new StringBuilder(256);
10127                    } else {
10128                        r.append(' ');
10129                    }
10130                    r.append(s.info.name);
10131                }
10132            }
10133            if (r != null) {
10134                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Services: " + r);
10135            }
10136
10137            N = pkg.receivers.size();
10138            r = null;
10139            for (i=0; i<N; i++) {
10140                PackageParser.Activity a = pkg.receivers.get(i);
10141                a.info.processName = fixProcessName(pkg.applicationInfo.processName,
10142                        a.info.processName);
10143                mReceivers.addActivity(a, "receiver");
10144                if (chatty) {
10145                    if (r == null) {
10146                        r = new StringBuilder(256);
10147                    } else {
10148                        r.append(' ');
10149                    }
10150                    r.append(a.info.name);
10151                }
10152            }
10153            if (r != null) {
10154                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Receivers: " + r);
10155            }
10156
10157            N = pkg.activities.size();
10158            r = null;
10159            for (i=0; i<N; i++) {
10160                PackageParser.Activity a = pkg.activities.get(i);
10161                a.info.processName = fixProcessName(pkg.applicationInfo.processName,
10162                        a.info.processName);
10163                mActivities.addActivity(a, "activity");
10164                if (chatty) {
10165                    if (r == null) {
10166                        r = new StringBuilder(256);
10167                    } else {
10168                        r.append(' ');
10169                    }
10170                    r.append(a.info.name);
10171                }
10172            }
10173            if (r != null) {
10174                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Activities: " + r);
10175            }
10176
10177            N = pkg.permissionGroups.size();
10178            r = null;
10179            for (i=0; i<N; i++) {
10180                PackageParser.PermissionGroup pg = pkg.permissionGroups.get(i);
10181                PackageParser.PermissionGroup cur = mPermissionGroups.get(pg.info.name);
10182                final String curPackageName = cur == null ? null : cur.info.packageName;
10183                // Dont allow ephemeral apps to define new permission groups.
10184                if ((scanFlags & SCAN_AS_INSTANT_APP) != 0) {
10185                    Slog.w(TAG, "Permission group " + pg.info.name + " from package "
10186                            + pg.info.packageName
10187                            + " ignored: instant apps cannot define new permission groups.");
10188                    continue;
10189                }
10190                final boolean isPackageUpdate = pg.info.packageName.equals(curPackageName);
10191                if (cur == null || isPackageUpdate) {
10192                    mPermissionGroups.put(pg.info.name, pg);
10193                    if (chatty) {
10194                        if (r == null) {
10195                            r = new StringBuilder(256);
10196                        } else {
10197                            r.append(' ');
10198                        }
10199                        if (isPackageUpdate) {
10200                            r.append("UPD:");
10201                        }
10202                        r.append(pg.info.name);
10203                    }
10204                } else {
10205                    Slog.w(TAG, "Permission group " + pg.info.name + " from package "
10206                            + pg.info.packageName + " ignored: original from "
10207                            + cur.info.packageName);
10208                    if (chatty) {
10209                        if (r == null) {
10210                            r = new StringBuilder(256);
10211                        } else {
10212                            r.append(' ');
10213                        }
10214                        r.append("DUP:");
10215                        r.append(pg.info.name);
10216                    }
10217                }
10218            }
10219            if (r != null) {
10220                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Permission Groups: " + r);
10221            }
10222
10223            N = pkg.permissions.size();
10224            r = null;
10225            for (i=0; i<N; i++) {
10226                PackageParser.Permission p = pkg.permissions.get(i);
10227
10228                // Dont allow ephemeral apps to define new permissions.
10229                if ((scanFlags & SCAN_AS_INSTANT_APP) != 0) {
10230                    Slog.w(TAG, "Permission " + p.info.name + " from package "
10231                            + p.info.packageName
10232                            + " ignored: instant apps cannot define new permissions.");
10233                    continue;
10234                }
10235
10236                // Assume by default that we did not install this permission into the system.
10237                p.info.flags &= ~PermissionInfo.FLAG_INSTALLED;
10238
10239                // Now that permission groups have a special meaning, we ignore permission
10240                // groups for legacy apps to prevent unexpected behavior. In particular,
10241                // permissions for one app being granted to someone just becase they happen
10242                // to be in a group defined by another app (before this had no implications).
10243                if (pkg.applicationInfo.targetSdkVersion > Build.VERSION_CODES.LOLLIPOP_MR1) {
10244                    p.group = mPermissionGroups.get(p.info.group);
10245                    // Warn for a permission in an unknown group.
10246                    if (p.info.group != null && p.group == null) {
10247                        Slog.w(TAG, "Permission " + p.info.name + " from package "
10248                                + p.info.packageName + " in an unknown group " + p.info.group);
10249                    }
10250                }
10251
10252                ArrayMap<String, BasePermission> permissionMap =
10253                        p.tree ? mSettings.mPermissionTrees
10254                                : mSettings.mPermissions;
10255                BasePermission bp = permissionMap.get(p.info.name);
10256
10257                // Allow system apps to redefine non-system permissions
10258                if (bp != null && !Objects.equals(bp.sourcePackage, p.info.packageName)) {
10259                    final boolean currentOwnerIsSystem = (bp.perm != null
10260                            && isSystemApp(bp.perm.owner));
10261                    if (isSystemApp(p.owner)) {
10262                        if (bp.type == BasePermission.TYPE_BUILTIN && bp.perm == null) {
10263                            // It's a built-in permission and no owner, take ownership now
10264                            bp.packageSetting = pkgSetting;
10265                            bp.perm = p;
10266                            bp.uid = pkg.applicationInfo.uid;
10267                            bp.sourcePackage = p.info.packageName;
10268                            p.info.flags |= PermissionInfo.FLAG_INSTALLED;
10269                        } else if (!currentOwnerIsSystem) {
10270                            String msg = "New decl " + p.owner + " of permission  "
10271                                    + p.info.name + " is system; overriding " + bp.sourcePackage;
10272                            reportSettingsProblem(Log.WARN, msg);
10273                            bp = null;
10274                        }
10275                    }
10276                }
10277
10278                if (bp == null) {
10279                    bp = new BasePermission(p.info.name, p.info.packageName,
10280                            BasePermission.TYPE_NORMAL);
10281                    permissionMap.put(p.info.name, bp);
10282                }
10283
10284                if (bp.perm == null) {
10285                    if (bp.sourcePackage == null
10286                            || bp.sourcePackage.equals(p.info.packageName)) {
10287                        BasePermission tree = findPermissionTreeLP(p.info.name);
10288                        if (tree == null
10289                                || tree.sourcePackage.equals(p.info.packageName)) {
10290                            bp.packageSetting = pkgSetting;
10291                            bp.perm = p;
10292                            bp.uid = pkg.applicationInfo.uid;
10293                            bp.sourcePackage = p.info.packageName;
10294                            p.info.flags |= PermissionInfo.FLAG_INSTALLED;
10295                            if (chatty) {
10296                                if (r == null) {
10297                                    r = new StringBuilder(256);
10298                                } else {
10299                                    r.append(' ');
10300                                }
10301                                r.append(p.info.name);
10302                            }
10303                        } else {
10304                            Slog.w(TAG, "Permission " + p.info.name + " from package "
10305                                    + p.info.packageName + " ignored: base tree "
10306                                    + tree.name + " is from package "
10307                                    + tree.sourcePackage);
10308                        }
10309                    } else {
10310                        Slog.w(TAG, "Permission " + p.info.name + " from package "
10311                                + p.info.packageName + " ignored: original from "
10312                                + bp.sourcePackage);
10313                    }
10314                } else if (chatty) {
10315                    if (r == null) {
10316                        r = new StringBuilder(256);
10317                    } else {
10318                        r.append(' ');
10319                    }
10320                    r.append("DUP:");
10321                    r.append(p.info.name);
10322                }
10323                if (bp.perm == p) {
10324                    bp.protectionLevel = p.info.protectionLevel;
10325                }
10326            }
10327
10328            if (r != null) {
10329                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Permissions: " + r);
10330            }
10331
10332            N = pkg.instrumentation.size();
10333            r = null;
10334            for (i=0; i<N; i++) {
10335                PackageParser.Instrumentation a = pkg.instrumentation.get(i);
10336                a.info.packageName = pkg.applicationInfo.packageName;
10337                a.info.sourceDir = pkg.applicationInfo.sourceDir;
10338                a.info.publicSourceDir = pkg.applicationInfo.publicSourceDir;
10339                a.info.splitNames = pkg.splitNames;
10340                a.info.splitSourceDirs = pkg.applicationInfo.splitSourceDirs;
10341                a.info.splitPublicSourceDirs = pkg.applicationInfo.splitPublicSourceDirs;
10342                a.info.splitDependencies = pkg.applicationInfo.splitDependencies;
10343                a.info.dataDir = pkg.applicationInfo.dataDir;
10344                a.info.deviceProtectedDataDir = pkg.applicationInfo.deviceProtectedDataDir;
10345                a.info.credentialProtectedDataDir = pkg.applicationInfo.credentialProtectedDataDir;
10346                a.info.nativeLibraryDir = pkg.applicationInfo.nativeLibraryDir;
10347                a.info.secondaryNativeLibraryDir = pkg.applicationInfo.secondaryNativeLibraryDir;
10348                mInstrumentation.put(a.getComponentName(), a);
10349                if (chatty) {
10350                    if (r == null) {
10351                        r = new StringBuilder(256);
10352                    } else {
10353                        r.append(' ');
10354                    }
10355                    r.append(a.info.name);
10356                }
10357            }
10358            if (r != null) {
10359                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Instrumentation: " + r);
10360            }
10361
10362            if (pkg.protectedBroadcasts != null) {
10363                N = pkg.protectedBroadcasts.size();
10364                for (i=0; i<N; i++) {
10365                    mProtectedBroadcasts.add(pkg.protectedBroadcasts.get(i));
10366                }
10367            }
10368
10369            // Create idmap files for pairs of (packages, overlay packages).
10370            // Note: "android", ie framework-res.apk, is handled by native layers.
10371            if (pkg.mOverlayTarget != null) {
10372                // This is an overlay package.
10373                if (pkg.mOverlayTarget != null && !pkg.mOverlayTarget.equals("android")) {
10374                    if (!mOverlays.containsKey(pkg.mOverlayTarget)) {
10375                        mOverlays.put(pkg.mOverlayTarget,
10376                                new ArrayMap<String, PackageParser.Package>());
10377                    }
10378                    ArrayMap<String, PackageParser.Package> map = mOverlays.get(pkg.mOverlayTarget);
10379                    map.put(pkg.packageName, pkg);
10380                    PackageParser.Package orig = mPackages.get(pkg.mOverlayTarget);
10381                    if (orig != null && !createIdmapForPackagePairLI(orig, pkg)) {
10382                        createIdmapFailed = true;
10383                    }
10384                }
10385            } else if (mOverlays.containsKey(pkg.packageName) &&
10386                    !pkg.packageName.equals("android")) {
10387                // This is a regular package, with one or more known overlay packages.
10388                createIdmapsForPackageLI(pkg);
10389            }
10390        }
10391
10392        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
10393
10394        if (createIdmapFailed) {
10395            throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
10396                    "scanPackageLI failed to createIdmap");
10397        }
10398    }
10399
10400    private static void maybeRenameForeignDexMarkers(PackageParser.Package existing,
10401            PackageParser.Package update, int[] userIds) {
10402        if (existing.applicationInfo == null || update.applicationInfo == null) {
10403            // This isn't due to an app installation.
10404            return;
10405        }
10406
10407        final File oldCodePath = new File(existing.applicationInfo.getCodePath());
10408        final File newCodePath = new File(update.applicationInfo.getCodePath());
10409
10410        // The codePath hasn't changed, so there's nothing for us to do.
10411        if (Objects.equals(oldCodePath, newCodePath)) {
10412            return;
10413        }
10414
10415        File canonicalNewCodePath;
10416        try {
10417            canonicalNewCodePath = new File(PackageManagerServiceUtils.realpath(newCodePath));
10418        } catch (IOException e) {
10419            Slog.w(TAG, "Failed to get canonical path.", e);
10420            return;
10421        }
10422
10423        // This is a bit of a hack. The oldCodePath doesn't exist at this point (because
10424        // we've already renamed / deleted it) so we cannot call realpath on it. Here we assume
10425        // that the last component of the path (i.e, the name) doesn't need canonicalization
10426        // (i.e, that it isn't ".", ".." or a symbolic link). This is a valid assumption for now
10427        // but may change in the future. Hopefully this function won't exist at that point.
10428        final File canonicalOldCodePath = new File(canonicalNewCodePath.getParentFile(),
10429                oldCodePath.getName());
10430
10431        // Calculate the prefixes of the markers. These are just the paths with "/" replaced
10432        // with "@".
10433        String oldMarkerPrefix = canonicalOldCodePath.getAbsolutePath().replace('/', '@');
10434        if (!oldMarkerPrefix.endsWith("@")) {
10435            oldMarkerPrefix += "@";
10436        }
10437        String newMarkerPrefix = canonicalNewCodePath.getAbsolutePath().replace('/', '@');
10438        if (!newMarkerPrefix.endsWith("@")) {
10439            newMarkerPrefix += "@";
10440        }
10441
10442        List<String> updatedPaths = update.getAllCodePathsExcludingResourceOnly();
10443        List<String> markerSuffixes = new ArrayList<String>(updatedPaths.size());
10444        for (String updatedPath : updatedPaths) {
10445            String updatedPathName = new File(updatedPath).getName();
10446            markerSuffixes.add(updatedPathName.replace('/', '@'));
10447        }
10448
10449        for (int userId : userIds) {
10450            File profileDir = Environment.getDataProfilesDeForeignDexDirectory(userId);
10451
10452            for (String markerSuffix : markerSuffixes) {
10453                File oldForeignUseMark = new File(profileDir, oldMarkerPrefix + markerSuffix);
10454                File newForeignUseMark = new File(profileDir, newMarkerPrefix + markerSuffix);
10455                if (oldForeignUseMark.exists()) {
10456                    try {
10457                        Os.rename(oldForeignUseMark.getAbsolutePath(),
10458                                newForeignUseMark.getAbsolutePath());
10459                    } catch (ErrnoException e) {
10460                        Slog.w(TAG, "Failed to rename foreign use marker", e);
10461                        oldForeignUseMark.delete();
10462                    }
10463                }
10464            }
10465        }
10466    }
10467
10468    /**
10469     * Derive the ABI of a non-system package located at {@code scanFile}. This information
10470     * is derived purely on the basis of the contents of {@code scanFile} and
10471     * {@code cpuAbiOverride}.
10472     *
10473     * If {@code extractLibs} is true, native libraries are extracted from the app if required.
10474     */
10475    private static void derivePackageAbi(PackageParser.Package pkg, File scanFile,
10476                                 String cpuAbiOverride, boolean extractLibs,
10477                                 File appLib32InstallDir)
10478            throws PackageManagerException {
10479        // Give ourselves some initial paths; we'll come back for another
10480        // pass once we've determined ABI below.
10481        setNativeLibraryPaths(pkg, appLib32InstallDir);
10482
10483        // We would never need to extract libs for forward-locked and external packages,
10484        // since the container service will do it for us. We shouldn't attempt to
10485        // extract libs from system app when it was not updated.
10486        if (pkg.isForwardLocked() || pkg.applicationInfo.isExternalAsec() ||
10487                (isSystemApp(pkg) && !pkg.isUpdatedSystemApp())) {
10488            extractLibs = false;
10489        }
10490
10491        final String nativeLibraryRootStr = pkg.applicationInfo.nativeLibraryRootDir;
10492        final boolean useIsaSpecificSubdirs = pkg.applicationInfo.nativeLibraryRootRequiresIsa;
10493
10494        NativeLibraryHelper.Handle handle = null;
10495        try {
10496            handle = NativeLibraryHelper.Handle.create(pkg);
10497            // TODO(multiArch): This can be null for apps that didn't go through the
10498            // usual installation process. We can calculate it again, like we
10499            // do during install time.
10500            //
10501            // TODO(multiArch): Why do we need to rescan ASEC apps again ? It seems totally
10502            // unnecessary.
10503            final File nativeLibraryRoot = new File(nativeLibraryRootStr);
10504
10505            // Null out the abis so that they can be recalculated.
10506            pkg.applicationInfo.primaryCpuAbi = null;
10507            pkg.applicationInfo.secondaryCpuAbi = null;
10508            if (isMultiArch(pkg.applicationInfo)) {
10509                // Warn if we've set an abiOverride for multi-lib packages..
10510                // By definition, we need to copy both 32 and 64 bit libraries for
10511                // such packages.
10512                if (pkg.cpuAbiOverride != null
10513                        && !NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(pkg.cpuAbiOverride)) {
10514                    Slog.w(TAG, "Ignoring abiOverride for multi arch application.");
10515                }
10516
10517                int abi32 = PackageManager.NO_NATIVE_LIBRARIES;
10518                int abi64 = PackageManager.NO_NATIVE_LIBRARIES;
10519                if (Build.SUPPORTED_32_BIT_ABIS.length > 0) {
10520                    if (extractLibs) {
10521                        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyNativeBinaries");
10522                        abi32 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
10523                                nativeLibraryRoot, Build.SUPPORTED_32_BIT_ABIS,
10524                                useIsaSpecificSubdirs);
10525                    } else {
10526                        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "findSupportedAbi");
10527                        abi32 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_32_BIT_ABIS);
10528                    }
10529                    Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
10530                }
10531
10532                maybeThrowExceptionForMultiArchCopy(
10533                        "Error unpackaging 32 bit native libs for multiarch app.", abi32);
10534
10535                if (Build.SUPPORTED_64_BIT_ABIS.length > 0) {
10536                    if (extractLibs) {
10537                        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyNativeBinaries");
10538                        abi64 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
10539                                nativeLibraryRoot, Build.SUPPORTED_64_BIT_ABIS,
10540                                useIsaSpecificSubdirs);
10541                    } else {
10542                        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "findSupportedAbi");
10543                        abi64 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_64_BIT_ABIS);
10544                    }
10545                    Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
10546                }
10547
10548                maybeThrowExceptionForMultiArchCopy(
10549                        "Error unpackaging 64 bit native libs for multiarch app.", abi64);
10550
10551                if (abi64 >= 0) {
10552                    pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[abi64];
10553                }
10554
10555                if (abi32 >= 0) {
10556                    final String abi = Build.SUPPORTED_32_BIT_ABIS[abi32];
10557                    if (abi64 >= 0) {
10558                        if (pkg.use32bitAbi) {
10559                            pkg.applicationInfo.secondaryCpuAbi = pkg.applicationInfo.primaryCpuAbi;
10560                            pkg.applicationInfo.primaryCpuAbi = abi;
10561                        } else {
10562                            pkg.applicationInfo.secondaryCpuAbi = abi;
10563                        }
10564                    } else {
10565                        pkg.applicationInfo.primaryCpuAbi = abi;
10566                    }
10567                }
10568
10569            } else {
10570                String[] abiList = (cpuAbiOverride != null) ?
10571                        new String[] { cpuAbiOverride } : Build.SUPPORTED_ABIS;
10572
10573                // Enable gross and lame hacks for apps that are built with old
10574                // SDK tools. We must scan their APKs for renderscript bitcode and
10575                // not launch them if it's present. Don't bother checking on devices
10576                // that don't have 64 bit support.
10577                boolean needsRenderScriptOverride = false;
10578                if (Build.SUPPORTED_64_BIT_ABIS.length > 0 && cpuAbiOverride == null &&
10579                        NativeLibraryHelper.hasRenderscriptBitcode(handle)) {
10580                    abiList = Build.SUPPORTED_32_BIT_ABIS;
10581                    needsRenderScriptOverride = true;
10582                }
10583
10584                final int copyRet;
10585                if (extractLibs) {
10586                    Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyNativeBinaries");
10587                    copyRet = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
10588                            nativeLibraryRoot, abiList, useIsaSpecificSubdirs);
10589                } else {
10590                    Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "findSupportedAbi");
10591                    copyRet = NativeLibraryHelper.findSupportedAbi(handle, abiList);
10592                }
10593                Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
10594
10595                if (copyRet < 0 && copyRet != PackageManager.NO_NATIVE_LIBRARIES) {
10596                    throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR,
10597                            "Error unpackaging native libs for app, errorCode=" + copyRet);
10598                }
10599
10600                if (copyRet >= 0) {
10601                    pkg.applicationInfo.primaryCpuAbi = abiList[copyRet];
10602                } else if (copyRet == PackageManager.NO_NATIVE_LIBRARIES && cpuAbiOverride != null) {
10603                    pkg.applicationInfo.primaryCpuAbi = cpuAbiOverride;
10604                } else if (needsRenderScriptOverride) {
10605                    pkg.applicationInfo.primaryCpuAbi = abiList[0];
10606                }
10607            }
10608        } catch (IOException ioe) {
10609            Slog.e(TAG, "Unable to get canonical file " + ioe.toString());
10610        } finally {
10611            IoUtils.closeQuietly(handle);
10612        }
10613
10614        // Now that we've calculated the ABIs and determined if it's an internal app,
10615        // we will go ahead and populate the nativeLibraryPath.
10616        setNativeLibraryPaths(pkg, appLib32InstallDir);
10617    }
10618
10619    /**
10620     * Adjusts ABIs for a set of packages belonging to a shared user so that they all match.
10621     * i.e, so that all packages can be run inside a single process if required.
10622     *
10623     * Optionally, callers can pass in a parsed package via {@code newPackage} in which case
10624     * this function will either try and make the ABI for all packages in {@code packagesForUser}
10625     * match {@code scannedPackage} or will update the ABI of {@code scannedPackage} to match
10626     * the ABI selected for {@code packagesForUser}. This variant is used when installing or
10627     * updating a package that belongs to a shared user.
10628     *
10629     * NOTE: We currently only match for the primary CPU abi string. Matching the secondary
10630     * adds unnecessary complexity.
10631     */
10632    private void adjustCpuAbisForSharedUserLPw(Set<PackageSetting> packagesForUser,
10633            PackageParser.Package scannedPackage) {
10634        String requiredInstructionSet = null;
10635        if (scannedPackage != null && scannedPackage.applicationInfo.primaryCpuAbi != null) {
10636            requiredInstructionSet = VMRuntime.getInstructionSet(
10637                     scannedPackage.applicationInfo.primaryCpuAbi);
10638        }
10639
10640        PackageSetting requirer = null;
10641        for (PackageSetting ps : packagesForUser) {
10642            // If packagesForUser contains scannedPackage, we skip it. This will happen
10643            // when scannedPackage is an update of an existing package. Without this check,
10644            // we will never be able to change the ABI of any package belonging to a shared
10645            // user, even if it's compatible with other packages.
10646            if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) {
10647                if (ps.primaryCpuAbiString == null) {
10648                    continue;
10649                }
10650
10651                final String instructionSet = VMRuntime.getInstructionSet(ps.primaryCpuAbiString);
10652                if (requiredInstructionSet != null && !instructionSet.equals(requiredInstructionSet)) {
10653                    // We have a mismatch between instruction sets (say arm vs arm64) warn about
10654                    // this but there's not much we can do.
10655                    String errorMessage = "Instruction set mismatch, "
10656                            + ((requirer == null) ? "[caller]" : requirer)
10657                            + " requires " + requiredInstructionSet + " whereas " + ps
10658                            + " requires " + instructionSet;
10659                    Slog.w(TAG, errorMessage);
10660                }
10661
10662                if (requiredInstructionSet == null) {
10663                    requiredInstructionSet = instructionSet;
10664                    requirer = ps;
10665                }
10666            }
10667        }
10668
10669        if (requiredInstructionSet != null) {
10670            String adjustedAbi;
10671            if (requirer != null) {
10672                // requirer != null implies that either scannedPackage was null or that scannedPackage
10673                // did not require an ABI, in which case we have to adjust scannedPackage to match
10674                // the ABI of the set (which is the same as requirer's ABI)
10675                adjustedAbi = requirer.primaryCpuAbiString;
10676                if (scannedPackage != null) {
10677                    scannedPackage.applicationInfo.primaryCpuAbi = adjustedAbi;
10678                }
10679            } else {
10680                // requirer == null implies that we're updating all ABIs in the set to
10681                // match scannedPackage.
10682                adjustedAbi =  scannedPackage.applicationInfo.primaryCpuAbi;
10683            }
10684
10685            for (PackageSetting ps : packagesForUser) {
10686                if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) {
10687                    if (ps.primaryCpuAbiString != null) {
10688                        continue;
10689                    }
10690
10691                    ps.primaryCpuAbiString = adjustedAbi;
10692                    if (ps.pkg != null && ps.pkg.applicationInfo != null &&
10693                            !TextUtils.equals(adjustedAbi, ps.pkg.applicationInfo.primaryCpuAbi)) {
10694                        ps.pkg.applicationInfo.primaryCpuAbi = adjustedAbi;
10695                        Slog.i(TAG, "Adjusting ABI for " + ps.name + " to " + adjustedAbi
10696                                + " (requirer="
10697                                + (requirer == null ? "null" : requirer.pkg.packageName)
10698                                + ", scannedPackage="
10699                                + (scannedPackage != null ? scannedPackage.packageName : "null")
10700                                + ")");
10701                        try {
10702                            mInstaller.rmdex(ps.codePathString,
10703                                    getDexCodeInstructionSet(getPreferredInstructionSet()));
10704                        } catch (InstallerException ignored) {
10705                        }
10706                    }
10707                }
10708            }
10709        }
10710    }
10711
10712    private void setUpCustomResolverActivity(PackageParser.Package pkg) {
10713        synchronized (mPackages) {
10714            mResolverReplaced = true;
10715            // Set up information for custom user intent resolution activity.
10716            mResolveActivity.applicationInfo = pkg.applicationInfo;
10717            mResolveActivity.name = mCustomResolverComponentName.getClassName();
10718            mResolveActivity.packageName = pkg.applicationInfo.packageName;
10719            mResolveActivity.processName = pkg.applicationInfo.packageName;
10720            mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
10721            mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS |
10722                    ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS;
10723            mResolveActivity.theme = 0;
10724            mResolveActivity.exported = true;
10725            mResolveActivity.enabled = true;
10726            mResolveInfo.activityInfo = mResolveActivity;
10727            mResolveInfo.priority = 0;
10728            mResolveInfo.preferredOrder = 0;
10729            mResolveInfo.match = 0;
10730            mResolveComponentName = mCustomResolverComponentName;
10731            Slog.i(TAG, "Replacing default ResolverActivity with custom activity: " +
10732                    mResolveComponentName);
10733        }
10734    }
10735
10736    private void setUpInstantAppInstallerActivityLP(ComponentName installerComponent) {
10737        if (installerComponent == null) {
10738            if (DEBUG_EPHEMERAL) {
10739                Slog.d(TAG, "Clear ephemeral installer activity");
10740            }
10741            mInstantAppInstallerActivity.applicationInfo = null;
10742            return;
10743        }
10744
10745        if (DEBUG_EPHEMERAL) {
10746            Slog.d(TAG, "Set ephemeral installer activity: " + installerComponent);
10747        }
10748        final PackageParser.Package pkg = mPackages.get(installerComponent.getPackageName());
10749        // Set up information for ephemeral installer activity
10750        mInstantAppInstallerActivity.applicationInfo = pkg.applicationInfo;
10751        mInstantAppInstallerActivity.name = installerComponent.getClassName();
10752        mInstantAppInstallerActivity.packageName = pkg.applicationInfo.packageName;
10753        mInstantAppInstallerActivity.processName = pkg.applicationInfo.packageName;
10754        mInstantAppInstallerActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
10755        mInstantAppInstallerActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS
10756                | ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS;
10757        mInstantAppInstallerActivity.theme = 0;
10758        mInstantAppInstallerActivity.exported = true;
10759        mInstantAppInstallerActivity.enabled = true;
10760        mInstantAppInstallerInfo.activityInfo = mInstantAppInstallerActivity;
10761        mInstantAppInstallerInfo.priority = 0;
10762        mInstantAppInstallerInfo.preferredOrder = 1;
10763        mInstantAppInstallerInfo.isDefault = true;
10764        mInstantAppInstallerInfo.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART
10765                | IntentFilter.MATCH_ADJUSTMENT_NORMAL;
10766    }
10767
10768    private static String calculateBundledApkRoot(final String codePathString) {
10769        final File codePath = new File(codePathString);
10770        final File codeRoot;
10771        if (FileUtils.contains(Environment.getRootDirectory(), codePath)) {
10772            codeRoot = Environment.getRootDirectory();
10773        } else if (FileUtils.contains(Environment.getOemDirectory(), codePath)) {
10774            codeRoot = Environment.getOemDirectory();
10775        } else if (FileUtils.contains(Environment.getVendorDirectory(), codePath)) {
10776            codeRoot = Environment.getVendorDirectory();
10777        } else {
10778            // Unrecognized code path; take its top real segment as the apk root:
10779            // e.g. /something/app/blah.apk => /something
10780            try {
10781                File f = codePath.getCanonicalFile();
10782                File parent = f.getParentFile();    // non-null because codePath is a file
10783                File tmp;
10784                while ((tmp = parent.getParentFile()) != null) {
10785                    f = parent;
10786                    parent = tmp;
10787                }
10788                codeRoot = f;
10789                Slog.w(TAG, "Unrecognized code path "
10790                        + codePath + " - using " + codeRoot);
10791            } catch (IOException e) {
10792                // Can't canonicalize the code path -- shenanigans?
10793                Slog.w(TAG, "Can't canonicalize code path " + codePath);
10794                return Environment.getRootDirectory().getPath();
10795            }
10796        }
10797        return codeRoot.getPath();
10798    }
10799
10800    /**
10801     * Derive and set the location of native libraries for the given package,
10802     * which varies depending on where and how the package was installed.
10803     */
10804    private static void setNativeLibraryPaths(PackageParser.Package pkg, File appLib32InstallDir) {
10805        final ApplicationInfo info = pkg.applicationInfo;
10806        final String codePath = pkg.codePath;
10807        final File codeFile = new File(codePath);
10808        final boolean bundledApp = info.isSystemApp() && !info.isUpdatedSystemApp();
10809        final boolean asecApp = info.isForwardLocked() || info.isExternalAsec();
10810
10811        info.nativeLibraryRootDir = null;
10812        info.nativeLibraryRootRequiresIsa = false;
10813        info.nativeLibraryDir = null;
10814        info.secondaryNativeLibraryDir = null;
10815
10816        if (isApkFile(codeFile)) {
10817            // Monolithic install
10818            if (bundledApp) {
10819                // If "/system/lib64/apkname" exists, assume that is the per-package
10820                // native library directory to use; otherwise use "/system/lib/apkname".
10821                final String apkRoot = calculateBundledApkRoot(info.sourceDir);
10822                final boolean is64Bit = VMRuntime.is64BitInstructionSet(
10823                        getPrimaryInstructionSet(info));
10824
10825                // This is a bundled system app so choose the path based on the ABI.
10826                // if it's a 64 bit abi, use lib64 otherwise use lib32. Note that this
10827                // is just the default path.
10828                final String apkName = deriveCodePathName(codePath);
10829                final String libDir = is64Bit ? LIB64_DIR_NAME : LIB_DIR_NAME;
10830                info.nativeLibraryRootDir = Environment.buildPath(new File(apkRoot), libDir,
10831                        apkName).getAbsolutePath();
10832
10833                if (info.secondaryCpuAbi != null) {
10834                    final String secondaryLibDir = is64Bit ? LIB_DIR_NAME : LIB64_DIR_NAME;
10835                    info.secondaryNativeLibraryDir = Environment.buildPath(new File(apkRoot),
10836                            secondaryLibDir, apkName).getAbsolutePath();
10837                }
10838            } else if (asecApp) {
10839                info.nativeLibraryRootDir = new File(codeFile.getParentFile(), LIB_DIR_NAME)
10840                        .getAbsolutePath();
10841            } else {
10842                final String apkName = deriveCodePathName(codePath);
10843                info.nativeLibraryRootDir = new File(appLib32InstallDir, apkName)
10844                        .getAbsolutePath();
10845            }
10846
10847            info.nativeLibraryRootRequiresIsa = false;
10848            info.nativeLibraryDir = info.nativeLibraryRootDir;
10849        } else {
10850            // Cluster install
10851            info.nativeLibraryRootDir = new File(codeFile, LIB_DIR_NAME).getAbsolutePath();
10852            info.nativeLibraryRootRequiresIsa = true;
10853
10854            info.nativeLibraryDir = new File(info.nativeLibraryRootDir,
10855                    getPrimaryInstructionSet(info)).getAbsolutePath();
10856
10857            if (info.secondaryCpuAbi != null) {
10858                info.secondaryNativeLibraryDir = new File(info.nativeLibraryRootDir,
10859                        VMRuntime.getInstructionSet(info.secondaryCpuAbi)).getAbsolutePath();
10860            }
10861        }
10862    }
10863
10864    /**
10865     * Calculate the abis and roots for a bundled app. These can uniquely
10866     * be determined from the contents of the system partition, i.e whether
10867     * it contains 64 or 32 bit shared libraries etc. We do not validate any
10868     * of this information, and instead assume that the system was built
10869     * sensibly.
10870     */
10871    private static void setBundledAppAbisAndRoots(PackageParser.Package pkg,
10872                                           PackageSetting pkgSetting) {
10873        final String apkName = deriveCodePathName(pkg.applicationInfo.getCodePath());
10874
10875        // If "/system/lib64/apkname" exists, assume that is the per-package
10876        // native library directory to use; otherwise use "/system/lib/apkname".
10877        final String apkRoot = calculateBundledApkRoot(pkg.applicationInfo.sourceDir);
10878        setBundledAppAbi(pkg, apkRoot, apkName);
10879        // pkgSetting might be null during rescan following uninstall of updates
10880        // to a bundled app, so accommodate that possibility.  The settings in
10881        // that case will be established later from the parsed package.
10882        //
10883        // If the settings aren't null, sync them up with what we've just derived.
10884        // note that apkRoot isn't stored in the package settings.
10885        if (pkgSetting != null) {
10886            pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi;
10887            pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi;
10888        }
10889    }
10890
10891    /**
10892     * Deduces the ABI of a bundled app and sets the relevant fields on the
10893     * parsed pkg object.
10894     *
10895     * @param apkRoot the root of the installed apk, something like {@code /system} or {@code /oem}
10896     *        under which system libraries are installed.
10897     * @param apkName the name of the installed package.
10898     */
10899    private static void setBundledAppAbi(PackageParser.Package pkg, String apkRoot, String apkName) {
10900        final File codeFile = new File(pkg.codePath);
10901
10902        final boolean has64BitLibs;
10903        final boolean has32BitLibs;
10904        if (isApkFile(codeFile)) {
10905            // Monolithic install
10906            has64BitLibs = (new File(apkRoot, new File(LIB64_DIR_NAME, apkName).getPath())).exists();
10907            has32BitLibs = (new File(apkRoot, new File(LIB_DIR_NAME, apkName).getPath())).exists();
10908        } else {
10909            // Cluster install
10910            final File rootDir = new File(codeFile, LIB_DIR_NAME);
10911            if (!ArrayUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS)
10912                    && !TextUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS[0])) {
10913                final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_64_BIT_ABIS[0]);
10914                has64BitLibs = (new File(rootDir, isa)).exists();
10915            } else {
10916                has64BitLibs = false;
10917            }
10918            if (!ArrayUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS)
10919                    && !TextUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS[0])) {
10920                final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_32_BIT_ABIS[0]);
10921                has32BitLibs = (new File(rootDir, isa)).exists();
10922            } else {
10923                has32BitLibs = false;
10924            }
10925        }
10926
10927        if (has64BitLibs && !has32BitLibs) {
10928            // The package has 64 bit libs, but not 32 bit libs. Its primary
10929            // ABI should be 64 bit. We can safely assume here that the bundled
10930            // native libraries correspond to the most preferred ABI in the list.
10931
10932            pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
10933            pkg.applicationInfo.secondaryCpuAbi = null;
10934        } else if (has32BitLibs && !has64BitLibs) {
10935            // The package has 32 bit libs but not 64 bit libs. Its primary
10936            // ABI should be 32 bit.
10937
10938            pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
10939            pkg.applicationInfo.secondaryCpuAbi = null;
10940        } else if (has32BitLibs && has64BitLibs) {
10941            // The application has both 64 and 32 bit bundled libraries. We check
10942            // here that the app declares multiArch support, and warn if it doesn't.
10943            //
10944            // We will be lenient here and record both ABIs. The primary will be the
10945            // ABI that's higher on the list, i.e, a device that's configured to prefer
10946            // 64 bit apps will see a 64 bit primary ABI,
10947
10948            if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_MULTIARCH) == 0) {
10949                Slog.e(TAG, "Package " + pkg + " has multiple bundled libs, but is not multiarch.");
10950            }
10951
10952            if (VMRuntime.is64BitInstructionSet(getPreferredInstructionSet())) {
10953                pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
10954                pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
10955            } else {
10956                pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
10957                pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
10958            }
10959        } else {
10960            pkg.applicationInfo.primaryCpuAbi = null;
10961            pkg.applicationInfo.secondaryCpuAbi = null;
10962        }
10963    }
10964
10965    private void killApplication(String pkgName, int appId, String reason) {
10966        killApplication(pkgName, appId, UserHandle.USER_ALL, reason);
10967    }
10968
10969    private void killApplication(String pkgName, int appId, int userId, String reason) {
10970        // Request the ActivityManager to kill the process(only for existing packages)
10971        // so that we do not end up in a confused state while the user is still using the older
10972        // version of the application while the new one gets installed.
10973        final long token = Binder.clearCallingIdentity();
10974        try {
10975            IActivityManager am = ActivityManager.getService();
10976            if (am != null) {
10977                try {
10978                    am.killApplication(pkgName, appId, userId, reason);
10979                } catch (RemoteException e) {
10980                }
10981            }
10982        } finally {
10983            Binder.restoreCallingIdentity(token);
10984        }
10985    }
10986
10987    private void removePackageLI(PackageParser.Package pkg, boolean chatty) {
10988        // Remove the parent package setting
10989        PackageSetting ps = (PackageSetting) pkg.mExtras;
10990        if (ps != null) {
10991            removePackageLI(ps, chatty);
10992        }
10993        // Remove the child package setting
10994        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
10995        for (int i = 0; i < childCount; i++) {
10996            PackageParser.Package childPkg = pkg.childPackages.get(i);
10997            ps = (PackageSetting) childPkg.mExtras;
10998            if (ps != null) {
10999                removePackageLI(ps, chatty);
11000            }
11001        }
11002    }
11003
11004    void removePackageLI(PackageSetting ps, boolean chatty) {
11005        if (DEBUG_INSTALL) {
11006            if (chatty)
11007                Log.d(TAG, "Removing package " + ps.name);
11008        }
11009
11010        // writer
11011        synchronized (mPackages) {
11012            mPackages.remove(ps.name);
11013            final PackageParser.Package pkg = ps.pkg;
11014            if (pkg != null) {
11015                cleanPackageDataStructuresLILPw(pkg, chatty);
11016            }
11017        }
11018    }
11019
11020    void removeInstalledPackageLI(PackageParser.Package pkg, boolean chatty) {
11021        if (DEBUG_INSTALL) {
11022            if (chatty)
11023                Log.d(TAG, "Removing package " + pkg.applicationInfo.packageName);
11024        }
11025
11026        // writer
11027        synchronized (mPackages) {
11028            // Remove the parent package
11029            mPackages.remove(pkg.applicationInfo.packageName);
11030            cleanPackageDataStructuresLILPw(pkg, chatty);
11031
11032            // Remove the child packages
11033            final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
11034            for (int i = 0; i < childCount; i++) {
11035                PackageParser.Package childPkg = pkg.childPackages.get(i);
11036                mPackages.remove(childPkg.applicationInfo.packageName);
11037                cleanPackageDataStructuresLILPw(childPkg, chatty);
11038            }
11039        }
11040    }
11041
11042    void cleanPackageDataStructuresLILPw(PackageParser.Package pkg, boolean chatty) {
11043        int N = pkg.providers.size();
11044        StringBuilder r = null;
11045        int i;
11046        for (i=0; i<N; i++) {
11047            PackageParser.Provider p = pkg.providers.get(i);
11048            mProviders.removeProvider(p);
11049            if (p.info.authority == null) {
11050
11051                /* There was another ContentProvider with this authority when
11052                 * this app was installed so this authority is null,
11053                 * Ignore it as we don't have to unregister the provider.
11054                 */
11055                continue;
11056            }
11057            String names[] = p.info.authority.split(";");
11058            for (int j = 0; j < names.length; j++) {
11059                if (mProvidersByAuthority.get(names[j]) == p) {
11060                    mProvidersByAuthority.remove(names[j]);
11061                    if (DEBUG_REMOVE) {
11062                        if (chatty)
11063                            Log.d(TAG, "Unregistered content provider: " + names[j]
11064                                    + ", className = " + p.info.name + ", isSyncable = "
11065                                    + p.info.isSyncable);
11066                    }
11067                }
11068            }
11069            if (DEBUG_REMOVE && chatty) {
11070                if (r == null) {
11071                    r = new StringBuilder(256);
11072                } else {
11073                    r.append(' ');
11074                }
11075                r.append(p.info.name);
11076            }
11077        }
11078        if (r != null) {
11079            if (DEBUG_REMOVE) Log.d(TAG, "  Providers: " + r);
11080        }
11081
11082        N = pkg.services.size();
11083        r = null;
11084        for (i=0; i<N; i++) {
11085            PackageParser.Service s = pkg.services.get(i);
11086            mServices.removeService(s);
11087            if (chatty) {
11088                if (r == null) {
11089                    r = new StringBuilder(256);
11090                } else {
11091                    r.append(' ');
11092                }
11093                r.append(s.info.name);
11094            }
11095        }
11096        if (r != null) {
11097            if (DEBUG_REMOVE) Log.d(TAG, "  Services: " + r);
11098        }
11099
11100        N = pkg.receivers.size();
11101        r = null;
11102        for (i=0; i<N; i++) {
11103            PackageParser.Activity a = pkg.receivers.get(i);
11104            mReceivers.removeActivity(a, "receiver");
11105            if (DEBUG_REMOVE && chatty) {
11106                if (r == null) {
11107                    r = new StringBuilder(256);
11108                } else {
11109                    r.append(' ');
11110                }
11111                r.append(a.info.name);
11112            }
11113        }
11114        if (r != null) {
11115            if (DEBUG_REMOVE) Log.d(TAG, "  Receivers: " + r);
11116        }
11117
11118        N = pkg.activities.size();
11119        r = null;
11120        for (i=0; i<N; i++) {
11121            PackageParser.Activity a = pkg.activities.get(i);
11122            mActivities.removeActivity(a, "activity");
11123            if (DEBUG_REMOVE && chatty) {
11124                if (r == null) {
11125                    r = new StringBuilder(256);
11126                } else {
11127                    r.append(' ');
11128                }
11129                r.append(a.info.name);
11130            }
11131        }
11132        if (r != null) {
11133            if (DEBUG_REMOVE) Log.d(TAG, "  Activities: " + r);
11134        }
11135
11136        N = pkg.permissions.size();
11137        r = null;
11138        for (i=0; i<N; i++) {
11139            PackageParser.Permission p = pkg.permissions.get(i);
11140            BasePermission bp = mSettings.mPermissions.get(p.info.name);
11141            if (bp == null) {
11142                bp = mSettings.mPermissionTrees.get(p.info.name);
11143            }
11144            if (bp != null && bp.perm == p) {
11145                bp.perm = null;
11146                if (DEBUG_REMOVE && chatty) {
11147                    if (r == null) {
11148                        r = new StringBuilder(256);
11149                    } else {
11150                        r.append(' ');
11151                    }
11152                    r.append(p.info.name);
11153                }
11154            }
11155            if ((p.info.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
11156                ArraySet<String> appOpPkgs = mAppOpPermissionPackages.get(p.info.name);
11157                if (appOpPkgs != null) {
11158                    appOpPkgs.remove(pkg.packageName);
11159                }
11160            }
11161        }
11162        if (r != null) {
11163            if (DEBUG_REMOVE) Log.d(TAG, "  Permissions: " + r);
11164        }
11165
11166        N = pkg.requestedPermissions.size();
11167        r = null;
11168        for (i=0; i<N; i++) {
11169            String perm = pkg.requestedPermissions.get(i);
11170            BasePermission bp = mSettings.mPermissions.get(perm);
11171            if (bp != null && (bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
11172                ArraySet<String> appOpPkgs = mAppOpPermissionPackages.get(perm);
11173                if (appOpPkgs != null) {
11174                    appOpPkgs.remove(pkg.packageName);
11175                    if (appOpPkgs.isEmpty()) {
11176                        mAppOpPermissionPackages.remove(perm);
11177                    }
11178                }
11179            }
11180        }
11181        if (r != null) {
11182            if (DEBUG_REMOVE) Log.d(TAG, "  Permissions: " + r);
11183        }
11184
11185        N = pkg.instrumentation.size();
11186        r = null;
11187        for (i=0; i<N; i++) {
11188            PackageParser.Instrumentation a = pkg.instrumentation.get(i);
11189            mInstrumentation.remove(a.getComponentName());
11190            if (DEBUG_REMOVE && chatty) {
11191                if (r == null) {
11192                    r = new StringBuilder(256);
11193                } else {
11194                    r.append(' ');
11195                }
11196                r.append(a.info.name);
11197            }
11198        }
11199        if (r != null) {
11200            if (DEBUG_REMOVE) Log.d(TAG, "  Instrumentation: " + r);
11201        }
11202
11203        r = null;
11204        if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) {
11205            // Only system apps can hold shared libraries.
11206            if (pkg.libraryNames != null) {
11207                for (i = 0; i < pkg.libraryNames.size(); i++) {
11208                    String name = pkg.libraryNames.get(i);
11209                    if (removeSharedLibraryLPw(name, 0)) {
11210                        if (DEBUG_REMOVE && chatty) {
11211                            if (r == null) {
11212                                r = new StringBuilder(256);
11213                            } else {
11214                                r.append(' ');
11215                            }
11216                            r.append(name);
11217                        }
11218                    }
11219                }
11220            }
11221        }
11222
11223        r = null;
11224
11225        // Any package can hold static shared libraries.
11226        if (pkg.staticSharedLibName != null) {
11227            if (removeSharedLibraryLPw(pkg.staticSharedLibName, pkg.staticSharedLibVersion)) {
11228                if (DEBUG_REMOVE && chatty) {
11229                    if (r == null) {
11230                        r = new StringBuilder(256);
11231                    } else {
11232                        r.append(' ');
11233                    }
11234                    r.append(pkg.staticSharedLibName);
11235                }
11236            }
11237        }
11238
11239        if (r != null) {
11240            if (DEBUG_REMOVE) Log.d(TAG, "  Libraries: " + r);
11241        }
11242    }
11243
11244    private static boolean hasPermission(PackageParser.Package pkgInfo, String perm) {
11245        for (int i=pkgInfo.permissions.size()-1; i>=0; i--) {
11246            if (pkgInfo.permissions.get(i).info.name.equals(perm)) {
11247                return true;
11248            }
11249        }
11250        return false;
11251    }
11252
11253    static final int UPDATE_PERMISSIONS_ALL = 1<<0;
11254    static final int UPDATE_PERMISSIONS_REPLACE_PKG = 1<<1;
11255    static final int UPDATE_PERMISSIONS_REPLACE_ALL = 1<<2;
11256
11257    private void updatePermissionsLPw(PackageParser.Package pkg, int flags) {
11258        // Update the parent permissions
11259        updatePermissionsLPw(pkg.packageName, pkg, flags);
11260        // Update the child permissions
11261        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
11262        for (int i = 0; i < childCount; i++) {
11263            PackageParser.Package childPkg = pkg.childPackages.get(i);
11264            updatePermissionsLPw(childPkg.packageName, childPkg, flags);
11265        }
11266    }
11267
11268    private void updatePermissionsLPw(String changingPkg, PackageParser.Package pkgInfo,
11269            int flags) {
11270        final String volumeUuid = (pkgInfo != null) ? getVolumeUuidForPackage(pkgInfo) : null;
11271        updatePermissionsLPw(changingPkg, pkgInfo, volumeUuid, flags);
11272    }
11273
11274    private void updatePermissionsLPw(String changingPkg,
11275            PackageParser.Package pkgInfo, String replaceVolumeUuid, int flags) {
11276        // Make sure there are no dangling permission trees.
11277        Iterator<BasePermission> it = mSettings.mPermissionTrees.values().iterator();
11278        while (it.hasNext()) {
11279            final BasePermission bp = it.next();
11280            if (bp.packageSetting == null) {
11281                // We may not yet have parsed the package, so just see if
11282                // we still know about its settings.
11283                bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage);
11284            }
11285            if (bp.packageSetting == null) {
11286                Slog.w(TAG, "Removing dangling permission tree: " + bp.name
11287                        + " from package " + bp.sourcePackage);
11288                it.remove();
11289            } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) {
11290                if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) {
11291                    Slog.i(TAG, "Removing old permission tree: " + bp.name
11292                            + " from package " + bp.sourcePackage);
11293                    flags |= UPDATE_PERMISSIONS_ALL;
11294                    it.remove();
11295                }
11296            }
11297        }
11298
11299        // Make sure all dynamic permissions have been assigned to a package,
11300        // and make sure there are no dangling permissions.
11301        it = mSettings.mPermissions.values().iterator();
11302        while (it.hasNext()) {
11303            final BasePermission bp = it.next();
11304            if (bp.type == BasePermission.TYPE_DYNAMIC) {
11305                if (DEBUG_SETTINGS) Log.v(TAG, "Dynamic permission: name="
11306                        + bp.name + " pkg=" + bp.sourcePackage
11307                        + " info=" + bp.pendingInfo);
11308                if (bp.packageSetting == null && bp.pendingInfo != null) {
11309                    final BasePermission tree = findPermissionTreeLP(bp.name);
11310                    if (tree != null && tree.perm != null) {
11311                        bp.packageSetting = tree.packageSetting;
11312                        bp.perm = new PackageParser.Permission(tree.perm.owner,
11313                                new PermissionInfo(bp.pendingInfo));
11314                        bp.perm.info.packageName = tree.perm.info.packageName;
11315                        bp.perm.info.name = bp.name;
11316                        bp.uid = tree.uid;
11317                    }
11318                }
11319            }
11320            if (bp.packageSetting == null) {
11321                // We may not yet have parsed the package, so just see if
11322                // we still know about its settings.
11323                bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage);
11324            }
11325            if (bp.packageSetting == null) {
11326                Slog.w(TAG, "Removing dangling permission: " + bp.name
11327                        + " from package " + bp.sourcePackage);
11328                it.remove();
11329            } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) {
11330                if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) {
11331                    Slog.i(TAG, "Removing old permission: " + bp.name
11332                            + " from package " + bp.sourcePackage);
11333                    flags |= UPDATE_PERMISSIONS_ALL;
11334                    it.remove();
11335                }
11336            }
11337        }
11338
11339        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "grantPermissions");
11340        // Now update the permissions for all packages, in particular
11341        // replace the granted permissions of the system packages.
11342        if ((flags&UPDATE_PERMISSIONS_ALL) != 0) {
11343            for (PackageParser.Package pkg : mPackages.values()) {
11344                if (pkg != pkgInfo) {
11345                    // Only replace for packages on requested volume
11346                    final String volumeUuid = getVolumeUuidForPackage(pkg);
11347                    final boolean replace = ((flags & UPDATE_PERMISSIONS_REPLACE_ALL) != 0)
11348                            && Objects.equals(replaceVolumeUuid, volumeUuid);
11349                    grantPermissionsLPw(pkg, replace, changingPkg);
11350                }
11351            }
11352        }
11353
11354        if (pkgInfo != null) {
11355            // Only replace for packages on requested volume
11356            final String volumeUuid = getVolumeUuidForPackage(pkgInfo);
11357            final boolean replace = ((flags & UPDATE_PERMISSIONS_REPLACE_PKG) != 0)
11358                    && Objects.equals(replaceVolumeUuid, volumeUuid);
11359            grantPermissionsLPw(pkgInfo, replace, changingPkg);
11360        }
11361        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
11362    }
11363
11364    private void grantPermissionsLPw(PackageParser.Package pkg, boolean replace,
11365            String packageOfInterest) {
11366        // IMPORTANT: There are two types of permissions: install and runtime.
11367        // Install time permissions are granted when the app is installed to
11368        // all device users and users added in the future. Runtime permissions
11369        // are granted at runtime explicitly to specific users. Normal and signature
11370        // protected permissions are install time permissions. Dangerous permissions
11371        // are install permissions if the app's target SDK is Lollipop MR1 or older,
11372        // otherwise they are runtime permissions. This function does not manage
11373        // runtime permissions except for the case an app targeting Lollipop MR1
11374        // being upgraded to target a newer SDK, in which case dangerous permissions
11375        // are transformed from install time to runtime ones.
11376
11377        final PackageSetting ps = (PackageSetting) pkg.mExtras;
11378        if (ps == null) {
11379            return;
11380        }
11381
11382        PermissionsState permissionsState = ps.getPermissionsState();
11383        PermissionsState origPermissions = permissionsState;
11384
11385        final int[] currentUserIds = UserManagerService.getInstance().getUserIds();
11386
11387        boolean runtimePermissionsRevoked = false;
11388        int[] changedRuntimePermissionUserIds = EMPTY_INT_ARRAY;
11389
11390        boolean changedInstallPermission = false;
11391
11392        if (replace) {
11393            ps.installPermissionsFixed = false;
11394            if (!ps.isSharedUser()) {
11395                origPermissions = new PermissionsState(permissionsState);
11396                permissionsState.reset();
11397            } else {
11398                // We need to know only about runtime permission changes since the
11399                // calling code always writes the install permissions state but
11400                // the runtime ones are written only if changed. The only cases of
11401                // changed runtime permissions here are promotion of an install to
11402                // runtime and revocation of a runtime from a shared user.
11403                changedRuntimePermissionUserIds = revokeUnusedSharedUserPermissionsLPw(
11404                        ps.sharedUser, UserManagerService.getInstance().getUserIds());
11405                if (!ArrayUtils.isEmpty(changedRuntimePermissionUserIds)) {
11406                    runtimePermissionsRevoked = true;
11407                }
11408            }
11409        }
11410
11411        permissionsState.setGlobalGids(mGlobalGids);
11412
11413        final int N = pkg.requestedPermissions.size();
11414        for (int i=0; i<N; i++) {
11415            final String name = pkg.requestedPermissions.get(i);
11416            final BasePermission bp = mSettings.mPermissions.get(name);
11417
11418            if (DEBUG_INSTALL) {
11419                Log.i(TAG, "Package " + pkg.packageName + " checking " + name + ": " + bp);
11420            }
11421
11422            if (bp == null || bp.packageSetting == null) {
11423                if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) {
11424                    Slog.w(TAG, "Unknown permission " + name
11425                            + " in package " + pkg.packageName);
11426                }
11427                continue;
11428            }
11429
11430
11431            // Limit ephemeral apps to ephemeral allowed permissions.
11432            if (pkg.applicationInfo.isInstantApp() && !bp.isInstant()) {
11433                Log.i(TAG, "Denying non-ephemeral permission " + bp.name + " for package "
11434                        + pkg.packageName);
11435                continue;
11436            }
11437
11438            final String perm = bp.name;
11439            boolean allowedSig = false;
11440            int grant = GRANT_DENIED;
11441
11442            // Keep track of app op permissions.
11443            if ((bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
11444                ArraySet<String> pkgs = mAppOpPermissionPackages.get(bp.name);
11445                if (pkgs == null) {
11446                    pkgs = new ArraySet<>();
11447                    mAppOpPermissionPackages.put(bp.name, pkgs);
11448                }
11449                pkgs.add(pkg.packageName);
11450            }
11451
11452            final int level = bp.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE;
11453            final boolean appSupportsRuntimePermissions = pkg.applicationInfo.targetSdkVersion
11454                    >= Build.VERSION_CODES.M;
11455            switch (level) {
11456                case PermissionInfo.PROTECTION_NORMAL: {
11457                    // For all apps normal permissions are install time ones.
11458                    grant = GRANT_INSTALL;
11459                } break;
11460
11461                case PermissionInfo.PROTECTION_DANGEROUS: {
11462                    // If a permission review is required for legacy apps we represent
11463                    // their permissions as always granted runtime ones since we need
11464                    // to keep the review required permission flag per user while an
11465                    // install permission's state is shared across all users.
11466                    if (!appSupportsRuntimePermissions && !mPermissionReviewRequired) {
11467                        // For legacy apps dangerous permissions are install time ones.
11468                        grant = GRANT_INSTALL;
11469                    } else if (origPermissions.hasInstallPermission(bp.name)) {
11470                        // For legacy apps that became modern, install becomes runtime.
11471                        grant = GRANT_UPGRADE;
11472                    } else if (mPromoteSystemApps
11473                            && isSystemApp(ps)
11474                            && mExistingSystemPackages.contains(ps.name)) {
11475                        // For legacy system apps, install becomes runtime.
11476                        // We cannot check hasInstallPermission() for system apps since those
11477                        // permissions were granted implicitly and not persisted pre-M.
11478                        grant = GRANT_UPGRADE;
11479                    } else {
11480                        // For modern apps keep runtime permissions unchanged.
11481                        grant = GRANT_RUNTIME;
11482                    }
11483                } break;
11484
11485                case PermissionInfo.PROTECTION_SIGNATURE: {
11486                    // For all apps signature permissions are install time ones.
11487                    allowedSig = grantSignaturePermission(perm, pkg, bp, origPermissions);
11488                    if (allowedSig) {
11489                        grant = GRANT_INSTALL;
11490                    }
11491                } break;
11492            }
11493
11494            if (DEBUG_INSTALL) {
11495                Log.i(TAG, "Package " + pkg.packageName + " granting " + perm);
11496            }
11497
11498            if (grant != GRANT_DENIED) {
11499                if (!isSystemApp(ps) && ps.installPermissionsFixed) {
11500                    // If this is an existing, non-system package, then
11501                    // we can't add any new permissions to it.
11502                    if (!allowedSig && !origPermissions.hasInstallPermission(perm)) {
11503                        // Except...  if this is a permission that was added
11504                        // to the platform (note: need to only do this when
11505                        // updating the platform).
11506                        if (!isNewPlatformPermissionForPackage(perm, pkg)) {
11507                            grant = GRANT_DENIED;
11508                        }
11509                    }
11510                }
11511
11512                switch (grant) {
11513                    case GRANT_INSTALL: {
11514                        // Revoke this as runtime permission to handle the case of
11515                        // a runtime permission being downgraded to an install one.
11516                        // Also in permission review mode we keep dangerous permissions
11517                        // for legacy apps
11518                        for (int userId : UserManagerService.getInstance().getUserIds()) {
11519                            if (origPermissions.getRuntimePermissionState(
11520                                    bp.name, userId) != null) {
11521                                // Revoke the runtime permission and clear the flags.
11522                                origPermissions.revokeRuntimePermission(bp, userId);
11523                                origPermissions.updatePermissionFlags(bp, userId,
11524                                      PackageManager.MASK_PERMISSION_FLAGS, 0);
11525                                // If we revoked a permission permission, we have to write.
11526                                changedRuntimePermissionUserIds = ArrayUtils.appendInt(
11527                                        changedRuntimePermissionUserIds, userId);
11528                            }
11529                        }
11530                        // Grant an install permission.
11531                        if (permissionsState.grantInstallPermission(bp) !=
11532                                PermissionsState.PERMISSION_OPERATION_FAILURE) {
11533                            changedInstallPermission = true;
11534                        }
11535                    } break;
11536
11537                    case GRANT_RUNTIME: {
11538                        // Grant previously granted runtime permissions.
11539                        for (int userId : UserManagerService.getInstance().getUserIds()) {
11540                            PermissionState permissionState = origPermissions
11541                                    .getRuntimePermissionState(bp.name, userId);
11542                            int flags = permissionState != null
11543                                    ? permissionState.getFlags() : 0;
11544                            if (origPermissions.hasRuntimePermission(bp.name, userId)) {
11545                                // Don't propagate the permission in a permission review mode if
11546                                // the former was revoked, i.e. marked to not propagate on upgrade.
11547                                // Note that in a permission review mode install permissions are
11548                                // represented as constantly granted runtime ones since we need to
11549                                // keep a per user state associated with the permission. Also the
11550                                // revoke on upgrade flag is no longer applicable and is reset.
11551                                final boolean revokeOnUpgrade = (flags & PackageManager
11552                                        .FLAG_PERMISSION_REVOKE_ON_UPGRADE) != 0;
11553                                if (revokeOnUpgrade) {
11554                                    flags &= ~PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE;
11555                                    // Since we changed the flags, we have to write.
11556                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
11557                                            changedRuntimePermissionUserIds, userId);
11558                                }
11559                                if (!mPermissionReviewRequired || !revokeOnUpgrade) {
11560                                    if (permissionsState.grantRuntimePermission(bp, userId) ==
11561                                            PermissionsState.PERMISSION_OPERATION_FAILURE) {
11562                                        // If we cannot put the permission as it was,
11563                                        // we have to write.
11564                                        changedRuntimePermissionUserIds = ArrayUtils.appendInt(
11565                                                changedRuntimePermissionUserIds, userId);
11566                                    }
11567                                }
11568
11569                                // If the app supports runtime permissions no need for a review.
11570                                if (mPermissionReviewRequired
11571                                        && appSupportsRuntimePermissions
11572                                        && (flags & PackageManager
11573                                                .FLAG_PERMISSION_REVIEW_REQUIRED) != 0) {
11574                                    flags &= ~PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED;
11575                                    // Since we changed the flags, we have to write.
11576                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
11577                                            changedRuntimePermissionUserIds, userId);
11578                                }
11579                            } else if (mPermissionReviewRequired
11580                                    && !appSupportsRuntimePermissions) {
11581                                // For legacy apps that need a permission review, every new
11582                                // runtime permission is granted but it is pending a review.
11583                                // We also need to review only platform defined runtime
11584                                // permissions as these are the only ones the platform knows
11585                                // how to disable the API to simulate revocation as legacy
11586                                // apps don't expect to run with revoked permissions.
11587                                if (PLATFORM_PACKAGE_NAME.equals(bp.sourcePackage)) {
11588                                    if ((flags & FLAG_PERMISSION_REVIEW_REQUIRED) == 0) {
11589                                        flags |= FLAG_PERMISSION_REVIEW_REQUIRED;
11590                                        // We changed the flags, hence have to write.
11591                                        changedRuntimePermissionUserIds = ArrayUtils.appendInt(
11592                                                changedRuntimePermissionUserIds, userId);
11593                                    }
11594                                }
11595                                if (permissionsState.grantRuntimePermission(bp, userId)
11596                                        != PermissionsState.PERMISSION_OPERATION_FAILURE) {
11597                                    // We changed the permission, hence have to write.
11598                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
11599                                            changedRuntimePermissionUserIds, userId);
11600                                }
11601                            }
11602                            // Propagate the permission flags.
11603                            permissionsState.updatePermissionFlags(bp, userId, flags, flags);
11604                        }
11605                    } break;
11606
11607                    case GRANT_UPGRADE: {
11608                        // Grant runtime permissions for a previously held install permission.
11609                        PermissionState permissionState = origPermissions
11610                                .getInstallPermissionState(bp.name);
11611                        final int flags = permissionState != null ? permissionState.getFlags() : 0;
11612
11613                        if (origPermissions.revokeInstallPermission(bp)
11614                                != PermissionsState.PERMISSION_OPERATION_FAILURE) {
11615                            // We will be transferring the permission flags, so clear them.
11616                            origPermissions.updatePermissionFlags(bp, UserHandle.USER_ALL,
11617                                    PackageManager.MASK_PERMISSION_FLAGS, 0);
11618                            changedInstallPermission = true;
11619                        }
11620
11621                        // If the permission is not to be promoted to runtime we ignore it and
11622                        // also its other flags as they are not applicable to install permissions.
11623                        if ((flags & PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE) == 0) {
11624                            for (int userId : currentUserIds) {
11625                                if (permissionsState.grantRuntimePermission(bp, userId) !=
11626                                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
11627                                    // Transfer the permission flags.
11628                                    permissionsState.updatePermissionFlags(bp, userId,
11629                                            flags, flags);
11630                                    // If we granted the permission, we have to write.
11631                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
11632                                            changedRuntimePermissionUserIds, userId);
11633                                }
11634                            }
11635                        }
11636                    } break;
11637
11638                    default: {
11639                        if (packageOfInterest == null
11640                                || packageOfInterest.equals(pkg.packageName)) {
11641                            Slog.w(TAG, "Not granting permission " + perm
11642                                    + " to package " + pkg.packageName
11643                                    + " because it was previously installed without");
11644                        }
11645                    } break;
11646                }
11647            } else {
11648                if (permissionsState.revokeInstallPermission(bp) !=
11649                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
11650                    // Also drop the permission flags.
11651                    permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL,
11652                            PackageManager.MASK_PERMISSION_FLAGS, 0);
11653                    changedInstallPermission = true;
11654                    Slog.i(TAG, "Un-granting permission " + perm
11655                            + " from package " + pkg.packageName
11656                            + " (protectionLevel=" + bp.protectionLevel
11657                            + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
11658                            + ")");
11659                } else if ((bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) == 0) {
11660                    // Don't print warning for app op permissions, since it is fine for them
11661                    // not to be granted, there is a UI for the user to decide.
11662                    if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) {
11663                        Slog.w(TAG, "Not granting permission " + perm
11664                                + " to package " + pkg.packageName
11665                                + " (protectionLevel=" + bp.protectionLevel
11666                                + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
11667                                + ")");
11668                    }
11669                }
11670            }
11671        }
11672
11673        if ((changedInstallPermission || replace) && !ps.installPermissionsFixed &&
11674                !isSystemApp(ps) || isUpdatedSystemApp(ps)){
11675            // This is the first that we have heard about this package, so the
11676            // permissions we have now selected are fixed until explicitly
11677            // changed.
11678            ps.installPermissionsFixed = true;
11679        }
11680
11681        // Persist the runtime permissions state for users with changes. If permissions
11682        // were revoked because no app in the shared user declares them we have to
11683        // write synchronously to avoid losing runtime permissions state.
11684        for (int userId : changedRuntimePermissionUserIds) {
11685            mSettings.writeRuntimePermissionsForUserLPr(userId, runtimePermissionsRevoked);
11686        }
11687    }
11688
11689    private boolean isNewPlatformPermissionForPackage(String perm, PackageParser.Package pkg) {
11690        boolean allowed = false;
11691        final int NP = PackageParser.NEW_PERMISSIONS.length;
11692        for (int ip=0; ip<NP; ip++) {
11693            final PackageParser.NewPermissionInfo npi
11694                    = PackageParser.NEW_PERMISSIONS[ip];
11695            if (npi.name.equals(perm)
11696                    && pkg.applicationInfo.targetSdkVersion < npi.sdkVersion) {
11697                allowed = true;
11698                Log.i(TAG, "Auto-granting " + perm + " to old pkg "
11699                        + pkg.packageName);
11700                break;
11701            }
11702        }
11703        return allowed;
11704    }
11705
11706    private boolean grantSignaturePermission(String perm, PackageParser.Package pkg,
11707            BasePermission bp, PermissionsState origPermissions) {
11708        boolean privilegedPermission = (bp.protectionLevel
11709                & PermissionInfo.PROTECTION_FLAG_PRIVILEGED) != 0;
11710        boolean privappPermissionsDisable =
11711                RoSystemProperties.CONTROL_PRIVAPP_PERMISSIONS_DISABLE;
11712        boolean platformPermission = PLATFORM_PACKAGE_NAME.equals(bp.sourcePackage);
11713        boolean platformPackage = PLATFORM_PACKAGE_NAME.equals(pkg.packageName);
11714        if (!privappPermissionsDisable && privilegedPermission && pkg.isPrivilegedApp()
11715                && !platformPackage && platformPermission) {
11716            ArraySet<String> wlPermissions = SystemConfig.getInstance()
11717                    .getPrivAppPermissions(pkg.packageName);
11718            boolean whitelisted = wlPermissions != null && wlPermissions.contains(perm);
11719            if (!whitelisted) {
11720                Slog.w(TAG, "Privileged permission " + perm + " for package "
11721                        + pkg.packageName + " - not in privapp-permissions whitelist");
11722                if (!mSystemReady) {
11723                    if (mPrivappPermissionsViolations == null) {
11724                        mPrivappPermissionsViolations = new ArraySet<>();
11725                    }
11726                    mPrivappPermissionsViolations.add(pkg.packageName + ": " + perm);
11727                }
11728                if (RoSystemProperties.CONTROL_PRIVAPP_PERMISSIONS_ENFORCE) {
11729                    return false;
11730                }
11731            }
11732        }
11733        boolean allowed = (compareSignatures(
11734                bp.packageSetting.signatures.mSignatures, pkg.mSignatures)
11735                        == PackageManager.SIGNATURE_MATCH)
11736                || (compareSignatures(mPlatformPackage.mSignatures, pkg.mSignatures)
11737                        == PackageManager.SIGNATURE_MATCH);
11738        if (!allowed && privilegedPermission) {
11739            if (isSystemApp(pkg)) {
11740                // For updated system applications, a system permission
11741                // is granted only if it had been defined by the original application.
11742                if (pkg.isUpdatedSystemApp()) {
11743                    final PackageSetting sysPs = mSettings
11744                            .getDisabledSystemPkgLPr(pkg.packageName);
11745                    if (sysPs != null && sysPs.getPermissionsState().hasInstallPermission(perm)) {
11746                        // If the original was granted this permission, we take
11747                        // that grant decision as read and propagate it to the
11748                        // update.
11749                        if (sysPs.isPrivileged()) {
11750                            allowed = true;
11751                        }
11752                    } else {
11753                        // The system apk may have been updated with an older
11754                        // version of the one on the data partition, but which
11755                        // granted a new system permission that it didn't have
11756                        // before.  In this case we do want to allow the app to
11757                        // now get the new permission if the ancestral apk is
11758                        // privileged to get it.
11759                        if (sysPs != null && sysPs.pkg != null && sysPs.isPrivileged()) {
11760                            for (int j = 0; j < sysPs.pkg.requestedPermissions.size(); j++) {
11761                                if (perm.equals(sysPs.pkg.requestedPermissions.get(j))) {
11762                                    allowed = true;
11763                                    break;
11764                                }
11765                            }
11766                        }
11767                        // Also if a privileged parent package on the system image or any of
11768                        // its children requested a privileged permission, the updated child
11769                        // packages can also get the permission.
11770                        if (pkg.parentPackage != null) {
11771                            final PackageSetting disabledSysParentPs = mSettings
11772                                    .getDisabledSystemPkgLPr(pkg.parentPackage.packageName);
11773                            if (disabledSysParentPs != null && disabledSysParentPs.pkg != null
11774                                    && disabledSysParentPs.isPrivileged()) {
11775                                if (isPackageRequestingPermission(disabledSysParentPs.pkg, perm)) {
11776                                    allowed = true;
11777                                } else if (disabledSysParentPs.pkg.childPackages != null) {
11778                                    final int count = disabledSysParentPs.pkg.childPackages.size();
11779                                    for (int i = 0; i < count; i++) {
11780                                        PackageParser.Package disabledSysChildPkg =
11781                                                disabledSysParentPs.pkg.childPackages.get(i);
11782                                        if (isPackageRequestingPermission(disabledSysChildPkg,
11783                                                perm)) {
11784                                            allowed = true;
11785                                            break;
11786                                        }
11787                                    }
11788                                }
11789                            }
11790                        }
11791                    }
11792                } else {
11793                    allowed = isPrivilegedApp(pkg);
11794                }
11795            }
11796        }
11797        if (!allowed) {
11798            if (!allowed && (bp.protectionLevel
11799                    & PermissionInfo.PROTECTION_FLAG_PRE23) != 0
11800                    && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) {
11801                // If this was a previously normal/dangerous permission that got moved
11802                // to a system permission as part of the runtime permission redesign, then
11803                // we still want to blindly grant it to old apps.
11804                allowed = true;
11805            }
11806            if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_INSTALLER) != 0
11807                    && pkg.packageName.equals(mRequiredInstallerPackage)) {
11808                // If this permission is to be granted to the system installer and
11809                // this app is an installer, then it gets the permission.
11810                allowed = true;
11811            }
11812            if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_VERIFIER) != 0
11813                    && pkg.packageName.equals(mRequiredVerifierPackage)) {
11814                // If this permission is to be granted to the system verifier and
11815                // this app is a verifier, then it gets the permission.
11816                allowed = true;
11817            }
11818            if (!allowed && (bp.protectionLevel
11819                    & PermissionInfo.PROTECTION_FLAG_PREINSTALLED) != 0
11820                    && isSystemApp(pkg)) {
11821                // Any pre-installed system app is allowed to get this permission.
11822                allowed = true;
11823            }
11824            if (!allowed && (bp.protectionLevel
11825                    & PermissionInfo.PROTECTION_FLAG_DEVELOPMENT) != 0) {
11826                // For development permissions, a development permission
11827                // is granted only if it was already granted.
11828                allowed = origPermissions.hasInstallPermission(perm);
11829            }
11830            if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_SETUP) != 0
11831                    && pkg.packageName.equals(mSetupWizardPackage)) {
11832                // If this permission is to be granted to the system setup wizard and
11833                // this app is a setup wizard, then it gets the permission.
11834                allowed = true;
11835            }
11836        }
11837        return allowed;
11838    }
11839
11840    private boolean isPackageRequestingPermission(PackageParser.Package pkg, String permission) {
11841        final int permCount = pkg.requestedPermissions.size();
11842        for (int j = 0; j < permCount; j++) {
11843            String requestedPermission = pkg.requestedPermissions.get(j);
11844            if (permission.equals(requestedPermission)) {
11845                return true;
11846            }
11847        }
11848        return false;
11849    }
11850
11851    final class ActivityIntentResolver
11852            extends IntentResolver<PackageParser.ActivityIntentInfo, ResolveInfo> {
11853        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
11854                boolean defaultOnly, int userId) {
11855            if (!sUserManager.exists(userId)) return null;
11856            mFlags = (defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0);
11857            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
11858        }
11859
11860        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
11861                int userId) {
11862            if (!sUserManager.exists(userId)) return null;
11863            mFlags = flags;
11864            return super.queryIntent(intent, resolvedType,
11865                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0,
11866                    userId);
11867        }
11868
11869        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
11870                int flags, ArrayList<PackageParser.Activity> packageActivities, int userId) {
11871            if (!sUserManager.exists(userId)) return null;
11872            if (packageActivities == null) {
11873                return null;
11874            }
11875            mFlags = flags;
11876            final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0;
11877            final int N = packageActivities.size();
11878            ArrayList<PackageParser.ActivityIntentInfo[]> listCut =
11879                new ArrayList<PackageParser.ActivityIntentInfo[]>(N);
11880
11881            ArrayList<PackageParser.ActivityIntentInfo> intentFilters;
11882            for (int i = 0; i < N; ++i) {
11883                intentFilters = packageActivities.get(i).intents;
11884                if (intentFilters != null && intentFilters.size() > 0) {
11885                    PackageParser.ActivityIntentInfo[] array =
11886                            new PackageParser.ActivityIntentInfo[intentFilters.size()];
11887                    intentFilters.toArray(array);
11888                    listCut.add(array);
11889                }
11890            }
11891            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
11892        }
11893
11894        /**
11895         * Finds a privileged activity that matches the specified activity names.
11896         */
11897        private PackageParser.Activity findMatchingActivity(
11898                List<PackageParser.Activity> activityList, ActivityInfo activityInfo) {
11899            for (PackageParser.Activity sysActivity : activityList) {
11900                if (sysActivity.info.name.equals(activityInfo.name)) {
11901                    return sysActivity;
11902                }
11903                if (sysActivity.info.name.equals(activityInfo.targetActivity)) {
11904                    return sysActivity;
11905                }
11906                if (sysActivity.info.targetActivity != null) {
11907                    if (sysActivity.info.targetActivity.equals(activityInfo.name)) {
11908                        return sysActivity;
11909                    }
11910                    if (sysActivity.info.targetActivity.equals(activityInfo.targetActivity)) {
11911                        return sysActivity;
11912                    }
11913                }
11914            }
11915            return null;
11916        }
11917
11918        public class IterGenerator<E> {
11919            public Iterator<E> generate(ActivityIntentInfo info) {
11920                return null;
11921            }
11922        }
11923
11924        public class ActionIterGenerator extends IterGenerator<String> {
11925            @Override
11926            public Iterator<String> generate(ActivityIntentInfo info) {
11927                return info.actionsIterator();
11928            }
11929        }
11930
11931        public class CategoriesIterGenerator extends IterGenerator<String> {
11932            @Override
11933            public Iterator<String> generate(ActivityIntentInfo info) {
11934                return info.categoriesIterator();
11935            }
11936        }
11937
11938        public class SchemesIterGenerator extends IterGenerator<String> {
11939            @Override
11940            public Iterator<String> generate(ActivityIntentInfo info) {
11941                return info.schemesIterator();
11942            }
11943        }
11944
11945        public class AuthoritiesIterGenerator extends IterGenerator<IntentFilter.AuthorityEntry> {
11946            @Override
11947            public Iterator<IntentFilter.AuthorityEntry> generate(ActivityIntentInfo info) {
11948                return info.authoritiesIterator();
11949            }
11950        }
11951
11952        /**
11953         * <em>WARNING</em> for performance reasons, the passed in intentList WILL BE
11954         * MODIFIED. Do not pass in a list that should not be changed.
11955         */
11956        private <T> void getIntentListSubset(List<ActivityIntentInfo> intentList,
11957                IterGenerator<T> generator, Iterator<T> searchIterator) {
11958            // loop through the set of actions; every one must be found in the intent filter
11959            while (searchIterator.hasNext()) {
11960                // we must have at least one filter in the list to consider a match
11961                if (intentList.size() == 0) {
11962                    break;
11963                }
11964
11965                final T searchAction = searchIterator.next();
11966
11967                // loop through the set of intent filters
11968                final Iterator<ActivityIntentInfo> intentIter = intentList.iterator();
11969                while (intentIter.hasNext()) {
11970                    final ActivityIntentInfo intentInfo = intentIter.next();
11971                    boolean selectionFound = false;
11972
11973                    // loop through the intent filter's selection criteria; at least one
11974                    // of them must match the searched criteria
11975                    final Iterator<T> intentSelectionIter = generator.generate(intentInfo);
11976                    while (intentSelectionIter != null && intentSelectionIter.hasNext()) {
11977                        final T intentSelection = intentSelectionIter.next();
11978                        if (intentSelection != null && intentSelection.equals(searchAction)) {
11979                            selectionFound = true;
11980                            break;
11981                        }
11982                    }
11983
11984                    // the selection criteria wasn't found in this filter's set; this filter
11985                    // is not a potential match
11986                    if (!selectionFound) {
11987                        intentIter.remove();
11988                    }
11989                }
11990            }
11991        }
11992
11993        private boolean isProtectedAction(ActivityIntentInfo filter) {
11994            final Iterator<String> actionsIter = filter.actionsIterator();
11995            while (actionsIter != null && actionsIter.hasNext()) {
11996                final String filterAction = actionsIter.next();
11997                if (PROTECTED_ACTIONS.contains(filterAction)) {
11998                    return true;
11999                }
12000            }
12001            return false;
12002        }
12003
12004        /**
12005         * Adjusts the priority of the given intent filter according to policy.
12006         * <p>
12007         * <ul>
12008         * <li>The priority for non privileged applications is capped to '0'</li>
12009         * <li>The priority for protected actions on privileged applications is capped to '0'</li>
12010         * <li>The priority for unbundled updates to privileged applications is capped to the
12011         *      priority defined on the system partition</li>
12012         * </ul>
12013         * <p>
12014         * <em>NOTE:</em> There is one exception. For security reasons, the setup wizard is
12015         * allowed to obtain any priority on any action.
12016         */
12017        private void adjustPriority(
12018                List<PackageParser.Activity> systemActivities, ActivityIntentInfo intent) {
12019            // nothing to do; priority is fine as-is
12020            if (intent.getPriority() <= 0) {
12021                return;
12022            }
12023
12024            final ActivityInfo activityInfo = intent.activity.info;
12025            final ApplicationInfo applicationInfo = activityInfo.applicationInfo;
12026
12027            final boolean privilegedApp =
12028                    ((applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0);
12029            if (!privilegedApp) {
12030                // non-privileged applications can never define a priority >0
12031                Slog.w(TAG, "Non-privileged app; cap priority to 0;"
12032                        + " package: " + applicationInfo.packageName
12033                        + " activity: " + intent.activity.className
12034                        + " origPrio: " + intent.getPriority());
12035                intent.setPriority(0);
12036                return;
12037            }
12038
12039            if (systemActivities == null) {
12040                // the system package is not disabled; we're parsing the system partition
12041                if (isProtectedAction(intent)) {
12042                    if (mDeferProtectedFilters) {
12043                        // We can't deal with these just yet. No component should ever obtain a
12044                        // >0 priority for a protected actions, with ONE exception -- the setup
12045                        // wizard. The setup wizard, however, cannot be known until we're able to
12046                        // query it for the category CATEGORY_SETUP_WIZARD. Which we can't do
12047                        // until all intent filters have been processed. Chicken, meet egg.
12048                        // Let the filter temporarily have a high priority and rectify the
12049                        // priorities after all system packages have been scanned.
12050                        mProtectedFilters.add(intent);
12051                        if (DEBUG_FILTERS) {
12052                            Slog.i(TAG, "Protected action; save for later;"
12053                                    + " package: " + applicationInfo.packageName
12054                                    + " activity: " + intent.activity.className
12055                                    + " origPrio: " + intent.getPriority());
12056                        }
12057                        return;
12058                    } else {
12059                        if (DEBUG_FILTERS && mSetupWizardPackage == null) {
12060                            Slog.i(TAG, "No setup wizard;"
12061                                + " All protected intents capped to priority 0");
12062                        }
12063                        if (intent.activity.info.packageName.equals(mSetupWizardPackage)) {
12064                            if (DEBUG_FILTERS) {
12065                                Slog.i(TAG, "Found setup wizard;"
12066                                    + " allow priority " + intent.getPriority() + ";"
12067                                    + " package: " + intent.activity.info.packageName
12068                                    + " activity: " + intent.activity.className
12069                                    + " priority: " + intent.getPriority());
12070                            }
12071                            // setup wizard gets whatever it wants
12072                            return;
12073                        }
12074                        Slog.w(TAG, "Protected action; cap priority to 0;"
12075                                + " package: " + intent.activity.info.packageName
12076                                + " activity: " + intent.activity.className
12077                                + " origPrio: " + intent.getPriority());
12078                        intent.setPriority(0);
12079                        return;
12080                    }
12081                }
12082                // privileged apps on the system image get whatever priority they request
12083                return;
12084            }
12085
12086            // privileged app unbundled update ... try to find the same activity
12087            final PackageParser.Activity foundActivity =
12088                    findMatchingActivity(systemActivities, activityInfo);
12089            if (foundActivity == null) {
12090                // this is a new activity; it cannot obtain >0 priority
12091                if (DEBUG_FILTERS) {
12092                    Slog.i(TAG, "New activity; cap priority to 0;"
12093                            + " package: " + applicationInfo.packageName
12094                            + " activity: " + intent.activity.className
12095                            + " origPrio: " + intent.getPriority());
12096                }
12097                intent.setPriority(0);
12098                return;
12099            }
12100
12101            // found activity, now check for filter equivalence
12102
12103            // a shallow copy is enough; we modify the list, not its contents
12104            final List<ActivityIntentInfo> intentListCopy =
12105                    new ArrayList<>(foundActivity.intents);
12106            final List<ActivityIntentInfo> foundFilters = findFilters(intent);
12107
12108            // find matching action subsets
12109            final Iterator<String> actionsIterator = intent.actionsIterator();
12110            if (actionsIterator != null) {
12111                getIntentListSubset(
12112                        intentListCopy, new ActionIterGenerator(), actionsIterator);
12113                if (intentListCopy.size() == 0) {
12114                    // no more intents to match; we're not equivalent
12115                    if (DEBUG_FILTERS) {
12116                        Slog.i(TAG, "Mismatched action; cap priority to 0;"
12117                                + " package: " + applicationInfo.packageName
12118                                + " activity: " + intent.activity.className
12119                                + " origPrio: " + intent.getPriority());
12120                    }
12121                    intent.setPriority(0);
12122                    return;
12123                }
12124            }
12125
12126            // find matching category subsets
12127            final Iterator<String> categoriesIterator = intent.categoriesIterator();
12128            if (categoriesIterator != null) {
12129                getIntentListSubset(intentListCopy, new CategoriesIterGenerator(),
12130                        categoriesIterator);
12131                if (intentListCopy.size() == 0) {
12132                    // no more intents to match; we're not equivalent
12133                    if (DEBUG_FILTERS) {
12134                        Slog.i(TAG, "Mismatched category; cap priority to 0;"
12135                                + " package: " + applicationInfo.packageName
12136                                + " activity: " + intent.activity.className
12137                                + " origPrio: " + intent.getPriority());
12138                    }
12139                    intent.setPriority(0);
12140                    return;
12141                }
12142            }
12143
12144            // find matching schemes subsets
12145            final Iterator<String> schemesIterator = intent.schemesIterator();
12146            if (schemesIterator != null) {
12147                getIntentListSubset(intentListCopy, new SchemesIterGenerator(),
12148                        schemesIterator);
12149                if (intentListCopy.size() == 0) {
12150                    // no more intents to match; we're not equivalent
12151                    if (DEBUG_FILTERS) {
12152                        Slog.i(TAG, "Mismatched scheme; cap priority to 0;"
12153                                + " package: " + applicationInfo.packageName
12154                                + " activity: " + intent.activity.className
12155                                + " origPrio: " + intent.getPriority());
12156                    }
12157                    intent.setPriority(0);
12158                    return;
12159                }
12160            }
12161
12162            // find matching authorities subsets
12163            final Iterator<IntentFilter.AuthorityEntry>
12164                    authoritiesIterator = intent.authoritiesIterator();
12165            if (authoritiesIterator != null) {
12166                getIntentListSubset(intentListCopy,
12167                        new AuthoritiesIterGenerator(),
12168                        authoritiesIterator);
12169                if (intentListCopy.size() == 0) {
12170                    // no more intents to match; we're not equivalent
12171                    if (DEBUG_FILTERS) {
12172                        Slog.i(TAG, "Mismatched authority; cap priority to 0;"
12173                                + " package: " + applicationInfo.packageName
12174                                + " activity: " + intent.activity.className
12175                                + " origPrio: " + intent.getPriority());
12176                    }
12177                    intent.setPriority(0);
12178                    return;
12179                }
12180            }
12181
12182            // we found matching filter(s); app gets the max priority of all intents
12183            int cappedPriority = 0;
12184            for (int i = intentListCopy.size() - 1; i >= 0; --i) {
12185                cappedPriority = Math.max(cappedPriority, intentListCopy.get(i).getPriority());
12186            }
12187            if (intent.getPriority() > cappedPriority) {
12188                if (DEBUG_FILTERS) {
12189                    Slog.i(TAG, "Found matching filter(s);"
12190                            + " cap priority to " + cappedPriority + ";"
12191                            + " package: " + applicationInfo.packageName
12192                            + " activity: " + intent.activity.className
12193                            + " origPrio: " + intent.getPriority());
12194                }
12195                intent.setPriority(cappedPriority);
12196                return;
12197            }
12198            // all this for nothing; the requested priority was <= what was on the system
12199        }
12200
12201        public final void addActivity(PackageParser.Activity a, String type) {
12202            mActivities.put(a.getComponentName(), a);
12203            if (DEBUG_SHOW_INFO)
12204                Log.v(
12205                TAG, "  " + type + " " +
12206                (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":");
12207            if (DEBUG_SHOW_INFO)
12208                Log.v(TAG, "    Class=" + a.info.name);
12209            final int NI = a.intents.size();
12210            for (int j=0; j<NI; j++) {
12211                PackageParser.ActivityIntentInfo intent = a.intents.get(j);
12212                if ("activity".equals(type)) {
12213                    final PackageSetting ps =
12214                            mSettings.getDisabledSystemPkgLPr(intent.activity.info.packageName);
12215                    final List<PackageParser.Activity> systemActivities =
12216                            ps != null && ps.pkg != null ? ps.pkg.activities : null;
12217                    adjustPriority(systemActivities, intent);
12218                }
12219                if (DEBUG_SHOW_INFO) {
12220                    Log.v(TAG, "    IntentFilter:");
12221                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
12222                }
12223                if (!intent.debugCheck()) {
12224                    Log.w(TAG, "==> For Activity " + a.info.name);
12225                }
12226                addFilter(intent);
12227            }
12228        }
12229
12230        public final void removeActivity(PackageParser.Activity a, String type) {
12231            mActivities.remove(a.getComponentName());
12232            if (DEBUG_SHOW_INFO) {
12233                Log.v(TAG, "  " + type + " "
12234                        + (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel
12235                                : a.info.name) + ":");
12236                Log.v(TAG, "    Class=" + a.info.name);
12237            }
12238            final int NI = a.intents.size();
12239            for (int j=0; j<NI; j++) {
12240                PackageParser.ActivityIntentInfo intent = a.intents.get(j);
12241                if (DEBUG_SHOW_INFO) {
12242                    Log.v(TAG, "    IntentFilter:");
12243                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
12244                }
12245                removeFilter(intent);
12246            }
12247        }
12248
12249        @Override
12250        protected boolean allowFilterResult(
12251                PackageParser.ActivityIntentInfo filter, List<ResolveInfo> dest) {
12252            ActivityInfo filterAi = filter.activity.info;
12253            for (int i=dest.size()-1; i>=0; i--) {
12254                ActivityInfo destAi = dest.get(i).activityInfo;
12255                if (destAi.name == filterAi.name
12256                        && destAi.packageName == filterAi.packageName) {
12257                    return false;
12258                }
12259            }
12260            return true;
12261        }
12262
12263        @Override
12264        protected ActivityIntentInfo[] newArray(int size) {
12265            return new ActivityIntentInfo[size];
12266        }
12267
12268        @Override
12269        protected boolean isFilterStopped(PackageParser.ActivityIntentInfo filter, int userId) {
12270            if (!sUserManager.exists(userId)) return true;
12271            PackageParser.Package p = filter.activity.owner;
12272            if (p != null) {
12273                PackageSetting ps = (PackageSetting)p.mExtras;
12274                if (ps != null) {
12275                    // System apps are never considered stopped for purposes of
12276                    // filtering, because there may be no way for the user to
12277                    // actually re-launch them.
12278                    return (ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0
12279                            && ps.getStopped(userId);
12280                }
12281            }
12282            return false;
12283        }
12284
12285        @Override
12286        protected boolean isPackageForFilter(String packageName,
12287                PackageParser.ActivityIntentInfo info) {
12288            return packageName.equals(info.activity.owner.packageName);
12289        }
12290
12291        @Override
12292        protected ResolveInfo newResult(PackageParser.ActivityIntentInfo info,
12293                int match, int userId) {
12294            if (!sUserManager.exists(userId)) return null;
12295            if (!mSettings.isEnabledAndMatchLPr(info.activity.info, mFlags, userId)) {
12296                return null;
12297            }
12298            final PackageParser.Activity activity = info.activity;
12299            PackageSetting ps = (PackageSetting) activity.owner.mExtras;
12300            if (ps == null) {
12301                return null;
12302            }
12303            final PackageUserState userState = ps.readUserState(userId);
12304            ActivityInfo ai = PackageParser.generateActivityInfo(activity, mFlags,
12305                    userState, userId);
12306            if (ai == null) {
12307                return null;
12308            }
12309            final boolean matchVisibleToInstantApp =
12310                    (mFlags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
12311            final boolean isInstantApp = (mFlags & PackageManager.MATCH_INSTANT) != 0;
12312            // throw out filters that aren't visible to ephemeral apps
12313            if (matchVisibleToInstantApp
12314                    && !(info.isVisibleToInstantApp() || userState.instantApp)) {
12315                return null;
12316            }
12317            // throw out ephemeral filters if we're not explicitly requesting them
12318            if (!isInstantApp && userState.instantApp) {
12319                return null;
12320            }
12321            final ResolveInfo res = new ResolveInfo();
12322            res.activityInfo = ai;
12323            if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
12324                res.filter = info;
12325            }
12326            if (info != null) {
12327                res.handleAllWebDataURI = info.handleAllWebDataURI();
12328            }
12329            res.priority = info.getPriority();
12330            res.preferredOrder = activity.owner.mPreferredOrder;
12331            //System.out.println("Result: " + res.activityInfo.className +
12332            //                   " = " + res.priority);
12333            res.match = match;
12334            res.isDefault = info.hasDefault;
12335            res.labelRes = info.labelRes;
12336            res.nonLocalizedLabel = info.nonLocalizedLabel;
12337            if (userNeedsBadging(userId)) {
12338                res.noResourceId = true;
12339            } else {
12340                res.icon = info.icon;
12341            }
12342            res.iconResourceId = info.icon;
12343            res.system = res.activityInfo.applicationInfo.isSystemApp();
12344            return res;
12345        }
12346
12347        @Override
12348        protected void sortResults(List<ResolveInfo> results) {
12349            Collections.sort(results, mResolvePrioritySorter);
12350        }
12351
12352        @Override
12353        protected void dumpFilter(PrintWriter out, String prefix,
12354                PackageParser.ActivityIntentInfo filter) {
12355            out.print(prefix); out.print(
12356                    Integer.toHexString(System.identityHashCode(filter.activity)));
12357                    out.print(' ');
12358                    filter.activity.printComponentShortName(out);
12359                    out.print(" filter ");
12360                    out.println(Integer.toHexString(System.identityHashCode(filter)));
12361        }
12362
12363        @Override
12364        protected Object filterToLabel(PackageParser.ActivityIntentInfo filter) {
12365            return filter.activity;
12366        }
12367
12368        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
12369            PackageParser.Activity activity = (PackageParser.Activity)label;
12370            out.print(prefix); out.print(
12371                    Integer.toHexString(System.identityHashCode(activity)));
12372                    out.print(' ');
12373                    activity.printComponentShortName(out);
12374            if (count > 1) {
12375                out.print(" ("); out.print(count); out.print(" filters)");
12376            }
12377            out.println();
12378        }
12379
12380        // Keys are String (activity class name), values are Activity.
12381        private final ArrayMap<ComponentName, PackageParser.Activity> mActivities
12382                = new ArrayMap<ComponentName, PackageParser.Activity>();
12383        private int mFlags;
12384    }
12385
12386    private final class ServiceIntentResolver
12387            extends IntentResolver<PackageParser.ServiceIntentInfo, ResolveInfo> {
12388        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
12389                boolean defaultOnly, int userId) {
12390            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
12391            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
12392        }
12393
12394        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
12395                int userId) {
12396            if (!sUserManager.exists(userId)) return null;
12397            mFlags = flags;
12398            return super.queryIntent(intent, resolvedType,
12399                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0,
12400                    userId);
12401        }
12402
12403        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
12404                int flags, ArrayList<PackageParser.Service> packageServices, int userId) {
12405            if (!sUserManager.exists(userId)) return null;
12406            if (packageServices == null) {
12407                return null;
12408            }
12409            mFlags = flags;
12410            final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0;
12411            final int N = packageServices.size();
12412            ArrayList<PackageParser.ServiceIntentInfo[]> listCut =
12413                new ArrayList<PackageParser.ServiceIntentInfo[]>(N);
12414
12415            ArrayList<PackageParser.ServiceIntentInfo> intentFilters;
12416            for (int i = 0; i < N; ++i) {
12417                intentFilters = packageServices.get(i).intents;
12418                if (intentFilters != null && intentFilters.size() > 0) {
12419                    PackageParser.ServiceIntentInfo[] array =
12420                            new PackageParser.ServiceIntentInfo[intentFilters.size()];
12421                    intentFilters.toArray(array);
12422                    listCut.add(array);
12423                }
12424            }
12425            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
12426        }
12427
12428        public final void addService(PackageParser.Service s) {
12429            mServices.put(s.getComponentName(), s);
12430            if (DEBUG_SHOW_INFO) {
12431                Log.v(TAG, "  "
12432                        + (s.info.nonLocalizedLabel != null
12433                        ? s.info.nonLocalizedLabel : s.info.name) + ":");
12434                Log.v(TAG, "    Class=" + s.info.name);
12435            }
12436            final int NI = s.intents.size();
12437            int j;
12438            for (j=0; j<NI; j++) {
12439                PackageParser.ServiceIntentInfo intent = s.intents.get(j);
12440                if (DEBUG_SHOW_INFO) {
12441                    Log.v(TAG, "    IntentFilter:");
12442                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
12443                }
12444                if (!intent.debugCheck()) {
12445                    Log.w(TAG, "==> For Service " + s.info.name);
12446                }
12447                addFilter(intent);
12448            }
12449        }
12450
12451        public final void removeService(PackageParser.Service s) {
12452            mServices.remove(s.getComponentName());
12453            if (DEBUG_SHOW_INFO) {
12454                Log.v(TAG, "  " + (s.info.nonLocalizedLabel != null
12455                        ? s.info.nonLocalizedLabel : s.info.name) + ":");
12456                Log.v(TAG, "    Class=" + s.info.name);
12457            }
12458            final int NI = s.intents.size();
12459            int j;
12460            for (j=0; j<NI; j++) {
12461                PackageParser.ServiceIntentInfo intent = s.intents.get(j);
12462                if (DEBUG_SHOW_INFO) {
12463                    Log.v(TAG, "    IntentFilter:");
12464                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
12465                }
12466                removeFilter(intent);
12467            }
12468        }
12469
12470        @Override
12471        protected boolean allowFilterResult(
12472                PackageParser.ServiceIntentInfo filter, List<ResolveInfo> dest) {
12473            ServiceInfo filterSi = filter.service.info;
12474            for (int i=dest.size()-1; i>=0; i--) {
12475                ServiceInfo destAi = dest.get(i).serviceInfo;
12476                if (destAi.name == filterSi.name
12477                        && destAi.packageName == filterSi.packageName) {
12478                    return false;
12479                }
12480            }
12481            return true;
12482        }
12483
12484        @Override
12485        protected PackageParser.ServiceIntentInfo[] newArray(int size) {
12486            return new PackageParser.ServiceIntentInfo[size];
12487        }
12488
12489        @Override
12490        protected boolean isFilterStopped(PackageParser.ServiceIntentInfo filter, int userId) {
12491            if (!sUserManager.exists(userId)) return true;
12492            PackageParser.Package p = filter.service.owner;
12493            if (p != null) {
12494                PackageSetting ps = (PackageSetting)p.mExtras;
12495                if (ps != null) {
12496                    // System apps are never considered stopped for purposes of
12497                    // filtering, because there may be no way for the user to
12498                    // actually re-launch them.
12499                    return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0
12500                            && ps.getStopped(userId);
12501                }
12502            }
12503            return false;
12504        }
12505
12506        @Override
12507        protected boolean isPackageForFilter(String packageName,
12508                PackageParser.ServiceIntentInfo info) {
12509            return packageName.equals(info.service.owner.packageName);
12510        }
12511
12512        @Override
12513        protected ResolveInfo newResult(PackageParser.ServiceIntentInfo filter,
12514                int match, int userId) {
12515            if (!sUserManager.exists(userId)) return null;
12516            final PackageParser.ServiceIntentInfo info = (PackageParser.ServiceIntentInfo)filter;
12517            if (!mSettings.isEnabledAndMatchLPr(info.service.info, mFlags, userId)) {
12518                return null;
12519            }
12520            final PackageParser.Service service = info.service;
12521            PackageSetting ps = (PackageSetting) service.owner.mExtras;
12522            if (ps == null) {
12523                return null;
12524            }
12525            ServiceInfo si = PackageParser.generateServiceInfo(service, mFlags,
12526                    ps.readUserState(userId), userId);
12527            if (si == null) {
12528                return null;
12529            }
12530            final ResolveInfo res = new ResolveInfo();
12531            res.serviceInfo = si;
12532            if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
12533                res.filter = filter;
12534            }
12535            res.priority = info.getPriority();
12536            res.preferredOrder = service.owner.mPreferredOrder;
12537            res.match = match;
12538            res.isDefault = info.hasDefault;
12539            res.labelRes = info.labelRes;
12540            res.nonLocalizedLabel = info.nonLocalizedLabel;
12541            res.icon = info.icon;
12542            res.system = res.serviceInfo.applicationInfo.isSystemApp();
12543            return res;
12544        }
12545
12546        @Override
12547        protected void sortResults(List<ResolveInfo> results) {
12548            Collections.sort(results, mResolvePrioritySorter);
12549        }
12550
12551        @Override
12552        protected void dumpFilter(PrintWriter out, String prefix,
12553                PackageParser.ServiceIntentInfo filter) {
12554            out.print(prefix); out.print(
12555                    Integer.toHexString(System.identityHashCode(filter.service)));
12556                    out.print(' ');
12557                    filter.service.printComponentShortName(out);
12558                    out.print(" filter ");
12559                    out.println(Integer.toHexString(System.identityHashCode(filter)));
12560        }
12561
12562        @Override
12563        protected Object filterToLabel(PackageParser.ServiceIntentInfo filter) {
12564            return filter.service;
12565        }
12566
12567        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
12568            PackageParser.Service service = (PackageParser.Service)label;
12569            out.print(prefix); out.print(
12570                    Integer.toHexString(System.identityHashCode(service)));
12571                    out.print(' ');
12572                    service.printComponentShortName(out);
12573            if (count > 1) {
12574                out.print(" ("); out.print(count); out.print(" filters)");
12575            }
12576            out.println();
12577        }
12578
12579//        List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) {
12580//            final Iterator<ResolveInfo> i = resolveInfoList.iterator();
12581//            final List<ResolveInfo> retList = Lists.newArrayList();
12582//            while (i.hasNext()) {
12583//                final ResolveInfo resolveInfo = (ResolveInfo) i;
12584//                if (isEnabledLP(resolveInfo.serviceInfo)) {
12585//                    retList.add(resolveInfo);
12586//                }
12587//            }
12588//            return retList;
12589//        }
12590
12591        // Keys are String (activity class name), values are Activity.
12592        private final ArrayMap<ComponentName, PackageParser.Service> mServices
12593                = new ArrayMap<ComponentName, PackageParser.Service>();
12594        private int mFlags;
12595    }
12596
12597    private final class ProviderIntentResolver
12598            extends IntentResolver<PackageParser.ProviderIntentInfo, ResolveInfo> {
12599        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
12600                boolean defaultOnly, int userId) {
12601            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
12602            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
12603        }
12604
12605        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
12606                int userId) {
12607            if (!sUserManager.exists(userId))
12608                return null;
12609            mFlags = flags;
12610            return super.queryIntent(intent, resolvedType,
12611                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0,
12612                    userId);
12613        }
12614
12615        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
12616                int flags, ArrayList<PackageParser.Provider> packageProviders, int userId) {
12617            if (!sUserManager.exists(userId))
12618                return null;
12619            if (packageProviders == null) {
12620                return null;
12621            }
12622            mFlags = flags;
12623            final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0;
12624            final int N = packageProviders.size();
12625            ArrayList<PackageParser.ProviderIntentInfo[]> listCut =
12626                    new ArrayList<PackageParser.ProviderIntentInfo[]>(N);
12627
12628            ArrayList<PackageParser.ProviderIntentInfo> intentFilters;
12629            for (int i = 0; i < N; ++i) {
12630                intentFilters = packageProviders.get(i).intents;
12631                if (intentFilters != null && intentFilters.size() > 0) {
12632                    PackageParser.ProviderIntentInfo[] array =
12633                            new PackageParser.ProviderIntentInfo[intentFilters.size()];
12634                    intentFilters.toArray(array);
12635                    listCut.add(array);
12636                }
12637            }
12638            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
12639        }
12640
12641        public final void addProvider(PackageParser.Provider p) {
12642            if (mProviders.containsKey(p.getComponentName())) {
12643                Slog.w(TAG, "Provider " + p.getComponentName() + " already defined; ignoring");
12644                return;
12645            }
12646
12647            mProviders.put(p.getComponentName(), p);
12648            if (DEBUG_SHOW_INFO) {
12649                Log.v(TAG, "  "
12650                        + (p.info.nonLocalizedLabel != null
12651                                ? p.info.nonLocalizedLabel : p.info.name) + ":");
12652                Log.v(TAG, "    Class=" + p.info.name);
12653            }
12654            final int NI = p.intents.size();
12655            int j;
12656            for (j = 0; j < NI; j++) {
12657                PackageParser.ProviderIntentInfo intent = p.intents.get(j);
12658                if (DEBUG_SHOW_INFO) {
12659                    Log.v(TAG, "    IntentFilter:");
12660                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
12661                }
12662                if (!intent.debugCheck()) {
12663                    Log.w(TAG, "==> For Provider " + p.info.name);
12664                }
12665                addFilter(intent);
12666            }
12667        }
12668
12669        public final void removeProvider(PackageParser.Provider p) {
12670            mProviders.remove(p.getComponentName());
12671            if (DEBUG_SHOW_INFO) {
12672                Log.v(TAG, "  " + (p.info.nonLocalizedLabel != null
12673                        ? p.info.nonLocalizedLabel : p.info.name) + ":");
12674                Log.v(TAG, "    Class=" + p.info.name);
12675            }
12676            final int NI = p.intents.size();
12677            int j;
12678            for (j = 0; j < NI; j++) {
12679                PackageParser.ProviderIntentInfo intent = p.intents.get(j);
12680                if (DEBUG_SHOW_INFO) {
12681                    Log.v(TAG, "    IntentFilter:");
12682                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
12683                }
12684                removeFilter(intent);
12685            }
12686        }
12687
12688        @Override
12689        protected boolean allowFilterResult(
12690                PackageParser.ProviderIntentInfo filter, List<ResolveInfo> dest) {
12691            ProviderInfo filterPi = filter.provider.info;
12692            for (int i = dest.size() - 1; i >= 0; i--) {
12693                ProviderInfo destPi = dest.get(i).providerInfo;
12694                if (destPi.name == filterPi.name
12695                        && destPi.packageName == filterPi.packageName) {
12696                    return false;
12697                }
12698            }
12699            return true;
12700        }
12701
12702        @Override
12703        protected PackageParser.ProviderIntentInfo[] newArray(int size) {
12704            return new PackageParser.ProviderIntentInfo[size];
12705        }
12706
12707        @Override
12708        protected boolean isFilterStopped(PackageParser.ProviderIntentInfo filter, int userId) {
12709            if (!sUserManager.exists(userId))
12710                return true;
12711            PackageParser.Package p = filter.provider.owner;
12712            if (p != null) {
12713                PackageSetting ps = (PackageSetting) p.mExtras;
12714                if (ps != null) {
12715                    // System apps are never considered stopped for purposes of
12716                    // filtering, because there may be no way for the user to
12717                    // actually re-launch them.
12718                    return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0
12719                            && ps.getStopped(userId);
12720                }
12721            }
12722            return false;
12723        }
12724
12725        @Override
12726        protected boolean isPackageForFilter(String packageName,
12727                PackageParser.ProviderIntentInfo info) {
12728            return packageName.equals(info.provider.owner.packageName);
12729        }
12730
12731        @Override
12732        protected ResolveInfo newResult(PackageParser.ProviderIntentInfo filter,
12733                int match, int userId) {
12734            if (!sUserManager.exists(userId))
12735                return null;
12736            final PackageParser.ProviderIntentInfo info = filter;
12737            if (!mSettings.isEnabledAndMatchLPr(info.provider.info, mFlags, userId)) {
12738                return null;
12739            }
12740            final PackageParser.Provider provider = info.provider;
12741            PackageSetting ps = (PackageSetting) provider.owner.mExtras;
12742            if (ps == null) {
12743                return null;
12744            }
12745            ProviderInfo pi = PackageParser.generateProviderInfo(provider, mFlags,
12746                    ps.readUserState(userId), userId);
12747            if (pi == null) {
12748                return null;
12749            }
12750            final ResolveInfo res = new ResolveInfo();
12751            res.providerInfo = pi;
12752            if ((mFlags & PackageManager.GET_RESOLVED_FILTER) != 0) {
12753                res.filter = filter;
12754            }
12755            res.priority = info.getPriority();
12756            res.preferredOrder = provider.owner.mPreferredOrder;
12757            res.match = match;
12758            res.isDefault = info.hasDefault;
12759            res.labelRes = info.labelRes;
12760            res.nonLocalizedLabel = info.nonLocalizedLabel;
12761            res.icon = info.icon;
12762            res.system = res.providerInfo.applicationInfo.isSystemApp();
12763            return res;
12764        }
12765
12766        @Override
12767        protected void sortResults(List<ResolveInfo> results) {
12768            Collections.sort(results, mResolvePrioritySorter);
12769        }
12770
12771        @Override
12772        protected void dumpFilter(PrintWriter out, String prefix,
12773                PackageParser.ProviderIntentInfo filter) {
12774            out.print(prefix);
12775            out.print(
12776                    Integer.toHexString(System.identityHashCode(filter.provider)));
12777            out.print(' ');
12778            filter.provider.printComponentShortName(out);
12779            out.print(" filter ");
12780            out.println(Integer.toHexString(System.identityHashCode(filter)));
12781        }
12782
12783        @Override
12784        protected Object filterToLabel(PackageParser.ProviderIntentInfo filter) {
12785            return filter.provider;
12786        }
12787
12788        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
12789            PackageParser.Provider provider = (PackageParser.Provider)label;
12790            out.print(prefix); out.print(
12791                    Integer.toHexString(System.identityHashCode(provider)));
12792                    out.print(' ');
12793                    provider.printComponentShortName(out);
12794            if (count > 1) {
12795                out.print(" ("); out.print(count); out.print(" filters)");
12796            }
12797            out.println();
12798        }
12799
12800        private final ArrayMap<ComponentName, PackageParser.Provider> mProviders
12801                = new ArrayMap<ComponentName, PackageParser.Provider>();
12802        private int mFlags;
12803    }
12804
12805    static final class EphemeralIntentResolver
12806            extends IntentResolver<AuxiliaryResolveInfo, AuxiliaryResolveInfo> {
12807        /**
12808         * The result that has the highest defined order. Ordering applies on a
12809         * per-package basis. Mapping is from package name to Pair of order and
12810         * EphemeralResolveInfo.
12811         * <p>
12812         * NOTE: This is implemented as a field variable for convenience and efficiency.
12813         * By having a field variable, we're able to track filter ordering as soon as
12814         * a non-zero order is defined. Otherwise, multiple loops across the result set
12815         * would be needed to apply ordering. If the intent resolver becomes re-entrant,
12816         * this needs to be contained entirely within {@link #filterResults()}.
12817         */
12818        final ArrayMap<String, Pair<Integer, EphemeralResolveInfo>> mOrderResult = new ArrayMap<>();
12819
12820        @Override
12821        protected AuxiliaryResolveInfo[] newArray(int size) {
12822            return new AuxiliaryResolveInfo[size];
12823        }
12824
12825        @Override
12826        protected boolean isPackageForFilter(String packageName, AuxiliaryResolveInfo responseObj) {
12827            return true;
12828        }
12829
12830        @Override
12831        protected AuxiliaryResolveInfo newResult(AuxiliaryResolveInfo responseObj, int match,
12832                int userId) {
12833            if (!sUserManager.exists(userId)) {
12834                return null;
12835            }
12836            final String packageName = responseObj.resolveInfo.getPackageName();
12837            final Integer order = responseObj.getOrder();
12838            final Pair<Integer, EphemeralResolveInfo> lastOrderResult =
12839                    mOrderResult.get(packageName);
12840            // ordering is enabled and this item's order isn't high enough
12841            if (lastOrderResult != null && lastOrderResult.first >= order) {
12842                return null;
12843            }
12844            final EphemeralResolveInfo res = responseObj.resolveInfo;
12845            if (order > 0) {
12846                // non-zero order, enable ordering
12847                mOrderResult.put(packageName, new Pair<>(order, res));
12848            }
12849            return responseObj;
12850        }
12851
12852        @Override
12853        protected void filterResults(List<AuxiliaryResolveInfo> results) {
12854            // only do work if ordering is enabled [most of the time it won't be]
12855            if (mOrderResult.size() == 0) {
12856                return;
12857            }
12858            int resultSize = results.size();
12859            for (int i = 0; i < resultSize; i++) {
12860                final EphemeralResolveInfo info = results.get(i).resolveInfo;
12861                final String packageName = info.getPackageName();
12862                final Pair<Integer, EphemeralResolveInfo> savedInfo = mOrderResult.get(packageName);
12863                if (savedInfo == null) {
12864                    // package doesn't having ordering
12865                    continue;
12866                }
12867                if (savedInfo.second == info) {
12868                    // circled back to the highest ordered item; remove from order list
12869                    mOrderResult.remove(savedInfo);
12870                    if (mOrderResult.size() == 0) {
12871                        // no more ordered items
12872                        break;
12873                    }
12874                    continue;
12875                }
12876                // item has a worse order, remove it from the result list
12877                results.remove(i);
12878                resultSize--;
12879                i--;
12880            }
12881        }
12882    }
12883
12884    private static final Comparator<ResolveInfo> mResolvePrioritySorter =
12885            new Comparator<ResolveInfo>() {
12886        public int compare(ResolveInfo r1, ResolveInfo r2) {
12887            int v1 = r1.priority;
12888            int v2 = r2.priority;
12889            //System.out.println("Comparing: q1=" + q1 + " q2=" + q2);
12890            if (v1 != v2) {
12891                return (v1 > v2) ? -1 : 1;
12892            }
12893            v1 = r1.preferredOrder;
12894            v2 = r2.preferredOrder;
12895            if (v1 != v2) {
12896                return (v1 > v2) ? -1 : 1;
12897            }
12898            if (r1.isDefault != r2.isDefault) {
12899                return r1.isDefault ? -1 : 1;
12900            }
12901            v1 = r1.match;
12902            v2 = r2.match;
12903            //System.out.println("Comparing: m1=" + m1 + " m2=" + m2);
12904            if (v1 != v2) {
12905                return (v1 > v2) ? -1 : 1;
12906            }
12907            if (r1.system != r2.system) {
12908                return r1.system ? -1 : 1;
12909            }
12910            if (r1.activityInfo != null) {
12911                return r1.activityInfo.packageName.compareTo(r2.activityInfo.packageName);
12912            }
12913            if (r1.serviceInfo != null) {
12914                return r1.serviceInfo.packageName.compareTo(r2.serviceInfo.packageName);
12915            }
12916            if (r1.providerInfo != null) {
12917                return r1.providerInfo.packageName.compareTo(r2.providerInfo.packageName);
12918            }
12919            return 0;
12920        }
12921    };
12922
12923    private static final Comparator<ProviderInfo> mProviderInitOrderSorter =
12924            new Comparator<ProviderInfo>() {
12925        public int compare(ProviderInfo p1, ProviderInfo p2) {
12926            final int v1 = p1.initOrder;
12927            final int v2 = p2.initOrder;
12928            return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0);
12929        }
12930    };
12931
12932    final void sendPackageBroadcast(final String action, final String pkg, final Bundle extras,
12933            final int flags, final String targetPkg, final IIntentReceiver finishedReceiver,
12934            final int[] userIds) {
12935        mHandler.post(new Runnable() {
12936            @Override
12937            public void run() {
12938                try {
12939                    final IActivityManager am = ActivityManager.getService();
12940                    if (am == null) return;
12941                    final int[] resolvedUserIds;
12942                    if (userIds == null) {
12943                        resolvedUserIds = am.getRunningUserIds();
12944                    } else {
12945                        resolvedUserIds = userIds;
12946                    }
12947                    for (int id : resolvedUserIds) {
12948                        final Intent intent = new Intent(action,
12949                                pkg != null ? Uri.fromParts(PACKAGE_SCHEME, pkg, null) : null);
12950                        if (extras != null) {
12951                            intent.putExtras(extras);
12952                        }
12953                        if (targetPkg != null) {
12954                            intent.setPackage(targetPkg);
12955                        }
12956                        // Modify the UID when posting to other users
12957                        int uid = intent.getIntExtra(Intent.EXTRA_UID, -1);
12958                        if (uid > 0 && UserHandle.getUserId(uid) != id) {
12959                            uid = UserHandle.getUid(id, UserHandle.getAppId(uid));
12960                            intent.putExtra(Intent.EXTRA_UID, uid);
12961                        }
12962                        intent.putExtra(Intent.EXTRA_USER_HANDLE, id);
12963                        intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT | flags);
12964                        if (DEBUG_BROADCASTS) {
12965                            RuntimeException here = new RuntimeException("here");
12966                            here.fillInStackTrace();
12967                            Slog.d(TAG, "Sending to user " + id + ": "
12968                                    + intent.toShortString(false, true, false, false)
12969                                    + " " + intent.getExtras(), here);
12970                        }
12971                        am.broadcastIntent(null, intent, null, finishedReceiver,
12972                                0, null, null, null, android.app.AppOpsManager.OP_NONE,
12973                                null, finishedReceiver != null, false, id);
12974                    }
12975                } catch (RemoteException ex) {
12976                }
12977            }
12978        });
12979    }
12980
12981    /**
12982     * Check if the external storage media is available. This is true if there
12983     * is a mounted external storage medium or if the external storage is
12984     * emulated.
12985     */
12986    private boolean isExternalMediaAvailable() {
12987        return mMediaMounted || Environment.isExternalStorageEmulated();
12988    }
12989
12990    @Override
12991    public PackageCleanItem nextPackageToClean(PackageCleanItem lastPackage) {
12992        // writer
12993        synchronized (mPackages) {
12994            if (!isExternalMediaAvailable()) {
12995                // If the external storage is no longer mounted at this point,
12996                // the caller may not have been able to delete all of this
12997                // packages files and can not delete any more.  Bail.
12998                return null;
12999            }
13000            final ArrayList<PackageCleanItem> pkgs = mSettings.mPackagesToBeCleaned;
13001            if (lastPackage != null) {
13002                pkgs.remove(lastPackage);
13003            }
13004            if (pkgs.size() > 0) {
13005                return pkgs.get(0);
13006            }
13007        }
13008        return null;
13009    }
13010
13011    void schedulePackageCleaning(String packageName, int userId, boolean andCode) {
13012        final Message msg = mHandler.obtainMessage(START_CLEANING_PACKAGE,
13013                userId, andCode ? 1 : 0, packageName);
13014        if (mSystemReady) {
13015            msg.sendToTarget();
13016        } else {
13017            if (mPostSystemReadyMessages == null) {
13018                mPostSystemReadyMessages = new ArrayList<>();
13019            }
13020            mPostSystemReadyMessages.add(msg);
13021        }
13022    }
13023
13024    void startCleaningPackages() {
13025        // reader
13026        if (!isExternalMediaAvailable()) {
13027            return;
13028        }
13029        synchronized (mPackages) {
13030            if (mSettings.mPackagesToBeCleaned.isEmpty()) {
13031                return;
13032            }
13033        }
13034        Intent intent = new Intent(PackageManager.ACTION_CLEAN_EXTERNAL_STORAGE);
13035        intent.setComponent(DEFAULT_CONTAINER_COMPONENT);
13036        IActivityManager am = ActivityManager.getService();
13037        if (am != null) {
13038            try {
13039                am.startService(null, intent, null, -1, null, mContext.getOpPackageName(),
13040                        UserHandle.USER_SYSTEM);
13041            } catch (RemoteException e) {
13042            }
13043        }
13044    }
13045
13046    @Override
13047    public void installPackageAsUser(String originPath, IPackageInstallObserver2 observer,
13048            int installFlags, String installerPackageName, int userId) {
13049        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, null);
13050
13051        final int callingUid = Binder.getCallingUid();
13052        enforceCrossUserPermission(callingUid, userId,
13053                true /* requireFullPermission */, true /* checkShell */, "installPackageAsUser");
13054
13055        if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) {
13056            try {
13057                if (observer != null) {
13058                    observer.onPackageInstalled("", INSTALL_FAILED_USER_RESTRICTED, null, null);
13059                }
13060            } catch (RemoteException re) {
13061            }
13062            return;
13063        }
13064
13065        if ((callingUid == Process.SHELL_UID) || (callingUid == Process.ROOT_UID)) {
13066            installFlags |= PackageManager.INSTALL_FROM_ADB;
13067
13068        } else {
13069            // Caller holds INSTALL_PACKAGES permission, so we're less strict
13070            // about installerPackageName.
13071
13072            installFlags &= ~PackageManager.INSTALL_FROM_ADB;
13073            installFlags &= ~PackageManager.INSTALL_ALL_USERS;
13074        }
13075
13076        UserHandle user;
13077        if ((installFlags & PackageManager.INSTALL_ALL_USERS) != 0) {
13078            user = UserHandle.ALL;
13079        } else {
13080            user = new UserHandle(userId);
13081        }
13082
13083        // Only system components can circumvent runtime permissions when installing.
13084        if ((installFlags & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0
13085                && mContext.checkCallingOrSelfPermission(Manifest.permission
13086                .INSTALL_GRANT_RUNTIME_PERMISSIONS) == PackageManager.PERMISSION_DENIED) {
13087            throw new SecurityException("You need the "
13088                    + "android.permission.INSTALL_GRANT_RUNTIME_PERMISSIONS permission "
13089                    + "to use the PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS flag");
13090        }
13091
13092        final File originFile = new File(originPath);
13093        final OriginInfo origin = OriginInfo.fromUntrustedFile(originFile);
13094
13095        final Message msg = mHandler.obtainMessage(INIT_COPY);
13096        final VerificationInfo verificationInfo = new VerificationInfo(
13097                null /*originatingUri*/, null /*referrer*/, -1 /*originatingUid*/, callingUid);
13098        final InstallParams params = new InstallParams(origin, null /*moveInfo*/, observer,
13099                installFlags, installerPackageName, null /*volumeUuid*/, verificationInfo, user,
13100                null /*packageAbiOverride*/, null /*grantedPermissions*/,
13101                null /*certificates*/, PackageManager.INSTALL_REASON_UNKNOWN);
13102        params.setTraceMethod("installAsUser").setTraceCookie(System.identityHashCode(params));
13103        msg.obj = params;
13104
13105        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "installAsUser",
13106                System.identityHashCode(msg.obj));
13107        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
13108                System.identityHashCode(msg.obj));
13109
13110        mHandler.sendMessage(msg);
13111    }
13112
13113
13114    /**
13115     * Ensure that the install reason matches what we know about the package installer (e.g. whether
13116     * it is acting on behalf on an enterprise or the user).
13117     *
13118     * Note that the ordering of the conditionals in this method is important. The checks we perform
13119     * are as follows, in this order:
13120     *
13121     * 1) If the install is being performed by a system app, we can trust the app to have set the
13122     *    install reason correctly. Thus, we pass through the install reason unchanged, no matter
13123     *    what it is.
13124     * 2) If the install is being performed by a device or profile owner app, the install reason
13125     *    should be enterprise policy. However, we cannot be sure that the device or profile owner
13126     *    set the install reason correctly. If the app targets an older SDK version where install
13127     *    reasons did not exist yet, or if the app author simply forgot, the install reason may be
13128     *    unset or wrong. Thus, we force the install reason to be enterprise policy.
13129     * 3) In all other cases, the install is being performed by a regular app that is neither part
13130     *    of the system nor a device or profile owner. We have no reason to believe that this app is
13131     *    acting on behalf of the enterprise admin. Thus, we check whether the install reason was
13132     *    set to enterprise policy and if so, change it to unknown instead.
13133     */
13134    private int fixUpInstallReason(String installerPackageName, int installerUid,
13135            int installReason) {
13136        if (checkUidPermission(android.Manifest.permission.INSTALL_PACKAGES, installerUid)
13137                == PERMISSION_GRANTED) {
13138            // If the install is being performed by a system app, we trust that app to have set the
13139            // install reason correctly.
13140            return installReason;
13141        }
13142
13143        final IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface(
13144            ServiceManager.getService(Context.DEVICE_POLICY_SERVICE));
13145        if (dpm != null) {
13146            ComponentName owner = null;
13147            try {
13148                owner = dpm.getDeviceOwnerComponent(true /* callingUserOnly */);
13149                if (owner == null) {
13150                    owner = dpm.getProfileOwner(UserHandle.getUserId(installerUid));
13151                }
13152            } catch (RemoteException e) {
13153            }
13154            if (owner != null && owner.getPackageName().equals(installerPackageName)) {
13155                // If the install is being performed by a device or profile owner, the install
13156                // reason should be enterprise policy.
13157                return PackageManager.INSTALL_REASON_POLICY;
13158            }
13159        }
13160
13161        if (installReason == PackageManager.INSTALL_REASON_POLICY) {
13162            // If the install is being performed by a regular app (i.e. neither system app nor
13163            // device or profile owner), we have no reason to believe that the app is acting on
13164            // behalf of an enterprise. If the app set the install reason to enterprise policy,
13165            // change it to unknown instead.
13166            return PackageManager.INSTALL_REASON_UNKNOWN;
13167        }
13168
13169        // If the install is being performed by a regular app and the install reason was set to any
13170        // value but enterprise policy, leave the install reason unchanged.
13171        return installReason;
13172    }
13173
13174    void installStage(String packageName, File stagedDir, String stagedCid,
13175            IPackageInstallObserver2 observer, PackageInstaller.SessionParams sessionParams,
13176            String installerPackageName, int installerUid, UserHandle user,
13177            Certificate[][] certificates) {
13178        if (DEBUG_EPHEMERAL) {
13179            if ((sessionParams.installFlags & PackageManager.INSTALL_INSTANT_APP) != 0) {
13180                Slog.d(TAG, "Ephemeral install of " + packageName);
13181            }
13182        }
13183        final VerificationInfo verificationInfo = new VerificationInfo(
13184                sessionParams.originatingUri, sessionParams.referrerUri,
13185                sessionParams.originatingUid, installerUid);
13186
13187        final OriginInfo origin;
13188        if (stagedDir != null) {
13189            origin = OriginInfo.fromStagedFile(stagedDir);
13190        } else {
13191            origin = OriginInfo.fromStagedContainer(stagedCid);
13192        }
13193
13194        final Message msg = mHandler.obtainMessage(INIT_COPY);
13195        final int installReason = fixUpInstallReason(installerPackageName, installerUid,
13196                sessionParams.installReason);
13197        final InstallParams params = new InstallParams(origin, null, observer,
13198                sessionParams.installFlags, installerPackageName, sessionParams.volumeUuid,
13199                verificationInfo, user, sessionParams.abiOverride,
13200                sessionParams.grantedRuntimePermissions, certificates, installReason);
13201        params.setTraceMethod("installStage").setTraceCookie(System.identityHashCode(params));
13202        msg.obj = params;
13203
13204        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "installStage",
13205                System.identityHashCode(msg.obj));
13206        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
13207                System.identityHashCode(msg.obj));
13208
13209        mHandler.sendMessage(msg);
13210    }
13211
13212    private void sendPackageAddedForUser(String packageName, PackageSetting pkgSetting,
13213            int userId) {
13214        final boolean isSystem = isSystemApp(pkgSetting) || isUpdatedSystemApp(pkgSetting);
13215        sendPackageAddedForNewUsers(packageName, isSystem, pkgSetting.appId, userId);
13216    }
13217
13218    private void sendPackageAddedForNewUsers(String packageName, boolean isSystem,
13219            int appId, int... userIds) {
13220        if (ArrayUtils.isEmpty(userIds)) {
13221            return;
13222        }
13223        Bundle extras = new Bundle(1);
13224        // Set to UID of the first user, EXTRA_UID is automatically updated in sendPackageBroadcast
13225        extras.putInt(Intent.EXTRA_UID, UserHandle.getUid(userIds[0], appId));
13226
13227        sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
13228                packageName, extras, 0, null, null, userIds);
13229        if (isSystem) {
13230            mHandler.post(() -> {
13231                        for (int userId : userIds) {
13232                            sendBootCompletedBroadcastToSystemApp(packageName, userId);
13233                        }
13234                    }
13235            );
13236        }
13237    }
13238
13239    /**
13240     * The just-installed/enabled app is bundled on the system, so presumed to be able to run
13241     * automatically without needing an explicit launch.
13242     * Send it a LOCKED_BOOT_COMPLETED/BOOT_COMPLETED if it would ordinarily have gotten ones.
13243     */
13244    private void sendBootCompletedBroadcastToSystemApp(String packageName, int userId) {
13245        // If user is not running, the app didn't miss any broadcast
13246        if (!mUserManagerInternal.isUserRunning(userId)) {
13247            return;
13248        }
13249        final IActivityManager am = ActivityManager.getService();
13250        try {
13251            // Deliver LOCKED_BOOT_COMPLETED first
13252            Intent lockedBcIntent = new Intent(Intent.ACTION_LOCKED_BOOT_COMPLETED)
13253                    .setPackage(packageName);
13254            final String[] requiredPermissions = {Manifest.permission.RECEIVE_BOOT_COMPLETED};
13255            am.broadcastIntent(null, lockedBcIntent, null, null, 0, null, null, requiredPermissions,
13256                    android.app.AppOpsManager.OP_NONE, null, false, false, userId);
13257
13258            // Deliver BOOT_COMPLETED only if user is unlocked
13259            if (mUserManagerInternal.isUserUnlockingOrUnlocked(userId)) {
13260                Intent bcIntent = new Intent(Intent.ACTION_BOOT_COMPLETED).setPackage(packageName);
13261                am.broadcastIntent(null, bcIntent, null, null, 0, null, null, requiredPermissions,
13262                        android.app.AppOpsManager.OP_NONE, null, false, false, userId);
13263            }
13264        } catch (RemoteException e) {
13265            throw e.rethrowFromSystemServer();
13266        }
13267    }
13268
13269    @Override
13270    public boolean setApplicationHiddenSettingAsUser(String packageName, boolean hidden,
13271            int userId) {
13272        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
13273        PackageSetting pkgSetting;
13274        final int uid = Binder.getCallingUid();
13275        enforceCrossUserPermission(uid, userId,
13276                true /* requireFullPermission */, true /* checkShell */,
13277                "setApplicationHiddenSetting for user " + userId);
13278
13279        if (hidden && isPackageDeviceAdmin(packageName, userId)) {
13280            Slog.w(TAG, "Not hiding package " + packageName + ": has active device admin");
13281            return false;
13282        }
13283
13284        long callingId = Binder.clearCallingIdentity();
13285        try {
13286            boolean sendAdded = false;
13287            boolean sendRemoved = false;
13288            // writer
13289            synchronized (mPackages) {
13290                pkgSetting = mSettings.mPackages.get(packageName);
13291                if (pkgSetting == null) {
13292                    return false;
13293                }
13294                // Do not allow "android" is being disabled
13295                if ("android".equals(packageName)) {
13296                    Slog.w(TAG, "Cannot hide package: android");
13297                    return false;
13298                }
13299                // Cannot hide static shared libs as they are considered
13300                // a part of the using app (emulating static linking). Also
13301                // static libs are installed always on internal storage.
13302                PackageParser.Package pkg = mPackages.get(packageName);
13303                if (pkg != null && pkg.staticSharedLibName != null) {
13304                    Slog.w(TAG, "Cannot hide package: " + packageName
13305                            + " providing static shared library: "
13306                            + pkg.staticSharedLibName);
13307                    return false;
13308                }
13309                // Only allow protected packages to hide themselves.
13310                if (hidden && !UserHandle.isSameApp(uid, pkgSetting.appId)
13311                        && mProtectedPackages.isPackageStateProtected(userId, packageName)) {
13312                    Slog.w(TAG, "Not hiding protected package: " + packageName);
13313                    return false;
13314                }
13315
13316                if (pkgSetting.getHidden(userId) != hidden) {
13317                    pkgSetting.setHidden(hidden, userId);
13318                    mSettings.writePackageRestrictionsLPr(userId);
13319                    if (hidden) {
13320                        sendRemoved = true;
13321                    } else {
13322                        sendAdded = true;
13323                    }
13324                }
13325            }
13326            if (sendAdded) {
13327                sendPackageAddedForUser(packageName, pkgSetting, userId);
13328                return true;
13329            }
13330            if (sendRemoved) {
13331                killApplication(packageName, UserHandle.getUid(userId, pkgSetting.appId),
13332                        "hiding pkg");
13333                sendApplicationHiddenForUser(packageName, pkgSetting, userId);
13334                return true;
13335            }
13336        } finally {
13337            Binder.restoreCallingIdentity(callingId);
13338        }
13339        return false;
13340    }
13341
13342    private void sendApplicationHiddenForUser(String packageName, PackageSetting pkgSetting,
13343            int userId) {
13344        final PackageRemovedInfo info = new PackageRemovedInfo();
13345        info.removedPackage = packageName;
13346        info.removedUsers = new int[] {userId};
13347        info.uid = UserHandle.getUid(userId, pkgSetting.appId);
13348        info.sendPackageRemovedBroadcasts(true /*killApp*/);
13349    }
13350
13351    private void sendPackagesSuspendedForUser(String[] pkgList, int userId, boolean suspended) {
13352        if (pkgList.length > 0) {
13353            Bundle extras = new Bundle(1);
13354            extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList);
13355
13356            sendPackageBroadcast(
13357                    suspended ? Intent.ACTION_PACKAGES_SUSPENDED
13358                            : Intent.ACTION_PACKAGES_UNSUSPENDED,
13359                    null, extras, Intent.FLAG_RECEIVER_REGISTERED_ONLY, null, null,
13360                    new int[] {userId});
13361        }
13362    }
13363
13364    /**
13365     * Returns true if application is not found or there was an error. Otherwise it returns
13366     * the hidden state of the package for the given user.
13367     */
13368    @Override
13369    public boolean getApplicationHiddenSettingAsUser(String packageName, int userId) {
13370        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
13371        enforceCrossUserPermission(Binder.getCallingUid(), userId,
13372                true /* requireFullPermission */, false /* checkShell */,
13373                "getApplicationHidden for user " + userId);
13374        PackageSetting pkgSetting;
13375        long callingId = Binder.clearCallingIdentity();
13376        try {
13377            // writer
13378            synchronized (mPackages) {
13379                pkgSetting = mSettings.mPackages.get(packageName);
13380                if (pkgSetting == null) {
13381                    return true;
13382                }
13383                return pkgSetting.getHidden(userId);
13384            }
13385        } finally {
13386            Binder.restoreCallingIdentity(callingId);
13387        }
13388    }
13389
13390    /**
13391     * @hide
13392     */
13393    @Override
13394    public int installExistingPackageAsUser(String packageName, int userId, int installFlags,
13395            int installReason) {
13396        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES,
13397                null);
13398        PackageSetting pkgSetting;
13399        final int uid = Binder.getCallingUid();
13400        enforceCrossUserPermission(uid, userId,
13401                true /* requireFullPermission */, true /* checkShell */,
13402                "installExistingPackage for user " + userId);
13403        if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) {
13404            return PackageManager.INSTALL_FAILED_USER_RESTRICTED;
13405        }
13406
13407        long callingId = Binder.clearCallingIdentity();
13408        try {
13409            boolean installed = false;
13410            final boolean instantApp =
13411                    (installFlags & PackageManager.INSTALL_INSTANT_APP) != 0;
13412            final boolean fullApp =
13413                    (installFlags & PackageManager.INSTALL_FULL_APP) != 0;
13414
13415            // writer
13416            synchronized (mPackages) {
13417                pkgSetting = mSettings.mPackages.get(packageName);
13418                if (pkgSetting == null) {
13419                    return PackageManager.INSTALL_FAILED_INVALID_URI;
13420                }
13421                if (!pkgSetting.getInstalled(userId)) {
13422                    pkgSetting.setInstalled(true, userId);
13423                    pkgSetting.setHidden(false, userId);
13424                    pkgSetting.setInstallReason(installReason, userId);
13425                    mSettings.writePackageRestrictionsLPr(userId);
13426                    mSettings.writeKernelMappingLPr(pkgSetting);
13427                    installed = true;
13428                } else if (fullApp && pkgSetting.getInstantApp(userId)) {
13429                    // upgrade app from instant to full; we don't allow app downgrade
13430                    installed = true;
13431                }
13432                setInstantAppForUser(pkgSetting, userId, instantApp, fullApp);
13433            }
13434
13435            if (installed) {
13436                if (pkgSetting.pkg != null) {
13437                    synchronized (mInstallLock) {
13438                        // We don't need to freeze for a brand new install
13439                        prepareAppDataAfterInstallLIF(pkgSetting.pkg);
13440                    }
13441                }
13442                sendPackageAddedForUser(packageName, pkgSetting, userId);
13443                synchronized (mPackages) {
13444                    updateSequenceNumberLP(packageName, new int[]{ userId });
13445                }
13446            }
13447        } finally {
13448            Binder.restoreCallingIdentity(callingId);
13449        }
13450
13451        return PackageManager.INSTALL_SUCCEEDED;
13452    }
13453
13454    void setInstantAppForUser(PackageSetting pkgSetting, int userId,
13455            boolean instantApp, boolean fullApp) {
13456        // no state specified; do nothing
13457        if (!instantApp && !fullApp) {
13458            return;
13459        }
13460        if (userId != UserHandle.USER_ALL) {
13461            if (instantApp && !pkgSetting.getInstantApp(userId)) {
13462                pkgSetting.setInstantApp(true /*instantApp*/, userId);
13463            } else if (fullApp && pkgSetting.getInstantApp(userId)) {
13464                pkgSetting.setInstantApp(false /*instantApp*/, userId);
13465            }
13466        } else {
13467            for (int currentUserId : sUserManager.getUserIds()) {
13468                if (instantApp && !pkgSetting.getInstantApp(currentUserId)) {
13469                    pkgSetting.setInstantApp(true /*instantApp*/, currentUserId);
13470                } else if (fullApp && pkgSetting.getInstantApp(currentUserId)) {
13471                    pkgSetting.setInstantApp(false /*instantApp*/, currentUserId);
13472                }
13473            }
13474        }
13475    }
13476
13477    boolean isUserRestricted(int userId, String restrictionKey) {
13478        Bundle restrictions = sUserManager.getUserRestrictions(userId);
13479        if (restrictions.getBoolean(restrictionKey, false)) {
13480            Log.w(TAG, "User is restricted: " + restrictionKey);
13481            return true;
13482        }
13483        return false;
13484    }
13485
13486    @Override
13487    public String[] setPackagesSuspendedAsUser(String[] packageNames, boolean suspended,
13488            int userId) {
13489        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
13490        enforceCrossUserPermission(Binder.getCallingUid(), userId,
13491                true /* requireFullPermission */, true /* checkShell */,
13492                "setPackagesSuspended for user " + userId);
13493
13494        if (ArrayUtils.isEmpty(packageNames)) {
13495            return packageNames;
13496        }
13497
13498        // List of package names for whom the suspended state has changed.
13499        List<String> changedPackages = new ArrayList<>(packageNames.length);
13500        // List of package names for whom the suspended state is not set as requested in this
13501        // method.
13502        List<String> unactionedPackages = new ArrayList<>(packageNames.length);
13503        long callingId = Binder.clearCallingIdentity();
13504        try {
13505            for (int i = 0; i < packageNames.length; i++) {
13506                String packageName = packageNames[i];
13507                boolean changed = false;
13508                final int appId;
13509                synchronized (mPackages) {
13510                    final PackageSetting pkgSetting = mSettings.mPackages.get(packageName);
13511                    if (pkgSetting == null) {
13512                        Slog.w(TAG, "Could not find package setting for package \"" + packageName
13513                                + "\". Skipping suspending/un-suspending.");
13514                        unactionedPackages.add(packageName);
13515                        continue;
13516                    }
13517                    appId = pkgSetting.appId;
13518                    if (pkgSetting.getSuspended(userId) != suspended) {
13519                        if (!canSuspendPackageForUserLocked(packageName, userId)) {
13520                            unactionedPackages.add(packageName);
13521                            continue;
13522                        }
13523                        pkgSetting.setSuspended(suspended, userId);
13524                        mSettings.writePackageRestrictionsLPr(userId);
13525                        changed = true;
13526                        changedPackages.add(packageName);
13527                    }
13528                }
13529
13530                if (changed && suspended) {
13531                    killApplication(packageName, UserHandle.getUid(userId, appId),
13532                            "suspending package");
13533                }
13534            }
13535        } finally {
13536            Binder.restoreCallingIdentity(callingId);
13537        }
13538
13539        if (!changedPackages.isEmpty()) {
13540            sendPackagesSuspendedForUser(changedPackages.toArray(
13541                    new String[changedPackages.size()]), userId, suspended);
13542        }
13543
13544        return unactionedPackages.toArray(new String[unactionedPackages.size()]);
13545    }
13546
13547    @Override
13548    public boolean isPackageSuspendedForUser(String packageName, int userId) {
13549        enforceCrossUserPermission(Binder.getCallingUid(), userId,
13550                true /* requireFullPermission */, false /* checkShell */,
13551                "isPackageSuspendedForUser for user " + userId);
13552        synchronized (mPackages) {
13553            final PackageSetting pkgSetting = mSettings.mPackages.get(packageName);
13554            if (pkgSetting == null) {
13555                throw new IllegalArgumentException("Unknown target package: " + packageName);
13556            }
13557            return pkgSetting.getSuspended(userId);
13558        }
13559    }
13560
13561    private boolean canSuspendPackageForUserLocked(String packageName, int userId) {
13562        if (isPackageDeviceAdmin(packageName, userId)) {
13563            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
13564                    + "\": has an active device admin");
13565            return false;
13566        }
13567
13568        String activeLauncherPackageName = getActiveLauncherPackageName(userId);
13569        if (packageName.equals(activeLauncherPackageName)) {
13570            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
13571                    + "\": contains the active launcher");
13572            return false;
13573        }
13574
13575        if (packageName.equals(mRequiredInstallerPackage)) {
13576            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
13577                    + "\": required for package installation");
13578            return false;
13579        }
13580
13581        if (packageName.equals(mRequiredUninstallerPackage)) {
13582            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
13583                    + "\": required for package uninstallation");
13584            return false;
13585        }
13586
13587        if (packageName.equals(mRequiredVerifierPackage)) {
13588            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
13589                    + "\": required for package verification");
13590            return false;
13591        }
13592
13593        if (packageName.equals(getDefaultDialerPackageName(userId))) {
13594            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
13595                    + "\": is the default dialer");
13596            return false;
13597        }
13598
13599        if (mProtectedPackages.isPackageStateProtected(userId, packageName)) {
13600            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
13601                    + "\": protected package");
13602            return false;
13603        }
13604
13605        // Cannot suspend static shared libs as they are considered
13606        // a part of the using app (emulating static linking). Also
13607        // static libs are installed always on internal storage.
13608        PackageParser.Package pkg = mPackages.get(packageName);
13609        if (pkg != null && pkg.applicationInfo.isStaticSharedLibrary()) {
13610            Slog.w(TAG, "Cannot suspend package: " + packageName
13611                    + " providing static shared library: "
13612                    + pkg.staticSharedLibName);
13613            return false;
13614        }
13615
13616        return true;
13617    }
13618
13619    private String getActiveLauncherPackageName(int userId) {
13620        Intent intent = new Intent(Intent.ACTION_MAIN);
13621        intent.addCategory(Intent.CATEGORY_HOME);
13622        ResolveInfo resolveInfo = resolveIntent(
13623                intent,
13624                intent.resolveTypeIfNeeded(mContext.getContentResolver()),
13625                PackageManager.MATCH_DEFAULT_ONLY,
13626                userId);
13627
13628        return resolveInfo == null ? null : resolveInfo.activityInfo.packageName;
13629    }
13630
13631    private String getDefaultDialerPackageName(int userId) {
13632        synchronized (mPackages) {
13633            return mSettings.getDefaultDialerPackageNameLPw(userId);
13634        }
13635    }
13636
13637    @Override
13638    public void verifyPendingInstall(int id, int verificationCode) throws RemoteException {
13639        mContext.enforceCallingOrSelfPermission(
13640                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
13641                "Only package verification agents can verify applications");
13642
13643        final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED);
13644        final PackageVerificationResponse response = new PackageVerificationResponse(
13645                verificationCode, Binder.getCallingUid());
13646        msg.arg1 = id;
13647        msg.obj = response;
13648        mHandler.sendMessage(msg);
13649    }
13650
13651    @Override
13652    public void extendVerificationTimeout(int id, int verificationCodeAtTimeout,
13653            long millisecondsToDelay) {
13654        mContext.enforceCallingOrSelfPermission(
13655                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
13656                "Only package verification agents can extend verification timeouts");
13657
13658        final PackageVerificationState state = mPendingVerification.get(id);
13659        final PackageVerificationResponse response = new PackageVerificationResponse(
13660                verificationCodeAtTimeout, Binder.getCallingUid());
13661
13662        if (millisecondsToDelay > PackageManager.MAXIMUM_VERIFICATION_TIMEOUT) {
13663            millisecondsToDelay = PackageManager.MAXIMUM_VERIFICATION_TIMEOUT;
13664        }
13665        if (millisecondsToDelay < 0) {
13666            millisecondsToDelay = 0;
13667        }
13668        if ((verificationCodeAtTimeout != PackageManager.VERIFICATION_ALLOW)
13669                && (verificationCodeAtTimeout != PackageManager.VERIFICATION_REJECT)) {
13670            verificationCodeAtTimeout = PackageManager.VERIFICATION_REJECT;
13671        }
13672
13673        if ((state != null) && !state.timeoutExtended()) {
13674            state.extendTimeout();
13675
13676            final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED);
13677            msg.arg1 = id;
13678            msg.obj = response;
13679            mHandler.sendMessageDelayed(msg, millisecondsToDelay);
13680        }
13681    }
13682
13683    private void broadcastPackageVerified(int verificationId, Uri packageUri,
13684            int verificationCode, UserHandle user) {
13685        final Intent intent = new Intent(Intent.ACTION_PACKAGE_VERIFIED);
13686        intent.setDataAndType(packageUri, PACKAGE_MIME_TYPE);
13687        intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
13688        intent.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId);
13689        intent.putExtra(PackageManager.EXTRA_VERIFICATION_RESULT, verificationCode);
13690
13691        mContext.sendBroadcastAsUser(intent, user,
13692                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT);
13693    }
13694
13695    private ComponentName matchComponentForVerifier(String packageName,
13696            List<ResolveInfo> receivers) {
13697        ActivityInfo targetReceiver = null;
13698
13699        final int NR = receivers.size();
13700        for (int i = 0; i < NR; i++) {
13701            final ResolveInfo info = receivers.get(i);
13702            if (info.activityInfo == null) {
13703                continue;
13704            }
13705
13706            if (packageName.equals(info.activityInfo.packageName)) {
13707                targetReceiver = info.activityInfo;
13708                break;
13709            }
13710        }
13711
13712        if (targetReceiver == null) {
13713            return null;
13714        }
13715
13716        return new ComponentName(targetReceiver.packageName, targetReceiver.name);
13717    }
13718
13719    private List<ComponentName> matchVerifiers(PackageInfoLite pkgInfo,
13720            List<ResolveInfo> receivers, final PackageVerificationState verificationState) {
13721        if (pkgInfo.verifiers.length == 0) {
13722            return null;
13723        }
13724
13725        final int N = pkgInfo.verifiers.length;
13726        final List<ComponentName> sufficientVerifiers = new ArrayList<ComponentName>(N + 1);
13727        for (int i = 0; i < N; i++) {
13728            final VerifierInfo verifierInfo = pkgInfo.verifiers[i];
13729
13730            final ComponentName comp = matchComponentForVerifier(verifierInfo.packageName,
13731                    receivers);
13732            if (comp == null) {
13733                continue;
13734            }
13735
13736            final int verifierUid = getUidForVerifier(verifierInfo);
13737            if (verifierUid == -1) {
13738                continue;
13739            }
13740
13741            if (DEBUG_VERIFY) {
13742                Slog.d(TAG, "Added sufficient verifier " + verifierInfo.packageName
13743                        + " with the correct signature");
13744            }
13745            sufficientVerifiers.add(comp);
13746            verificationState.addSufficientVerifier(verifierUid);
13747        }
13748
13749        return sufficientVerifiers;
13750    }
13751
13752    private int getUidForVerifier(VerifierInfo verifierInfo) {
13753        synchronized (mPackages) {
13754            final PackageParser.Package pkg = mPackages.get(verifierInfo.packageName);
13755            if (pkg == null) {
13756                return -1;
13757            } else if (pkg.mSignatures.length != 1) {
13758                Slog.i(TAG, "Verifier package " + verifierInfo.packageName
13759                        + " has more than one signature; ignoring");
13760                return -1;
13761            }
13762
13763            /*
13764             * If the public key of the package's signature does not match
13765             * our expected public key, then this is a different package and
13766             * we should skip.
13767             */
13768
13769            final byte[] expectedPublicKey;
13770            try {
13771                final Signature verifierSig = pkg.mSignatures[0];
13772                final PublicKey publicKey = verifierSig.getPublicKey();
13773                expectedPublicKey = publicKey.getEncoded();
13774            } catch (CertificateException e) {
13775                return -1;
13776            }
13777
13778            final byte[] actualPublicKey = verifierInfo.publicKey.getEncoded();
13779
13780            if (!Arrays.equals(actualPublicKey, expectedPublicKey)) {
13781                Slog.i(TAG, "Verifier package " + verifierInfo.packageName
13782                        + " does not have the expected public key; ignoring");
13783                return -1;
13784            }
13785
13786            return pkg.applicationInfo.uid;
13787        }
13788    }
13789
13790    @Override
13791    public void finishPackageInstall(int token, boolean didLaunch) {
13792        enforceSystemOrRoot("Only the system is allowed to finish installs");
13793
13794        if (DEBUG_INSTALL) {
13795            Slog.v(TAG, "BM finishing package install for " + token);
13796        }
13797        Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "restore", token);
13798
13799        final Message msg = mHandler.obtainMessage(POST_INSTALL, token, didLaunch ? 1 : 0);
13800        mHandler.sendMessage(msg);
13801    }
13802
13803    /**
13804     * Get the verification agent timeout.
13805     *
13806     * @return verification timeout in milliseconds
13807     */
13808    private long getVerificationTimeout() {
13809        return android.provider.Settings.Global.getLong(mContext.getContentResolver(),
13810                android.provider.Settings.Global.PACKAGE_VERIFIER_TIMEOUT,
13811                DEFAULT_VERIFICATION_TIMEOUT);
13812    }
13813
13814    /**
13815     * Get the default verification agent response code.
13816     *
13817     * @return default verification response code
13818     */
13819    private int getDefaultVerificationResponse() {
13820        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
13821                android.provider.Settings.Global.PACKAGE_VERIFIER_DEFAULT_RESPONSE,
13822                DEFAULT_VERIFICATION_RESPONSE);
13823    }
13824
13825    /**
13826     * Check whether or not package verification has been enabled.
13827     *
13828     * @return true if verification should be performed
13829     */
13830    private boolean isVerificationEnabled(int userId, int installFlags) {
13831        if (!DEFAULT_VERIFY_ENABLE) {
13832            return false;
13833        }
13834        // Ephemeral apps don't get the full verification treatment
13835        if ((installFlags & PackageManager.INSTALL_INSTANT_APP) != 0) {
13836            if (DEBUG_EPHEMERAL) {
13837                Slog.d(TAG, "INSTALL_EPHEMERAL so skipping verification");
13838            }
13839            return false;
13840        }
13841
13842        boolean ensureVerifyAppsEnabled = isUserRestricted(userId, UserManager.ENSURE_VERIFY_APPS);
13843
13844        // Check if installing from ADB
13845        if ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0) {
13846            // Do not run verification in a test harness environment
13847            if (ActivityManager.isRunningInTestHarness()) {
13848                return false;
13849            }
13850            if (ensureVerifyAppsEnabled) {
13851                return true;
13852            }
13853            // Check if the developer does not want package verification for ADB installs
13854            if (android.provider.Settings.Global.getInt(mContext.getContentResolver(),
13855                    android.provider.Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB, 1) == 0) {
13856                return false;
13857            }
13858        }
13859
13860        if (ensureVerifyAppsEnabled) {
13861            return true;
13862        }
13863
13864        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
13865                android.provider.Settings.Global.PACKAGE_VERIFIER_ENABLE, 1) == 1;
13866    }
13867
13868    @Override
13869    public void verifyIntentFilter(int id, int verificationCode, List<String> failedDomains)
13870            throws RemoteException {
13871        mContext.enforceCallingOrSelfPermission(
13872                Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT,
13873                "Only intentfilter verification agents can verify applications");
13874
13875        final Message msg = mHandler.obtainMessage(INTENT_FILTER_VERIFIED);
13876        final IntentFilterVerificationResponse response = new IntentFilterVerificationResponse(
13877                Binder.getCallingUid(), verificationCode, failedDomains);
13878        msg.arg1 = id;
13879        msg.obj = response;
13880        mHandler.sendMessage(msg);
13881    }
13882
13883    @Override
13884    public int getIntentVerificationStatus(String packageName, int userId) {
13885        synchronized (mPackages) {
13886            return mSettings.getIntentFilterVerificationStatusLPr(packageName, userId);
13887        }
13888    }
13889
13890    @Override
13891    public boolean updateIntentVerificationStatus(String packageName, int status, int userId) {
13892        mContext.enforceCallingOrSelfPermission(
13893                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
13894
13895        boolean result = false;
13896        synchronized (mPackages) {
13897            result = mSettings.updateIntentFilterVerificationStatusLPw(packageName, status, userId);
13898        }
13899        if (result) {
13900            scheduleWritePackageRestrictionsLocked(userId);
13901        }
13902        return result;
13903    }
13904
13905    @Override
13906    public @NonNull ParceledListSlice<IntentFilterVerificationInfo> getIntentFilterVerifications(
13907            String packageName) {
13908        synchronized (mPackages) {
13909            return new ParceledListSlice<>(mSettings.getIntentFilterVerificationsLPr(packageName));
13910        }
13911    }
13912
13913    @Override
13914    public @NonNull ParceledListSlice<IntentFilter> getAllIntentFilters(String packageName) {
13915        if (TextUtils.isEmpty(packageName)) {
13916            return ParceledListSlice.emptyList();
13917        }
13918        synchronized (mPackages) {
13919            PackageParser.Package pkg = mPackages.get(packageName);
13920            if (pkg == null || pkg.activities == null) {
13921                return ParceledListSlice.emptyList();
13922            }
13923            final int count = pkg.activities.size();
13924            ArrayList<IntentFilter> result = new ArrayList<>();
13925            for (int n=0; n<count; n++) {
13926                PackageParser.Activity activity = pkg.activities.get(n);
13927                if (activity.intents != null && activity.intents.size() > 0) {
13928                    result.addAll(activity.intents);
13929                }
13930            }
13931            return new ParceledListSlice<>(result);
13932        }
13933    }
13934
13935    @Override
13936    public boolean setDefaultBrowserPackageName(String packageName, int userId) {
13937        mContext.enforceCallingOrSelfPermission(
13938                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
13939
13940        synchronized (mPackages) {
13941            boolean result = mSettings.setDefaultBrowserPackageNameLPw(packageName, userId);
13942            if (packageName != null) {
13943                result |= updateIntentVerificationStatus(packageName,
13944                        PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS,
13945                        userId);
13946                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultBrowserLPr(
13947                        packageName, userId);
13948            }
13949            return result;
13950        }
13951    }
13952
13953    @Override
13954    public String getDefaultBrowserPackageName(int userId) {
13955        synchronized (mPackages) {
13956            return mSettings.getDefaultBrowserPackageNameLPw(userId);
13957        }
13958    }
13959
13960    /**
13961     * Get the "allow unknown sources" setting.
13962     *
13963     * @return the current "allow unknown sources" setting
13964     */
13965    private int getUnknownSourcesSettings() {
13966        return android.provider.Settings.Secure.getInt(mContext.getContentResolver(),
13967                android.provider.Settings.Secure.INSTALL_NON_MARKET_APPS,
13968                -1);
13969    }
13970
13971    @Override
13972    public void setInstallerPackageName(String targetPackage, String installerPackageName) {
13973        final int uid = Binder.getCallingUid();
13974        // writer
13975        synchronized (mPackages) {
13976            PackageSetting targetPackageSetting = mSettings.mPackages.get(targetPackage);
13977            if (targetPackageSetting == null) {
13978                throw new IllegalArgumentException("Unknown target package: " + targetPackage);
13979            }
13980
13981            PackageSetting installerPackageSetting;
13982            if (installerPackageName != null) {
13983                installerPackageSetting = mSettings.mPackages.get(installerPackageName);
13984                if (installerPackageSetting == null) {
13985                    throw new IllegalArgumentException("Unknown installer package: "
13986                            + installerPackageName);
13987                }
13988            } else {
13989                installerPackageSetting = null;
13990            }
13991
13992            Signature[] callerSignature;
13993            Object obj = mSettings.getUserIdLPr(uid);
13994            if (obj != null) {
13995                if (obj instanceof SharedUserSetting) {
13996                    callerSignature = ((SharedUserSetting)obj).signatures.mSignatures;
13997                } else if (obj instanceof PackageSetting) {
13998                    callerSignature = ((PackageSetting)obj).signatures.mSignatures;
13999                } else {
14000                    throw new SecurityException("Bad object " + obj + " for uid " + uid);
14001                }
14002            } else {
14003                throw new SecurityException("Unknown calling UID: " + uid);
14004            }
14005
14006            // Verify: can't set installerPackageName to a package that is
14007            // not signed with the same cert as the caller.
14008            if (installerPackageSetting != null) {
14009                if (compareSignatures(callerSignature,
14010                        installerPackageSetting.signatures.mSignatures)
14011                        != PackageManager.SIGNATURE_MATCH) {
14012                    throw new SecurityException(
14013                            "Caller does not have same cert as new installer package "
14014                            + installerPackageName);
14015                }
14016            }
14017
14018            // Verify: if target already has an installer package, it must
14019            // be signed with the same cert as the caller.
14020            if (targetPackageSetting.installerPackageName != null) {
14021                PackageSetting setting = mSettings.mPackages.get(
14022                        targetPackageSetting.installerPackageName);
14023                // If the currently set package isn't valid, then it's always
14024                // okay to change it.
14025                if (setting != null) {
14026                    if (compareSignatures(callerSignature,
14027                            setting.signatures.mSignatures)
14028                            != PackageManager.SIGNATURE_MATCH) {
14029                        throw new SecurityException(
14030                                "Caller does not have same cert as old installer package "
14031                                + targetPackageSetting.installerPackageName);
14032                    }
14033                }
14034            }
14035
14036            // Okay!
14037            targetPackageSetting.installerPackageName = installerPackageName;
14038            if (installerPackageName != null) {
14039                mSettings.mInstallerPackages.add(installerPackageName);
14040            }
14041            scheduleWriteSettingsLocked();
14042        }
14043    }
14044
14045    @Override
14046    public void setApplicationCategoryHint(String packageName, int categoryHint,
14047            String callerPackageName) {
14048        mContext.getSystemService(AppOpsManager.class).checkPackage(Binder.getCallingUid(),
14049                callerPackageName);
14050        synchronized (mPackages) {
14051            PackageSetting ps = mSettings.mPackages.get(packageName);
14052            if (ps == null) {
14053                throw new IllegalArgumentException("Unknown target package " + packageName);
14054            }
14055
14056            if (!Objects.equals(callerPackageName, ps.installerPackageName)) {
14057                throw new IllegalArgumentException("Calling package " + callerPackageName
14058                        + " is not installer for " + packageName);
14059            }
14060
14061            if (ps.categoryHint != categoryHint) {
14062                ps.categoryHint = categoryHint;
14063                scheduleWriteSettingsLocked();
14064            }
14065        }
14066    }
14067
14068    private void processPendingInstall(final InstallArgs args, final int currentStatus) {
14069        // Queue up an async operation since the package installation may take a little while.
14070        mHandler.post(new Runnable() {
14071            public void run() {
14072                mHandler.removeCallbacks(this);
14073                 // Result object to be returned
14074                PackageInstalledInfo res = new PackageInstalledInfo();
14075                res.setReturnCode(currentStatus);
14076                res.uid = -1;
14077                res.pkg = null;
14078                res.removedInfo = null;
14079                if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
14080                    args.doPreInstall(res.returnCode);
14081                    synchronized (mInstallLock) {
14082                        installPackageTracedLI(args, res);
14083                    }
14084                    args.doPostInstall(res.returnCode, res.uid);
14085                }
14086
14087                // A restore should be performed at this point if (a) the install
14088                // succeeded, (b) the operation is not an update, and (c) the new
14089                // package has not opted out of backup participation.
14090                final boolean update = res.removedInfo != null
14091                        && res.removedInfo.removedPackage != null;
14092                final int flags = (res.pkg == null) ? 0 : res.pkg.applicationInfo.flags;
14093                boolean doRestore = !update
14094                        && ((flags & ApplicationInfo.FLAG_ALLOW_BACKUP) != 0);
14095
14096                // Set up the post-install work request bookkeeping.  This will be used
14097                // and cleaned up by the post-install event handling regardless of whether
14098                // there's a restore pass performed.  Token values are >= 1.
14099                int token;
14100                if (mNextInstallToken < 0) mNextInstallToken = 1;
14101                token = mNextInstallToken++;
14102
14103                PostInstallData data = new PostInstallData(args, res);
14104                mRunningInstalls.put(token, data);
14105                if (DEBUG_INSTALL) Log.v(TAG, "+ starting restore round-trip " + token);
14106
14107                if (res.returnCode == PackageManager.INSTALL_SUCCEEDED && doRestore) {
14108                    // Pass responsibility to the Backup Manager.  It will perform a
14109                    // restore if appropriate, then pass responsibility back to the
14110                    // Package Manager to run the post-install observer callbacks
14111                    // and broadcasts.
14112                    IBackupManager bm = IBackupManager.Stub.asInterface(
14113                            ServiceManager.getService(Context.BACKUP_SERVICE));
14114                    if (bm != null) {
14115                        if (DEBUG_INSTALL) Log.v(TAG, "token " + token
14116                                + " to BM for possible restore");
14117                        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "restore", token);
14118                        try {
14119                            // TODO: http://b/22388012
14120                            if (bm.isBackupServiceActive(UserHandle.USER_SYSTEM)) {
14121                                bm.restoreAtInstall(res.pkg.applicationInfo.packageName, token);
14122                            } else {
14123                                doRestore = false;
14124                            }
14125                        } catch (RemoteException e) {
14126                            // can't happen; the backup manager is local
14127                        } catch (Exception e) {
14128                            Slog.e(TAG, "Exception trying to enqueue restore", e);
14129                            doRestore = false;
14130                        }
14131                    } else {
14132                        Slog.e(TAG, "Backup Manager not found!");
14133                        doRestore = false;
14134                    }
14135                }
14136
14137                if (!doRestore) {
14138                    // No restore possible, or the Backup Manager was mysteriously not
14139                    // available -- just fire the post-install work request directly.
14140                    if (DEBUG_INSTALL) Log.v(TAG, "No restore - queue post-install for " + token);
14141
14142                    Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "postInstall", token);
14143
14144                    Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0);
14145                    mHandler.sendMessage(msg);
14146                }
14147            }
14148        });
14149    }
14150
14151    /**
14152     * Callback from PackageSettings whenever an app is first transitioned out of the
14153     * 'stopped' state.  Normally we just issue the broadcast, but we can't do that if
14154     * the app was "launched" for a restoreAtInstall operation.  Therefore we check
14155     * here whether the app is the target of an ongoing install, and only send the
14156     * broadcast immediately if it is not in that state.  If it *is* undergoing a restore,
14157     * the first-launch broadcast will be sent implicitly on that basis in POST_INSTALL
14158     * handling.
14159     */
14160    void notifyFirstLaunch(final String pkgName, final String installerPackage, final int userId) {
14161        // Serialize this with the rest of the install-process message chain.  In the
14162        // restore-at-install case, this Runnable will necessarily run before the
14163        // POST_INSTALL message is processed, so the contents of mRunningInstalls
14164        // are coherent.  In the non-restore case, the app has already completed install
14165        // and been launched through some other means, so it is not in a problematic
14166        // state for observers to see the FIRST_LAUNCH signal.
14167        mHandler.post(new Runnable() {
14168            @Override
14169            public void run() {
14170                for (int i = 0; i < mRunningInstalls.size(); i++) {
14171                    final PostInstallData data = mRunningInstalls.valueAt(i);
14172                    if (data.res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
14173                        continue;
14174                    }
14175                    if (pkgName.equals(data.res.pkg.applicationInfo.packageName)) {
14176                        // right package; but is it for the right user?
14177                        for (int uIndex = 0; uIndex < data.res.newUsers.length; uIndex++) {
14178                            if (userId == data.res.newUsers[uIndex]) {
14179                                if (DEBUG_BACKUP) {
14180                                    Slog.i(TAG, "Package " + pkgName
14181                                            + " being restored so deferring FIRST_LAUNCH");
14182                                }
14183                                return;
14184                            }
14185                        }
14186                    }
14187                }
14188                // didn't find it, so not being restored
14189                if (DEBUG_BACKUP) {
14190                    Slog.i(TAG, "Package " + pkgName + " sending normal FIRST_LAUNCH");
14191                }
14192                sendFirstLaunchBroadcast(pkgName, installerPackage, new int[] {userId});
14193            }
14194        });
14195    }
14196
14197    private void sendFirstLaunchBroadcast(String pkgName, String installerPkg, int[] userIds) {
14198        sendPackageBroadcast(Intent.ACTION_PACKAGE_FIRST_LAUNCH, pkgName, null, 0,
14199                installerPkg, null, userIds);
14200    }
14201
14202    private abstract class HandlerParams {
14203        private static final int MAX_RETRIES = 4;
14204
14205        /**
14206         * Number of times startCopy() has been attempted and had a non-fatal
14207         * error.
14208         */
14209        private int mRetries = 0;
14210
14211        /** User handle for the user requesting the information or installation. */
14212        private final UserHandle mUser;
14213        String traceMethod;
14214        int traceCookie;
14215
14216        HandlerParams(UserHandle user) {
14217            mUser = user;
14218        }
14219
14220        UserHandle getUser() {
14221            return mUser;
14222        }
14223
14224        HandlerParams setTraceMethod(String traceMethod) {
14225            this.traceMethod = traceMethod;
14226            return this;
14227        }
14228
14229        HandlerParams setTraceCookie(int traceCookie) {
14230            this.traceCookie = traceCookie;
14231            return this;
14232        }
14233
14234        final boolean startCopy() {
14235            boolean res;
14236            try {
14237                if (DEBUG_INSTALL) Slog.i(TAG, "startCopy " + mUser + ": " + this);
14238
14239                if (++mRetries > MAX_RETRIES) {
14240                    Slog.w(TAG, "Failed to invoke remote methods on default container service. Giving up");
14241                    mHandler.sendEmptyMessage(MCS_GIVE_UP);
14242                    handleServiceError();
14243                    return false;
14244                } else {
14245                    handleStartCopy();
14246                    res = true;
14247                }
14248            } catch (RemoteException e) {
14249                if (DEBUG_INSTALL) Slog.i(TAG, "Posting install MCS_RECONNECT");
14250                mHandler.sendEmptyMessage(MCS_RECONNECT);
14251                res = false;
14252            }
14253            handleReturnCode();
14254            return res;
14255        }
14256
14257        final void serviceError() {
14258            if (DEBUG_INSTALL) Slog.i(TAG, "serviceError");
14259            handleServiceError();
14260            handleReturnCode();
14261        }
14262
14263        abstract void handleStartCopy() throws RemoteException;
14264        abstract void handleServiceError();
14265        abstract void handleReturnCode();
14266    }
14267
14268    private static void clearDirectory(IMediaContainerService mcs, File[] paths) {
14269        for (File path : paths) {
14270            try {
14271                mcs.clearDirectory(path.getAbsolutePath());
14272            } catch (RemoteException e) {
14273            }
14274        }
14275    }
14276
14277    static class OriginInfo {
14278        /**
14279         * Location where install is coming from, before it has been
14280         * copied/renamed into place. This could be a single monolithic APK
14281         * file, or a cluster directory. This location may be untrusted.
14282         */
14283        final File file;
14284        final String cid;
14285
14286        /**
14287         * Flag indicating that {@link #file} or {@link #cid} has already been
14288         * staged, meaning downstream users don't need to defensively copy the
14289         * contents.
14290         */
14291        final boolean staged;
14292
14293        /**
14294         * Flag indicating that {@link #file} or {@link #cid} is an already
14295         * installed app that is being moved.
14296         */
14297        final boolean existing;
14298
14299        final String resolvedPath;
14300        final File resolvedFile;
14301
14302        static OriginInfo fromNothing() {
14303            return new OriginInfo(null, null, false, false);
14304        }
14305
14306        static OriginInfo fromUntrustedFile(File file) {
14307            return new OriginInfo(file, null, false, false);
14308        }
14309
14310        static OriginInfo fromExistingFile(File file) {
14311            return new OriginInfo(file, null, false, true);
14312        }
14313
14314        static OriginInfo fromStagedFile(File file) {
14315            return new OriginInfo(file, null, true, false);
14316        }
14317
14318        static OriginInfo fromStagedContainer(String cid) {
14319            return new OriginInfo(null, cid, true, false);
14320        }
14321
14322        private OriginInfo(File file, String cid, boolean staged, boolean existing) {
14323            this.file = file;
14324            this.cid = cid;
14325            this.staged = staged;
14326            this.existing = existing;
14327
14328            if (cid != null) {
14329                resolvedPath = PackageHelper.getSdDir(cid);
14330                resolvedFile = new File(resolvedPath);
14331            } else if (file != null) {
14332                resolvedPath = file.getAbsolutePath();
14333                resolvedFile = file;
14334            } else {
14335                resolvedPath = null;
14336                resolvedFile = null;
14337            }
14338        }
14339    }
14340
14341    static class MoveInfo {
14342        final int moveId;
14343        final String fromUuid;
14344        final String toUuid;
14345        final String packageName;
14346        final String dataAppName;
14347        final int appId;
14348        final String seinfo;
14349        final int targetSdkVersion;
14350
14351        public MoveInfo(int moveId, String fromUuid, String toUuid, String packageName,
14352                String dataAppName, int appId, String seinfo, int targetSdkVersion) {
14353            this.moveId = moveId;
14354            this.fromUuid = fromUuid;
14355            this.toUuid = toUuid;
14356            this.packageName = packageName;
14357            this.dataAppName = dataAppName;
14358            this.appId = appId;
14359            this.seinfo = seinfo;
14360            this.targetSdkVersion = targetSdkVersion;
14361        }
14362    }
14363
14364    static class VerificationInfo {
14365        /** A constant used to indicate that a uid value is not present. */
14366        public static final int NO_UID = -1;
14367
14368        /** URI referencing where the package was downloaded from. */
14369        final Uri originatingUri;
14370
14371        /** HTTP referrer URI associated with the originatingURI. */
14372        final Uri referrer;
14373
14374        /** UID of the application that the install request originated from. */
14375        final int originatingUid;
14376
14377        /** UID of application requesting the install */
14378        final int installerUid;
14379
14380        VerificationInfo(Uri originatingUri, Uri referrer, int originatingUid, int installerUid) {
14381            this.originatingUri = originatingUri;
14382            this.referrer = referrer;
14383            this.originatingUid = originatingUid;
14384            this.installerUid = installerUid;
14385        }
14386    }
14387
14388    class InstallParams extends HandlerParams {
14389        final OriginInfo origin;
14390        final MoveInfo move;
14391        final IPackageInstallObserver2 observer;
14392        int installFlags;
14393        final String installerPackageName;
14394        final String volumeUuid;
14395        private InstallArgs mArgs;
14396        private int mRet;
14397        final String packageAbiOverride;
14398        final String[] grantedRuntimePermissions;
14399        final VerificationInfo verificationInfo;
14400        final Certificate[][] certificates;
14401        final int installReason;
14402
14403        InstallParams(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer,
14404                int installFlags, String installerPackageName, String volumeUuid,
14405                VerificationInfo verificationInfo, UserHandle user, String packageAbiOverride,
14406                String[] grantedPermissions, Certificate[][] certificates, int installReason) {
14407            super(user);
14408            this.origin = origin;
14409            this.move = move;
14410            this.observer = observer;
14411            this.installFlags = installFlags;
14412            this.installerPackageName = installerPackageName;
14413            this.volumeUuid = volumeUuid;
14414            this.verificationInfo = verificationInfo;
14415            this.packageAbiOverride = packageAbiOverride;
14416            this.grantedRuntimePermissions = grantedPermissions;
14417            this.certificates = certificates;
14418            this.installReason = installReason;
14419        }
14420
14421        @Override
14422        public String toString() {
14423            return "InstallParams{" + Integer.toHexString(System.identityHashCode(this))
14424                    + " file=" + origin.file + " cid=" + origin.cid + "}";
14425        }
14426
14427        private int installLocationPolicy(PackageInfoLite pkgLite) {
14428            String packageName = pkgLite.packageName;
14429            int installLocation = pkgLite.installLocation;
14430            boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
14431            // reader
14432            synchronized (mPackages) {
14433                // Currently installed package which the new package is attempting to replace or
14434                // null if no such package is installed.
14435                PackageParser.Package installedPkg = mPackages.get(packageName);
14436                // Package which currently owns the data which the new package will own if installed.
14437                // If an app is unstalled while keeping data (e.g., adb uninstall -k), installedPkg
14438                // will be null whereas dataOwnerPkg will contain information about the package
14439                // which was uninstalled while keeping its data.
14440                PackageParser.Package dataOwnerPkg = installedPkg;
14441                if (dataOwnerPkg  == null) {
14442                    PackageSetting ps = mSettings.mPackages.get(packageName);
14443                    if (ps != null) {
14444                        dataOwnerPkg = ps.pkg;
14445                    }
14446                }
14447
14448                if (dataOwnerPkg != null) {
14449                    // If installed, the package will get access to data left on the device by its
14450                    // predecessor. As a security measure, this is permited only if this is not a
14451                    // version downgrade or if the predecessor package is marked as debuggable and
14452                    // a downgrade is explicitly requested.
14453                    //
14454                    // On debuggable platform builds, downgrades are permitted even for
14455                    // non-debuggable packages to make testing easier. Debuggable platform builds do
14456                    // not offer security guarantees and thus it's OK to disable some security
14457                    // mechanisms to make debugging/testing easier on those builds. However, even on
14458                    // debuggable builds downgrades of packages are permitted only if requested via
14459                    // installFlags. This is because we aim to keep the behavior of debuggable
14460                    // platform builds as close as possible to the behavior of non-debuggable
14461                    // platform builds.
14462                    final boolean downgradeRequested =
14463                            (installFlags & PackageManager.INSTALL_ALLOW_DOWNGRADE) != 0;
14464                    final boolean packageDebuggable =
14465                                (dataOwnerPkg.applicationInfo.flags
14466                                        & ApplicationInfo.FLAG_DEBUGGABLE) != 0;
14467                    final boolean downgradePermitted =
14468                            (downgradeRequested) && ((Build.IS_DEBUGGABLE) || (packageDebuggable));
14469                    if (!downgradePermitted) {
14470                        try {
14471                            checkDowngrade(dataOwnerPkg, pkgLite);
14472                        } catch (PackageManagerException e) {
14473                            Slog.w(TAG, "Downgrade detected: " + e.getMessage());
14474                            return PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE;
14475                        }
14476                    }
14477                }
14478
14479                if (installedPkg != null) {
14480                    if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
14481                        // Check for updated system application.
14482                        if ((installedPkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
14483                            if (onSd) {
14484                                Slog.w(TAG, "Cannot install update to system app on sdcard");
14485                                return PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION;
14486                            }
14487                            return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
14488                        } else {
14489                            if (onSd) {
14490                                // Install flag overrides everything.
14491                                return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
14492                            }
14493                            // If current upgrade specifies particular preference
14494                            if (installLocation == PackageInfo.INSTALL_LOCATION_INTERNAL_ONLY) {
14495                                // Application explicitly specified internal.
14496                                return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
14497                            } else if (installLocation == PackageInfo.INSTALL_LOCATION_PREFER_EXTERNAL) {
14498                                // App explictly prefers external. Let policy decide
14499                            } else {
14500                                // Prefer previous location
14501                                if (isExternal(installedPkg)) {
14502                                    return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
14503                                }
14504                                return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
14505                            }
14506                        }
14507                    } else {
14508                        // Invalid install. Return error code
14509                        return PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS;
14510                    }
14511                }
14512            }
14513            // All the special cases have been taken care of.
14514            // Return result based on recommended install location.
14515            if (onSd) {
14516                return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
14517            }
14518            return pkgLite.recommendedInstallLocation;
14519        }
14520
14521        /*
14522         * Invoke remote method to get package information and install
14523         * location values. Override install location based on default
14524         * policy if needed and then create install arguments based
14525         * on the install location.
14526         */
14527        public void handleStartCopy() throws RemoteException {
14528            int ret = PackageManager.INSTALL_SUCCEEDED;
14529
14530            // If we're already staged, we've firmly committed to an install location
14531            if (origin.staged) {
14532                if (origin.file != null) {
14533                    installFlags |= PackageManager.INSTALL_INTERNAL;
14534                    installFlags &= ~PackageManager.INSTALL_EXTERNAL;
14535                } else if (origin.cid != null) {
14536                    installFlags |= PackageManager.INSTALL_EXTERNAL;
14537                    installFlags &= ~PackageManager.INSTALL_INTERNAL;
14538                } else {
14539                    throw new IllegalStateException("Invalid stage location");
14540                }
14541            }
14542
14543            final boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
14544            final boolean onInt = (installFlags & PackageManager.INSTALL_INTERNAL) != 0;
14545            final boolean ephemeral = (installFlags & PackageManager.INSTALL_INSTANT_APP) != 0;
14546            PackageInfoLite pkgLite = null;
14547
14548            if (onInt && onSd) {
14549                // Check if both bits are set.
14550                Slog.w(TAG, "Conflicting flags specified for installing on both internal and external");
14551                ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
14552            } else if (onSd && ephemeral) {
14553                Slog.w(TAG,  "Conflicting flags specified for installing ephemeral on external");
14554                ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
14555            } else {
14556                pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, installFlags,
14557                        packageAbiOverride);
14558
14559                if (DEBUG_EPHEMERAL && ephemeral) {
14560                    Slog.v(TAG, "pkgLite for install: " + pkgLite);
14561                }
14562
14563                /*
14564                 * If we have too little free space, try to free cache
14565                 * before giving up.
14566                 */
14567                if (!origin.staged && pkgLite.recommendedInstallLocation
14568                        == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) {
14569                    // TODO: focus freeing disk space on the target device
14570                    final StorageManager storage = StorageManager.from(mContext);
14571                    final long lowThreshold = storage.getStorageLowBytes(
14572                            Environment.getDataDirectory());
14573
14574                    final long sizeBytes = mContainerService.calculateInstalledSize(
14575                            origin.resolvedPath, isForwardLocked(), packageAbiOverride);
14576
14577                    try {
14578                        mInstaller.freeCache(null, sizeBytes + lowThreshold, 0);
14579                        pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath,
14580                                installFlags, packageAbiOverride);
14581                    } catch (InstallerException e) {
14582                        Slog.w(TAG, "Failed to free cache", e);
14583                    }
14584
14585                    /*
14586                     * The cache free must have deleted the file we
14587                     * downloaded to install.
14588                     *
14589                     * TODO: fix the "freeCache" call to not delete
14590                     *       the file we care about.
14591                     */
14592                    if (pkgLite.recommendedInstallLocation
14593                            == PackageHelper.RECOMMEND_FAILED_INVALID_URI) {
14594                        pkgLite.recommendedInstallLocation
14595                            = PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE;
14596                    }
14597                }
14598            }
14599
14600            if (ret == PackageManager.INSTALL_SUCCEEDED) {
14601                int loc = pkgLite.recommendedInstallLocation;
14602                if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION) {
14603                    ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
14604                } else if (loc == PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS) {
14605                    ret = PackageManager.INSTALL_FAILED_ALREADY_EXISTS;
14606                } else if (loc == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) {
14607                    ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
14608                } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_APK) {
14609                    ret = PackageManager.INSTALL_FAILED_INVALID_APK;
14610                } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_URI) {
14611                    ret = PackageManager.INSTALL_FAILED_INVALID_URI;
14612                } else if (loc == PackageHelper.RECOMMEND_MEDIA_UNAVAILABLE) {
14613                    ret = PackageManager.INSTALL_FAILED_MEDIA_UNAVAILABLE;
14614                } else {
14615                    // Override with defaults if needed.
14616                    loc = installLocationPolicy(pkgLite);
14617                    if (loc == PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE) {
14618                        ret = PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE;
14619                    } else if (!onSd && !onInt) {
14620                        // Override install location with flags
14621                        if (loc == PackageHelper.RECOMMEND_INSTALL_EXTERNAL) {
14622                            // Set the flag to install on external media.
14623                            installFlags |= PackageManager.INSTALL_EXTERNAL;
14624                            installFlags &= ~PackageManager.INSTALL_INTERNAL;
14625                        } else if (loc == PackageHelper.RECOMMEND_INSTALL_EPHEMERAL) {
14626                            if (DEBUG_EPHEMERAL) {
14627                                Slog.v(TAG, "...setting INSTALL_EPHEMERAL install flag");
14628                            }
14629                            installFlags |= PackageManager.INSTALL_INSTANT_APP;
14630                            installFlags &= ~(PackageManager.INSTALL_EXTERNAL
14631                                    |PackageManager.INSTALL_INTERNAL);
14632                        } else {
14633                            // Make sure the flag for installing on external
14634                            // media is unset
14635                            installFlags |= PackageManager.INSTALL_INTERNAL;
14636                            installFlags &= ~PackageManager.INSTALL_EXTERNAL;
14637                        }
14638                    }
14639                }
14640            }
14641
14642            final InstallArgs args = createInstallArgs(this);
14643            mArgs = args;
14644
14645            if (ret == PackageManager.INSTALL_SUCCEEDED) {
14646                // TODO: http://b/22976637
14647                // Apps installed for "all" users use the device owner to verify the app
14648                UserHandle verifierUser = getUser();
14649                if (verifierUser == UserHandle.ALL) {
14650                    verifierUser = UserHandle.SYSTEM;
14651                }
14652
14653                /*
14654                 * Determine if we have any installed package verifiers. If we
14655                 * do, then we'll defer to them to verify the packages.
14656                 */
14657                final int requiredUid = mRequiredVerifierPackage == null ? -1
14658                        : getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING,
14659                                verifierUser.getIdentifier());
14660                if (!origin.existing && requiredUid != -1
14661                        && isVerificationEnabled(verifierUser.getIdentifier(), installFlags)) {
14662                    final Intent verification = new Intent(
14663                            Intent.ACTION_PACKAGE_NEEDS_VERIFICATION);
14664                    verification.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
14665                    verification.setDataAndType(Uri.fromFile(new File(origin.resolvedPath)),
14666                            PACKAGE_MIME_TYPE);
14667                    verification.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
14668
14669                    // Query all live verifiers based on current user state
14670                    final List<ResolveInfo> receivers = queryIntentReceiversInternal(verification,
14671                            PACKAGE_MIME_TYPE, 0, verifierUser.getIdentifier());
14672
14673                    if (DEBUG_VERIFY) {
14674                        Slog.d(TAG, "Found " + receivers.size() + " verifiers for intent "
14675                                + verification.toString() + " with " + pkgLite.verifiers.length
14676                                + " optional verifiers");
14677                    }
14678
14679                    final int verificationId = mPendingVerificationToken++;
14680
14681                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId);
14682
14683                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_PACKAGE,
14684                            installerPackageName);
14685
14686                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALL_FLAGS,
14687                            installFlags);
14688
14689                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_PACKAGE_NAME,
14690                            pkgLite.packageName);
14691
14692                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_VERSION_CODE,
14693                            pkgLite.versionCode);
14694
14695                    if (verificationInfo != null) {
14696                        if (verificationInfo.originatingUri != null) {
14697                            verification.putExtra(Intent.EXTRA_ORIGINATING_URI,
14698                                    verificationInfo.originatingUri);
14699                        }
14700                        if (verificationInfo.referrer != null) {
14701                            verification.putExtra(Intent.EXTRA_REFERRER,
14702                                    verificationInfo.referrer);
14703                        }
14704                        if (verificationInfo.originatingUid >= 0) {
14705                            verification.putExtra(Intent.EXTRA_ORIGINATING_UID,
14706                                    verificationInfo.originatingUid);
14707                        }
14708                        if (verificationInfo.installerUid >= 0) {
14709                            verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_UID,
14710                                    verificationInfo.installerUid);
14711                        }
14712                    }
14713
14714                    final PackageVerificationState verificationState = new PackageVerificationState(
14715                            requiredUid, args);
14716
14717                    mPendingVerification.append(verificationId, verificationState);
14718
14719                    final List<ComponentName> sufficientVerifiers = matchVerifiers(pkgLite,
14720                            receivers, verificationState);
14721
14722                    DeviceIdleController.LocalService idleController = getDeviceIdleController();
14723                    final long idleDuration = getVerificationTimeout();
14724
14725                    /*
14726                     * If any sufficient verifiers were listed in the package
14727                     * manifest, attempt to ask them.
14728                     */
14729                    if (sufficientVerifiers != null) {
14730                        final int N = sufficientVerifiers.size();
14731                        if (N == 0) {
14732                            Slog.i(TAG, "Additional verifiers required, but none installed.");
14733                            ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
14734                        } else {
14735                            for (int i = 0; i < N; i++) {
14736                                final ComponentName verifierComponent = sufficientVerifiers.get(i);
14737                                idleController.addPowerSaveTempWhitelistApp(Process.myUid(),
14738                                        verifierComponent.getPackageName(), idleDuration,
14739                                        verifierUser.getIdentifier(), false, "package verifier");
14740
14741                                final Intent sufficientIntent = new Intent(verification);
14742                                sufficientIntent.setComponent(verifierComponent);
14743                                mContext.sendBroadcastAsUser(sufficientIntent, verifierUser);
14744                            }
14745                        }
14746                    }
14747
14748                    final ComponentName requiredVerifierComponent = matchComponentForVerifier(
14749                            mRequiredVerifierPackage, receivers);
14750                    if (ret == PackageManager.INSTALL_SUCCEEDED
14751                            && mRequiredVerifierPackage != null) {
14752                        Trace.asyncTraceBegin(
14753                                TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId);
14754                        /*
14755                         * Send the intent to the required verification agent,
14756                         * but only start the verification timeout after the
14757                         * target BroadcastReceivers have run.
14758                         */
14759                        verification.setComponent(requiredVerifierComponent);
14760                        idleController.addPowerSaveTempWhitelistApp(Process.myUid(),
14761                                requiredVerifierComponent.getPackageName(), idleDuration,
14762                                verifierUser.getIdentifier(), false, "package verifier");
14763                        mContext.sendOrderedBroadcastAsUser(verification, verifierUser,
14764                                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
14765                                new BroadcastReceiver() {
14766                                    @Override
14767                                    public void onReceive(Context context, Intent intent) {
14768                                        final Message msg = mHandler
14769                                                .obtainMessage(CHECK_PENDING_VERIFICATION);
14770                                        msg.arg1 = verificationId;
14771                                        mHandler.sendMessageDelayed(msg, getVerificationTimeout());
14772                                    }
14773                                }, null, 0, null, null);
14774
14775                        /*
14776                         * We don't want the copy to proceed until verification
14777                         * succeeds, so null out this field.
14778                         */
14779                        mArgs = null;
14780                    }
14781                } else {
14782                    /*
14783                     * No package verification is enabled, so immediately start
14784                     * the remote call to initiate copy using temporary file.
14785                     */
14786                    ret = args.copyApk(mContainerService, true);
14787                }
14788            }
14789
14790            mRet = ret;
14791        }
14792
14793        @Override
14794        void handleReturnCode() {
14795            // If mArgs is null, then MCS couldn't be reached. When it
14796            // reconnects, it will try again to install. At that point, this
14797            // will succeed.
14798            if (mArgs != null) {
14799                processPendingInstall(mArgs, mRet);
14800            }
14801        }
14802
14803        @Override
14804        void handleServiceError() {
14805            mArgs = createInstallArgs(this);
14806            mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
14807        }
14808
14809        public boolean isForwardLocked() {
14810            return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
14811        }
14812    }
14813
14814    /**
14815     * Used during creation of InstallArgs
14816     *
14817     * @param installFlags package installation flags
14818     * @return true if should be installed on external storage
14819     */
14820    private static boolean installOnExternalAsec(int installFlags) {
14821        if ((installFlags & PackageManager.INSTALL_INTERNAL) != 0) {
14822            return false;
14823        }
14824        if ((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) {
14825            return true;
14826        }
14827        return false;
14828    }
14829
14830    /**
14831     * Used during creation of InstallArgs
14832     *
14833     * @param installFlags package installation flags
14834     * @return true if should be installed as forward locked
14835     */
14836    private static boolean installForwardLocked(int installFlags) {
14837        return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
14838    }
14839
14840    private InstallArgs createInstallArgs(InstallParams params) {
14841        if (params.move != null) {
14842            return new MoveInstallArgs(params);
14843        } else if (installOnExternalAsec(params.installFlags) || params.isForwardLocked()) {
14844            return new AsecInstallArgs(params);
14845        } else {
14846            return new FileInstallArgs(params);
14847        }
14848    }
14849
14850    /**
14851     * Create args that describe an existing installed package. Typically used
14852     * when cleaning up old installs, or used as a move source.
14853     */
14854    private InstallArgs createInstallArgsForExisting(int installFlags, String codePath,
14855            String resourcePath, String[] instructionSets) {
14856        final boolean isInAsec;
14857        if (installOnExternalAsec(installFlags)) {
14858            /* Apps on SD card are always in ASEC containers. */
14859            isInAsec = true;
14860        } else if (installForwardLocked(installFlags)
14861                && !codePath.startsWith(mDrmAppPrivateInstallDir.getAbsolutePath())) {
14862            /*
14863             * Forward-locked apps are only in ASEC containers if they're the
14864             * new style
14865             */
14866            isInAsec = true;
14867        } else {
14868            isInAsec = false;
14869        }
14870
14871        if (isInAsec) {
14872            return new AsecInstallArgs(codePath, instructionSets,
14873                    installOnExternalAsec(installFlags), installForwardLocked(installFlags));
14874        } else {
14875            return new FileInstallArgs(codePath, resourcePath, instructionSets);
14876        }
14877    }
14878
14879    static abstract class InstallArgs {
14880        /** @see InstallParams#origin */
14881        final OriginInfo origin;
14882        /** @see InstallParams#move */
14883        final MoveInfo move;
14884
14885        final IPackageInstallObserver2 observer;
14886        // Always refers to PackageManager flags only
14887        final int installFlags;
14888        final String installerPackageName;
14889        final String volumeUuid;
14890        final UserHandle user;
14891        final String abiOverride;
14892        final String[] installGrantPermissions;
14893        /** If non-null, drop an async trace when the install completes */
14894        final String traceMethod;
14895        final int traceCookie;
14896        final Certificate[][] certificates;
14897        final int installReason;
14898
14899        // The list of instruction sets supported by this app. This is currently
14900        // only used during the rmdex() phase to clean up resources. We can get rid of this
14901        // if we move dex files under the common app path.
14902        /* nullable */ String[] instructionSets;
14903
14904        InstallArgs(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer,
14905                int installFlags, String installerPackageName, String volumeUuid,
14906                UserHandle user, String[] instructionSets,
14907                String abiOverride, String[] installGrantPermissions,
14908                String traceMethod, int traceCookie, Certificate[][] certificates,
14909                int installReason) {
14910            this.origin = origin;
14911            this.move = move;
14912            this.installFlags = installFlags;
14913            this.observer = observer;
14914            this.installerPackageName = installerPackageName;
14915            this.volumeUuid = volumeUuid;
14916            this.user = user;
14917            this.instructionSets = instructionSets;
14918            this.abiOverride = abiOverride;
14919            this.installGrantPermissions = installGrantPermissions;
14920            this.traceMethod = traceMethod;
14921            this.traceCookie = traceCookie;
14922            this.certificates = certificates;
14923            this.installReason = installReason;
14924        }
14925
14926        abstract int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException;
14927        abstract int doPreInstall(int status);
14928
14929        /**
14930         * Rename package into final resting place. All paths on the given
14931         * scanned package should be updated to reflect the rename.
14932         */
14933        abstract boolean doRename(int status, PackageParser.Package pkg, String oldCodePath);
14934        abstract int doPostInstall(int status, int uid);
14935
14936        /** @see PackageSettingBase#codePathString */
14937        abstract String getCodePath();
14938        /** @see PackageSettingBase#resourcePathString */
14939        abstract String getResourcePath();
14940
14941        // Need installer lock especially for dex file removal.
14942        abstract void cleanUpResourcesLI();
14943        abstract boolean doPostDeleteLI(boolean delete);
14944
14945        /**
14946         * Called before the source arguments are copied. This is used mostly
14947         * for MoveParams when it needs to read the source file to put it in the
14948         * destination.
14949         */
14950        int doPreCopy() {
14951            return PackageManager.INSTALL_SUCCEEDED;
14952        }
14953
14954        /**
14955         * Called after the source arguments are copied. This is used mostly for
14956         * MoveParams when it needs to read the source file to put it in the
14957         * destination.
14958         */
14959        int doPostCopy(int uid) {
14960            return PackageManager.INSTALL_SUCCEEDED;
14961        }
14962
14963        protected boolean isFwdLocked() {
14964            return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
14965        }
14966
14967        protected boolean isExternalAsec() {
14968            return (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
14969        }
14970
14971        protected boolean isEphemeral() {
14972            return (installFlags & PackageManager.INSTALL_INSTANT_APP) != 0;
14973        }
14974
14975        UserHandle getUser() {
14976            return user;
14977        }
14978    }
14979
14980    private void removeDexFiles(List<String> allCodePaths, String[] instructionSets) {
14981        if (!allCodePaths.isEmpty()) {
14982            if (instructionSets == null) {
14983                throw new IllegalStateException("instructionSet == null");
14984            }
14985            String[] dexCodeInstructionSets = getDexCodeInstructionSets(instructionSets);
14986            for (String codePath : allCodePaths) {
14987                for (String dexCodeInstructionSet : dexCodeInstructionSets) {
14988                    try {
14989                        mInstaller.rmdex(codePath, dexCodeInstructionSet);
14990                    } catch (InstallerException ignored) {
14991                    }
14992                }
14993            }
14994        }
14995    }
14996
14997    /**
14998     * Logic to handle installation of non-ASEC applications, including copying
14999     * and renaming logic.
15000     */
15001    class FileInstallArgs extends InstallArgs {
15002        private File codeFile;
15003        private File resourceFile;
15004
15005        // Example topology:
15006        // /data/app/com.example/base.apk
15007        // /data/app/com.example/split_foo.apk
15008        // /data/app/com.example/lib/arm/libfoo.so
15009        // /data/app/com.example/lib/arm64/libfoo.so
15010        // /data/app/com.example/dalvik/arm/base.apk@classes.dex
15011
15012        /** New install */
15013        FileInstallArgs(InstallParams params) {
15014            super(params.origin, params.move, params.observer, params.installFlags,
15015                    params.installerPackageName, params.volumeUuid,
15016                    params.getUser(), null /*instructionSets*/, params.packageAbiOverride,
15017                    params.grantedRuntimePermissions,
15018                    params.traceMethod, params.traceCookie, params.certificates,
15019                    params.installReason);
15020            if (isFwdLocked()) {
15021                throw new IllegalArgumentException("Forward locking only supported in ASEC");
15022            }
15023        }
15024
15025        /** Existing install */
15026        FileInstallArgs(String codePath, String resourcePath, String[] instructionSets) {
15027            super(OriginInfo.fromNothing(), null, null, 0, null, null, null, instructionSets,
15028                    null, null, null, 0, null /*certificates*/,
15029                    PackageManager.INSTALL_REASON_UNKNOWN);
15030            this.codeFile = (codePath != null) ? new File(codePath) : null;
15031            this.resourceFile = (resourcePath != null) ? new File(resourcePath) : null;
15032        }
15033
15034        int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
15035            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyApk");
15036            try {
15037                return doCopyApk(imcs, temp);
15038            } finally {
15039                Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
15040            }
15041        }
15042
15043        private int doCopyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
15044            if (origin.staged) {
15045                if (DEBUG_INSTALL) Slog.d(TAG, origin.file + " already staged; skipping copy");
15046                codeFile = origin.file;
15047                resourceFile = origin.file;
15048                return PackageManager.INSTALL_SUCCEEDED;
15049            }
15050
15051            try {
15052                final boolean isEphemeral = (installFlags & PackageManager.INSTALL_INSTANT_APP) != 0;
15053                final File tempDir =
15054                        mInstallerService.allocateStageDirLegacy(volumeUuid, isEphemeral);
15055                codeFile = tempDir;
15056                resourceFile = tempDir;
15057            } catch (IOException e) {
15058                Slog.w(TAG, "Failed to create copy file: " + e);
15059                return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
15060            }
15061
15062            final IParcelFileDescriptorFactory target = new IParcelFileDescriptorFactory.Stub() {
15063                @Override
15064                public ParcelFileDescriptor open(String name, int mode) throws RemoteException {
15065                    if (!FileUtils.isValidExtFilename(name)) {
15066                        throw new IllegalArgumentException("Invalid filename: " + name);
15067                    }
15068                    try {
15069                        final File file = new File(codeFile, name);
15070                        final FileDescriptor fd = Os.open(file.getAbsolutePath(),
15071                                O_RDWR | O_CREAT, 0644);
15072                        Os.chmod(file.getAbsolutePath(), 0644);
15073                        return new ParcelFileDescriptor(fd);
15074                    } catch (ErrnoException e) {
15075                        throw new RemoteException("Failed to open: " + e.getMessage());
15076                    }
15077                }
15078            };
15079
15080            int ret = PackageManager.INSTALL_SUCCEEDED;
15081            ret = imcs.copyPackage(origin.file.getAbsolutePath(), target);
15082            if (ret != PackageManager.INSTALL_SUCCEEDED) {
15083                Slog.e(TAG, "Failed to copy package");
15084                return ret;
15085            }
15086
15087            final File libraryRoot = new File(codeFile, LIB_DIR_NAME);
15088            NativeLibraryHelper.Handle handle = null;
15089            try {
15090                handle = NativeLibraryHelper.Handle.create(codeFile);
15091                ret = NativeLibraryHelper.copyNativeBinariesWithOverride(handle, libraryRoot,
15092                        abiOverride);
15093            } catch (IOException e) {
15094                Slog.e(TAG, "Copying native libraries failed", e);
15095                ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
15096            } finally {
15097                IoUtils.closeQuietly(handle);
15098            }
15099
15100            return ret;
15101        }
15102
15103        int doPreInstall(int status) {
15104            if (status != PackageManager.INSTALL_SUCCEEDED) {
15105                cleanUp();
15106            }
15107            return status;
15108        }
15109
15110        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
15111            if (status != PackageManager.INSTALL_SUCCEEDED) {
15112                cleanUp();
15113                return false;
15114            }
15115
15116            final File targetDir = codeFile.getParentFile();
15117            final File beforeCodeFile = codeFile;
15118            final File afterCodeFile = getNextCodePath(targetDir, pkg.packageName);
15119
15120            if (DEBUG_INSTALL) Slog.d(TAG, "Renaming " + beforeCodeFile + " to " + afterCodeFile);
15121            try {
15122                Os.rename(beforeCodeFile.getAbsolutePath(), afterCodeFile.getAbsolutePath());
15123            } catch (ErrnoException e) {
15124                Slog.w(TAG, "Failed to rename", e);
15125                return false;
15126            }
15127
15128            if (!SELinux.restoreconRecursive(afterCodeFile)) {
15129                Slog.w(TAG, "Failed to restorecon");
15130                return false;
15131            }
15132
15133            // Reflect the rename internally
15134            codeFile = afterCodeFile;
15135            resourceFile = afterCodeFile;
15136
15137            // Reflect the rename in scanned details
15138            pkg.setCodePath(afterCodeFile.getAbsolutePath());
15139            pkg.setBaseCodePath(FileUtils.rewriteAfterRename(beforeCodeFile,
15140                    afterCodeFile, pkg.baseCodePath));
15141            pkg.setSplitCodePaths(FileUtils.rewriteAfterRename(beforeCodeFile,
15142                    afterCodeFile, pkg.splitCodePaths));
15143
15144            // Reflect the rename in app info
15145            pkg.setApplicationVolumeUuid(pkg.volumeUuid);
15146            pkg.setApplicationInfoCodePath(pkg.codePath);
15147            pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
15148            pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
15149            pkg.setApplicationInfoResourcePath(pkg.codePath);
15150            pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath);
15151            pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
15152
15153            return true;
15154        }
15155
15156        int doPostInstall(int status, int uid) {
15157            if (status != PackageManager.INSTALL_SUCCEEDED) {
15158                cleanUp();
15159            }
15160            return status;
15161        }
15162
15163        @Override
15164        String getCodePath() {
15165            return (codeFile != null) ? codeFile.getAbsolutePath() : null;
15166        }
15167
15168        @Override
15169        String getResourcePath() {
15170            return (resourceFile != null) ? resourceFile.getAbsolutePath() : null;
15171        }
15172
15173        private boolean cleanUp() {
15174            if (codeFile == null || !codeFile.exists()) {
15175                return false;
15176            }
15177
15178            removeCodePathLI(codeFile);
15179
15180            if (resourceFile != null && !FileUtils.contains(codeFile, resourceFile)) {
15181                resourceFile.delete();
15182            }
15183
15184            return true;
15185        }
15186
15187        void cleanUpResourcesLI() {
15188            // Try enumerating all code paths before deleting
15189            List<String> allCodePaths = Collections.EMPTY_LIST;
15190            if (codeFile != null && codeFile.exists()) {
15191                try {
15192                    final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0);
15193                    allCodePaths = pkg.getAllCodePaths();
15194                } catch (PackageParserException e) {
15195                    // Ignored; we tried our best
15196                }
15197            }
15198
15199            cleanUp();
15200            removeDexFiles(allCodePaths, instructionSets);
15201        }
15202
15203        boolean doPostDeleteLI(boolean delete) {
15204            // XXX err, shouldn't we respect the delete flag?
15205            cleanUpResourcesLI();
15206            return true;
15207        }
15208    }
15209
15210    private boolean isAsecExternal(String cid) {
15211        final String asecPath = PackageHelper.getSdFilesystem(cid);
15212        return !asecPath.startsWith(mAsecInternalPath);
15213    }
15214
15215    private static void maybeThrowExceptionForMultiArchCopy(String message, int copyRet) throws
15216            PackageManagerException {
15217        if (copyRet < 0) {
15218            if (copyRet != PackageManager.NO_NATIVE_LIBRARIES &&
15219                    copyRet != PackageManager.INSTALL_FAILED_NO_MATCHING_ABIS) {
15220                throw new PackageManagerException(copyRet, message);
15221            }
15222        }
15223    }
15224
15225    /**
15226     * Extract the StorageManagerService "container ID" from the full code path of an
15227     * .apk.
15228     */
15229    static String cidFromCodePath(String fullCodePath) {
15230        int eidx = fullCodePath.lastIndexOf("/");
15231        String subStr1 = fullCodePath.substring(0, eidx);
15232        int sidx = subStr1.lastIndexOf("/");
15233        return subStr1.substring(sidx+1, eidx);
15234    }
15235
15236    /**
15237     * Logic to handle installation of ASEC applications, including copying and
15238     * renaming logic.
15239     */
15240    class AsecInstallArgs extends InstallArgs {
15241        static final String RES_FILE_NAME = "pkg.apk";
15242        static final String PUBLIC_RES_FILE_NAME = "res.zip";
15243
15244        String cid;
15245        String packagePath;
15246        String resourcePath;
15247
15248        /** New install */
15249        AsecInstallArgs(InstallParams params) {
15250            super(params.origin, params.move, params.observer, params.installFlags,
15251                    params.installerPackageName, params.volumeUuid,
15252                    params.getUser(), null /* instruction sets */, params.packageAbiOverride,
15253                    params.grantedRuntimePermissions,
15254                    params.traceMethod, params.traceCookie, params.certificates,
15255                    params.installReason);
15256        }
15257
15258        /** Existing install */
15259        AsecInstallArgs(String fullCodePath, String[] instructionSets,
15260                        boolean isExternal, boolean isForwardLocked) {
15261            super(OriginInfo.fromNothing(), null, null, (isExternal ? INSTALL_EXTERNAL : 0)
15262                    | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null,
15263                    instructionSets, null, null, null, 0, null /*certificates*/,
15264                    PackageManager.INSTALL_REASON_UNKNOWN);
15265            // Hackily pretend we're still looking at a full code path
15266            if (!fullCodePath.endsWith(RES_FILE_NAME)) {
15267                fullCodePath = new File(fullCodePath, RES_FILE_NAME).getAbsolutePath();
15268            }
15269
15270            // Extract cid from fullCodePath
15271            int eidx = fullCodePath.lastIndexOf("/");
15272            String subStr1 = fullCodePath.substring(0, eidx);
15273            int sidx = subStr1.lastIndexOf("/");
15274            cid = subStr1.substring(sidx+1, eidx);
15275            setMountPath(subStr1);
15276        }
15277
15278        AsecInstallArgs(String cid, String[] instructionSets, boolean isForwardLocked) {
15279            super(OriginInfo.fromNothing(), null, null, (isAsecExternal(cid) ? INSTALL_EXTERNAL : 0)
15280                    | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null,
15281                    instructionSets, null, null, null, 0, null /*certificates*/,
15282                    PackageManager.INSTALL_REASON_UNKNOWN);
15283            this.cid = cid;
15284            setMountPath(PackageHelper.getSdDir(cid));
15285        }
15286
15287        void createCopyFile() {
15288            cid = mInstallerService.allocateExternalStageCidLegacy();
15289        }
15290
15291        int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
15292            if (origin.staged && origin.cid != null) {
15293                if (DEBUG_INSTALL) Slog.d(TAG, origin.cid + " already staged; skipping copy");
15294                cid = origin.cid;
15295                setMountPath(PackageHelper.getSdDir(cid));
15296                return PackageManager.INSTALL_SUCCEEDED;
15297            }
15298
15299            if (temp) {
15300                createCopyFile();
15301            } else {
15302                /*
15303                 * Pre-emptively destroy the container since it's destroyed if
15304                 * copying fails due to it existing anyway.
15305                 */
15306                PackageHelper.destroySdDir(cid);
15307            }
15308
15309            final String newMountPath = imcs.copyPackageToContainer(
15310                    origin.file.getAbsolutePath(), cid, getEncryptKey(), isExternalAsec(),
15311                    isFwdLocked(), deriveAbiOverride(abiOverride, null /* settings */));
15312
15313            if (newMountPath != null) {
15314                setMountPath(newMountPath);
15315                return PackageManager.INSTALL_SUCCEEDED;
15316            } else {
15317                return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
15318            }
15319        }
15320
15321        @Override
15322        String getCodePath() {
15323            return packagePath;
15324        }
15325
15326        @Override
15327        String getResourcePath() {
15328            return resourcePath;
15329        }
15330
15331        int doPreInstall(int status) {
15332            if (status != PackageManager.INSTALL_SUCCEEDED) {
15333                // Destroy container
15334                PackageHelper.destroySdDir(cid);
15335            } else {
15336                boolean mounted = PackageHelper.isContainerMounted(cid);
15337                if (!mounted) {
15338                    String newMountPath = PackageHelper.mountSdDir(cid, getEncryptKey(),
15339                            Process.SYSTEM_UID);
15340                    if (newMountPath != null) {
15341                        setMountPath(newMountPath);
15342                    } else {
15343                        return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
15344                    }
15345                }
15346            }
15347            return status;
15348        }
15349
15350        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
15351            String newCacheId = getNextCodePath(oldCodePath, pkg.packageName, "/" + RES_FILE_NAME);
15352            String newMountPath = null;
15353            if (PackageHelper.isContainerMounted(cid)) {
15354                // Unmount the container
15355                if (!PackageHelper.unMountSdDir(cid)) {
15356                    Slog.i(TAG, "Failed to unmount " + cid + " before renaming");
15357                    return false;
15358                }
15359            }
15360            if (!PackageHelper.renameSdDir(cid, newCacheId)) {
15361                Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId +
15362                        " which might be stale. Will try to clean up.");
15363                // Clean up the stale container and proceed to recreate.
15364                if (!PackageHelper.destroySdDir(newCacheId)) {
15365                    Slog.e(TAG, "Very strange. Cannot clean up stale container " + newCacheId);
15366                    return false;
15367                }
15368                // Successfully cleaned up stale container. Try to rename again.
15369                if (!PackageHelper.renameSdDir(cid, newCacheId)) {
15370                    Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId
15371                            + " inspite of cleaning it up.");
15372                    return false;
15373                }
15374            }
15375            if (!PackageHelper.isContainerMounted(newCacheId)) {
15376                Slog.w(TAG, "Mounting container " + newCacheId);
15377                newMountPath = PackageHelper.mountSdDir(newCacheId,
15378                        getEncryptKey(), Process.SYSTEM_UID);
15379            } else {
15380                newMountPath = PackageHelper.getSdDir(newCacheId);
15381            }
15382            if (newMountPath == null) {
15383                Slog.w(TAG, "Failed to get cache path for  " + newCacheId);
15384                return false;
15385            }
15386            Log.i(TAG, "Succesfully renamed " + cid +
15387                    " to " + newCacheId +
15388                    " at new path: " + newMountPath);
15389            cid = newCacheId;
15390
15391            final File beforeCodeFile = new File(packagePath);
15392            setMountPath(newMountPath);
15393            final File afterCodeFile = new File(packagePath);
15394
15395            // Reflect the rename in scanned details
15396            pkg.setCodePath(afterCodeFile.getAbsolutePath());
15397            pkg.setBaseCodePath(FileUtils.rewriteAfterRename(beforeCodeFile,
15398                    afterCodeFile, pkg.baseCodePath));
15399            pkg.setSplitCodePaths(FileUtils.rewriteAfterRename(beforeCodeFile,
15400                    afterCodeFile, pkg.splitCodePaths));
15401
15402            // Reflect the rename in app info
15403            pkg.setApplicationVolumeUuid(pkg.volumeUuid);
15404            pkg.setApplicationInfoCodePath(pkg.codePath);
15405            pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
15406            pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
15407            pkg.setApplicationInfoResourcePath(pkg.codePath);
15408            pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath);
15409            pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
15410
15411            return true;
15412        }
15413
15414        private void setMountPath(String mountPath) {
15415            final File mountFile = new File(mountPath);
15416
15417            final File monolithicFile = new File(mountFile, RES_FILE_NAME);
15418            if (monolithicFile.exists()) {
15419                packagePath = monolithicFile.getAbsolutePath();
15420                if (isFwdLocked()) {
15421                    resourcePath = new File(mountFile, PUBLIC_RES_FILE_NAME).getAbsolutePath();
15422                } else {
15423                    resourcePath = packagePath;
15424                }
15425            } else {
15426                packagePath = mountFile.getAbsolutePath();
15427                resourcePath = packagePath;
15428            }
15429        }
15430
15431        int doPostInstall(int status, int uid) {
15432            if (status != PackageManager.INSTALL_SUCCEEDED) {
15433                cleanUp();
15434            } else {
15435                final int groupOwner;
15436                final String protectedFile;
15437                if (isFwdLocked()) {
15438                    groupOwner = UserHandle.getSharedAppGid(uid);
15439                    protectedFile = RES_FILE_NAME;
15440                } else {
15441                    groupOwner = -1;
15442                    protectedFile = null;
15443                }
15444
15445                if (uid < Process.FIRST_APPLICATION_UID
15446                        || !PackageHelper.fixSdPermissions(cid, groupOwner, protectedFile)) {
15447                    Slog.e(TAG, "Failed to finalize " + cid);
15448                    PackageHelper.destroySdDir(cid);
15449                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
15450                }
15451
15452                boolean mounted = PackageHelper.isContainerMounted(cid);
15453                if (!mounted) {
15454                    PackageHelper.mountSdDir(cid, getEncryptKey(), Process.myUid());
15455                }
15456            }
15457            return status;
15458        }
15459
15460        private void cleanUp() {
15461            if (DEBUG_SD_INSTALL) Slog.i(TAG, "cleanUp");
15462
15463            // Destroy secure container
15464            PackageHelper.destroySdDir(cid);
15465        }
15466
15467        private List<String> getAllCodePaths() {
15468            final File codeFile = new File(getCodePath());
15469            if (codeFile != null && codeFile.exists()) {
15470                try {
15471                    final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0);
15472                    return pkg.getAllCodePaths();
15473                } catch (PackageParserException e) {
15474                    // Ignored; we tried our best
15475                }
15476            }
15477            return Collections.EMPTY_LIST;
15478        }
15479
15480        void cleanUpResourcesLI() {
15481            // Enumerate all code paths before deleting
15482            cleanUpResourcesLI(getAllCodePaths());
15483        }
15484
15485        private void cleanUpResourcesLI(List<String> allCodePaths) {
15486            cleanUp();
15487            removeDexFiles(allCodePaths, instructionSets);
15488        }
15489
15490        String getPackageName() {
15491            return getAsecPackageName(cid);
15492        }
15493
15494        boolean doPostDeleteLI(boolean delete) {
15495            if (DEBUG_SD_INSTALL) Slog.i(TAG, "doPostDeleteLI() del=" + delete);
15496            final List<String> allCodePaths = getAllCodePaths();
15497            boolean mounted = PackageHelper.isContainerMounted(cid);
15498            if (mounted) {
15499                // Unmount first
15500                if (PackageHelper.unMountSdDir(cid)) {
15501                    mounted = false;
15502                }
15503            }
15504            if (!mounted && delete) {
15505                cleanUpResourcesLI(allCodePaths);
15506            }
15507            return !mounted;
15508        }
15509
15510        @Override
15511        int doPreCopy() {
15512            if (isFwdLocked()) {
15513                if (!PackageHelper.fixSdPermissions(cid, getPackageUid(DEFAULT_CONTAINER_PACKAGE,
15514                        MATCH_SYSTEM_ONLY, UserHandle.USER_SYSTEM), RES_FILE_NAME)) {
15515                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
15516                }
15517            }
15518
15519            return PackageManager.INSTALL_SUCCEEDED;
15520        }
15521
15522        @Override
15523        int doPostCopy(int uid) {
15524            if (isFwdLocked()) {
15525                if (uid < Process.FIRST_APPLICATION_UID
15526                        || !PackageHelper.fixSdPermissions(cid, UserHandle.getSharedAppGid(uid),
15527                                RES_FILE_NAME)) {
15528                    Slog.e(TAG, "Failed to finalize " + cid);
15529                    PackageHelper.destroySdDir(cid);
15530                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
15531                }
15532            }
15533
15534            return PackageManager.INSTALL_SUCCEEDED;
15535        }
15536    }
15537
15538    /**
15539     * Logic to handle movement of existing installed applications.
15540     */
15541    class MoveInstallArgs extends InstallArgs {
15542        private File codeFile;
15543        private File resourceFile;
15544
15545        /** New install */
15546        MoveInstallArgs(InstallParams params) {
15547            super(params.origin, params.move, params.observer, params.installFlags,
15548                    params.installerPackageName, params.volumeUuid,
15549                    params.getUser(), null /* instruction sets */, params.packageAbiOverride,
15550                    params.grantedRuntimePermissions,
15551                    params.traceMethod, params.traceCookie, params.certificates,
15552                    params.installReason);
15553        }
15554
15555        int copyApk(IMediaContainerService imcs, boolean temp) {
15556            if (DEBUG_INSTALL) Slog.d(TAG, "Moving " + move.packageName + " from "
15557                    + move.fromUuid + " to " + move.toUuid);
15558            synchronized (mInstaller) {
15559                try {
15560                    mInstaller.moveCompleteApp(move.fromUuid, move.toUuid, move.packageName,
15561                            move.dataAppName, move.appId, move.seinfo, move.targetSdkVersion);
15562                } catch (InstallerException e) {
15563                    Slog.w(TAG, "Failed to move app", e);
15564                    return PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
15565                }
15566            }
15567
15568            codeFile = new File(Environment.getDataAppDirectory(move.toUuid), move.dataAppName);
15569            resourceFile = codeFile;
15570            if (DEBUG_INSTALL) Slog.d(TAG, "codeFile after move is " + codeFile);
15571
15572            return PackageManager.INSTALL_SUCCEEDED;
15573        }
15574
15575        int doPreInstall(int status) {
15576            if (status != PackageManager.INSTALL_SUCCEEDED) {
15577                cleanUp(move.toUuid);
15578            }
15579            return status;
15580        }
15581
15582        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
15583            if (status != PackageManager.INSTALL_SUCCEEDED) {
15584                cleanUp(move.toUuid);
15585                return false;
15586            }
15587
15588            // Reflect the move in app info
15589            pkg.setApplicationVolumeUuid(pkg.volumeUuid);
15590            pkg.setApplicationInfoCodePath(pkg.codePath);
15591            pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
15592            pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
15593            pkg.setApplicationInfoResourcePath(pkg.codePath);
15594            pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath);
15595            pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
15596
15597            return true;
15598        }
15599
15600        int doPostInstall(int status, int uid) {
15601            if (status == PackageManager.INSTALL_SUCCEEDED) {
15602                cleanUp(move.fromUuid);
15603            } else {
15604                cleanUp(move.toUuid);
15605            }
15606            return status;
15607        }
15608
15609        @Override
15610        String getCodePath() {
15611            return (codeFile != null) ? codeFile.getAbsolutePath() : null;
15612        }
15613
15614        @Override
15615        String getResourcePath() {
15616            return (resourceFile != null) ? resourceFile.getAbsolutePath() : null;
15617        }
15618
15619        private boolean cleanUp(String volumeUuid) {
15620            final File codeFile = new File(Environment.getDataAppDirectory(volumeUuid),
15621                    move.dataAppName);
15622            Slog.d(TAG, "Cleaning up " + move.packageName + " on " + volumeUuid);
15623            final int[] userIds = sUserManager.getUserIds();
15624            synchronized (mInstallLock) {
15625                // Clean up both app data and code
15626                // All package moves are frozen until finished
15627                for (int userId : userIds) {
15628                    try {
15629                        mInstaller.destroyAppData(volumeUuid, move.packageName, userId,
15630                                StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE, 0);
15631                    } catch (InstallerException e) {
15632                        Slog.w(TAG, String.valueOf(e));
15633                    }
15634                }
15635                removeCodePathLI(codeFile);
15636            }
15637            return true;
15638        }
15639
15640        void cleanUpResourcesLI() {
15641            throw new UnsupportedOperationException();
15642        }
15643
15644        boolean doPostDeleteLI(boolean delete) {
15645            throw new UnsupportedOperationException();
15646        }
15647    }
15648
15649    static String getAsecPackageName(String packageCid) {
15650        int idx = packageCid.lastIndexOf("-");
15651        if (idx == -1) {
15652            return packageCid;
15653        }
15654        return packageCid.substring(0, idx);
15655    }
15656
15657    // Utility method used to create code paths based on package name and available index.
15658    private static String getNextCodePath(String oldCodePath, String prefix, String suffix) {
15659        String idxStr = "";
15660        int idx = 1;
15661        // Fall back to default value of idx=1 if prefix is not
15662        // part of oldCodePath
15663        if (oldCodePath != null) {
15664            String subStr = oldCodePath;
15665            // Drop the suffix right away
15666            if (suffix != null && subStr.endsWith(suffix)) {
15667                subStr = subStr.substring(0, subStr.length() - suffix.length());
15668            }
15669            // If oldCodePath already contains prefix find out the
15670            // ending index to either increment or decrement.
15671            int sidx = subStr.lastIndexOf(prefix);
15672            if (sidx != -1) {
15673                subStr = subStr.substring(sidx + prefix.length());
15674                if (subStr != null) {
15675                    if (subStr.startsWith(INSTALL_PACKAGE_SUFFIX)) {
15676                        subStr = subStr.substring(INSTALL_PACKAGE_SUFFIX.length());
15677                    }
15678                    try {
15679                        idx = Integer.parseInt(subStr);
15680                        if (idx <= 1) {
15681                            idx++;
15682                        } else {
15683                            idx--;
15684                        }
15685                    } catch(NumberFormatException e) {
15686                    }
15687                }
15688            }
15689        }
15690        idxStr = INSTALL_PACKAGE_SUFFIX + Integer.toString(idx);
15691        return prefix + idxStr;
15692    }
15693
15694    private File getNextCodePath(File targetDir, String packageName) {
15695        File result;
15696        SecureRandom random = new SecureRandom();
15697        byte[] bytes = new byte[16];
15698        do {
15699            random.nextBytes(bytes);
15700            String suffix = Base64.encodeToString(bytes, Base64.URL_SAFE | Base64.NO_WRAP);
15701            result = new File(targetDir, packageName + "-" + suffix);
15702        } while (result.exists());
15703        return result;
15704    }
15705
15706    // Utility method that returns the relative package path with respect
15707    // to the installation directory. Like say for /data/data/com.test-1.apk
15708    // string com.test-1 is returned.
15709    static String deriveCodePathName(String codePath) {
15710        if (codePath == null) {
15711            return null;
15712        }
15713        final File codeFile = new File(codePath);
15714        final String name = codeFile.getName();
15715        if (codeFile.isDirectory()) {
15716            return name;
15717        } else if (name.endsWith(".apk") || name.endsWith(".tmp")) {
15718            final int lastDot = name.lastIndexOf('.');
15719            return name.substring(0, lastDot);
15720        } else {
15721            Slog.w(TAG, "Odd, " + codePath + " doesn't look like an APK");
15722            return null;
15723        }
15724    }
15725
15726    static class PackageInstalledInfo {
15727        String name;
15728        int uid;
15729        // The set of users that originally had this package installed.
15730        int[] origUsers;
15731        // The set of users that now have this package installed.
15732        int[] newUsers;
15733        PackageParser.Package pkg;
15734        int returnCode;
15735        String returnMsg;
15736        PackageRemovedInfo removedInfo;
15737        ArrayMap<String, PackageInstalledInfo> addedChildPackages;
15738
15739        public void setError(int code, String msg) {
15740            setReturnCode(code);
15741            setReturnMessage(msg);
15742            Slog.w(TAG, msg);
15743        }
15744
15745        public void setError(String msg, PackageParserException e) {
15746            setReturnCode(e.error);
15747            setReturnMessage(ExceptionUtils.getCompleteMessage(msg, e));
15748            Slog.w(TAG, msg, e);
15749        }
15750
15751        public void setError(String msg, PackageManagerException e) {
15752            returnCode = e.error;
15753            setReturnMessage(ExceptionUtils.getCompleteMessage(msg, e));
15754            Slog.w(TAG, msg, e);
15755        }
15756
15757        public void setReturnCode(int returnCode) {
15758            this.returnCode = returnCode;
15759            final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0;
15760            for (int i = 0; i < childCount; i++) {
15761                addedChildPackages.valueAt(i).returnCode = returnCode;
15762            }
15763        }
15764
15765        private void setReturnMessage(String returnMsg) {
15766            this.returnMsg = returnMsg;
15767            final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0;
15768            for (int i = 0; i < childCount; i++) {
15769                addedChildPackages.valueAt(i).returnMsg = returnMsg;
15770            }
15771        }
15772
15773        // In some error cases we want to convey more info back to the observer
15774        String origPackage;
15775        String origPermission;
15776    }
15777
15778    /*
15779     * Install a non-existing package.
15780     */
15781    private void installNewPackageLIF(PackageParser.Package pkg, final int policyFlags,
15782            int scanFlags, UserHandle user, String installerPackageName, String volumeUuid,
15783            PackageInstalledInfo res, int installReason) {
15784        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installNewPackage");
15785
15786        // Remember this for later, in case we need to rollback this install
15787        String pkgName = pkg.packageName;
15788
15789        if (DEBUG_INSTALL) Slog.d(TAG, "installNewPackageLI: " + pkg);
15790
15791        synchronized(mPackages) {
15792            final String renamedPackage = mSettings.getRenamedPackageLPr(pkgName);
15793            if (renamedPackage != null) {
15794                // A package with the same name is already installed, though
15795                // it has been renamed to an older name.  The package we
15796                // are trying to install should be installed as an update to
15797                // the existing one, but that has not been requested, so bail.
15798                res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName
15799                        + " without first uninstalling package running as "
15800                        + renamedPackage);
15801                return;
15802            }
15803            if (mPackages.containsKey(pkgName)) {
15804                // Don't allow installation over an existing package with the same name.
15805                res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName
15806                        + " without first uninstalling.");
15807                return;
15808            }
15809        }
15810
15811        try {
15812            PackageParser.Package newPackage = scanPackageTracedLI(pkg, policyFlags, scanFlags,
15813                    System.currentTimeMillis(), user);
15814
15815            updateSettingsLI(newPackage, installerPackageName, null, res, user, installReason);
15816
15817            if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
15818                prepareAppDataAfterInstallLIF(newPackage);
15819
15820            } else {
15821                // Remove package from internal structures, but keep around any
15822                // data that might have already existed
15823                deletePackageLIF(pkgName, UserHandle.ALL, false, null,
15824                        PackageManager.DELETE_KEEP_DATA, res.removedInfo, true, null);
15825            }
15826        } catch (PackageManagerException e) {
15827            res.setError("Package couldn't be installed in " + pkg.codePath, e);
15828        }
15829
15830        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
15831    }
15832
15833    private boolean shouldCheckUpgradeKeySetLP(PackageSetting oldPs, int scanFlags) {
15834        // Can't rotate keys during boot or if sharedUser.
15835        if (oldPs == null || (scanFlags&SCAN_INITIAL) != 0 || oldPs.sharedUser != null
15836                || !oldPs.keySetData.isUsingUpgradeKeySets()) {
15837            return false;
15838        }
15839        // app is using upgradeKeySets; make sure all are valid
15840        KeySetManagerService ksms = mSettings.mKeySetManagerService;
15841        long[] upgradeKeySets = oldPs.keySetData.getUpgradeKeySets();
15842        for (int i = 0; i < upgradeKeySets.length; i++) {
15843            if (!ksms.isIdValidKeySetId(upgradeKeySets[i])) {
15844                Slog.wtf(TAG, "Package "
15845                         + (oldPs.name != null ? oldPs.name : "<null>")
15846                         + " contains upgrade-key-set reference to unknown key-set: "
15847                         + upgradeKeySets[i]
15848                         + " reverting to signatures check.");
15849                return false;
15850            }
15851        }
15852        return true;
15853    }
15854
15855    private boolean checkUpgradeKeySetLP(PackageSetting oldPS, PackageParser.Package newPkg) {
15856        // Upgrade keysets are being used.  Determine if new package has a superset of the
15857        // required keys.
15858        long[] upgradeKeySets = oldPS.keySetData.getUpgradeKeySets();
15859        KeySetManagerService ksms = mSettings.mKeySetManagerService;
15860        for (int i = 0; i < upgradeKeySets.length; i++) {
15861            Set<PublicKey> upgradeSet = ksms.getPublicKeysFromKeySetLPr(upgradeKeySets[i]);
15862            if (upgradeSet != null && newPkg.mSigningKeys.containsAll(upgradeSet)) {
15863                return true;
15864            }
15865        }
15866        return false;
15867    }
15868
15869    private static void updateDigest(MessageDigest digest, File file) throws IOException {
15870        try (DigestInputStream digestStream =
15871                new DigestInputStream(new FileInputStream(file), digest)) {
15872            while (digestStream.read() != -1) {} // nothing to do; just plow through the file
15873        }
15874    }
15875
15876    private void replacePackageLIF(PackageParser.Package pkg, final int policyFlags, int scanFlags,
15877            UserHandle user, String installerPackageName, PackageInstalledInfo res,
15878            int installReason) {
15879        final boolean isInstantApp = (scanFlags & SCAN_AS_INSTANT_APP) != 0;
15880
15881        final PackageParser.Package oldPackage;
15882        final String pkgName = pkg.packageName;
15883        final int[] allUsers;
15884        final int[] installedUsers;
15885
15886        synchronized(mPackages) {
15887            oldPackage = mPackages.get(pkgName);
15888            if (DEBUG_INSTALL) Slog.d(TAG, "replacePackageLI: new=" + pkg + ", old=" + oldPackage);
15889
15890            // don't allow upgrade to target a release SDK from a pre-release SDK
15891            final boolean oldTargetsPreRelease = oldPackage.applicationInfo.targetSdkVersion
15892                    == android.os.Build.VERSION_CODES.CUR_DEVELOPMENT;
15893            final boolean newTargetsPreRelease = pkg.applicationInfo.targetSdkVersion
15894                    == android.os.Build.VERSION_CODES.CUR_DEVELOPMENT;
15895            if (oldTargetsPreRelease
15896                    && !newTargetsPreRelease
15897                    && ((policyFlags & PackageParser.PARSE_FORCE_SDK) == 0)) {
15898                Slog.w(TAG, "Can't install package targeting released sdk");
15899                res.setReturnCode(PackageManager.INSTALL_FAILED_UPDATE_INCOMPATIBLE);
15900                return;
15901            }
15902
15903            final PackageSetting ps = mSettings.mPackages.get(pkgName);
15904
15905            // don't allow an upgrade from full to ephemeral
15906            if (isInstantApp && !ps.getInstantApp(user.getIdentifier())) {
15907                // can't downgrade from full to instant
15908                Slog.w(TAG, "Can't replace app with instant app: " + pkgName);
15909                res.setReturnCode(PackageManager.INSTALL_FAILED_INSTANT_APP_INVALID);
15910                return;
15911            }
15912
15913            // verify signatures are valid
15914            if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) {
15915                if (!checkUpgradeKeySetLP(ps, pkg)) {
15916                    res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
15917                            "New package not signed by keys specified by upgrade-keysets: "
15918                                    + pkgName);
15919                    return;
15920                }
15921            } else {
15922                // default to original signature matching
15923                if (compareSignatures(oldPackage.mSignatures, pkg.mSignatures)
15924                        != PackageManager.SIGNATURE_MATCH) {
15925                    res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
15926                            "New package has a different signature: " + pkgName);
15927                    return;
15928                }
15929            }
15930
15931            // don't allow a system upgrade unless the upgrade hash matches
15932            if (oldPackage.restrictUpdateHash != null && oldPackage.isSystemApp()) {
15933                byte[] digestBytes = null;
15934                try {
15935                    final MessageDigest digest = MessageDigest.getInstance("SHA-512");
15936                    updateDigest(digest, new File(pkg.baseCodePath));
15937                    if (!ArrayUtils.isEmpty(pkg.splitCodePaths)) {
15938                        for (String path : pkg.splitCodePaths) {
15939                            updateDigest(digest, new File(path));
15940                        }
15941                    }
15942                    digestBytes = digest.digest();
15943                } catch (NoSuchAlgorithmException | IOException e) {
15944                    res.setError(INSTALL_FAILED_INVALID_APK,
15945                            "Could not compute hash: " + pkgName);
15946                    return;
15947                }
15948                if (!Arrays.equals(oldPackage.restrictUpdateHash, digestBytes)) {
15949                    res.setError(INSTALL_FAILED_INVALID_APK,
15950                            "New package fails restrict-update check: " + pkgName);
15951                    return;
15952                }
15953                // retain upgrade restriction
15954                pkg.restrictUpdateHash = oldPackage.restrictUpdateHash;
15955            }
15956
15957            // Check for shared user id changes
15958            String invalidPackageName =
15959                    getParentOrChildPackageChangedSharedUser(oldPackage, pkg);
15960            if (invalidPackageName != null) {
15961                res.setError(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE,
15962                        "Package " + invalidPackageName + " tried to change user "
15963                                + oldPackage.mSharedUserId);
15964                return;
15965            }
15966
15967            // In case of rollback, remember per-user/profile install state
15968            allUsers = sUserManager.getUserIds();
15969            installedUsers = ps.queryInstalledUsers(allUsers, true);
15970        }
15971
15972        // Update what is removed
15973        res.removedInfo = new PackageRemovedInfo();
15974        res.removedInfo.uid = oldPackage.applicationInfo.uid;
15975        res.removedInfo.removedPackage = oldPackage.packageName;
15976        res.removedInfo.isStaticSharedLib = pkg.staticSharedLibName != null;
15977        res.removedInfo.isUpdate = true;
15978        res.removedInfo.origUsers = installedUsers;
15979        final PackageSetting ps = mSettings.getPackageLPr(pkgName);
15980        res.removedInfo.installReasons = new SparseArray<>(installedUsers.length);
15981        for (int i = 0; i < installedUsers.length; i++) {
15982            final int userId = installedUsers[i];
15983            res.removedInfo.installReasons.put(userId, ps.getInstallReason(userId));
15984        }
15985
15986        final int childCount = (oldPackage.childPackages != null)
15987                ? oldPackage.childPackages.size() : 0;
15988        for (int i = 0; i < childCount; i++) {
15989            boolean childPackageUpdated = false;
15990            PackageParser.Package childPkg = oldPackage.childPackages.get(i);
15991            final PackageSetting childPs = mSettings.getPackageLPr(childPkg.packageName);
15992            if (res.addedChildPackages != null) {
15993                PackageInstalledInfo childRes = res.addedChildPackages.get(childPkg.packageName);
15994                if (childRes != null) {
15995                    childRes.removedInfo.uid = childPkg.applicationInfo.uid;
15996                    childRes.removedInfo.removedPackage = childPkg.packageName;
15997                    childRes.removedInfo.isUpdate = true;
15998                    childRes.removedInfo.installReasons = res.removedInfo.installReasons;
15999                    childPackageUpdated = true;
16000                }
16001            }
16002            if (!childPackageUpdated) {
16003                PackageRemovedInfo childRemovedRes = new PackageRemovedInfo();
16004                childRemovedRes.removedPackage = childPkg.packageName;
16005                childRemovedRes.isUpdate = false;
16006                childRemovedRes.dataRemoved = true;
16007                synchronized (mPackages) {
16008                    if (childPs != null) {
16009                        childRemovedRes.origUsers = childPs.queryInstalledUsers(allUsers, true);
16010                    }
16011                }
16012                if (res.removedInfo.removedChildPackages == null) {
16013                    res.removedInfo.removedChildPackages = new ArrayMap<>();
16014                }
16015                res.removedInfo.removedChildPackages.put(childPkg.packageName, childRemovedRes);
16016            }
16017        }
16018
16019        boolean sysPkg = (isSystemApp(oldPackage));
16020        if (sysPkg) {
16021            // Set the system/privileged flags as needed
16022            final boolean privileged =
16023                    (oldPackage.applicationInfo.privateFlags
16024                            & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0;
16025            final int systemPolicyFlags = policyFlags
16026                    | PackageParser.PARSE_IS_SYSTEM
16027                    | (privileged ? PackageParser.PARSE_IS_PRIVILEGED : 0);
16028
16029            replaceSystemPackageLIF(oldPackage, pkg, systemPolicyFlags, scanFlags,
16030                    user, allUsers, installerPackageName, res, installReason);
16031        } else {
16032            replaceNonSystemPackageLIF(oldPackage, pkg, policyFlags, scanFlags,
16033                    user, allUsers, installerPackageName, res, installReason);
16034        }
16035    }
16036
16037    public List<String> getPreviousCodePaths(String packageName) {
16038        final PackageSetting ps = mSettings.mPackages.get(packageName);
16039        final List<String> result = new ArrayList<String>();
16040        if (ps != null && ps.oldCodePaths != null) {
16041            result.addAll(ps.oldCodePaths);
16042        }
16043        return result;
16044    }
16045
16046    private void replaceNonSystemPackageLIF(PackageParser.Package deletedPackage,
16047            PackageParser.Package pkg, final int policyFlags, int scanFlags, UserHandle user,
16048            int[] allUsers, String installerPackageName, PackageInstalledInfo res,
16049            int installReason) {
16050        if (DEBUG_INSTALL) Slog.d(TAG, "replaceNonSystemPackageLI: new=" + pkg + ", old="
16051                + deletedPackage);
16052
16053        String pkgName = deletedPackage.packageName;
16054        boolean deletedPkg = true;
16055        boolean addedPkg = false;
16056        boolean updatedSettings = false;
16057        final boolean killApp = (scanFlags & SCAN_DONT_KILL_APP) == 0;
16058        final int deleteFlags = PackageManager.DELETE_KEEP_DATA
16059                | (killApp ? 0 : PackageManager.DELETE_DONT_KILL_APP);
16060
16061        final long origUpdateTime = (pkg.mExtras != null)
16062                ? ((PackageSetting)pkg.mExtras).lastUpdateTime : 0;
16063
16064        // First delete the existing package while retaining the data directory
16065        if (!deletePackageLIF(pkgName, null, true, allUsers, deleteFlags,
16066                res.removedInfo, true, pkg)) {
16067            // If the existing package wasn't successfully deleted
16068            res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, "replaceNonSystemPackageLI");
16069            deletedPkg = false;
16070        } else {
16071            // Successfully deleted the old package; proceed with replace.
16072
16073            // If deleted package lived in a container, give users a chance to
16074            // relinquish resources before killing.
16075            if (deletedPackage.isForwardLocked() || isExternal(deletedPackage)) {
16076                if (DEBUG_INSTALL) {
16077                    Slog.i(TAG, "upgrading pkg " + deletedPackage + " is ASEC-hosted -> UNAVAILABLE");
16078                }
16079                final int[] uidArray = new int[] { deletedPackage.applicationInfo.uid };
16080                final ArrayList<String> pkgList = new ArrayList<String>(1);
16081                pkgList.add(deletedPackage.applicationInfo.packageName);
16082                sendResourcesChangedBroadcast(false, true, pkgList, uidArray, null);
16083            }
16084
16085            clearAppDataLIF(pkg, UserHandle.USER_ALL, StorageManager.FLAG_STORAGE_DE
16086                    | StorageManager.FLAG_STORAGE_CE | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
16087            clearAppProfilesLIF(deletedPackage, UserHandle.USER_ALL);
16088
16089            try {
16090                final PackageParser.Package newPackage = scanPackageTracedLI(pkg, policyFlags,
16091                        scanFlags | SCAN_UPDATE_TIME, System.currentTimeMillis(), user);
16092                updateSettingsLI(newPackage, installerPackageName, allUsers, res, user,
16093                        installReason);
16094
16095                // Update the in-memory copy of the previous code paths.
16096                PackageSetting ps = mSettings.mPackages.get(pkgName);
16097                if (!killApp) {
16098                    if (ps.oldCodePaths == null) {
16099                        ps.oldCodePaths = new ArraySet<>();
16100                    }
16101                    Collections.addAll(ps.oldCodePaths, deletedPackage.baseCodePath);
16102                    if (deletedPackage.splitCodePaths != null) {
16103                        Collections.addAll(ps.oldCodePaths, deletedPackage.splitCodePaths);
16104                    }
16105                } else {
16106                    ps.oldCodePaths = null;
16107                }
16108                if (ps.childPackageNames != null) {
16109                    for (int i = ps.childPackageNames.size() - 1; i >= 0; --i) {
16110                        final String childPkgName = ps.childPackageNames.get(i);
16111                        final PackageSetting childPs = mSettings.mPackages.get(childPkgName);
16112                        childPs.oldCodePaths = ps.oldCodePaths;
16113                    }
16114                }
16115                // set instant app status, but, only if it's explicitly specified
16116                final boolean instantApp = (scanFlags & SCAN_AS_INSTANT_APP) != 0;
16117                final boolean fullApp = (scanFlags & SCAN_AS_FULL_APP) != 0;
16118                setInstantAppForUser(ps, user.getIdentifier(), instantApp, fullApp);
16119                prepareAppDataAfterInstallLIF(newPackage);
16120                addedPkg = true;
16121            } catch (PackageManagerException e) {
16122                res.setError("Package couldn't be installed in " + pkg.codePath, e);
16123            }
16124        }
16125
16126        if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
16127            if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, rolling pack: " + pkgName);
16128
16129            // Revert all internal state mutations and added folders for the failed install
16130            if (addedPkg) {
16131                deletePackageLIF(pkgName, null, true, allUsers, deleteFlags,
16132                        res.removedInfo, true, null);
16133            }
16134
16135            // Restore the old package
16136            if (deletedPkg) {
16137                if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, reinstalling: " + deletedPackage);
16138                File restoreFile = new File(deletedPackage.codePath);
16139                // Parse old package
16140                boolean oldExternal = isExternal(deletedPackage);
16141                int oldParseFlags  = mDefParseFlags | PackageParser.PARSE_CHATTY |
16142                        (deletedPackage.isForwardLocked() ? PackageParser.PARSE_FORWARD_LOCK : 0) |
16143                        (oldExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0);
16144                int oldScanFlags = SCAN_UPDATE_SIGNATURE | SCAN_UPDATE_TIME;
16145                try {
16146                    scanPackageTracedLI(restoreFile, oldParseFlags, oldScanFlags, origUpdateTime,
16147                            null);
16148                } catch (PackageManagerException e) {
16149                    Slog.e(TAG, "Failed to restore package : " + pkgName + " after failed upgrade: "
16150                            + e.getMessage());
16151                    return;
16152                }
16153
16154                synchronized (mPackages) {
16155                    // Ensure the installer package name up to date
16156                    setInstallerPackageNameLPw(deletedPackage, installerPackageName);
16157
16158                    // Update permissions for restored package
16159                    updatePermissionsLPw(deletedPackage, UPDATE_PERMISSIONS_ALL);
16160
16161                    mSettings.writeLPr();
16162                }
16163
16164                Slog.i(TAG, "Successfully restored package : " + pkgName + " after failed upgrade");
16165            }
16166        } else {
16167            synchronized (mPackages) {
16168                PackageSetting ps = mSettings.getPackageLPr(pkg.packageName);
16169                if (ps != null) {
16170                    res.removedInfo.removedForAllUsers = mPackages.get(ps.name) == null;
16171                    if (res.removedInfo.removedChildPackages != null) {
16172                        final int childCount = res.removedInfo.removedChildPackages.size();
16173                        // Iterate in reverse as we may modify the collection
16174                        for (int i = childCount - 1; i >= 0; i--) {
16175                            String childPackageName = res.removedInfo.removedChildPackages.keyAt(i);
16176                            if (res.addedChildPackages.containsKey(childPackageName)) {
16177                                res.removedInfo.removedChildPackages.removeAt(i);
16178                            } else {
16179                                PackageRemovedInfo childInfo = res.removedInfo
16180                                        .removedChildPackages.valueAt(i);
16181                                childInfo.removedForAllUsers = mPackages.get(
16182                                        childInfo.removedPackage) == null;
16183                            }
16184                        }
16185                    }
16186                }
16187            }
16188        }
16189    }
16190
16191    private void replaceSystemPackageLIF(PackageParser.Package deletedPackage,
16192            PackageParser.Package pkg, final int policyFlags, int scanFlags, UserHandle user,
16193            int[] allUsers, String installerPackageName, PackageInstalledInfo res,
16194            int installReason) {
16195        if (DEBUG_INSTALL) Slog.d(TAG, "replaceSystemPackageLI: new=" + pkg
16196                + ", old=" + deletedPackage);
16197
16198        final boolean disabledSystem;
16199
16200        // Remove existing system package
16201        removePackageLI(deletedPackage, true);
16202
16203        synchronized (mPackages) {
16204            disabledSystem = disableSystemPackageLPw(deletedPackage, pkg);
16205        }
16206        if (!disabledSystem) {
16207            // We didn't need to disable the .apk as a current system package,
16208            // which means we are replacing another update that is already
16209            // installed.  We need to make sure to delete the older one's .apk.
16210            res.removedInfo.args = createInstallArgsForExisting(0,
16211                    deletedPackage.applicationInfo.getCodePath(),
16212                    deletedPackage.applicationInfo.getResourcePath(),
16213                    getAppDexInstructionSets(deletedPackage.applicationInfo));
16214        } else {
16215            res.removedInfo.args = null;
16216        }
16217
16218        // Successfully disabled the old package. Now proceed with re-installation
16219        clearAppDataLIF(pkg, UserHandle.USER_ALL, StorageManager.FLAG_STORAGE_DE
16220                | StorageManager.FLAG_STORAGE_CE | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
16221        clearAppProfilesLIF(deletedPackage, UserHandle.USER_ALL);
16222
16223        res.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
16224        pkg.setApplicationInfoFlags(ApplicationInfo.FLAG_UPDATED_SYSTEM_APP,
16225                ApplicationInfo.FLAG_UPDATED_SYSTEM_APP);
16226
16227        PackageParser.Package newPackage = null;
16228        try {
16229            // Add the package to the internal data structures
16230            newPackage = scanPackageTracedLI(pkg, policyFlags, scanFlags, 0, user);
16231
16232            // Set the update and install times
16233            PackageSetting deletedPkgSetting = (PackageSetting) deletedPackage.mExtras;
16234            setInstallAndUpdateTime(newPackage, deletedPkgSetting.firstInstallTime,
16235                    System.currentTimeMillis());
16236
16237            // Update the package dynamic state if succeeded
16238            if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
16239                // Now that the install succeeded make sure we remove data
16240                // directories for any child package the update removed.
16241                final int deletedChildCount = (deletedPackage.childPackages != null)
16242                        ? deletedPackage.childPackages.size() : 0;
16243                final int newChildCount = (newPackage.childPackages != null)
16244                        ? newPackage.childPackages.size() : 0;
16245                for (int i = 0; i < deletedChildCount; i++) {
16246                    PackageParser.Package deletedChildPkg = deletedPackage.childPackages.get(i);
16247                    boolean childPackageDeleted = true;
16248                    for (int j = 0; j < newChildCount; j++) {
16249                        PackageParser.Package newChildPkg = newPackage.childPackages.get(j);
16250                        if (deletedChildPkg.packageName.equals(newChildPkg.packageName)) {
16251                            childPackageDeleted = false;
16252                            break;
16253                        }
16254                    }
16255                    if (childPackageDeleted) {
16256                        PackageSetting ps = mSettings.getDisabledSystemPkgLPr(
16257                                deletedChildPkg.packageName);
16258                        if (ps != null && res.removedInfo.removedChildPackages != null) {
16259                            PackageRemovedInfo removedChildRes = res.removedInfo
16260                                    .removedChildPackages.get(deletedChildPkg.packageName);
16261                            removePackageDataLIF(ps, allUsers, removedChildRes, 0, false);
16262                            removedChildRes.removedForAllUsers = mPackages.get(ps.name) == null;
16263                        }
16264                    }
16265                }
16266
16267                updateSettingsLI(newPackage, installerPackageName, allUsers, res, user,
16268                        installReason);
16269                prepareAppDataAfterInstallLIF(newPackage);
16270            }
16271        } catch (PackageManagerException e) {
16272            res.setReturnCode(INSTALL_FAILED_INTERNAL_ERROR);
16273            res.setError("Package couldn't be installed in " + pkg.codePath, e);
16274        }
16275
16276        if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
16277            // Re installation failed. Restore old information
16278            // Remove new pkg information
16279            if (newPackage != null) {
16280                removeInstalledPackageLI(newPackage, true);
16281            }
16282            // Add back the old system package
16283            try {
16284                scanPackageTracedLI(deletedPackage, policyFlags, SCAN_UPDATE_SIGNATURE, 0, user);
16285            } catch (PackageManagerException e) {
16286                Slog.e(TAG, "Failed to restore original package: " + e.getMessage());
16287            }
16288
16289            synchronized (mPackages) {
16290                if (disabledSystem) {
16291                    enableSystemPackageLPw(deletedPackage);
16292                }
16293
16294                // Ensure the installer package name up to date
16295                setInstallerPackageNameLPw(deletedPackage, installerPackageName);
16296
16297                // Update permissions for restored package
16298                updatePermissionsLPw(deletedPackage, UPDATE_PERMISSIONS_ALL);
16299
16300                mSettings.writeLPr();
16301            }
16302
16303            Slog.i(TAG, "Successfully restored package : " + deletedPackage.packageName
16304                    + " after failed upgrade");
16305        }
16306    }
16307
16308    /**
16309     * Checks whether the parent or any of the child packages have a change shared
16310     * user. For a package to be a valid update the shred users of the parent and
16311     * the children should match. We may later support changing child shared users.
16312     * @param oldPkg The updated package.
16313     * @param newPkg The update package.
16314     * @return The shared user that change between the versions.
16315     */
16316    private String getParentOrChildPackageChangedSharedUser(PackageParser.Package oldPkg,
16317            PackageParser.Package newPkg) {
16318        // Check parent shared user
16319        if (!Objects.equals(oldPkg.mSharedUserId, newPkg.mSharedUserId)) {
16320            return newPkg.packageName;
16321        }
16322        // Check child shared users
16323        final int oldChildCount = (oldPkg.childPackages != null) ? oldPkg.childPackages.size() : 0;
16324        final int newChildCount = (newPkg.childPackages != null) ? newPkg.childPackages.size() : 0;
16325        for (int i = 0; i < newChildCount; i++) {
16326            PackageParser.Package newChildPkg = newPkg.childPackages.get(i);
16327            // If this child was present, did it have the same shared user?
16328            for (int j = 0; j < oldChildCount; j++) {
16329                PackageParser.Package oldChildPkg = oldPkg.childPackages.get(j);
16330                if (newChildPkg.packageName.equals(oldChildPkg.packageName)
16331                        && !Objects.equals(newChildPkg.mSharedUserId, oldChildPkg.mSharedUserId)) {
16332                    return newChildPkg.packageName;
16333                }
16334            }
16335        }
16336        return null;
16337    }
16338
16339    private void removeNativeBinariesLI(PackageSetting ps) {
16340        // Remove the lib path for the parent package
16341        if (ps != null) {
16342            NativeLibraryHelper.removeNativeBinariesLI(ps.legacyNativeLibraryPathString);
16343            // Remove the lib path for the child packages
16344            final int childCount = (ps.childPackageNames != null) ? ps.childPackageNames.size() : 0;
16345            for (int i = 0; i < childCount; i++) {
16346                PackageSetting childPs = null;
16347                synchronized (mPackages) {
16348                    childPs = mSettings.getPackageLPr(ps.childPackageNames.get(i));
16349                }
16350                if (childPs != null) {
16351                    NativeLibraryHelper.removeNativeBinariesLI(childPs
16352                            .legacyNativeLibraryPathString);
16353                }
16354            }
16355        }
16356    }
16357
16358    private void enableSystemPackageLPw(PackageParser.Package pkg) {
16359        // Enable the parent package
16360        mSettings.enableSystemPackageLPw(pkg.packageName);
16361        // Enable the child packages
16362        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
16363        for (int i = 0; i < childCount; i++) {
16364            PackageParser.Package childPkg = pkg.childPackages.get(i);
16365            mSettings.enableSystemPackageLPw(childPkg.packageName);
16366        }
16367    }
16368
16369    private boolean disableSystemPackageLPw(PackageParser.Package oldPkg,
16370            PackageParser.Package newPkg) {
16371        // Disable the parent package (parent always replaced)
16372        boolean disabled = mSettings.disableSystemPackageLPw(oldPkg.packageName, true);
16373        // Disable the child packages
16374        final int childCount = (oldPkg.childPackages != null) ? oldPkg.childPackages.size() : 0;
16375        for (int i = 0; i < childCount; i++) {
16376            PackageParser.Package childPkg = oldPkg.childPackages.get(i);
16377            final boolean replace = newPkg.hasChildPackage(childPkg.packageName);
16378            disabled |= mSettings.disableSystemPackageLPw(childPkg.packageName, replace);
16379        }
16380        return disabled;
16381    }
16382
16383    private void setInstallerPackageNameLPw(PackageParser.Package pkg,
16384            String installerPackageName) {
16385        // Enable the parent package
16386        mSettings.setInstallerPackageName(pkg.packageName, installerPackageName);
16387        // Enable the child packages
16388        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
16389        for (int i = 0; i < childCount; i++) {
16390            PackageParser.Package childPkg = pkg.childPackages.get(i);
16391            mSettings.setInstallerPackageName(childPkg.packageName, installerPackageName);
16392        }
16393    }
16394
16395    private int[] revokeUnusedSharedUserPermissionsLPw(SharedUserSetting su, int[] allUserIds) {
16396        // Collect all used permissions in the UID
16397        ArraySet<String> usedPermissions = new ArraySet<>();
16398        final int packageCount = su.packages.size();
16399        for (int i = 0; i < packageCount; i++) {
16400            PackageSetting ps = su.packages.valueAt(i);
16401            if (ps.pkg == null) {
16402                continue;
16403            }
16404            final int requestedPermCount = ps.pkg.requestedPermissions.size();
16405            for (int j = 0; j < requestedPermCount; j++) {
16406                String permission = ps.pkg.requestedPermissions.get(j);
16407                BasePermission bp = mSettings.mPermissions.get(permission);
16408                if (bp != null) {
16409                    usedPermissions.add(permission);
16410                }
16411            }
16412        }
16413
16414        PermissionsState permissionsState = su.getPermissionsState();
16415        // Prune install permissions
16416        List<PermissionState> installPermStates = permissionsState.getInstallPermissionStates();
16417        final int installPermCount = installPermStates.size();
16418        for (int i = installPermCount - 1; i >= 0;  i--) {
16419            PermissionState permissionState = installPermStates.get(i);
16420            if (!usedPermissions.contains(permissionState.getName())) {
16421                BasePermission bp = mSettings.mPermissions.get(permissionState.getName());
16422                if (bp != null) {
16423                    permissionsState.revokeInstallPermission(bp);
16424                    permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL,
16425                            PackageManager.MASK_PERMISSION_FLAGS, 0);
16426                }
16427            }
16428        }
16429
16430        int[] runtimePermissionChangedUserIds = EmptyArray.INT;
16431
16432        // Prune runtime permissions
16433        for (int userId : allUserIds) {
16434            List<PermissionState> runtimePermStates = permissionsState
16435                    .getRuntimePermissionStates(userId);
16436            final int runtimePermCount = runtimePermStates.size();
16437            for (int i = runtimePermCount - 1; i >= 0; i--) {
16438                PermissionState permissionState = runtimePermStates.get(i);
16439                if (!usedPermissions.contains(permissionState.getName())) {
16440                    BasePermission bp = mSettings.mPermissions.get(permissionState.getName());
16441                    if (bp != null) {
16442                        permissionsState.revokeRuntimePermission(bp, userId);
16443                        permissionsState.updatePermissionFlags(bp, userId,
16444                                PackageManager.MASK_PERMISSION_FLAGS, 0);
16445                        runtimePermissionChangedUserIds = ArrayUtils.appendInt(
16446                                runtimePermissionChangedUserIds, userId);
16447                    }
16448                }
16449            }
16450        }
16451
16452        return runtimePermissionChangedUserIds;
16453    }
16454
16455    private void updateSettingsLI(PackageParser.Package newPackage, String installerPackageName,
16456            int[] allUsers, PackageInstalledInfo res, UserHandle user, int installReason) {
16457        // Update the parent package setting
16458        updateSettingsInternalLI(newPackage, installerPackageName, allUsers, res.origUsers,
16459                res, user, installReason);
16460        // Update the child packages setting
16461        final int childCount = (newPackage.childPackages != null)
16462                ? newPackage.childPackages.size() : 0;
16463        for (int i = 0; i < childCount; i++) {
16464            PackageParser.Package childPackage = newPackage.childPackages.get(i);
16465            PackageInstalledInfo childRes = res.addedChildPackages.get(childPackage.packageName);
16466            updateSettingsInternalLI(childPackage, installerPackageName, allUsers,
16467                    childRes.origUsers, childRes, user, installReason);
16468        }
16469    }
16470
16471    private void updateSettingsInternalLI(PackageParser.Package newPackage,
16472            String installerPackageName, int[] allUsers, int[] installedForUsers,
16473            PackageInstalledInfo res, UserHandle user, int installReason) {
16474        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings");
16475
16476        String pkgName = newPackage.packageName;
16477        synchronized (mPackages) {
16478            //write settings. the installStatus will be incomplete at this stage.
16479            //note that the new package setting would have already been
16480            //added to mPackages. It hasn't been persisted yet.
16481            mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_INCOMPLETE);
16482            // TODO: Remove this write? It's also written at the end of this method
16483            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings");
16484            mSettings.writeLPr();
16485            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
16486        }
16487
16488        if (DEBUG_INSTALL) Slog.d(TAG, "New package installed in " + newPackage.codePath);
16489        synchronized (mPackages) {
16490            updatePermissionsLPw(newPackage.packageName, newPackage,
16491                    UPDATE_PERMISSIONS_REPLACE_PKG | (newPackage.permissions.size() > 0
16492                            ? UPDATE_PERMISSIONS_ALL : 0));
16493            // For system-bundled packages, we assume that installing an upgraded version
16494            // of the package implies that the user actually wants to run that new code,
16495            // so we enable the package.
16496            PackageSetting ps = mSettings.mPackages.get(pkgName);
16497            final int userId = user.getIdentifier();
16498            if (ps != null) {
16499                if (isSystemApp(newPackage)) {
16500                    if (DEBUG_INSTALL) {
16501                        Slog.d(TAG, "Implicitly enabling system package on upgrade: " + pkgName);
16502                    }
16503                    // Enable system package for requested users
16504                    if (res.origUsers != null) {
16505                        for (int origUserId : res.origUsers) {
16506                            if (userId == UserHandle.USER_ALL || userId == origUserId) {
16507                                ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT,
16508                                        origUserId, installerPackageName);
16509                            }
16510                        }
16511                    }
16512                    // Also convey the prior install/uninstall state
16513                    if (allUsers != null && installedForUsers != null) {
16514                        for (int currentUserId : allUsers) {
16515                            final boolean installed = ArrayUtils.contains(
16516                                    installedForUsers, currentUserId);
16517                            if (DEBUG_INSTALL) {
16518                                Slog.d(TAG, "    user " + currentUserId + " => " + installed);
16519                            }
16520                            ps.setInstalled(installed, currentUserId);
16521                        }
16522                        // these install state changes will be persisted in the
16523                        // upcoming call to mSettings.writeLPr().
16524                    }
16525                }
16526                // It's implied that when a user requests installation, they want the app to be
16527                // installed and enabled.
16528                if (userId != UserHandle.USER_ALL) {
16529                    ps.setInstalled(true, userId);
16530                    ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, userId, installerPackageName);
16531                }
16532
16533                // When replacing an existing package, preserve the original install reason for all
16534                // users that had the package installed before.
16535                final Set<Integer> previousUserIds = new ArraySet<>();
16536                if (res.removedInfo != null && res.removedInfo.installReasons != null) {
16537                    final int installReasonCount = res.removedInfo.installReasons.size();
16538                    for (int i = 0; i < installReasonCount; i++) {
16539                        final int previousUserId = res.removedInfo.installReasons.keyAt(i);
16540                        final int previousInstallReason = res.removedInfo.installReasons.valueAt(i);
16541                        ps.setInstallReason(previousInstallReason, previousUserId);
16542                        previousUserIds.add(previousUserId);
16543                    }
16544                }
16545
16546                // Set install reason for users that are having the package newly installed.
16547                if (userId == UserHandle.USER_ALL) {
16548                    for (int currentUserId : sUserManager.getUserIds()) {
16549                        if (!previousUserIds.contains(currentUserId)) {
16550                            ps.setInstallReason(installReason, currentUserId);
16551                        }
16552                    }
16553                } else if (!previousUserIds.contains(userId)) {
16554                    ps.setInstallReason(installReason, userId);
16555                }
16556                mSettings.writeKernelMappingLPr(ps);
16557            }
16558            res.name = pkgName;
16559            res.uid = newPackage.applicationInfo.uid;
16560            res.pkg = newPackage;
16561            mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_COMPLETE);
16562            mSettings.setInstallerPackageName(pkgName, installerPackageName);
16563            res.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
16564            //to update install status
16565            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings");
16566            mSettings.writeLPr();
16567            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
16568        }
16569
16570        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
16571    }
16572
16573    private void installPackageTracedLI(InstallArgs args, PackageInstalledInfo res) {
16574        try {
16575            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installPackage");
16576            installPackageLI(args, res);
16577        } finally {
16578            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
16579        }
16580    }
16581
16582    private void installPackageLI(InstallArgs args, PackageInstalledInfo res) {
16583        final int installFlags = args.installFlags;
16584        final String installerPackageName = args.installerPackageName;
16585        final String volumeUuid = args.volumeUuid;
16586        final File tmpPackageFile = new File(args.getCodePath());
16587        final boolean forwardLocked = ((installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0);
16588        final boolean onExternal = (((installFlags & PackageManager.INSTALL_EXTERNAL) != 0)
16589                || (args.volumeUuid != null));
16590        final boolean instantApp = ((installFlags & PackageManager.INSTALL_INSTANT_APP) != 0);
16591        final boolean fullApp = ((installFlags & PackageManager.INSTALL_FULL_APP) != 0);
16592        final boolean forceSdk = ((installFlags & PackageManager.INSTALL_FORCE_SDK) != 0);
16593        boolean replace = false;
16594        int scanFlags = SCAN_NEW_INSTALL | SCAN_UPDATE_SIGNATURE;
16595        if (args.move != null) {
16596            // moving a complete application; perform an initial scan on the new install location
16597            scanFlags |= SCAN_INITIAL;
16598        }
16599        if ((installFlags & PackageManager.INSTALL_DONT_KILL_APP) != 0) {
16600            scanFlags |= SCAN_DONT_KILL_APP;
16601        }
16602        if (instantApp) {
16603            scanFlags |= SCAN_AS_INSTANT_APP;
16604        }
16605        if (fullApp) {
16606            scanFlags |= SCAN_AS_FULL_APP;
16607        }
16608
16609        // Result object to be returned
16610        res.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
16611
16612        if (DEBUG_INSTALL) Slog.d(TAG, "installPackageLI: path=" + tmpPackageFile);
16613
16614        // Sanity check
16615        if (instantApp && (forwardLocked || onExternal)) {
16616            Slog.i(TAG, "Incompatible ephemeral install; fwdLocked=" + forwardLocked
16617                    + " external=" + onExternal);
16618            res.setReturnCode(PackageManager.INSTALL_FAILED_INSTANT_APP_INVALID);
16619            return;
16620        }
16621
16622        // Retrieve PackageSettings and parse package
16623        final int parseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY
16624                | PackageParser.PARSE_ENFORCE_CODE
16625                | (forwardLocked ? PackageParser.PARSE_FORWARD_LOCK : 0)
16626                | (onExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0)
16627                | (instantApp ? PackageParser.PARSE_IS_EPHEMERAL : 0)
16628                | (forceSdk ? PackageParser.PARSE_FORCE_SDK : 0);
16629        PackageParser pp = new PackageParser();
16630        pp.setSeparateProcesses(mSeparateProcesses);
16631        pp.setDisplayMetrics(mMetrics);
16632
16633        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "parsePackage");
16634        final PackageParser.Package pkg;
16635        try {
16636            pkg = pp.parsePackage(tmpPackageFile, parseFlags);
16637        } catch (PackageParserException e) {
16638            res.setError("Failed parse during installPackageLI", e);
16639            return;
16640        } finally {
16641            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
16642        }
16643
16644//        // Ephemeral apps must have target SDK >= O.
16645//        // TODO: Update conditional and error message when O gets locked down
16646//        if (instantApp && pkg.applicationInfo.targetSdkVersion <= Build.VERSION_CODES.N_MR1) {
16647//            res.setError(PackageManager.INSTALL_FAILED_EPHEMERAL_INVALID,
16648//                    "Ephemeral apps must have target SDK version of at least O");
16649//            return;
16650//        }
16651
16652        if (pkg.applicationInfo.isStaticSharedLibrary()) {
16653            // Static shared libraries have synthetic package names
16654            renameStaticSharedLibraryPackage(pkg);
16655
16656            // No static shared libs on external storage
16657            if (onExternal) {
16658                Slog.i(TAG, "Static shared libs can only be installed on internal storage.");
16659                res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION,
16660                        "Packages declaring static-shared libs cannot be updated");
16661                return;
16662            }
16663        }
16664
16665        // If we are installing a clustered package add results for the children
16666        if (pkg.childPackages != null) {
16667            synchronized (mPackages) {
16668                final int childCount = pkg.childPackages.size();
16669                for (int i = 0; i < childCount; i++) {
16670                    PackageParser.Package childPkg = pkg.childPackages.get(i);
16671                    PackageInstalledInfo childRes = new PackageInstalledInfo();
16672                    childRes.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
16673                    childRes.pkg = childPkg;
16674                    childRes.name = childPkg.packageName;
16675                    PackageSetting childPs = mSettings.getPackageLPr(childPkg.packageName);
16676                    if (childPs != null) {
16677                        childRes.origUsers = childPs.queryInstalledUsers(
16678                                sUserManager.getUserIds(), true);
16679                    }
16680                    if ((mPackages.containsKey(childPkg.packageName))) {
16681                        childRes.removedInfo = new PackageRemovedInfo();
16682                        childRes.removedInfo.removedPackage = childPkg.packageName;
16683                    }
16684                    if (res.addedChildPackages == null) {
16685                        res.addedChildPackages = new ArrayMap<>();
16686                    }
16687                    res.addedChildPackages.put(childPkg.packageName, childRes);
16688                }
16689            }
16690        }
16691
16692        // If package doesn't declare API override, mark that we have an install
16693        // time CPU ABI override.
16694        if (TextUtils.isEmpty(pkg.cpuAbiOverride)) {
16695            pkg.cpuAbiOverride = args.abiOverride;
16696        }
16697
16698        String pkgName = res.name = pkg.packageName;
16699        if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_TEST_ONLY) != 0) {
16700            if ((installFlags & PackageManager.INSTALL_ALLOW_TEST) == 0) {
16701                res.setError(INSTALL_FAILED_TEST_ONLY, "installPackageLI");
16702                return;
16703            }
16704        }
16705
16706        try {
16707            // either use what we've been given or parse directly from the APK
16708            if (args.certificates != null) {
16709                try {
16710                    PackageParser.populateCertificates(pkg, args.certificates);
16711                } catch (PackageParserException e) {
16712                    // there was something wrong with the certificates we were given;
16713                    // try to pull them from the APK
16714                    PackageParser.collectCertificates(pkg, parseFlags);
16715                }
16716            } else {
16717                PackageParser.collectCertificates(pkg, parseFlags);
16718            }
16719        } catch (PackageParserException e) {
16720            res.setError("Failed collect during installPackageLI", e);
16721            return;
16722        }
16723
16724        // Get rid of all references to package scan path via parser.
16725        pp = null;
16726        String oldCodePath = null;
16727        boolean systemApp = false;
16728        synchronized (mPackages) {
16729            // Check if installing already existing package
16730            if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
16731                String oldName = mSettings.getRenamedPackageLPr(pkgName);
16732                if (pkg.mOriginalPackages != null
16733                        && pkg.mOriginalPackages.contains(oldName)
16734                        && mPackages.containsKey(oldName)) {
16735                    // This package is derived from an original package,
16736                    // and this device has been updating from that original
16737                    // name.  We must continue using the original name, so
16738                    // rename the new package here.
16739                    pkg.setPackageName(oldName);
16740                    pkgName = pkg.packageName;
16741                    replace = true;
16742                    if (DEBUG_INSTALL) Slog.d(TAG, "Replacing existing renamed package: oldName="
16743                            + oldName + " pkgName=" + pkgName);
16744                } else if (mPackages.containsKey(pkgName)) {
16745                    // This package, under its official name, already exists
16746                    // on the device; we should replace it.
16747                    replace = true;
16748                    if (DEBUG_INSTALL) Slog.d(TAG, "Replace existing pacakge: " + pkgName);
16749                }
16750
16751                // Child packages are installed through the parent package
16752                if (pkg.parentPackage != null) {
16753                    res.setError(PackageManager.INSTALL_PARSE_FAILED_BAD_PACKAGE_NAME,
16754                            "Package " + pkg.packageName + " is child of package "
16755                                    + pkg.parentPackage.parentPackage + ". Child packages "
16756                                    + "can be updated only through the parent package.");
16757                    return;
16758                }
16759
16760                if (replace) {
16761                    // Prevent apps opting out from runtime permissions
16762                    PackageParser.Package oldPackage = mPackages.get(pkgName);
16763                    final int oldTargetSdk = oldPackage.applicationInfo.targetSdkVersion;
16764                    final int newTargetSdk = pkg.applicationInfo.targetSdkVersion;
16765                    if (oldTargetSdk > Build.VERSION_CODES.LOLLIPOP_MR1
16766                            && newTargetSdk <= Build.VERSION_CODES.LOLLIPOP_MR1) {
16767                        res.setError(PackageManager.INSTALL_FAILED_PERMISSION_MODEL_DOWNGRADE,
16768                                "Package " + pkg.packageName + " new target SDK " + newTargetSdk
16769                                        + " doesn't support runtime permissions but the old"
16770                                        + " target SDK " + oldTargetSdk + " does.");
16771                        return;
16772                    }
16773
16774                    // Prevent installing of child packages
16775                    if (oldPackage.parentPackage != null) {
16776                        res.setError(PackageManager.INSTALL_PARSE_FAILED_BAD_PACKAGE_NAME,
16777                                "Package " + pkg.packageName + " is child of package "
16778                                        + oldPackage.parentPackage + ". Child packages "
16779                                        + "can be updated only through the parent package.");
16780                        return;
16781                    }
16782                }
16783            }
16784
16785            PackageSetting ps = mSettings.mPackages.get(pkgName);
16786            if (ps != null) {
16787                if (DEBUG_INSTALL) Slog.d(TAG, "Existing package: " + ps);
16788
16789                // Static shared libs have same package with different versions where
16790                // we internally use a synthetic package name to allow multiple versions
16791                // of the same package, therefore we need to compare signatures against
16792                // the package setting for the latest library version.
16793                PackageSetting signatureCheckPs = ps;
16794                if (pkg.applicationInfo.isStaticSharedLibrary()) {
16795                    SharedLibraryEntry libraryEntry = getLatestSharedLibraVersionLPr(pkg);
16796                    if (libraryEntry != null) {
16797                        signatureCheckPs = mSettings.getPackageLPr(libraryEntry.apk);
16798                    }
16799                }
16800
16801                // Quick sanity check that we're signed correctly if updating;
16802                // we'll check this again later when scanning, but we want to
16803                // bail early here before tripping over redefined permissions.
16804                if (shouldCheckUpgradeKeySetLP(signatureCheckPs, scanFlags)) {
16805                    if (!checkUpgradeKeySetLP(signatureCheckPs, pkg)) {
16806                        res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package "
16807                                + pkg.packageName + " upgrade keys do not match the "
16808                                + "previously installed version");
16809                        return;
16810                    }
16811                } else {
16812                    try {
16813                        verifySignaturesLP(signatureCheckPs, pkg);
16814                    } catch (PackageManagerException e) {
16815                        res.setError(e.error, e.getMessage());
16816                        return;
16817                    }
16818                }
16819
16820                oldCodePath = mSettings.mPackages.get(pkgName).codePathString;
16821                if (ps.pkg != null && ps.pkg.applicationInfo != null) {
16822                    systemApp = (ps.pkg.applicationInfo.flags &
16823                            ApplicationInfo.FLAG_SYSTEM) != 0;
16824                }
16825                res.origUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
16826            }
16827
16828            // Check whether the newly-scanned package wants to define an already-defined perm
16829            int N = pkg.permissions.size();
16830            for (int i = N-1; i >= 0; i--) {
16831                PackageParser.Permission perm = pkg.permissions.get(i);
16832                BasePermission bp = mSettings.mPermissions.get(perm.info.name);
16833                if (bp != null) {
16834                    // If the defining package is signed with our cert, it's okay.  This
16835                    // also includes the "updating the same package" case, of course.
16836                    // "updating same package" could also involve key-rotation.
16837                    final boolean sigsOk;
16838                    if (bp.sourcePackage.equals(pkg.packageName)
16839                            && (bp.packageSetting instanceof PackageSetting)
16840                            && (shouldCheckUpgradeKeySetLP((PackageSetting) bp.packageSetting,
16841                                    scanFlags))) {
16842                        sigsOk = checkUpgradeKeySetLP((PackageSetting) bp.packageSetting, pkg);
16843                    } else {
16844                        sigsOk = compareSignatures(bp.packageSetting.signatures.mSignatures,
16845                                pkg.mSignatures) == PackageManager.SIGNATURE_MATCH;
16846                    }
16847                    if (!sigsOk) {
16848                        // If the owning package is the system itself, we log but allow
16849                        // install to proceed; we fail the install on all other permission
16850                        // redefinitions.
16851                        if (!bp.sourcePackage.equals("android")) {
16852                            res.setError(INSTALL_FAILED_DUPLICATE_PERMISSION, "Package "
16853                                    + pkg.packageName + " attempting to redeclare permission "
16854                                    + perm.info.name + " already owned by " + bp.sourcePackage);
16855                            res.origPermission = perm.info.name;
16856                            res.origPackage = bp.sourcePackage;
16857                            return;
16858                        } else {
16859                            Slog.w(TAG, "Package " + pkg.packageName
16860                                    + " attempting to redeclare system permission "
16861                                    + perm.info.name + "; ignoring new declaration");
16862                            pkg.permissions.remove(i);
16863                        }
16864                    } else if (!PLATFORM_PACKAGE_NAME.equals(pkg.packageName)) {
16865                        // Prevent apps to change protection level to dangerous from any other
16866                        // type as this would allow a privilege escalation where an app adds a
16867                        // normal/signature permission in other app's group and later redefines
16868                        // it as dangerous leading to the group auto-grant.
16869                        if ((perm.info.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE)
16870                                == PermissionInfo.PROTECTION_DANGEROUS) {
16871                            if (bp != null && !bp.isRuntime()) {
16872                                Slog.w(TAG, "Package " + pkg.packageName + " trying to change a "
16873                                        + "non-runtime permission " + perm.info.name
16874                                        + " to runtime; keeping old protection level");
16875                                perm.info.protectionLevel = bp.protectionLevel;
16876                            }
16877                        }
16878                    }
16879                }
16880            }
16881        }
16882
16883        if (systemApp) {
16884            if (onExternal) {
16885                // Abort update; system app can't be replaced with app on sdcard
16886                res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION,
16887                        "Cannot install updates to system apps on sdcard");
16888                return;
16889            } else if (instantApp) {
16890                // Abort update; system app can't be replaced with an instant app
16891                res.setError(INSTALL_FAILED_INSTANT_APP_INVALID,
16892                        "Cannot update a system app with an instant app");
16893                return;
16894            }
16895        }
16896
16897        if (args.move != null) {
16898            // We did an in-place move, so dex is ready to roll
16899            scanFlags |= SCAN_NO_DEX;
16900            scanFlags |= SCAN_MOVE;
16901
16902            synchronized (mPackages) {
16903                final PackageSetting ps = mSettings.mPackages.get(pkgName);
16904                if (ps == null) {
16905                    res.setError(INSTALL_FAILED_INTERNAL_ERROR,
16906                            "Missing settings for moved package " + pkgName);
16907                }
16908
16909                // We moved the entire application as-is, so bring over the
16910                // previously derived ABI information.
16911                pkg.applicationInfo.primaryCpuAbi = ps.primaryCpuAbiString;
16912                pkg.applicationInfo.secondaryCpuAbi = ps.secondaryCpuAbiString;
16913            }
16914
16915        } else if (!forwardLocked && !pkg.applicationInfo.isExternalAsec()) {
16916            // Enable SCAN_NO_DEX flag to skip dexopt at a later stage
16917            scanFlags |= SCAN_NO_DEX;
16918
16919            try {
16920                String abiOverride = (TextUtils.isEmpty(pkg.cpuAbiOverride) ?
16921                    args.abiOverride : pkg.cpuAbiOverride);
16922                derivePackageAbi(pkg, new File(pkg.codePath), abiOverride,
16923                        true /*extractLibs*/, mAppLib32InstallDir);
16924            } catch (PackageManagerException pme) {
16925                Slog.e(TAG, "Error deriving application ABI", pme);
16926                res.setError(INSTALL_FAILED_INTERNAL_ERROR, "Error deriving application ABI");
16927                return;
16928            }
16929
16930            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt");
16931            // Do not run PackageDexOptimizer through the local performDexOpt
16932            // method because `pkg` may not be in `mPackages` yet.
16933            //
16934            // Also, don't fail application installs if the dexopt step fails.
16935            mPackageDexOptimizer.performDexOpt(pkg, pkg.usesLibraryFiles,
16936                    null /* instructionSets */, false /* checkProfiles */,
16937                    getCompilerFilterForReason(REASON_INSTALL),
16938                    getOrCreateCompilerPackageStats(pkg));
16939            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
16940
16941            // Notify BackgroundDexOptJobService that the package has been changed.
16942            // If this is an update of a package which used to fail to compile,
16943            // BDOS will remove it from its blacklist.
16944            // TODO: Layering violation
16945            BackgroundDexOptJobService.notifyPackageChanged(pkg.packageName);
16946        }
16947
16948        if (!args.doRename(res.returnCode, pkg, oldCodePath)) {
16949            res.setError(INSTALL_FAILED_INSUFFICIENT_STORAGE, "Failed rename");
16950            return;
16951        }
16952
16953        startIntentFilterVerifications(args.user.getIdentifier(), replace, pkg);
16954
16955        try (PackageFreezer freezer = freezePackageForInstall(pkgName, installFlags,
16956                "installPackageLI")) {
16957            if (replace) {
16958                if (pkg.applicationInfo.isStaticSharedLibrary()) {
16959                    // Static libs have a synthetic package name containing the version
16960                    // and cannot be updated as an update would get a new package name,
16961                    // unless this is the exact same version code which is useful for
16962                    // development.
16963                    PackageParser.Package existingPkg = mPackages.get(pkg.packageName);
16964                    if (existingPkg != null && existingPkg.mVersionCode != pkg.mVersionCode) {
16965                        res.setError(INSTALL_FAILED_DUPLICATE_PACKAGE, "Packages declaring "
16966                                + "static-shared libs cannot be updated");
16967                        return;
16968                    }
16969                }
16970                replacePackageLIF(pkg, parseFlags, scanFlags | SCAN_REPLACING, args.user,
16971                        installerPackageName, res, args.installReason);
16972            } else {
16973                installNewPackageLIF(pkg, parseFlags, scanFlags | SCAN_DELETE_DATA_ON_FAILURES,
16974                        args.user, installerPackageName, volumeUuid, res, args.installReason);
16975            }
16976        }
16977        synchronized (mPackages) {
16978            final PackageSetting ps = mSettings.mPackages.get(pkgName);
16979            if (ps != null) {
16980                res.newUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
16981            }
16982
16983            final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
16984            for (int i = 0; i < childCount; i++) {
16985                PackageParser.Package childPkg = pkg.childPackages.get(i);
16986                PackageInstalledInfo childRes = res.addedChildPackages.get(childPkg.packageName);
16987                PackageSetting childPs = mSettings.getPackageLPr(childPkg.packageName);
16988                if (childPs != null) {
16989                    childRes.newUsers = childPs.queryInstalledUsers(
16990                            sUserManager.getUserIds(), true);
16991                }
16992            }
16993
16994            if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
16995                updateSequenceNumberLP(pkgName, res.newUsers);
16996            }
16997        }
16998    }
16999
17000    private void startIntentFilterVerifications(int userId, boolean replacing,
17001            PackageParser.Package pkg) {
17002        if (mIntentFilterVerifierComponent == null) {
17003            Slog.w(TAG, "No IntentFilter verification will not be done as "
17004                    + "there is no IntentFilterVerifier available!");
17005            return;
17006        }
17007
17008        final int verifierUid = getPackageUid(
17009                mIntentFilterVerifierComponent.getPackageName(),
17010                MATCH_DEBUG_TRIAGED_MISSING,
17011                (userId == UserHandle.USER_ALL) ? UserHandle.USER_SYSTEM : userId);
17012
17013        Message msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS);
17014        msg.obj = new IFVerificationParams(pkg, replacing, userId, verifierUid);
17015        mHandler.sendMessage(msg);
17016
17017        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
17018        for (int i = 0; i < childCount; i++) {
17019            PackageParser.Package childPkg = pkg.childPackages.get(i);
17020            msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS);
17021            msg.obj = new IFVerificationParams(childPkg, replacing, userId, verifierUid);
17022            mHandler.sendMessage(msg);
17023        }
17024    }
17025
17026    private void verifyIntentFiltersIfNeeded(int userId, int verifierUid, boolean replacing,
17027            PackageParser.Package pkg) {
17028        int size = pkg.activities.size();
17029        if (size == 0) {
17030            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
17031                    "No activity, so no need to verify any IntentFilter!");
17032            return;
17033        }
17034
17035        final boolean hasDomainURLs = hasDomainURLs(pkg);
17036        if (!hasDomainURLs) {
17037            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
17038                    "No domain URLs, so no need to verify any IntentFilter!");
17039            return;
17040        }
17041
17042        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Checking for userId:" + userId
17043                + " if any IntentFilter from the " + size
17044                + " Activities needs verification ...");
17045
17046        int count = 0;
17047        final String packageName = pkg.packageName;
17048
17049        synchronized (mPackages) {
17050            // If this is a new install and we see that we've already run verification for this
17051            // package, we have nothing to do: it means the state was restored from backup.
17052            if (!replacing) {
17053                IntentFilterVerificationInfo ivi =
17054                        mSettings.getIntentFilterVerificationLPr(packageName);
17055                if (ivi != null) {
17056                    if (DEBUG_DOMAIN_VERIFICATION) {
17057                        Slog.i(TAG, "Package " + packageName+ " already verified: status="
17058                                + ivi.getStatusString());
17059                    }
17060                    return;
17061                }
17062            }
17063
17064            // If any filters need to be verified, then all need to be.
17065            boolean needToVerify = false;
17066            for (PackageParser.Activity a : pkg.activities) {
17067                for (ActivityIntentInfo filter : a.intents) {
17068                    if (filter.needsVerification() && needsNetworkVerificationLPr(filter)) {
17069                        if (DEBUG_DOMAIN_VERIFICATION) {
17070                            Slog.d(TAG, "Intent filter needs verification, so processing all filters");
17071                        }
17072                        needToVerify = true;
17073                        break;
17074                    }
17075                }
17076            }
17077
17078            if (needToVerify) {
17079                final int verificationId = mIntentFilterVerificationToken++;
17080                for (PackageParser.Activity a : pkg.activities) {
17081                    for (ActivityIntentInfo filter : a.intents) {
17082                        if (filter.handlesWebUris(true) && needsNetworkVerificationLPr(filter)) {
17083                            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
17084                                    "Verification needed for IntentFilter:" + filter.toString());
17085                            mIntentFilterVerifier.addOneIntentFilterVerification(
17086                                    verifierUid, userId, verificationId, filter, packageName);
17087                            count++;
17088                        }
17089                    }
17090                }
17091            }
17092        }
17093
17094        if (count > 0) {
17095            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Starting " + count
17096                    + " IntentFilter verification" + (count > 1 ? "s" : "")
17097                    +  " for userId:" + userId);
17098            mIntentFilterVerifier.startVerifications(userId);
17099        } else {
17100            if (DEBUG_DOMAIN_VERIFICATION) {
17101                Slog.d(TAG, "No filters or not all autoVerify for " + packageName);
17102            }
17103        }
17104    }
17105
17106    private boolean needsNetworkVerificationLPr(ActivityIntentInfo filter) {
17107        final ComponentName cn  = filter.activity.getComponentName();
17108        final String packageName = cn.getPackageName();
17109
17110        IntentFilterVerificationInfo ivi = mSettings.getIntentFilterVerificationLPr(
17111                packageName);
17112        if (ivi == null) {
17113            return true;
17114        }
17115        int status = ivi.getStatus();
17116        switch (status) {
17117            case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED:
17118            case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK:
17119                return true;
17120
17121            default:
17122                // Nothing to do
17123                return false;
17124        }
17125    }
17126
17127    private static boolean isMultiArch(ApplicationInfo info) {
17128        return (info.flags & ApplicationInfo.FLAG_MULTIARCH) != 0;
17129    }
17130
17131    private static boolean isExternal(PackageParser.Package pkg) {
17132        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
17133    }
17134
17135    private static boolean isExternal(PackageSetting ps) {
17136        return (ps.pkgFlags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
17137    }
17138
17139    private static boolean isSystemApp(PackageParser.Package pkg) {
17140        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0;
17141    }
17142
17143    private static boolean isPrivilegedApp(PackageParser.Package pkg) {
17144        return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0;
17145    }
17146
17147    private static boolean hasDomainURLs(PackageParser.Package pkg) {
17148        return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_HAS_DOMAIN_URLS) != 0;
17149    }
17150
17151    private static boolean isSystemApp(PackageSetting ps) {
17152        return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0;
17153    }
17154
17155    private static boolean isUpdatedSystemApp(PackageSetting ps) {
17156        return (ps.pkgFlags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0;
17157    }
17158
17159    private int packageFlagsToInstallFlags(PackageSetting ps) {
17160        int installFlags = 0;
17161        if (isExternal(ps) && TextUtils.isEmpty(ps.volumeUuid)) {
17162            // This existing package was an external ASEC install when we have
17163            // the external flag without a UUID
17164            installFlags |= PackageManager.INSTALL_EXTERNAL;
17165        }
17166        if (ps.isForwardLocked()) {
17167            installFlags |= PackageManager.INSTALL_FORWARD_LOCK;
17168        }
17169        return installFlags;
17170    }
17171
17172    private String getVolumeUuidForPackage(PackageParser.Package pkg) {
17173        if (isExternal(pkg)) {
17174            if (TextUtils.isEmpty(pkg.volumeUuid)) {
17175                return StorageManager.UUID_PRIMARY_PHYSICAL;
17176            } else {
17177                return pkg.volumeUuid;
17178            }
17179        } else {
17180            return StorageManager.UUID_PRIVATE_INTERNAL;
17181        }
17182    }
17183
17184    private VersionInfo getSettingsVersionForPackage(PackageParser.Package pkg) {
17185        if (isExternal(pkg)) {
17186            if (TextUtils.isEmpty(pkg.volumeUuid)) {
17187                return mSettings.getExternalVersion();
17188            } else {
17189                return mSettings.findOrCreateVersion(pkg.volumeUuid);
17190            }
17191        } else {
17192            return mSettings.getInternalVersion();
17193        }
17194    }
17195
17196    private void deleteTempPackageFiles() {
17197        final FilenameFilter filter = new FilenameFilter() {
17198            public boolean accept(File dir, String name) {
17199                return name.startsWith("vmdl") && name.endsWith(".tmp");
17200            }
17201        };
17202        for (File file : mDrmAppPrivateInstallDir.listFiles(filter)) {
17203            file.delete();
17204        }
17205    }
17206
17207    @Override
17208    public void deletePackageAsUser(String packageName, int versionCode,
17209            IPackageDeleteObserver observer, int userId, int flags) {
17210        deletePackageVersioned(new VersionedPackage(packageName, versionCode),
17211                new LegacyPackageDeleteObserver(observer).getBinder(), userId, flags);
17212    }
17213
17214    @Override
17215    public void deletePackageVersioned(VersionedPackage versionedPackage,
17216            final IPackageDeleteObserver2 observer, final int userId, final int deleteFlags) {
17217        mContext.enforceCallingOrSelfPermission(
17218                android.Manifest.permission.DELETE_PACKAGES, null);
17219        Preconditions.checkNotNull(versionedPackage);
17220        Preconditions.checkNotNull(observer);
17221        Preconditions.checkArgumentInRange(versionedPackage.getVersionCode(),
17222                PackageManager.VERSION_CODE_HIGHEST,
17223                Integer.MAX_VALUE, "versionCode must be >= -1");
17224
17225        final String packageName = versionedPackage.getPackageName();
17226        // TODO: We will change version code to long, so in the new API it is long
17227        final int versionCode = (int) versionedPackage.getVersionCode();
17228        final String internalPackageName;
17229        synchronized (mPackages) {
17230            // Normalize package name to handle renamed packages and static libs
17231            internalPackageName = resolveInternalPackageNameLPr(versionedPackage.getPackageName(),
17232                    // TODO: We will change version code to long, so in the new API it is long
17233                    (int) versionedPackage.getVersionCode());
17234        }
17235
17236        final int uid = Binder.getCallingUid();
17237        if (!isOrphaned(internalPackageName)
17238                && !isCallerAllowedToSilentlyUninstall(uid, internalPackageName)) {
17239            try {
17240                final Intent intent = new Intent(Intent.ACTION_UNINSTALL_PACKAGE);
17241                intent.setData(Uri.fromParts(PACKAGE_SCHEME, packageName, null));
17242                intent.putExtra(PackageInstaller.EXTRA_CALLBACK, observer.asBinder());
17243                observer.onUserActionRequired(intent);
17244            } catch (RemoteException re) {
17245            }
17246            return;
17247        }
17248        final boolean deleteAllUsers = (deleteFlags & PackageManager.DELETE_ALL_USERS) != 0;
17249        final int[] users = deleteAllUsers ? sUserManager.getUserIds() : new int[]{ userId };
17250        if (UserHandle.getUserId(uid) != userId || (deleteAllUsers && users.length > 1)) {
17251            mContext.enforceCallingOrSelfPermission(
17252                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
17253                    "deletePackage for user " + userId);
17254        }
17255
17256        if (isUserRestricted(userId, UserManager.DISALLOW_UNINSTALL_APPS)) {
17257            try {
17258                observer.onPackageDeleted(packageName,
17259                        PackageManager.DELETE_FAILED_USER_RESTRICTED, null);
17260            } catch (RemoteException re) {
17261            }
17262            return;
17263        }
17264
17265        if (!deleteAllUsers && getBlockUninstallForUser(internalPackageName, userId)) {
17266            try {
17267                observer.onPackageDeleted(packageName,
17268                        PackageManager.DELETE_FAILED_OWNER_BLOCKED, null);
17269            } catch (RemoteException re) {
17270            }
17271            return;
17272        }
17273
17274        if (DEBUG_REMOVE) {
17275            Slog.d(TAG, "deletePackageAsUser: pkg=" + internalPackageName + " user=" + userId
17276                    + " deleteAllUsers: " + deleteAllUsers + " version="
17277                    + (versionCode == PackageManager.VERSION_CODE_HIGHEST
17278                    ? "VERSION_CODE_HIGHEST" : versionCode));
17279        }
17280        // Queue up an async operation since the package deletion may take a little while.
17281        mHandler.post(new Runnable() {
17282            public void run() {
17283                mHandler.removeCallbacks(this);
17284                int returnCode;
17285                if (!deleteAllUsers) {
17286                    returnCode = deletePackageX(internalPackageName, versionCode,
17287                            userId, deleteFlags);
17288                } else {
17289                    int[] blockUninstallUserIds = getBlockUninstallForUsers(
17290                            internalPackageName, users);
17291                    // If nobody is blocking uninstall, proceed with delete for all users
17292                    if (ArrayUtils.isEmpty(blockUninstallUserIds)) {
17293                        returnCode = deletePackageX(internalPackageName, versionCode,
17294                                userId, deleteFlags);
17295                    } else {
17296                        // Otherwise uninstall individually for users with blockUninstalls=false
17297                        final int userFlags = deleteFlags & ~PackageManager.DELETE_ALL_USERS;
17298                        for (int userId : users) {
17299                            if (!ArrayUtils.contains(blockUninstallUserIds, userId)) {
17300                                returnCode = deletePackageX(internalPackageName, versionCode,
17301                                        userId, userFlags);
17302                                if (returnCode != PackageManager.DELETE_SUCCEEDED) {
17303                                    Slog.w(TAG, "Package delete failed for user " + userId
17304                                            + ", returnCode " + returnCode);
17305                                }
17306                            }
17307                        }
17308                        // The app has only been marked uninstalled for certain users.
17309                        // We still need to report that delete was blocked
17310                        returnCode = PackageManager.DELETE_FAILED_OWNER_BLOCKED;
17311                    }
17312                }
17313                try {
17314                    observer.onPackageDeleted(packageName, returnCode, null);
17315                } catch (RemoteException e) {
17316                    Log.i(TAG, "Observer no longer exists.");
17317                } //end catch
17318            } //end run
17319        });
17320    }
17321
17322    private String resolveExternalPackageNameLPr(PackageParser.Package pkg) {
17323        if (pkg.staticSharedLibName != null) {
17324            return pkg.manifestPackageName;
17325        }
17326        return pkg.packageName;
17327    }
17328
17329    private String resolveInternalPackageNameLPr(String packageName, int versionCode) {
17330        // Handle renamed packages
17331        String normalizedPackageName = mSettings.getRenamedPackageLPr(packageName);
17332        packageName = normalizedPackageName != null ? normalizedPackageName : packageName;
17333
17334        // Is this a static library?
17335        SparseArray<SharedLibraryEntry> versionedLib =
17336                mStaticLibsByDeclaringPackage.get(packageName);
17337        if (versionedLib == null || versionedLib.size() <= 0) {
17338            return packageName;
17339        }
17340
17341        // Figure out which lib versions the caller can see
17342        SparseIntArray versionsCallerCanSee = null;
17343        final int callingAppId = UserHandle.getAppId(Binder.getCallingUid());
17344        if (callingAppId != Process.SYSTEM_UID && callingAppId != Process.SHELL_UID
17345                && callingAppId != Process.ROOT_UID) {
17346            versionsCallerCanSee = new SparseIntArray();
17347            String libName = versionedLib.valueAt(0).info.getName();
17348            String[] uidPackages = getPackagesForUid(Binder.getCallingUid());
17349            if (uidPackages != null) {
17350                for (String uidPackage : uidPackages) {
17351                    PackageSetting ps = mSettings.getPackageLPr(uidPackage);
17352                    final int libIdx = ArrayUtils.indexOf(ps.usesStaticLibraries, libName);
17353                    if (libIdx >= 0) {
17354                        final int libVersion = ps.usesStaticLibrariesVersions[libIdx];
17355                        versionsCallerCanSee.append(libVersion, libVersion);
17356                    }
17357                }
17358            }
17359        }
17360
17361        // Caller can see nothing - done
17362        if (versionsCallerCanSee != null && versionsCallerCanSee.size() <= 0) {
17363            return packageName;
17364        }
17365
17366        // Find the version the caller can see and the app version code
17367        SharedLibraryEntry highestVersion = null;
17368        final int versionCount = versionedLib.size();
17369        for (int i = 0; i < versionCount; i++) {
17370            SharedLibraryEntry libEntry = versionedLib.valueAt(i);
17371            if (versionsCallerCanSee != null && versionsCallerCanSee.indexOfKey(
17372                    libEntry.info.getVersion()) < 0) {
17373                continue;
17374            }
17375            // TODO: We will change version code to long, so in the new API it is long
17376            final int libVersionCode = (int) libEntry.info.getDeclaringPackage().getVersionCode();
17377            if (versionCode != PackageManager.VERSION_CODE_HIGHEST) {
17378                if (libVersionCode == versionCode) {
17379                    return libEntry.apk;
17380                }
17381            } else if (highestVersion == null) {
17382                highestVersion = libEntry;
17383            } else if (libVersionCode  > highestVersion.info
17384                    .getDeclaringPackage().getVersionCode()) {
17385                highestVersion = libEntry;
17386            }
17387        }
17388
17389        if (highestVersion != null) {
17390            return highestVersion.apk;
17391        }
17392
17393        return packageName;
17394    }
17395
17396    private boolean isCallerAllowedToSilentlyUninstall(int callingUid, String pkgName) {
17397        if (callingUid == Process.SHELL_UID || callingUid == Process.ROOT_UID
17398              || callingUid == Process.SYSTEM_UID) {
17399            return true;
17400        }
17401        final int callingUserId = UserHandle.getUserId(callingUid);
17402        // If the caller installed the pkgName, then allow it to silently uninstall.
17403        if (callingUid == getPackageUid(getInstallerPackageName(pkgName), 0, callingUserId)) {
17404            return true;
17405        }
17406
17407        // Allow package verifier to silently uninstall.
17408        if (mRequiredVerifierPackage != null &&
17409                callingUid == getPackageUid(mRequiredVerifierPackage, 0, callingUserId)) {
17410            return true;
17411        }
17412
17413        // Allow package uninstaller to silently uninstall.
17414        if (mRequiredUninstallerPackage != null &&
17415                callingUid == getPackageUid(mRequiredUninstallerPackage, 0, callingUserId)) {
17416            return true;
17417        }
17418
17419        // Allow storage manager to silently uninstall.
17420        if (mStorageManagerPackage != null &&
17421                callingUid == getPackageUid(mStorageManagerPackage, 0, callingUserId)) {
17422            return true;
17423        }
17424        return false;
17425    }
17426
17427    private int[] getBlockUninstallForUsers(String packageName, int[] userIds) {
17428        int[] result = EMPTY_INT_ARRAY;
17429        for (int userId : userIds) {
17430            if (getBlockUninstallForUser(packageName, userId)) {
17431                result = ArrayUtils.appendInt(result, userId);
17432            }
17433        }
17434        return result;
17435    }
17436
17437    @Override
17438    public boolean isPackageDeviceAdminOnAnyUser(String packageName) {
17439        return isPackageDeviceAdmin(packageName, UserHandle.USER_ALL);
17440    }
17441
17442    private boolean isPackageDeviceAdmin(String packageName, int userId) {
17443        IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface(
17444                ServiceManager.getService(Context.DEVICE_POLICY_SERVICE));
17445        try {
17446            if (dpm != null) {
17447                final ComponentName deviceOwnerComponentName = dpm.getDeviceOwnerComponent(
17448                        /* callingUserOnly =*/ false);
17449                final String deviceOwnerPackageName = deviceOwnerComponentName == null ? null
17450                        : deviceOwnerComponentName.getPackageName();
17451                // Does the package contains the device owner?
17452                // TODO Do we have to do it even if userId != UserHandle.USER_ALL?  Otherwise,
17453                // this check is probably not needed, since DO should be registered as a device
17454                // admin on some user too. (Original bug for this: b/17657954)
17455                if (packageName.equals(deviceOwnerPackageName)) {
17456                    return true;
17457                }
17458                // Does it contain a device admin for any user?
17459                int[] users;
17460                if (userId == UserHandle.USER_ALL) {
17461                    users = sUserManager.getUserIds();
17462                } else {
17463                    users = new int[]{userId};
17464                }
17465                for (int i = 0; i < users.length; ++i) {
17466                    if (dpm.packageHasActiveAdmins(packageName, users[i])) {
17467                        return true;
17468                    }
17469                }
17470            }
17471        } catch (RemoteException e) {
17472        }
17473        return false;
17474    }
17475
17476    private boolean shouldKeepUninstalledPackageLPr(String packageName) {
17477        return mKeepUninstalledPackages != null && mKeepUninstalledPackages.contains(packageName);
17478    }
17479
17480    /**
17481     *  This method is an internal method that could be get invoked either
17482     *  to delete an installed package or to clean up a failed installation.
17483     *  After deleting an installed package, a broadcast is sent to notify any
17484     *  listeners that the package has been removed. For cleaning up a failed
17485     *  installation, the broadcast is not necessary since the package's
17486     *  installation wouldn't have sent the initial broadcast either
17487     *  The key steps in deleting a package are
17488     *  deleting the package information in internal structures like mPackages,
17489     *  deleting the packages base directories through installd
17490     *  updating mSettings to reflect current status
17491     *  persisting settings for later use
17492     *  sending a broadcast if necessary
17493     */
17494    private int deletePackageX(String packageName, int versionCode, int userId, int deleteFlags) {
17495        final PackageRemovedInfo info = new PackageRemovedInfo();
17496        final boolean res;
17497
17498        final int removeUser = (deleteFlags & PackageManager.DELETE_ALL_USERS) != 0
17499                ? UserHandle.USER_ALL : userId;
17500
17501        if (isPackageDeviceAdmin(packageName, removeUser)) {
17502            Slog.w(TAG, "Not removing package " + packageName + ": has active device admin");
17503            return PackageManager.DELETE_FAILED_DEVICE_POLICY_MANAGER;
17504        }
17505
17506        PackageSetting uninstalledPs = null;
17507
17508        // for the uninstall-updates case and restricted profiles, remember the per-
17509        // user handle installed state
17510        int[] allUsers;
17511        synchronized (mPackages) {
17512            uninstalledPs = mSettings.mPackages.get(packageName);
17513            if (uninstalledPs == null) {
17514                Slog.w(TAG, "Not removing non-existent package " + packageName);
17515                return PackageManager.DELETE_FAILED_INTERNAL_ERROR;
17516            }
17517
17518            if (versionCode != PackageManager.VERSION_CODE_HIGHEST
17519                    && uninstalledPs.versionCode != versionCode) {
17520                Slog.w(TAG, "Not removing package " + packageName + " with versionCode "
17521                        + uninstalledPs.versionCode + " != " + versionCode);
17522                return PackageManager.DELETE_FAILED_INTERNAL_ERROR;
17523            }
17524
17525            // Static shared libs can be declared by any package, so let us not
17526            // allow removing a package if it provides a lib others depend on.
17527            PackageParser.Package pkg = mPackages.get(packageName);
17528            if (pkg != null && pkg.staticSharedLibName != null) {
17529                SharedLibraryEntry libEntry = getSharedLibraryEntryLPr(pkg.staticSharedLibName,
17530                        pkg.staticSharedLibVersion);
17531                if (libEntry != null) {
17532                    List<VersionedPackage> libClientPackages = getPackagesUsingSharedLibraryLPr(
17533                            libEntry.info, 0, userId);
17534                    if (!ArrayUtils.isEmpty(libClientPackages)) {
17535                        Slog.w(TAG, "Not removing package " + pkg.manifestPackageName
17536                                + " hosting lib " + libEntry.info.getName() + " version "
17537                                + libEntry.info.getVersion()  + " used by " + libClientPackages);
17538                        return PackageManager.DELETE_FAILED_USED_SHARED_LIBRARY;
17539                    }
17540                }
17541            }
17542
17543            allUsers = sUserManager.getUserIds();
17544            info.origUsers = uninstalledPs.queryInstalledUsers(allUsers, true);
17545        }
17546
17547        final int freezeUser;
17548        if (isUpdatedSystemApp(uninstalledPs)
17549                && ((deleteFlags & PackageManager.DELETE_SYSTEM_APP) == 0)) {
17550            // We're downgrading a system app, which will apply to all users, so
17551            // freeze them all during the downgrade
17552            freezeUser = UserHandle.USER_ALL;
17553        } else {
17554            freezeUser = removeUser;
17555        }
17556
17557        synchronized (mInstallLock) {
17558            if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageX: pkg=" + packageName + " user=" + userId);
17559            try (PackageFreezer freezer = freezePackageForDelete(packageName, freezeUser,
17560                    deleteFlags, "deletePackageX")) {
17561                res = deletePackageLIF(packageName, UserHandle.of(removeUser), true, allUsers,
17562                        deleteFlags | FLAGS_REMOVE_CHATTY, info, true, null);
17563            }
17564            synchronized (mPackages) {
17565                if (res) {
17566                    mInstantAppRegistry.onPackageUninstalledLPw(uninstalledPs.pkg,
17567                            info.removedUsers);
17568                    updateSequenceNumberLP(packageName, info.removedUsers);
17569                }
17570            }
17571        }
17572
17573        if (res) {
17574            final boolean killApp = (deleteFlags & PackageManager.DELETE_DONT_KILL_APP) == 0;
17575            info.sendPackageRemovedBroadcasts(killApp);
17576            info.sendSystemPackageUpdatedBroadcasts();
17577            info.sendSystemPackageAppearedBroadcasts();
17578        }
17579        // Force a gc here.
17580        Runtime.getRuntime().gc();
17581        // Delete the resources here after sending the broadcast to let
17582        // other processes clean up before deleting resources.
17583        if (info.args != null) {
17584            synchronized (mInstallLock) {
17585                info.args.doPostDeleteLI(true);
17586            }
17587        }
17588
17589        return res ? PackageManager.DELETE_SUCCEEDED : PackageManager.DELETE_FAILED_INTERNAL_ERROR;
17590    }
17591
17592    class PackageRemovedInfo {
17593        String removedPackage;
17594        int uid = -1;
17595        int removedAppId = -1;
17596        int[] origUsers;
17597        int[] removedUsers = null;
17598        SparseArray<Integer> installReasons;
17599        boolean isRemovedPackageSystemUpdate = false;
17600        boolean isUpdate;
17601        boolean dataRemoved;
17602        boolean removedForAllUsers;
17603        boolean isStaticSharedLib;
17604        // Clean up resources deleted packages.
17605        InstallArgs args = null;
17606        ArrayMap<String, PackageRemovedInfo> removedChildPackages;
17607        ArrayMap<String, PackageInstalledInfo> appearedChildPackages;
17608
17609        void sendPackageRemovedBroadcasts(boolean killApp) {
17610            sendPackageRemovedBroadcastInternal(killApp);
17611            final int childCount = removedChildPackages != null ? removedChildPackages.size() : 0;
17612            for (int i = 0; i < childCount; i++) {
17613                PackageRemovedInfo childInfo = removedChildPackages.valueAt(i);
17614                childInfo.sendPackageRemovedBroadcastInternal(killApp);
17615            }
17616        }
17617
17618        void sendSystemPackageUpdatedBroadcasts() {
17619            if (isRemovedPackageSystemUpdate) {
17620                sendSystemPackageUpdatedBroadcastsInternal();
17621                final int childCount = (removedChildPackages != null)
17622                        ? removedChildPackages.size() : 0;
17623                for (int i = 0; i < childCount; i++) {
17624                    PackageRemovedInfo childInfo = removedChildPackages.valueAt(i);
17625                    if (childInfo.isRemovedPackageSystemUpdate) {
17626                        childInfo.sendSystemPackageUpdatedBroadcastsInternal();
17627                    }
17628                }
17629            }
17630        }
17631
17632        void sendSystemPackageAppearedBroadcasts() {
17633            final int packageCount = (appearedChildPackages != null)
17634                    ? appearedChildPackages.size() : 0;
17635            for (int i = 0; i < packageCount; i++) {
17636                PackageInstalledInfo installedInfo = appearedChildPackages.valueAt(i);
17637                sendPackageAddedForNewUsers(installedInfo.name, true,
17638                        UserHandle.getAppId(installedInfo.uid), installedInfo.newUsers);
17639            }
17640        }
17641
17642        private void sendSystemPackageUpdatedBroadcastsInternal() {
17643            Bundle extras = new Bundle(2);
17644            extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid);
17645            extras.putBoolean(Intent.EXTRA_REPLACING, true);
17646            sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, removedPackage,
17647                    extras, 0, null, null, null);
17648            sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, removedPackage,
17649                    extras, 0, null, null, null);
17650            sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, null,
17651                    null, 0, removedPackage, null, null);
17652        }
17653
17654        private void sendPackageRemovedBroadcastInternal(boolean killApp) {
17655            // Don't send static shared library removal broadcasts as these
17656            // libs are visible only the the apps that depend on them an one
17657            // cannot remove the library if it has a dependency.
17658            if (isStaticSharedLib) {
17659                return;
17660            }
17661            Bundle extras = new Bundle(2);
17662            extras.putInt(Intent.EXTRA_UID, removedAppId >= 0  ? removedAppId : uid);
17663            extras.putBoolean(Intent.EXTRA_DATA_REMOVED, dataRemoved);
17664            extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, !killApp);
17665            if (isUpdate || isRemovedPackageSystemUpdate) {
17666                extras.putBoolean(Intent.EXTRA_REPLACING, true);
17667            }
17668            extras.putBoolean(Intent.EXTRA_REMOVED_FOR_ALL_USERS, removedForAllUsers);
17669            if (removedPackage != null) {
17670                sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, removedPackage,
17671                        extras, 0, null, null, removedUsers);
17672                if (dataRemoved && !isRemovedPackageSystemUpdate) {
17673                    sendPackageBroadcast(Intent.ACTION_PACKAGE_FULLY_REMOVED,
17674                            removedPackage, extras, Intent.FLAG_RECEIVER_INCLUDE_BACKGROUND,
17675                            null, null, removedUsers);
17676                }
17677            }
17678            if (removedAppId >= 0) {
17679                sendPackageBroadcast(Intent.ACTION_UID_REMOVED, null, extras, 0, null, null,
17680                        removedUsers);
17681            }
17682        }
17683    }
17684
17685    /*
17686     * This method deletes the package from internal data structures. If the DONT_DELETE_DATA
17687     * flag is not set, the data directory is removed as well.
17688     * make sure this flag is set for partially installed apps. If not its meaningless to
17689     * delete a partially installed application.
17690     */
17691    private void removePackageDataLIF(PackageSetting ps, int[] allUserHandles,
17692            PackageRemovedInfo outInfo, int flags, boolean writeSettings) {
17693        String packageName = ps.name;
17694        if (DEBUG_REMOVE) Slog.d(TAG, "removePackageDataLI: " + ps);
17695        // Retrieve object to delete permissions for shared user later on
17696        final PackageParser.Package deletedPkg;
17697        final PackageSetting deletedPs;
17698        // reader
17699        synchronized (mPackages) {
17700            deletedPkg = mPackages.get(packageName);
17701            deletedPs = mSettings.mPackages.get(packageName);
17702            if (outInfo != null) {
17703                outInfo.removedPackage = packageName;
17704                outInfo.isStaticSharedLib = deletedPkg != null
17705                        && deletedPkg.staticSharedLibName != null;
17706                outInfo.removedUsers = deletedPs != null
17707                        ? deletedPs.queryInstalledUsers(sUserManager.getUserIds(), true)
17708                        : null;
17709            }
17710        }
17711
17712        removePackageLI(ps, (flags & FLAGS_REMOVE_CHATTY) != 0);
17713
17714        if ((flags & PackageManager.DELETE_KEEP_DATA) == 0) {
17715            final PackageParser.Package resolvedPkg;
17716            if (deletedPkg != null) {
17717                resolvedPkg = deletedPkg;
17718            } else {
17719                // We don't have a parsed package when it lives on an ejected
17720                // adopted storage device, so fake something together
17721                resolvedPkg = new PackageParser.Package(ps.name);
17722                resolvedPkg.setVolumeUuid(ps.volumeUuid);
17723            }
17724            destroyAppDataLIF(resolvedPkg, UserHandle.USER_ALL,
17725                    StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
17726            destroyAppProfilesLIF(resolvedPkg, UserHandle.USER_ALL);
17727            if (outInfo != null) {
17728                outInfo.dataRemoved = true;
17729            }
17730            schedulePackageCleaning(packageName, UserHandle.USER_ALL, true);
17731        }
17732
17733        int removedAppId = -1;
17734
17735        // writer
17736        synchronized (mPackages) {
17737            boolean installedStateChanged = false;
17738            if (deletedPs != null) {
17739                if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) {
17740                    clearIntentFilterVerificationsLPw(deletedPs.name, UserHandle.USER_ALL);
17741                    clearDefaultBrowserIfNeeded(packageName);
17742                    mSettings.mKeySetManagerService.removeAppKeySetDataLPw(packageName);
17743                    removedAppId = mSettings.removePackageLPw(packageName);
17744                    if (outInfo != null) {
17745                        outInfo.removedAppId = removedAppId;
17746                    }
17747                    updatePermissionsLPw(deletedPs.name, null, 0);
17748                    if (deletedPs.sharedUser != null) {
17749                        // Remove permissions associated with package. Since runtime
17750                        // permissions are per user we have to kill the removed package
17751                        // or packages running under the shared user of the removed
17752                        // package if revoking the permissions requested only by the removed
17753                        // package is successful and this causes a change in gids.
17754                        for (int userId : UserManagerService.getInstance().getUserIds()) {
17755                            final int userIdToKill = mSettings.updateSharedUserPermsLPw(deletedPs,
17756                                    userId);
17757                            if (userIdToKill == UserHandle.USER_ALL
17758                                    || userIdToKill >= UserHandle.USER_SYSTEM) {
17759                                // If gids changed for this user, kill all affected packages.
17760                                mHandler.post(new Runnable() {
17761                                    @Override
17762                                    public void run() {
17763                                        // This has to happen with no lock held.
17764                                        killApplication(deletedPs.name, deletedPs.appId,
17765                                                KILL_APP_REASON_GIDS_CHANGED);
17766                                    }
17767                                });
17768                                break;
17769                            }
17770                        }
17771                    }
17772                    clearPackagePreferredActivitiesLPw(deletedPs.name, UserHandle.USER_ALL);
17773                }
17774                // make sure to preserve per-user disabled state if this removal was just
17775                // a downgrade of a system app to the factory package
17776                if (allUserHandles != null && outInfo != null && outInfo.origUsers != null) {
17777                    if (DEBUG_REMOVE) {
17778                        Slog.d(TAG, "Propagating install state across downgrade");
17779                    }
17780                    for (int userId : allUserHandles) {
17781                        final boolean installed = ArrayUtils.contains(outInfo.origUsers, userId);
17782                        if (DEBUG_REMOVE) {
17783                            Slog.d(TAG, "    user " + userId + " => " + installed);
17784                        }
17785                        if (installed != ps.getInstalled(userId)) {
17786                            installedStateChanged = true;
17787                        }
17788                        ps.setInstalled(installed, userId);
17789                    }
17790                }
17791            }
17792            // can downgrade to reader
17793            if (writeSettings) {
17794                // Save settings now
17795                mSettings.writeLPr();
17796            }
17797            if (installedStateChanged) {
17798                mSettings.writeKernelMappingLPr(ps);
17799            }
17800        }
17801        if (removedAppId != -1) {
17802            // A user ID was deleted here. Go through all users and remove it
17803            // from KeyStore.
17804            removeKeystoreDataIfNeeded(UserHandle.USER_ALL, removedAppId);
17805        }
17806    }
17807
17808    static boolean locationIsPrivileged(File path) {
17809        try {
17810            final String privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app")
17811                    .getCanonicalPath();
17812            return path.getCanonicalPath().startsWith(privilegedAppDir);
17813        } catch (IOException e) {
17814            Slog.e(TAG, "Unable to access code path " + path);
17815        }
17816        return false;
17817    }
17818
17819    /*
17820     * Tries to delete system package.
17821     */
17822    private boolean deleteSystemPackageLIF(PackageParser.Package deletedPkg,
17823            PackageSetting deletedPs, int[] allUserHandles, int flags, PackageRemovedInfo outInfo,
17824            boolean writeSettings) {
17825        if (deletedPs.parentPackageName != null) {
17826            Slog.w(TAG, "Attempt to delete child system package " + deletedPkg.packageName);
17827            return false;
17828        }
17829
17830        final boolean applyUserRestrictions
17831                = (allUserHandles != null) && (outInfo.origUsers != null);
17832        final PackageSetting disabledPs;
17833        // Confirm if the system package has been updated
17834        // An updated system app can be deleted. This will also have to restore
17835        // the system pkg from system partition
17836        // reader
17837        synchronized (mPackages) {
17838            disabledPs = mSettings.getDisabledSystemPkgLPr(deletedPs.name);
17839        }
17840
17841        if (DEBUG_REMOVE) Slog.d(TAG, "deleteSystemPackageLI: newPs=" + deletedPkg.packageName
17842                + " disabledPs=" + disabledPs);
17843
17844        if (disabledPs == null) {
17845            Slog.w(TAG, "Attempt to delete unknown system package "+ deletedPkg.packageName);
17846            return false;
17847        } else if (DEBUG_REMOVE) {
17848            Slog.d(TAG, "Deleting system pkg from data partition");
17849        }
17850
17851        if (DEBUG_REMOVE) {
17852            if (applyUserRestrictions) {
17853                Slog.d(TAG, "Remembering install states:");
17854                for (int userId : allUserHandles) {
17855                    final boolean finstalled = ArrayUtils.contains(outInfo.origUsers, userId);
17856                    Slog.d(TAG, "   u=" + userId + " inst=" + finstalled);
17857                }
17858            }
17859        }
17860
17861        // Delete the updated package
17862        outInfo.isRemovedPackageSystemUpdate = true;
17863        if (outInfo.removedChildPackages != null) {
17864            final int childCount = (deletedPs.childPackageNames != null)
17865                    ? deletedPs.childPackageNames.size() : 0;
17866            for (int i = 0; i < childCount; i++) {
17867                String childPackageName = deletedPs.childPackageNames.get(i);
17868                if (disabledPs.childPackageNames != null && disabledPs.childPackageNames
17869                        .contains(childPackageName)) {
17870                    PackageRemovedInfo childInfo = outInfo.removedChildPackages.get(
17871                            childPackageName);
17872                    if (childInfo != null) {
17873                        childInfo.isRemovedPackageSystemUpdate = true;
17874                    }
17875                }
17876            }
17877        }
17878
17879        if (disabledPs.versionCode < deletedPs.versionCode) {
17880            // Delete data for downgrades
17881            flags &= ~PackageManager.DELETE_KEEP_DATA;
17882        } else {
17883            // Preserve data by setting flag
17884            flags |= PackageManager.DELETE_KEEP_DATA;
17885        }
17886
17887        boolean ret = deleteInstalledPackageLIF(deletedPs, true, flags, allUserHandles,
17888                outInfo, writeSettings, disabledPs.pkg);
17889        if (!ret) {
17890            return false;
17891        }
17892
17893        // writer
17894        synchronized (mPackages) {
17895            // Reinstate the old system package
17896            enableSystemPackageLPw(disabledPs.pkg);
17897            // Remove any native libraries from the upgraded package.
17898            removeNativeBinariesLI(deletedPs);
17899        }
17900
17901        // Install the system package
17902        if (DEBUG_REMOVE) Slog.d(TAG, "Re-installing system package: " + disabledPs);
17903        int parseFlags = mDefParseFlags
17904                | PackageParser.PARSE_MUST_BE_APK
17905                | PackageParser.PARSE_IS_SYSTEM
17906                | PackageParser.PARSE_IS_SYSTEM_DIR;
17907        if (locationIsPrivileged(disabledPs.codePath)) {
17908            parseFlags |= PackageParser.PARSE_IS_PRIVILEGED;
17909        }
17910
17911        final PackageParser.Package newPkg;
17912        try {
17913            newPkg = scanPackageTracedLI(disabledPs.codePath, parseFlags, 0 /* scanFlags */,
17914                0 /* currentTime */, null);
17915        } catch (PackageManagerException e) {
17916            Slog.w(TAG, "Failed to restore system package:" + deletedPkg.packageName + ": "
17917                    + e.getMessage());
17918            return false;
17919        }
17920
17921        try {
17922            // update shared libraries for the newly re-installed system package
17923            updateSharedLibrariesLPr(newPkg, null);
17924        } catch (PackageManagerException e) {
17925            Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
17926        }
17927
17928        prepareAppDataAfterInstallLIF(newPkg);
17929
17930        // writer
17931        synchronized (mPackages) {
17932            PackageSetting ps = mSettings.mPackages.get(newPkg.packageName);
17933
17934            // Propagate the permissions state as we do not want to drop on the floor
17935            // runtime permissions. The update permissions method below will take
17936            // care of removing obsolete permissions and grant install permissions.
17937            ps.getPermissionsState().copyFrom(deletedPs.getPermissionsState());
17938            updatePermissionsLPw(newPkg.packageName, newPkg,
17939                    UPDATE_PERMISSIONS_ALL | UPDATE_PERMISSIONS_REPLACE_PKG);
17940
17941            if (applyUserRestrictions) {
17942                boolean installedStateChanged = false;
17943                if (DEBUG_REMOVE) {
17944                    Slog.d(TAG, "Propagating install state across reinstall");
17945                }
17946                for (int userId : allUserHandles) {
17947                    final boolean installed = ArrayUtils.contains(outInfo.origUsers, userId);
17948                    if (DEBUG_REMOVE) {
17949                        Slog.d(TAG, "    user " + userId + " => " + installed);
17950                    }
17951                    if (installed != ps.getInstalled(userId)) {
17952                        installedStateChanged = true;
17953                    }
17954                    ps.setInstalled(installed, userId);
17955
17956                    mSettings.writeRuntimePermissionsForUserLPr(userId, false);
17957                }
17958                // Regardless of writeSettings we need to ensure that this restriction
17959                // state propagation is persisted
17960                mSettings.writeAllUsersPackageRestrictionsLPr();
17961                if (installedStateChanged) {
17962                    mSettings.writeKernelMappingLPr(ps);
17963                }
17964            }
17965            // can downgrade to reader here
17966            if (writeSettings) {
17967                mSettings.writeLPr();
17968            }
17969        }
17970        return true;
17971    }
17972
17973    private boolean deleteInstalledPackageLIF(PackageSetting ps,
17974            boolean deleteCodeAndResources, int flags, int[] allUserHandles,
17975            PackageRemovedInfo outInfo, boolean writeSettings,
17976            PackageParser.Package replacingPackage) {
17977        synchronized (mPackages) {
17978            if (outInfo != null) {
17979                outInfo.uid = ps.appId;
17980            }
17981
17982            if (outInfo != null && outInfo.removedChildPackages != null) {
17983                final int childCount = (ps.childPackageNames != null)
17984                        ? ps.childPackageNames.size() : 0;
17985                for (int i = 0; i < childCount; i++) {
17986                    String childPackageName = ps.childPackageNames.get(i);
17987                    PackageSetting childPs = mSettings.mPackages.get(childPackageName);
17988                    if (childPs == null) {
17989                        return false;
17990                    }
17991                    PackageRemovedInfo childInfo = outInfo.removedChildPackages.get(
17992                            childPackageName);
17993                    if (childInfo != null) {
17994                        childInfo.uid = childPs.appId;
17995                    }
17996                }
17997            }
17998        }
17999
18000        // Delete package data from internal structures and also remove data if flag is set
18001        removePackageDataLIF(ps, allUserHandles, outInfo, flags, writeSettings);
18002
18003        // Delete the child packages data
18004        final int childCount = (ps.childPackageNames != null) ? ps.childPackageNames.size() : 0;
18005        for (int i = 0; i < childCount; i++) {
18006            PackageSetting childPs;
18007            synchronized (mPackages) {
18008                childPs = mSettings.getPackageLPr(ps.childPackageNames.get(i));
18009            }
18010            if (childPs != null) {
18011                PackageRemovedInfo childOutInfo = (outInfo != null
18012                        && outInfo.removedChildPackages != null)
18013                        ? outInfo.removedChildPackages.get(childPs.name) : null;
18014                final int deleteFlags = (flags & DELETE_KEEP_DATA) != 0
18015                        && (replacingPackage != null
18016                        && !replacingPackage.hasChildPackage(childPs.name))
18017                        ? flags & ~DELETE_KEEP_DATA : flags;
18018                removePackageDataLIF(childPs, allUserHandles, childOutInfo,
18019                        deleteFlags, writeSettings);
18020            }
18021        }
18022
18023        // Delete application code and resources only for parent packages
18024        if (ps.parentPackageName == null) {
18025            if (deleteCodeAndResources && (outInfo != null)) {
18026                outInfo.args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
18027                        ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
18028                if (DEBUG_SD_INSTALL) Slog.i(TAG, "args=" + outInfo.args);
18029            }
18030        }
18031
18032        return true;
18033    }
18034
18035    @Override
18036    public boolean setBlockUninstallForUser(String packageName, boolean blockUninstall,
18037            int userId) {
18038        mContext.enforceCallingOrSelfPermission(
18039                android.Manifest.permission.DELETE_PACKAGES, null);
18040        synchronized (mPackages) {
18041            PackageSetting ps = mSettings.mPackages.get(packageName);
18042            if (ps == null) {
18043                Log.i(TAG, "Package doesn't exist in set block uninstall " + packageName);
18044                return false;
18045            }
18046            // Cannot block uninstall of static shared libs as they are
18047            // considered a part of the using app (emulating static linking).
18048            // Also static libs are installed always on internal storage.
18049            PackageParser.Package pkg = mPackages.get(packageName);
18050            if (pkg != null && pkg.staticSharedLibName != null) {
18051                Slog.w(TAG, "Cannot block uninstall of package: " + packageName
18052                        + " providing static shared library: " + pkg.staticSharedLibName);
18053                return false;
18054            }
18055            if (!ps.getInstalled(userId)) {
18056                // Can't block uninstall for an app that is not installed or enabled.
18057                Log.i(TAG, "Package not installed in set block uninstall " + packageName);
18058                return false;
18059            }
18060            ps.setBlockUninstall(blockUninstall, userId);
18061            mSettings.writePackageRestrictionsLPr(userId);
18062        }
18063        return true;
18064    }
18065
18066    @Override
18067    public boolean getBlockUninstallForUser(String packageName, int userId) {
18068        synchronized (mPackages) {
18069            PackageSetting ps = mSettings.mPackages.get(packageName);
18070            if (ps == null) {
18071                Log.i(TAG, "Package doesn't exist in get block uninstall " + packageName);
18072                return false;
18073            }
18074            return ps.getBlockUninstall(userId);
18075        }
18076    }
18077
18078    @Override
18079    public boolean setRequiredForSystemUser(String packageName, boolean systemUserApp) {
18080        int callingUid = Binder.getCallingUid();
18081        if (callingUid != Process.SYSTEM_UID && callingUid != Process.ROOT_UID) {
18082            throw new SecurityException(
18083                    "setRequiredForSystemUser can only be run by the system or root");
18084        }
18085        synchronized (mPackages) {
18086            PackageSetting ps = mSettings.mPackages.get(packageName);
18087            if (ps == null) {
18088                Log.w(TAG, "Package doesn't exist: " + packageName);
18089                return false;
18090            }
18091            if (systemUserApp) {
18092                ps.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_REQUIRED_FOR_SYSTEM_USER;
18093            } else {
18094                ps.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_REQUIRED_FOR_SYSTEM_USER;
18095            }
18096            mSettings.writeLPr();
18097        }
18098        return true;
18099    }
18100
18101    /*
18102     * This method handles package deletion in general
18103     */
18104    private boolean deletePackageLIF(String packageName, UserHandle user,
18105            boolean deleteCodeAndResources, int[] allUserHandles, int flags,
18106            PackageRemovedInfo outInfo, boolean writeSettings,
18107            PackageParser.Package replacingPackage) {
18108        if (packageName == null) {
18109            Slog.w(TAG, "Attempt to delete null packageName.");
18110            return false;
18111        }
18112
18113        if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageLI: " + packageName + " user " + user);
18114
18115        PackageSetting ps;
18116        synchronized (mPackages) {
18117            ps = mSettings.mPackages.get(packageName);
18118            if (ps == null) {
18119                Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
18120                return false;
18121            }
18122
18123            if (ps.parentPackageName != null && (!isSystemApp(ps)
18124                    || (flags & PackageManager.DELETE_SYSTEM_APP) != 0)) {
18125                if (DEBUG_REMOVE) {
18126                    Slog.d(TAG, "Uninstalled child package:" + packageName + " for user:"
18127                            + ((user == null) ? UserHandle.USER_ALL : user));
18128                }
18129                final int removedUserId = (user != null) ? user.getIdentifier()
18130                        : UserHandle.USER_ALL;
18131                if (!clearPackageStateForUserLIF(ps, removedUserId, outInfo)) {
18132                    return false;
18133                }
18134                markPackageUninstalledForUserLPw(ps, user);
18135                scheduleWritePackageRestrictionsLocked(user);
18136                return true;
18137            }
18138        }
18139
18140        if (((!isSystemApp(ps) || (flags&PackageManager.DELETE_SYSTEM_APP) != 0) && user != null
18141                && user.getIdentifier() != UserHandle.USER_ALL)) {
18142            // The caller is asking that the package only be deleted for a single
18143            // user.  To do this, we just mark its uninstalled state and delete
18144            // its data. If this is a system app, we only allow this to happen if
18145            // they have set the special DELETE_SYSTEM_APP which requests different
18146            // semantics than normal for uninstalling system apps.
18147            markPackageUninstalledForUserLPw(ps, user);
18148
18149            if (!isSystemApp(ps)) {
18150                // Do not uninstall the APK if an app should be cached
18151                boolean keepUninstalledPackage = shouldKeepUninstalledPackageLPr(packageName);
18152                if (ps.isAnyInstalled(sUserManager.getUserIds()) || keepUninstalledPackage) {
18153                    // Other user still have this package installed, so all
18154                    // we need to do is clear this user's data and save that
18155                    // it is uninstalled.
18156                    if (DEBUG_REMOVE) Slog.d(TAG, "Still installed by other users");
18157                    if (!clearPackageStateForUserLIF(ps, user.getIdentifier(), outInfo)) {
18158                        return false;
18159                    }
18160                    scheduleWritePackageRestrictionsLocked(user);
18161                    return true;
18162                } else {
18163                    // We need to set it back to 'installed' so the uninstall
18164                    // broadcasts will be sent correctly.
18165                    if (DEBUG_REMOVE) Slog.d(TAG, "Not installed by other users, full delete");
18166                    ps.setInstalled(true, user.getIdentifier());
18167                    mSettings.writeKernelMappingLPr(ps);
18168                }
18169            } else {
18170                // This is a system app, so we assume that the
18171                // other users still have this package installed, so all
18172                // we need to do is clear this user's data and save that
18173                // it is uninstalled.
18174                if (DEBUG_REMOVE) Slog.d(TAG, "Deleting system app");
18175                if (!clearPackageStateForUserLIF(ps, user.getIdentifier(), outInfo)) {
18176                    return false;
18177                }
18178                scheduleWritePackageRestrictionsLocked(user);
18179                return true;
18180            }
18181        }
18182
18183        // If we are deleting a composite package for all users, keep track
18184        // of result for each child.
18185        if (ps.childPackageNames != null && outInfo != null) {
18186            synchronized (mPackages) {
18187                final int childCount = ps.childPackageNames.size();
18188                outInfo.removedChildPackages = new ArrayMap<>(childCount);
18189                for (int i = 0; i < childCount; i++) {
18190                    String childPackageName = ps.childPackageNames.get(i);
18191                    PackageRemovedInfo childInfo = new PackageRemovedInfo();
18192                    childInfo.removedPackage = childPackageName;
18193                    outInfo.removedChildPackages.put(childPackageName, childInfo);
18194                    PackageSetting childPs = mSettings.getPackageLPr(childPackageName);
18195                    if (childPs != null) {
18196                        childInfo.origUsers = childPs.queryInstalledUsers(allUserHandles, true);
18197                    }
18198                }
18199            }
18200        }
18201
18202        boolean ret = false;
18203        if (isSystemApp(ps)) {
18204            if (DEBUG_REMOVE) Slog.d(TAG, "Removing system package: " + ps.name);
18205            // When an updated system application is deleted we delete the existing resources
18206            // as well and fall back to existing code in system partition
18207            ret = deleteSystemPackageLIF(ps.pkg, ps, allUserHandles, flags, outInfo, writeSettings);
18208        } else {
18209            if (DEBUG_REMOVE) Slog.d(TAG, "Removing non-system package: " + ps.name);
18210            ret = deleteInstalledPackageLIF(ps, deleteCodeAndResources, flags, allUserHandles,
18211                    outInfo, writeSettings, replacingPackage);
18212        }
18213
18214        // Take a note whether we deleted the package for all users
18215        if (outInfo != null) {
18216            outInfo.removedForAllUsers = mPackages.get(ps.name) == null;
18217            if (outInfo.removedChildPackages != null) {
18218                synchronized (mPackages) {
18219                    final int childCount = outInfo.removedChildPackages.size();
18220                    for (int i = 0; i < childCount; i++) {
18221                        PackageRemovedInfo childInfo = outInfo.removedChildPackages.valueAt(i);
18222                        if (childInfo != null) {
18223                            childInfo.removedForAllUsers = mPackages.get(
18224                                    childInfo.removedPackage) == null;
18225                        }
18226                    }
18227                }
18228            }
18229            // If we uninstalled an update to a system app there may be some
18230            // child packages that appeared as they are declared in the system
18231            // app but were not declared in the update.
18232            if (isSystemApp(ps)) {
18233                synchronized (mPackages) {
18234                    PackageSetting updatedPs = mSettings.getPackageLPr(ps.name);
18235                    final int childCount = (updatedPs.childPackageNames != null)
18236                            ? updatedPs.childPackageNames.size() : 0;
18237                    for (int i = 0; i < childCount; i++) {
18238                        String childPackageName = updatedPs.childPackageNames.get(i);
18239                        if (outInfo.removedChildPackages == null
18240                                || outInfo.removedChildPackages.indexOfKey(childPackageName) < 0) {
18241                            PackageSetting childPs = mSettings.getPackageLPr(childPackageName);
18242                            if (childPs == null) {
18243                                continue;
18244                            }
18245                            PackageInstalledInfo installRes = new PackageInstalledInfo();
18246                            installRes.name = childPackageName;
18247                            installRes.newUsers = childPs.queryInstalledUsers(allUserHandles, true);
18248                            installRes.pkg = mPackages.get(childPackageName);
18249                            installRes.uid = childPs.pkg.applicationInfo.uid;
18250                            if (outInfo.appearedChildPackages == null) {
18251                                outInfo.appearedChildPackages = new ArrayMap<>();
18252                            }
18253                            outInfo.appearedChildPackages.put(childPackageName, installRes);
18254                        }
18255                    }
18256                }
18257            }
18258        }
18259
18260        return ret;
18261    }
18262
18263    private void markPackageUninstalledForUserLPw(PackageSetting ps, UserHandle user) {
18264        final int[] userIds = (user == null || user.getIdentifier() == UserHandle.USER_ALL)
18265                ? sUserManager.getUserIds() : new int[] {user.getIdentifier()};
18266        for (int nextUserId : userIds) {
18267            if (DEBUG_REMOVE) {
18268                Slog.d(TAG, "Marking package:" + ps.name + " uninstalled for user:" + nextUserId);
18269            }
18270            ps.setUserState(nextUserId, 0, COMPONENT_ENABLED_STATE_DEFAULT,
18271                    false /*installed*/,
18272                    true /*stopped*/,
18273                    true /*notLaunched*/,
18274                    false /*hidden*/,
18275                    false /*suspended*/,
18276                    false /*instantApp*/,
18277                    null /*lastDisableAppCaller*/,
18278                    null /*enabledComponents*/,
18279                    null /*disabledComponents*/,
18280                    false /*blockUninstall*/,
18281                    ps.readUserState(nextUserId).domainVerificationStatus,
18282                    0, PackageManager.INSTALL_REASON_UNKNOWN);
18283        }
18284        mSettings.writeKernelMappingLPr(ps);
18285    }
18286
18287    private boolean clearPackageStateForUserLIF(PackageSetting ps, int userId,
18288            PackageRemovedInfo outInfo) {
18289        final PackageParser.Package pkg;
18290        synchronized (mPackages) {
18291            pkg = mPackages.get(ps.name);
18292        }
18293
18294        final int[] userIds = (userId == UserHandle.USER_ALL) ? sUserManager.getUserIds()
18295                : new int[] {userId};
18296        for (int nextUserId : userIds) {
18297            if (DEBUG_REMOVE) {
18298                Slog.d(TAG, "Updating package:" + ps.name + " install state for user:"
18299                        + nextUserId);
18300            }
18301
18302            destroyAppDataLIF(pkg, userId,
18303                    StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
18304            destroyAppProfilesLIF(pkg, userId);
18305            removeKeystoreDataIfNeeded(nextUserId, ps.appId);
18306            schedulePackageCleaning(ps.name, nextUserId, false);
18307            synchronized (mPackages) {
18308                if (clearPackagePreferredActivitiesLPw(ps.name, nextUserId)) {
18309                    scheduleWritePackageRestrictionsLocked(nextUserId);
18310                }
18311                resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, nextUserId);
18312            }
18313        }
18314
18315        if (outInfo != null) {
18316            outInfo.removedPackage = ps.name;
18317            outInfo.isStaticSharedLib = pkg != null && pkg.staticSharedLibName != null;
18318            outInfo.removedAppId = ps.appId;
18319            outInfo.removedUsers = userIds;
18320        }
18321
18322        return true;
18323    }
18324
18325    private final class ClearStorageConnection implements ServiceConnection {
18326        IMediaContainerService mContainerService;
18327
18328        @Override
18329        public void onServiceConnected(ComponentName name, IBinder service) {
18330            synchronized (this) {
18331                mContainerService = IMediaContainerService.Stub
18332                        .asInterface(Binder.allowBlocking(service));
18333                notifyAll();
18334            }
18335        }
18336
18337        @Override
18338        public void onServiceDisconnected(ComponentName name) {
18339        }
18340    }
18341
18342    private void clearExternalStorageDataSync(String packageName, int userId, boolean allData) {
18343        if (DEFAULT_CONTAINER_PACKAGE.equals(packageName)) return;
18344
18345        final boolean mounted;
18346        if (Environment.isExternalStorageEmulated()) {
18347            mounted = true;
18348        } else {
18349            final String status = Environment.getExternalStorageState();
18350
18351            mounted = status.equals(Environment.MEDIA_MOUNTED)
18352                    || status.equals(Environment.MEDIA_MOUNTED_READ_ONLY);
18353        }
18354
18355        if (!mounted) {
18356            return;
18357        }
18358
18359        final Intent containerIntent = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
18360        int[] users;
18361        if (userId == UserHandle.USER_ALL) {
18362            users = sUserManager.getUserIds();
18363        } else {
18364            users = new int[] { userId };
18365        }
18366        final ClearStorageConnection conn = new ClearStorageConnection();
18367        if (mContext.bindServiceAsUser(
18368                containerIntent, conn, Context.BIND_AUTO_CREATE, UserHandle.SYSTEM)) {
18369            try {
18370                for (int curUser : users) {
18371                    long timeout = SystemClock.uptimeMillis() + 5000;
18372                    synchronized (conn) {
18373                        long now;
18374                        while (conn.mContainerService == null &&
18375                                (now = SystemClock.uptimeMillis()) < timeout) {
18376                            try {
18377                                conn.wait(timeout - now);
18378                            } catch (InterruptedException e) {
18379                            }
18380                        }
18381                    }
18382                    if (conn.mContainerService == null) {
18383                        return;
18384                    }
18385
18386                    final UserEnvironment userEnv = new UserEnvironment(curUser);
18387                    clearDirectory(conn.mContainerService,
18388                            userEnv.buildExternalStorageAppCacheDirs(packageName));
18389                    if (allData) {
18390                        clearDirectory(conn.mContainerService,
18391                                userEnv.buildExternalStorageAppDataDirs(packageName));
18392                        clearDirectory(conn.mContainerService,
18393                                userEnv.buildExternalStorageAppMediaDirs(packageName));
18394                    }
18395                }
18396            } finally {
18397                mContext.unbindService(conn);
18398            }
18399        }
18400    }
18401
18402    @Override
18403    public void clearApplicationProfileData(String packageName) {
18404        enforceSystemOrRoot("Only the system can clear all profile data");
18405
18406        final PackageParser.Package pkg;
18407        synchronized (mPackages) {
18408            pkg = mPackages.get(packageName);
18409        }
18410
18411        try (PackageFreezer freezer = freezePackage(packageName, "clearApplicationProfileData")) {
18412            synchronized (mInstallLock) {
18413                clearAppProfilesLIF(pkg, UserHandle.USER_ALL);
18414                destroyAppReferenceProfileLeafLIF(pkg, UserHandle.USER_ALL,
18415                        true /* removeBaseMarker */);
18416            }
18417        }
18418    }
18419
18420    @Override
18421    public void clearApplicationUserData(final String packageName,
18422            final IPackageDataObserver observer, final int userId) {
18423        mContext.enforceCallingOrSelfPermission(
18424                android.Manifest.permission.CLEAR_APP_USER_DATA, null);
18425
18426        enforceCrossUserPermission(Binder.getCallingUid(), userId,
18427                true /* requireFullPermission */, false /* checkShell */, "clear application data");
18428
18429        if (mProtectedPackages.isPackageDataProtected(userId, packageName)) {
18430            throw new SecurityException("Cannot clear data for a protected package: "
18431                    + packageName);
18432        }
18433        // Queue up an async operation since the package deletion may take a little while.
18434        mHandler.post(new Runnable() {
18435            public void run() {
18436                mHandler.removeCallbacks(this);
18437                final boolean succeeded;
18438                try (PackageFreezer freezer = freezePackage(packageName,
18439                        "clearApplicationUserData")) {
18440                    synchronized (mInstallLock) {
18441                        succeeded = clearApplicationUserDataLIF(packageName, userId);
18442                    }
18443                    clearExternalStorageDataSync(packageName, userId, true);
18444                    synchronized (mPackages) {
18445                        mInstantAppRegistry.deleteInstantApplicationMetadataLPw(
18446                                packageName, userId);
18447                    }
18448                }
18449                if (succeeded) {
18450                    // invoke DeviceStorageMonitor's update method to clear any notifications
18451                    DeviceStorageMonitorInternal dsm = LocalServices
18452                            .getService(DeviceStorageMonitorInternal.class);
18453                    if (dsm != null) {
18454                        dsm.checkMemory();
18455                    }
18456                }
18457                if(observer != null) {
18458                    try {
18459                        observer.onRemoveCompleted(packageName, succeeded);
18460                    } catch (RemoteException e) {
18461                        Log.i(TAG, "Observer no longer exists.");
18462                    }
18463                } //end if observer
18464            } //end run
18465        });
18466    }
18467
18468    private boolean clearApplicationUserDataLIF(String packageName, int userId) {
18469        if (packageName == null) {
18470            Slog.w(TAG, "Attempt to delete null packageName.");
18471            return false;
18472        }
18473
18474        // Try finding details about the requested package
18475        PackageParser.Package pkg;
18476        synchronized (mPackages) {
18477            pkg = mPackages.get(packageName);
18478            if (pkg == null) {
18479                final PackageSetting ps = mSettings.mPackages.get(packageName);
18480                if (ps != null) {
18481                    pkg = ps.pkg;
18482                }
18483            }
18484
18485            if (pkg == null) {
18486                Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
18487                return false;
18488            }
18489
18490            PackageSetting ps = (PackageSetting) pkg.mExtras;
18491            resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
18492        }
18493
18494        clearAppDataLIF(pkg, userId,
18495                StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
18496
18497        final int appId = UserHandle.getAppId(pkg.applicationInfo.uid);
18498        removeKeystoreDataIfNeeded(userId, appId);
18499
18500        UserManagerInternal umInternal = getUserManagerInternal();
18501        final int flags;
18502        if (umInternal.isUserUnlockingOrUnlocked(userId)) {
18503            flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
18504        } else if (umInternal.isUserRunning(userId)) {
18505            flags = StorageManager.FLAG_STORAGE_DE;
18506        } else {
18507            flags = 0;
18508        }
18509        prepareAppDataContentsLIF(pkg, userId, flags);
18510
18511        return true;
18512    }
18513
18514    /**
18515     * Reverts user permission state changes (permissions and flags) in
18516     * all packages for a given user.
18517     *
18518     * @param userId The device user for which to do a reset.
18519     */
18520    private void resetUserChangesToRuntimePermissionsAndFlagsLPw(int userId) {
18521        final int packageCount = mPackages.size();
18522        for (int i = 0; i < packageCount; i++) {
18523            PackageParser.Package pkg = mPackages.valueAt(i);
18524            PackageSetting ps = (PackageSetting) pkg.mExtras;
18525            resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
18526        }
18527    }
18528
18529    private void resetNetworkPolicies(int userId) {
18530        LocalServices.getService(NetworkPolicyManagerInternal.class).resetUserState(userId);
18531    }
18532
18533    /**
18534     * Reverts user permission state changes (permissions and flags).
18535     *
18536     * @param ps The package for which to reset.
18537     * @param userId The device user for which to do a reset.
18538     */
18539    private void resetUserChangesToRuntimePermissionsAndFlagsLPw(
18540            final PackageSetting ps, final int userId) {
18541        if (ps.pkg == null) {
18542            return;
18543        }
18544
18545        // These are flags that can change base on user actions.
18546        final int userSettableMask = FLAG_PERMISSION_USER_SET
18547                | FLAG_PERMISSION_USER_FIXED
18548                | FLAG_PERMISSION_REVOKE_ON_UPGRADE
18549                | FLAG_PERMISSION_REVIEW_REQUIRED;
18550
18551        final int policyOrSystemFlags = FLAG_PERMISSION_SYSTEM_FIXED
18552                | FLAG_PERMISSION_POLICY_FIXED;
18553
18554        boolean writeInstallPermissions = false;
18555        boolean writeRuntimePermissions = false;
18556
18557        final int permissionCount = ps.pkg.requestedPermissions.size();
18558        for (int i = 0; i < permissionCount; i++) {
18559            String permission = ps.pkg.requestedPermissions.get(i);
18560
18561            BasePermission bp = mSettings.mPermissions.get(permission);
18562            if (bp == null) {
18563                continue;
18564            }
18565
18566            // If shared user we just reset the state to which only this app contributed.
18567            if (ps.sharedUser != null) {
18568                boolean used = false;
18569                final int packageCount = ps.sharedUser.packages.size();
18570                for (int j = 0; j < packageCount; j++) {
18571                    PackageSetting pkg = ps.sharedUser.packages.valueAt(j);
18572                    if (pkg.pkg != null && !pkg.pkg.packageName.equals(ps.pkg.packageName)
18573                            && pkg.pkg.requestedPermissions.contains(permission)) {
18574                        used = true;
18575                        break;
18576                    }
18577                }
18578                if (used) {
18579                    continue;
18580                }
18581            }
18582
18583            PermissionsState permissionsState = ps.getPermissionsState();
18584
18585            final int oldFlags = permissionsState.getPermissionFlags(bp.name, userId);
18586
18587            // Always clear the user settable flags.
18588            final boolean hasInstallState = permissionsState.getInstallPermissionState(
18589                    bp.name) != null;
18590            // If permission review is enabled and this is a legacy app, mark the
18591            // permission as requiring a review as this is the initial state.
18592            int flags = 0;
18593            if (mPermissionReviewRequired
18594                    && ps.pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) {
18595                flags |= FLAG_PERMISSION_REVIEW_REQUIRED;
18596            }
18597            if (permissionsState.updatePermissionFlags(bp, userId, userSettableMask, flags)) {
18598                if (hasInstallState) {
18599                    writeInstallPermissions = true;
18600                } else {
18601                    writeRuntimePermissions = true;
18602                }
18603            }
18604
18605            // Below is only runtime permission handling.
18606            if (!bp.isRuntime()) {
18607                continue;
18608            }
18609
18610            // Never clobber system or policy.
18611            if ((oldFlags & policyOrSystemFlags) != 0) {
18612                continue;
18613            }
18614
18615            // If this permission was granted by default, make sure it is.
18616            if ((oldFlags & FLAG_PERMISSION_GRANTED_BY_DEFAULT) != 0) {
18617                if (permissionsState.grantRuntimePermission(bp, userId)
18618                        != PERMISSION_OPERATION_FAILURE) {
18619                    writeRuntimePermissions = true;
18620                }
18621            // If permission review is enabled the permissions for a legacy apps
18622            // are represented as constantly granted runtime ones, so don't revoke.
18623            } else if ((flags & FLAG_PERMISSION_REVIEW_REQUIRED) == 0) {
18624                // Otherwise, reset the permission.
18625                final int revokeResult = permissionsState.revokeRuntimePermission(bp, userId);
18626                switch (revokeResult) {
18627                    case PERMISSION_OPERATION_SUCCESS:
18628                    case PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: {
18629                        writeRuntimePermissions = true;
18630                        final int appId = ps.appId;
18631                        mHandler.post(new Runnable() {
18632                            @Override
18633                            public void run() {
18634                                killUid(appId, userId, KILL_APP_REASON_PERMISSIONS_REVOKED);
18635                            }
18636                        });
18637                    } break;
18638                }
18639            }
18640        }
18641
18642        // Synchronously write as we are taking permissions away.
18643        if (writeRuntimePermissions) {
18644            mSettings.writeRuntimePermissionsForUserLPr(userId, true);
18645        }
18646
18647        // Synchronously write as we are taking permissions away.
18648        if (writeInstallPermissions) {
18649            mSettings.writeLPr();
18650        }
18651    }
18652
18653    /**
18654     * Remove entries from the keystore daemon. Will only remove it if the
18655     * {@code appId} is valid.
18656     */
18657    private static void removeKeystoreDataIfNeeded(int userId, int appId) {
18658        if (appId < 0) {
18659            return;
18660        }
18661
18662        final KeyStore keyStore = KeyStore.getInstance();
18663        if (keyStore != null) {
18664            if (userId == UserHandle.USER_ALL) {
18665                for (final int individual : sUserManager.getUserIds()) {
18666                    keyStore.clearUid(UserHandle.getUid(individual, appId));
18667                }
18668            } else {
18669                keyStore.clearUid(UserHandle.getUid(userId, appId));
18670            }
18671        } else {
18672            Slog.w(TAG, "Could not contact keystore to clear entries for app id " + appId);
18673        }
18674    }
18675
18676    @Override
18677    public void deleteApplicationCacheFiles(final String packageName,
18678            final IPackageDataObserver observer) {
18679        final int userId = UserHandle.getCallingUserId();
18680        deleteApplicationCacheFilesAsUser(packageName, userId, observer);
18681    }
18682
18683    @Override
18684    public void deleteApplicationCacheFilesAsUser(final String packageName, final int userId,
18685            final IPackageDataObserver observer) {
18686        mContext.enforceCallingOrSelfPermission(
18687                android.Manifest.permission.DELETE_CACHE_FILES, null);
18688        enforceCrossUserPermission(Binder.getCallingUid(), userId,
18689                /* requireFullPermission= */ true, /* checkShell= */ false,
18690                "delete application cache files");
18691
18692        final PackageParser.Package pkg;
18693        synchronized (mPackages) {
18694            pkg = mPackages.get(packageName);
18695        }
18696
18697        // Queue up an async operation since the package deletion may take a little while.
18698        mHandler.post(new Runnable() {
18699            public void run() {
18700                synchronized (mInstallLock) {
18701                    final int flags = StorageManager.FLAG_STORAGE_DE
18702                            | StorageManager.FLAG_STORAGE_CE;
18703                    // We're only clearing cache files, so we don't care if the
18704                    // app is unfrozen and still able to run
18705                    clearAppDataLIF(pkg, userId, flags | Installer.FLAG_CLEAR_CACHE_ONLY);
18706                    clearAppDataLIF(pkg, userId, flags | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
18707                }
18708                clearExternalStorageDataSync(packageName, userId, false);
18709                if (observer != null) {
18710                    try {
18711                        observer.onRemoveCompleted(packageName, true);
18712                    } catch (RemoteException e) {
18713                        Log.i(TAG, "Observer no longer exists.");
18714                    }
18715                }
18716            }
18717        });
18718    }
18719
18720    @Override
18721    public void getPackageSizeInfo(final String packageName, int userHandle,
18722            final IPackageStatsObserver observer) {
18723        Slog.w(TAG, "Shame on you for calling a hidden API. Shame!");
18724        try {
18725            observer.onGetStatsCompleted(null, false);
18726        } catch (RemoteException ignored) {
18727        }
18728    }
18729
18730    private boolean getPackageSizeInfoLI(String packageName, int userId, PackageStats stats) {
18731        final PackageSetting ps;
18732        synchronized (mPackages) {
18733            ps = mSettings.mPackages.get(packageName);
18734            if (ps == null) {
18735                Slog.w(TAG, "Failed to find settings for " + packageName);
18736                return false;
18737            }
18738        }
18739
18740        final String[] packageNames = { packageName };
18741        final long[] ceDataInodes = { ps.getCeDataInode(userId) };
18742        final String[] codePaths = { ps.codePathString };
18743
18744        try {
18745            mInstaller.getAppSize(ps.volumeUuid, packageNames, userId, 0,
18746                    ps.appId, ceDataInodes, codePaths, stats);
18747
18748            // For now, ignore code size of packages on system partition
18749            if (isSystemApp(ps) && !isUpdatedSystemApp(ps)) {
18750                stats.codeSize = 0;
18751            }
18752
18753            // External clients expect these to be tracked separately
18754            stats.dataSize -= stats.cacheSize;
18755
18756        } catch (InstallerException e) {
18757            Slog.w(TAG, String.valueOf(e));
18758            return false;
18759        }
18760
18761        return true;
18762    }
18763
18764    private int getUidTargetSdkVersionLockedLPr(int uid) {
18765        Object obj = mSettings.getUserIdLPr(uid);
18766        if (obj instanceof SharedUserSetting) {
18767            final SharedUserSetting sus = (SharedUserSetting) obj;
18768            int vers = Build.VERSION_CODES.CUR_DEVELOPMENT;
18769            final Iterator<PackageSetting> it = sus.packages.iterator();
18770            while (it.hasNext()) {
18771                final PackageSetting ps = it.next();
18772                if (ps.pkg != null) {
18773                    int v = ps.pkg.applicationInfo.targetSdkVersion;
18774                    if (v < vers) vers = v;
18775                }
18776            }
18777            return vers;
18778        } else if (obj instanceof PackageSetting) {
18779            final PackageSetting ps = (PackageSetting) obj;
18780            if (ps.pkg != null) {
18781                return ps.pkg.applicationInfo.targetSdkVersion;
18782            }
18783        }
18784        return Build.VERSION_CODES.CUR_DEVELOPMENT;
18785    }
18786
18787    @Override
18788    public void addPreferredActivity(IntentFilter filter, int match,
18789            ComponentName[] set, ComponentName activity, int userId) {
18790        addPreferredActivityInternal(filter, match, set, activity, true, userId,
18791                "Adding preferred");
18792    }
18793
18794    private void addPreferredActivityInternal(IntentFilter filter, int match,
18795            ComponentName[] set, ComponentName activity, boolean always, int userId,
18796            String opname) {
18797        // writer
18798        int callingUid = Binder.getCallingUid();
18799        enforceCrossUserPermission(callingUid, userId,
18800                true /* requireFullPermission */, false /* checkShell */, "add preferred activity");
18801        if (filter.countActions() == 0) {
18802            Slog.w(TAG, "Cannot set a preferred activity with no filter actions");
18803            return;
18804        }
18805        synchronized (mPackages) {
18806            if (mContext.checkCallingOrSelfPermission(
18807                    android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
18808                    != PackageManager.PERMISSION_GRANTED) {
18809                if (getUidTargetSdkVersionLockedLPr(callingUid)
18810                        < Build.VERSION_CODES.FROYO) {
18811                    Slog.w(TAG, "Ignoring addPreferredActivity() from uid "
18812                            + callingUid);
18813                    return;
18814                }
18815                mContext.enforceCallingOrSelfPermission(
18816                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
18817            }
18818
18819            PreferredIntentResolver pir = mSettings.editPreferredActivitiesLPw(userId);
18820            Slog.i(TAG, opname + " activity " + activity.flattenToShortString() + " for user "
18821                    + userId + ":");
18822            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
18823            pir.addFilter(new PreferredActivity(filter, match, set, activity, always));
18824            scheduleWritePackageRestrictionsLocked(userId);
18825            postPreferredActivityChangedBroadcast(userId);
18826        }
18827    }
18828
18829    private void postPreferredActivityChangedBroadcast(int userId) {
18830        mHandler.post(() -> {
18831            final IActivityManager am = ActivityManager.getService();
18832            if (am == null) {
18833                return;
18834            }
18835
18836            final Intent intent = new Intent(Intent.ACTION_PREFERRED_ACTIVITY_CHANGED);
18837            intent.putExtra(Intent.EXTRA_USER_HANDLE, userId);
18838            try {
18839                am.broadcastIntent(null, intent, null, null,
18840                        0, null, null, null, android.app.AppOpsManager.OP_NONE,
18841                        null, false, false, userId);
18842            } catch (RemoteException e) {
18843            }
18844        });
18845    }
18846
18847    @Override
18848    public void replacePreferredActivity(IntentFilter filter, int match,
18849            ComponentName[] set, ComponentName activity, int userId) {
18850        if (filter.countActions() != 1) {
18851            throw new IllegalArgumentException(
18852                    "replacePreferredActivity expects filter to have only 1 action.");
18853        }
18854        if (filter.countDataAuthorities() != 0
18855                || filter.countDataPaths() != 0
18856                || filter.countDataSchemes() > 1
18857                || filter.countDataTypes() != 0) {
18858            throw new IllegalArgumentException(
18859                    "replacePreferredActivity expects filter to have no data authorities, " +
18860                    "paths, or types; and at most one scheme.");
18861        }
18862
18863        final int callingUid = Binder.getCallingUid();
18864        enforceCrossUserPermission(callingUid, userId,
18865                true /* requireFullPermission */, false /* checkShell */,
18866                "replace preferred activity");
18867        synchronized (mPackages) {
18868            if (mContext.checkCallingOrSelfPermission(
18869                    android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
18870                    != PackageManager.PERMISSION_GRANTED) {
18871                if (getUidTargetSdkVersionLockedLPr(callingUid)
18872                        < Build.VERSION_CODES.FROYO) {
18873                    Slog.w(TAG, "Ignoring replacePreferredActivity() from uid "
18874                            + Binder.getCallingUid());
18875                    return;
18876                }
18877                mContext.enforceCallingOrSelfPermission(
18878                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
18879            }
18880
18881            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
18882            if (pir != null) {
18883                // Get all of the existing entries that exactly match this filter.
18884                ArrayList<PreferredActivity> existing = pir.findFilters(filter);
18885                if (existing != null && existing.size() == 1) {
18886                    PreferredActivity cur = existing.get(0);
18887                    if (DEBUG_PREFERRED) {
18888                        Slog.i(TAG, "Checking replace of preferred:");
18889                        filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
18890                        if (!cur.mPref.mAlways) {
18891                            Slog.i(TAG, "  -- CUR; not mAlways!");
18892                        } else {
18893                            Slog.i(TAG, "  -- CUR: mMatch=" + cur.mPref.mMatch);
18894                            Slog.i(TAG, "  -- CUR: mSet="
18895                                    + Arrays.toString(cur.mPref.mSetComponents));
18896                            Slog.i(TAG, "  -- CUR: mComponent=" + cur.mPref.mShortComponent);
18897                            Slog.i(TAG, "  -- NEW: mMatch="
18898                                    + (match&IntentFilter.MATCH_CATEGORY_MASK));
18899                            Slog.i(TAG, "  -- CUR: mSet=" + Arrays.toString(set));
18900                            Slog.i(TAG, "  -- CUR: mComponent=" + activity.flattenToShortString());
18901                        }
18902                    }
18903                    if (cur.mPref.mAlways && cur.mPref.mComponent.equals(activity)
18904                            && cur.mPref.mMatch == (match&IntentFilter.MATCH_CATEGORY_MASK)
18905                            && cur.mPref.sameSet(set)) {
18906                        // Setting the preferred activity to what it happens to be already
18907                        if (DEBUG_PREFERRED) {
18908                            Slog.i(TAG, "Replacing with same preferred activity "
18909                                    + cur.mPref.mShortComponent + " for user "
18910                                    + userId + ":");
18911                            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
18912                        }
18913                        return;
18914                    }
18915                }
18916
18917                if (existing != null) {
18918                    if (DEBUG_PREFERRED) {
18919                        Slog.i(TAG, existing.size() + " existing preferred matches for:");
18920                        filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
18921                    }
18922                    for (int i = 0; i < existing.size(); i++) {
18923                        PreferredActivity pa = existing.get(i);
18924                        if (DEBUG_PREFERRED) {
18925                            Slog.i(TAG, "Removing existing preferred activity "
18926                                    + pa.mPref.mComponent + ":");
18927                            pa.dump(new LogPrinter(Log.INFO, TAG), "  ");
18928                        }
18929                        pir.removeFilter(pa);
18930                    }
18931                }
18932            }
18933            addPreferredActivityInternal(filter, match, set, activity, true, userId,
18934                    "Replacing preferred");
18935        }
18936    }
18937
18938    @Override
18939    public void clearPackagePreferredActivities(String packageName) {
18940        final int uid = Binder.getCallingUid();
18941        // writer
18942        synchronized (mPackages) {
18943            PackageParser.Package pkg = mPackages.get(packageName);
18944            if (pkg == null || pkg.applicationInfo.uid != uid) {
18945                if (mContext.checkCallingOrSelfPermission(
18946                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
18947                        != PackageManager.PERMISSION_GRANTED) {
18948                    if (getUidTargetSdkVersionLockedLPr(Binder.getCallingUid())
18949                            < Build.VERSION_CODES.FROYO) {
18950                        Slog.w(TAG, "Ignoring clearPackagePreferredActivities() from uid "
18951                                + Binder.getCallingUid());
18952                        return;
18953                    }
18954                    mContext.enforceCallingOrSelfPermission(
18955                            android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
18956                }
18957            }
18958
18959            int user = UserHandle.getCallingUserId();
18960            if (clearPackagePreferredActivitiesLPw(packageName, user)) {
18961                scheduleWritePackageRestrictionsLocked(user);
18962            }
18963        }
18964    }
18965
18966    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
18967    boolean clearPackagePreferredActivitiesLPw(String packageName, int userId) {
18968        ArrayList<PreferredActivity> removed = null;
18969        boolean changed = false;
18970        for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
18971            final int thisUserId = mSettings.mPreferredActivities.keyAt(i);
18972            PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
18973            if (userId != UserHandle.USER_ALL && userId != thisUserId) {
18974                continue;
18975            }
18976            Iterator<PreferredActivity> it = pir.filterIterator();
18977            while (it.hasNext()) {
18978                PreferredActivity pa = it.next();
18979                // Mark entry for removal only if it matches the package name
18980                // and the entry is of type "always".
18981                if (packageName == null ||
18982                        (pa.mPref.mComponent.getPackageName().equals(packageName)
18983                                && pa.mPref.mAlways)) {
18984                    if (removed == null) {
18985                        removed = new ArrayList<PreferredActivity>();
18986                    }
18987                    removed.add(pa);
18988                }
18989            }
18990            if (removed != null) {
18991                for (int j=0; j<removed.size(); j++) {
18992                    PreferredActivity pa = removed.get(j);
18993                    pir.removeFilter(pa);
18994                }
18995                changed = true;
18996            }
18997        }
18998        if (changed) {
18999            postPreferredActivityChangedBroadcast(userId);
19000        }
19001        return changed;
19002    }
19003
19004    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
19005    private void clearIntentFilterVerificationsLPw(int userId) {
19006        final int packageCount = mPackages.size();
19007        for (int i = 0; i < packageCount; i++) {
19008            PackageParser.Package pkg = mPackages.valueAt(i);
19009            clearIntentFilterVerificationsLPw(pkg.packageName, userId);
19010        }
19011    }
19012
19013    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
19014    void clearIntentFilterVerificationsLPw(String packageName, int userId) {
19015        if (userId == UserHandle.USER_ALL) {
19016            if (mSettings.removeIntentFilterVerificationLPw(packageName,
19017                    sUserManager.getUserIds())) {
19018                for (int oneUserId : sUserManager.getUserIds()) {
19019                    scheduleWritePackageRestrictionsLocked(oneUserId);
19020                }
19021            }
19022        } else {
19023            if (mSettings.removeIntentFilterVerificationLPw(packageName, userId)) {
19024                scheduleWritePackageRestrictionsLocked(userId);
19025            }
19026        }
19027    }
19028
19029    void clearDefaultBrowserIfNeeded(String packageName) {
19030        for (int oneUserId : sUserManager.getUserIds()) {
19031            String defaultBrowserPackageName = getDefaultBrowserPackageName(oneUserId);
19032            if (TextUtils.isEmpty(defaultBrowserPackageName)) continue;
19033            if (packageName.equals(defaultBrowserPackageName)) {
19034                setDefaultBrowserPackageName(null, oneUserId);
19035            }
19036        }
19037    }
19038
19039    @Override
19040    public void resetApplicationPreferences(int userId) {
19041        mContext.enforceCallingOrSelfPermission(
19042                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
19043        final long identity = Binder.clearCallingIdentity();
19044        // writer
19045        try {
19046            synchronized (mPackages) {
19047                clearPackagePreferredActivitiesLPw(null, userId);
19048                mSettings.applyDefaultPreferredAppsLPw(this, userId);
19049                // TODO: We have to reset the default SMS and Phone. This requires
19050                // significant refactoring to keep all default apps in the package
19051                // manager (cleaner but more work) or have the services provide
19052                // callbacks to the package manager to request a default app reset.
19053                applyFactoryDefaultBrowserLPw(userId);
19054                clearIntentFilterVerificationsLPw(userId);
19055                primeDomainVerificationsLPw(userId);
19056                resetUserChangesToRuntimePermissionsAndFlagsLPw(userId);
19057                scheduleWritePackageRestrictionsLocked(userId);
19058            }
19059            resetNetworkPolicies(userId);
19060        } finally {
19061            Binder.restoreCallingIdentity(identity);
19062        }
19063    }
19064
19065    @Override
19066    public int getPreferredActivities(List<IntentFilter> outFilters,
19067            List<ComponentName> outActivities, String packageName) {
19068
19069        int num = 0;
19070        final int userId = UserHandle.getCallingUserId();
19071        // reader
19072        synchronized (mPackages) {
19073            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
19074            if (pir != null) {
19075                final Iterator<PreferredActivity> it = pir.filterIterator();
19076                while (it.hasNext()) {
19077                    final PreferredActivity pa = it.next();
19078                    if (packageName == null
19079                            || (pa.mPref.mComponent.getPackageName().equals(packageName)
19080                                    && pa.mPref.mAlways)) {
19081                        if (outFilters != null) {
19082                            outFilters.add(new IntentFilter(pa));
19083                        }
19084                        if (outActivities != null) {
19085                            outActivities.add(pa.mPref.mComponent);
19086                        }
19087                    }
19088                }
19089            }
19090        }
19091
19092        return num;
19093    }
19094
19095    @Override
19096    public void addPersistentPreferredActivity(IntentFilter filter, ComponentName activity,
19097            int userId) {
19098        int callingUid = Binder.getCallingUid();
19099        if (callingUid != Process.SYSTEM_UID) {
19100            throw new SecurityException(
19101                    "addPersistentPreferredActivity can only be run by the system");
19102        }
19103        if (filter.countActions() == 0) {
19104            Slog.w(TAG, "Cannot set a preferred activity with no filter actions");
19105            return;
19106        }
19107        synchronized (mPackages) {
19108            Slog.i(TAG, "Adding persistent preferred activity " + activity + " for user " + userId +
19109                    ":");
19110            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
19111            mSettings.editPersistentPreferredActivitiesLPw(userId).addFilter(
19112                    new PersistentPreferredActivity(filter, activity));
19113            scheduleWritePackageRestrictionsLocked(userId);
19114            postPreferredActivityChangedBroadcast(userId);
19115        }
19116    }
19117
19118    @Override
19119    public void clearPackagePersistentPreferredActivities(String packageName, int userId) {
19120        int callingUid = Binder.getCallingUid();
19121        if (callingUid != Process.SYSTEM_UID) {
19122            throw new SecurityException(
19123                    "clearPackagePersistentPreferredActivities can only be run by the system");
19124        }
19125        ArrayList<PersistentPreferredActivity> removed = null;
19126        boolean changed = false;
19127        synchronized (mPackages) {
19128            for (int i=0; i<mSettings.mPersistentPreferredActivities.size(); i++) {
19129                final int thisUserId = mSettings.mPersistentPreferredActivities.keyAt(i);
19130                PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities
19131                        .valueAt(i);
19132                if (userId != thisUserId) {
19133                    continue;
19134                }
19135                Iterator<PersistentPreferredActivity> it = ppir.filterIterator();
19136                while (it.hasNext()) {
19137                    PersistentPreferredActivity ppa = it.next();
19138                    // Mark entry for removal only if it matches the package name.
19139                    if (ppa.mComponent.getPackageName().equals(packageName)) {
19140                        if (removed == null) {
19141                            removed = new ArrayList<PersistentPreferredActivity>();
19142                        }
19143                        removed.add(ppa);
19144                    }
19145                }
19146                if (removed != null) {
19147                    for (int j=0; j<removed.size(); j++) {
19148                        PersistentPreferredActivity ppa = removed.get(j);
19149                        ppir.removeFilter(ppa);
19150                    }
19151                    changed = true;
19152                }
19153            }
19154
19155            if (changed) {
19156                scheduleWritePackageRestrictionsLocked(userId);
19157                postPreferredActivityChangedBroadcast(userId);
19158            }
19159        }
19160    }
19161
19162    /**
19163     * Common machinery for picking apart a restored XML blob and passing
19164     * it to a caller-supplied functor to be applied to the running system.
19165     */
19166    private void restoreFromXml(XmlPullParser parser, int userId,
19167            String expectedStartTag, BlobXmlRestorer functor)
19168            throws IOException, XmlPullParserException {
19169        int type;
19170        while ((type = parser.next()) != XmlPullParser.START_TAG
19171                && type != XmlPullParser.END_DOCUMENT) {
19172        }
19173        if (type != XmlPullParser.START_TAG) {
19174            // oops didn't find a start tag?!
19175            if (DEBUG_BACKUP) {
19176                Slog.e(TAG, "Didn't find start tag during restore");
19177            }
19178            return;
19179        }
19180Slog.v(TAG, ":: restoreFromXml() : got to tag " + parser.getName());
19181        // this is supposed to be TAG_PREFERRED_BACKUP
19182        if (!expectedStartTag.equals(parser.getName())) {
19183            if (DEBUG_BACKUP) {
19184                Slog.e(TAG, "Found unexpected tag " + parser.getName());
19185            }
19186            return;
19187        }
19188
19189        // skip interfering stuff, then we're aligned with the backing implementation
19190        while ((type = parser.next()) == XmlPullParser.TEXT) { }
19191Slog.v(TAG, ":: stepped forward, applying functor at tag " + parser.getName());
19192        functor.apply(parser, userId);
19193    }
19194
19195    private interface BlobXmlRestorer {
19196        public void apply(XmlPullParser parser, int userId) throws IOException, XmlPullParserException;
19197    }
19198
19199    /**
19200     * Non-Binder method, support for the backup/restore mechanism: write the
19201     * full set of preferred activities in its canonical XML format.  Returns the
19202     * XML output as a byte array, or null if there is none.
19203     */
19204    @Override
19205    public byte[] getPreferredActivityBackup(int userId) {
19206        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
19207            throw new SecurityException("Only the system may call getPreferredActivityBackup()");
19208        }
19209
19210        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
19211        try {
19212            final XmlSerializer serializer = new FastXmlSerializer();
19213            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
19214            serializer.startDocument(null, true);
19215            serializer.startTag(null, TAG_PREFERRED_BACKUP);
19216
19217            synchronized (mPackages) {
19218                mSettings.writePreferredActivitiesLPr(serializer, userId, true);
19219            }
19220
19221            serializer.endTag(null, TAG_PREFERRED_BACKUP);
19222            serializer.endDocument();
19223            serializer.flush();
19224        } catch (Exception e) {
19225            if (DEBUG_BACKUP) {
19226                Slog.e(TAG, "Unable to write preferred activities for backup", e);
19227            }
19228            return null;
19229        }
19230
19231        return dataStream.toByteArray();
19232    }
19233
19234    @Override
19235    public void restorePreferredActivities(byte[] backup, int userId) {
19236        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
19237            throw new SecurityException("Only the system may call restorePreferredActivities()");
19238        }
19239
19240        try {
19241            final XmlPullParser parser = Xml.newPullParser();
19242            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
19243            restoreFromXml(parser, userId, TAG_PREFERRED_BACKUP,
19244                    new BlobXmlRestorer() {
19245                        @Override
19246                        public void apply(XmlPullParser parser, int userId)
19247                                throws XmlPullParserException, IOException {
19248                            synchronized (mPackages) {
19249                                mSettings.readPreferredActivitiesLPw(parser, userId);
19250                            }
19251                        }
19252                    } );
19253        } catch (Exception e) {
19254            if (DEBUG_BACKUP) {
19255                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
19256            }
19257        }
19258    }
19259
19260    /**
19261     * Non-Binder method, support for the backup/restore mechanism: write the
19262     * default browser (etc) settings in its canonical XML format.  Returns the default
19263     * browser XML representation as a byte array, or null if there is none.
19264     */
19265    @Override
19266    public byte[] getDefaultAppsBackup(int userId) {
19267        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
19268            throw new SecurityException("Only the system may call getDefaultAppsBackup()");
19269        }
19270
19271        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
19272        try {
19273            final XmlSerializer serializer = new FastXmlSerializer();
19274            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
19275            serializer.startDocument(null, true);
19276            serializer.startTag(null, TAG_DEFAULT_APPS);
19277
19278            synchronized (mPackages) {
19279                mSettings.writeDefaultAppsLPr(serializer, userId);
19280            }
19281
19282            serializer.endTag(null, TAG_DEFAULT_APPS);
19283            serializer.endDocument();
19284            serializer.flush();
19285        } catch (Exception e) {
19286            if (DEBUG_BACKUP) {
19287                Slog.e(TAG, "Unable to write default apps for backup", e);
19288            }
19289            return null;
19290        }
19291
19292        return dataStream.toByteArray();
19293    }
19294
19295    @Override
19296    public void restoreDefaultApps(byte[] backup, int userId) {
19297        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
19298            throw new SecurityException("Only the system may call restoreDefaultApps()");
19299        }
19300
19301        try {
19302            final XmlPullParser parser = Xml.newPullParser();
19303            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
19304            restoreFromXml(parser, userId, TAG_DEFAULT_APPS,
19305                    new BlobXmlRestorer() {
19306                        @Override
19307                        public void apply(XmlPullParser parser, int userId)
19308                                throws XmlPullParserException, IOException {
19309                            synchronized (mPackages) {
19310                                mSettings.readDefaultAppsLPw(parser, userId);
19311                            }
19312                        }
19313                    } );
19314        } catch (Exception e) {
19315            if (DEBUG_BACKUP) {
19316                Slog.e(TAG, "Exception restoring default apps: " + e.getMessage());
19317            }
19318        }
19319    }
19320
19321    @Override
19322    public byte[] getIntentFilterVerificationBackup(int userId) {
19323        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
19324            throw new SecurityException("Only the system may call getIntentFilterVerificationBackup()");
19325        }
19326
19327        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
19328        try {
19329            final XmlSerializer serializer = new FastXmlSerializer();
19330            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
19331            serializer.startDocument(null, true);
19332            serializer.startTag(null, TAG_INTENT_FILTER_VERIFICATION);
19333
19334            synchronized (mPackages) {
19335                mSettings.writeAllDomainVerificationsLPr(serializer, userId);
19336            }
19337
19338            serializer.endTag(null, TAG_INTENT_FILTER_VERIFICATION);
19339            serializer.endDocument();
19340            serializer.flush();
19341        } catch (Exception e) {
19342            if (DEBUG_BACKUP) {
19343                Slog.e(TAG, "Unable to write default apps for backup", e);
19344            }
19345            return null;
19346        }
19347
19348        return dataStream.toByteArray();
19349    }
19350
19351    @Override
19352    public void restoreIntentFilterVerification(byte[] backup, int userId) {
19353        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
19354            throw new SecurityException("Only the system may call restorePreferredActivities()");
19355        }
19356
19357        try {
19358            final XmlPullParser parser = Xml.newPullParser();
19359            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
19360            restoreFromXml(parser, userId, TAG_INTENT_FILTER_VERIFICATION,
19361                    new BlobXmlRestorer() {
19362                        @Override
19363                        public void apply(XmlPullParser parser, int userId)
19364                                throws XmlPullParserException, IOException {
19365                            synchronized (mPackages) {
19366                                mSettings.readAllDomainVerificationsLPr(parser, userId);
19367                                mSettings.writeLPr();
19368                            }
19369                        }
19370                    } );
19371        } catch (Exception e) {
19372            if (DEBUG_BACKUP) {
19373                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
19374            }
19375        }
19376    }
19377
19378    @Override
19379    public byte[] getPermissionGrantBackup(int userId) {
19380        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
19381            throw new SecurityException("Only the system may call getPermissionGrantBackup()");
19382        }
19383
19384        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
19385        try {
19386            final XmlSerializer serializer = new FastXmlSerializer();
19387            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
19388            serializer.startDocument(null, true);
19389            serializer.startTag(null, TAG_PERMISSION_BACKUP);
19390
19391            synchronized (mPackages) {
19392                serializeRuntimePermissionGrantsLPr(serializer, userId);
19393            }
19394
19395            serializer.endTag(null, TAG_PERMISSION_BACKUP);
19396            serializer.endDocument();
19397            serializer.flush();
19398        } catch (Exception e) {
19399            if (DEBUG_BACKUP) {
19400                Slog.e(TAG, "Unable to write default apps for backup", e);
19401            }
19402            return null;
19403        }
19404
19405        return dataStream.toByteArray();
19406    }
19407
19408    @Override
19409    public void restorePermissionGrants(byte[] backup, int userId) {
19410        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
19411            throw new SecurityException("Only the system may call restorePermissionGrants()");
19412        }
19413
19414        try {
19415            final XmlPullParser parser = Xml.newPullParser();
19416            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
19417            restoreFromXml(parser, userId, TAG_PERMISSION_BACKUP,
19418                    new BlobXmlRestorer() {
19419                        @Override
19420                        public void apply(XmlPullParser parser, int userId)
19421                                throws XmlPullParserException, IOException {
19422                            synchronized (mPackages) {
19423                                processRestoredPermissionGrantsLPr(parser, userId);
19424                            }
19425                        }
19426                    } );
19427        } catch (Exception e) {
19428            if (DEBUG_BACKUP) {
19429                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
19430            }
19431        }
19432    }
19433
19434    private void serializeRuntimePermissionGrantsLPr(XmlSerializer serializer, final int userId)
19435            throws IOException {
19436        serializer.startTag(null, TAG_ALL_GRANTS);
19437
19438        final int N = mSettings.mPackages.size();
19439        for (int i = 0; i < N; i++) {
19440            final PackageSetting ps = mSettings.mPackages.valueAt(i);
19441            boolean pkgGrantsKnown = false;
19442
19443            PermissionsState packagePerms = ps.getPermissionsState();
19444
19445            for (PermissionState state : packagePerms.getRuntimePermissionStates(userId)) {
19446                final int grantFlags = state.getFlags();
19447                // only look at grants that are not system/policy fixed
19448                if ((grantFlags & SYSTEM_RUNTIME_GRANT_MASK) == 0) {
19449                    final boolean isGranted = state.isGranted();
19450                    // And only back up the user-twiddled state bits
19451                    if (isGranted || (grantFlags & USER_RUNTIME_GRANT_MASK) != 0) {
19452                        final String packageName = mSettings.mPackages.keyAt(i);
19453                        if (!pkgGrantsKnown) {
19454                            serializer.startTag(null, TAG_GRANT);
19455                            serializer.attribute(null, ATTR_PACKAGE_NAME, packageName);
19456                            pkgGrantsKnown = true;
19457                        }
19458
19459                        final boolean userSet =
19460                                (grantFlags & FLAG_PERMISSION_USER_SET) != 0;
19461                        final boolean userFixed =
19462                                (grantFlags & FLAG_PERMISSION_USER_FIXED) != 0;
19463                        final boolean revoke =
19464                                (grantFlags & FLAG_PERMISSION_REVOKE_ON_UPGRADE) != 0;
19465
19466                        serializer.startTag(null, TAG_PERMISSION);
19467                        serializer.attribute(null, ATTR_PERMISSION_NAME, state.getName());
19468                        if (isGranted) {
19469                            serializer.attribute(null, ATTR_IS_GRANTED, "true");
19470                        }
19471                        if (userSet) {
19472                            serializer.attribute(null, ATTR_USER_SET, "true");
19473                        }
19474                        if (userFixed) {
19475                            serializer.attribute(null, ATTR_USER_FIXED, "true");
19476                        }
19477                        if (revoke) {
19478                            serializer.attribute(null, ATTR_REVOKE_ON_UPGRADE, "true");
19479                        }
19480                        serializer.endTag(null, TAG_PERMISSION);
19481                    }
19482                }
19483            }
19484
19485            if (pkgGrantsKnown) {
19486                serializer.endTag(null, TAG_GRANT);
19487            }
19488        }
19489
19490        serializer.endTag(null, TAG_ALL_GRANTS);
19491    }
19492
19493    private void processRestoredPermissionGrantsLPr(XmlPullParser parser, int userId)
19494            throws XmlPullParserException, IOException {
19495        String pkgName = null;
19496        int outerDepth = parser.getDepth();
19497        int type;
19498        while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
19499                && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) {
19500            if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) {
19501                continue;
19502            }
19503
19504            final String tagName = parser.getName();
19505            if (tagName.equals(TAG_GRANT)) {
19506                pkgName = parser.getAttributeValue(null, ATTR_PACKAGE_NAME);
19507                if (DEBUG_BACKUP) {
19508                    Slog.v(TAG, "+++ Restoring grants for package " + pkgName);
19509                }
19510            } else if (tagName.equals(TAG_PERMISSION)) {
19511
19512                final boolean isGranted = "true".equals(parser.getAttributeValue(null, ATTR_IS_GRANTED));
19513                final String permName = parser.getAttributeValue(null, ATTR_PERMISSION_NAME);
19514
19515                int newFlagSet = 0;
19516                if ("true".equals(parser.getAttributeValue(null, ATTR_USER_SET))) {
19517                    newFlagSet |= FLAG_PERMISSION_USER_SET;
19518                }
19519                if ("true".equals(parser.getAttributeValue(null, ATTR_USER_FIXED))) {
19520                    newFlagSet |= FLAG_PERMISSION_USER_FIXED;
19521                }
19522                if ("true".equals(parser.getAttributeValue(null, ATTR_REVOKE_ON_UPGRADE))) {
19523                    newFlagSet |= FLAG_PERMISSION_REVOKE_ON_UPGRADE;
19524                }
19525                if (DEBUG_BACKUP) {
19526                    Slog.v(TAG, "  + Restoring grant: pkg=" + pkgName + " perm=" + permName
19527                            + " granted=" + isGranted + " bits=0x" + Integer.toHexString(newFlagSet));
19528                }
19529                final PackageSetting ps = mSettings.mPackages.get(pkgName);
19530                if (ps != null) {
19531                    // Already installed so we apply the grant immediately
19532                    if (DEBUG_BACKUP) {
19533                        Slog.v(TAG, "        + already installed; applying");
19534                    }
19535                    PermissionsState perms = ps.getPermissionsState();
19536                    BasePermission bp = mSettings.mPermissions.get(permName);
19537                    if (bp != null) {
19538                        if (isGranted) {
19539                            perms.grantRuntimePermission(bp, userId);
19540                        }
19541                        if (newFlagSet != 0) {
19542                            perms.updatePermissionFlags(bp, userId, USER_RUNTIME_GRANT_MASK, newFlagSet);
19543                        }
19544                    }
19545                } else {
19546                    // Need to wait for post-restore install to apply the grant
19547                    if (DEBUG_BACKUP) {
19548                        Slog.v(TAG, "        - not yet installed; saving for later");
19549                    }
19550                    mSettings.processRestoredPermissionGrantLPr(pkgName, permName,
19551                            isGranted, newFlagSet, userId);
19552                }
19553            } else {
19554                PackageManagerService.reportSettingsProblem(Log.WARN,
19555                        "Unknown element under <" + TAG_PERMISSION_BACKUP + ">: " + tagName);
19556                XmlUtils.skipCurrentTag(parser);
19557            }
19558        }
19559
19560        scheduleWriteSettingsLocked();
19561        mSettings.writeRuntimePermissionsForUserLPr(userId, false);
19562    }
19563
19564    @Override
19565    public void addCrossProfileIntentFilter(IntentFilter intentFilter, String ownerPackage,
19566            int sourceUserId, int targetUserId, int flags) {
19567        mContext.enforceCallingOrSelfPermission(
19568                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
19569        int callingUid = Binder.getCallingUid();
19570        enforceOwnerRights(ownerPackage, callingUid);
19571        enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId);
19572        if (intentFilter.countActions() == 0) {
19573            Slog.w(TAG, "Cannot set a crossProfile intent filter with no filter actions");
19574            return;
19575        }
19576        synchronized (mPackages) {
19577            CrossProfileIntentFilter newFilter = new CrossProfileIntentFilter(intentFilter,
19578                    ownerPackage, targetUserId, flags);
19579            CrossProfileIntentResolver resolver =
19580                    mSettings.editCrossProfileIntentResolverLPw(sourceUserId);
19581            ArrayList<CrossProfileIntentFilter> existing = resolver.findFilters(intentFilter);
19582            // We have all those whose filter is equal. Now checking if the rest is equal as well.
19583            if (existing != null) {
19584                int size = existing.size();
19585                for (int i = 0; i < size; i++) {
19586                    if (newFilter.equalsIgnoreFilter(existing.get(i))) {
19587                        return;
19588                    }
19589                }
19590            }
19591            resolver.addFilter(newFilter);
19592            scheduleWritePackageRestrictionsLocked(sourceUserId);
19593        }
19594    }
19595
19596    @Override
19597    public void clearCrossProfileIntentFilters(int sourceUserId, String ownerPackage) {
19598        mContext.enforceCallingOrSelfPermission(
19599                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
19600        int callingUid = Binder.getCallingUid();
19601        enforceOwnerRights(ownerPackage, callingUid);
19602        enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId);
19603        synchronized (mPackages) {
19604            CrossProfileIntentResolver resolver =
19605                    mSettings.editCrossProfileIntentResolverLPw(sourceUserId);
19606            ArraySet<CrossProfileIntentFilter> set =
19607                    new ArraySet<CrossProfileIntentFilter>(resolver.filterSet());
19608            for (CrossProfileIntentFilter filter : set) {
19609                if (filter.getOwnerPackage().equals(ownerPackage)) {
19610                    resolver.removeFilter(filter);
19611                }
19612            }
19613            scheduleWritePackageRestrictionsLocked(sourceUserId);
19614        }
19615    }
19616
19617    // Enforcing that callingUid is owning pkg on userId
19618    private void enforceOwnerRights(String pkg, int callingUid) {
19619        // The system owns everything.
19620        if (UserHandle.getAppId(callingUid) == Process.SYSTEM_UID) {
19621            return;
19622        }
19623        int callingUserId = UserHandle.getUserId(callingUid);
19624        PackageInfo pi = getPackageInfo(pkg, 0, callingUserId);
19625        if (pi == null) {
19626            throw new IllegalArgumentException("Unknown package " + pkg + " on user "
19627                    + callingUserId);
19628        }
19629        if (!UserHandle.isSameApp(pi.applicationInfo.uid, callingUid)) {
19630            throw new SecurityException("Calling uid " + callingUid
19631                    + " does not own package " + pkg);
19632        }
19633    }
19634
19635    @Override
19636    public ComponentName getHomeActivities(List<ResolveInfo> allHomeCandidates) {
19637        return getHomeActivitiesAsUser(allHomeCandidates, UserHandle.getCallingUserId());
19638    }
19639
19640    private Intent getHomeIntent() {
19641        Intent intent = new Intent(Intent.ACTION_MAIN);
19642        intent.addCategory(Intent.CATEGORY_HOME);
19643        intent.addCategory(Intent.CATEGORY_DEFAULT);
19644        return intent;
19645    }
19646
19647    private IntentFilter getHomeFilter() {
19648        IntentFilter filter = new IntentFilter(Intent.ACTION_MAIN);
19649        filter.addCategory(Intent.CATEGORY_HOME);
19650        filter.addCategory(Intent.CATEGORY_DEFAULT);
19651        return filter;
19652    }
19653
19654    ComponentName getHomeActivitiesAsUser(List<ResolveInfo> allHomeCandidates,
19655            int userId) {
19656        Intent intent  = getHomeIntent();
19657        List<ResolveInfo> list = queryIntentActivitiesInternal(intent, null,
19658                PackageManager.GET_META_DATA, userId);
19659        ResolveInfo preferred = findPreferredActivity(intent, null, 0, list, 0,
19660                true, false, false, userId);
19661
19662        allHomeCandidates.clear();
19663        if (list != null) {
19664            for (ResolveInfo ri : list) {
19665                allHomeCandidates.add(ri);
19666            }
19667        }
19668        return (preferred == null || preferred.activityInfo == null)
19669                ? null
19670                : new ComponentName(preferred.activityInfo.packageName,
19671                        preferred.activityInfo.name);
19672    }
19673
19674    @Override
19675    public void setHomeActivity(ComponentName comp, int userId) {
19676        ArrayList<ResolveInfo> homeActivities = new ArrayList<>();
19677        getHomeActivitiesAsUser(homeActivities, userId);
19678
19679        boolean found = false;
19680
19681        final int size = homeActivities.size();
19682        final ComponentName[] set = new ComponentName[size];
19683        for (int i = 0; i < size; i++) {
19684            final ResolveInfo candidate = homeActivities.get(i);
19685            final ActivityInfo info = candidate.activityInfo;
19686            final ComponentName activityName = new ComponentName(info.packageName, info.name);
19687            set[i] = activityName;
19688            if (!found && activityName.equals(comp)) {
19689                found = true;
19690            }
19691        }
19692        if (!found) {
19693            throw new IllegalArgumentException("Component " + comp + " cannot be home on user "
19694                    + userId);
19695        }
19696        replacePreferredActivity(getHomeFilter(), IntentFilter.MATCH_CATEGORY_EMPTY,
19697                set, comp, userId);
19698    }
19699
19700    private @Nullable String getSetupWizardPackageName() {
19701        final Intent intent = new Intent(Intent.ACTION_MAIN);
19702        intent.addCategory(Intent.CATEGORY_SETUP_WIZARD);
19703
19704        final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, null,
19705                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE
19706                        | MATCH_DISABLED_COMPONENTS,
19707                UserHandle.myUserId());
19708        if (matches.size() == 1) {
19709            return matches.get(0).getComponentInfo().packageName;
19710        } else {
19711            Slog.e(TAG, "There should probably be exactly one setup wizard; found " + matches.size()
19712                    + ": matches=" + matches);
19713            return null;
19714        }
19715    }
19716
19717    private @Nullable String getStorageManagerPackageName() {
19718        final Intent intent = new Intent(StorageManager.ACTION_MANAGE_STORAGE);
19719
19720        final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, null,
19721                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE
19722                        | MATCH_DISABLED_COMPONENTS,
19723                UserHandle.myUserId());
19724        if (matches.size() == 1) {
19725            return matches.get(0).getComponentInfo().packageName;
19726        } else {
19727            Slog.e(TAG, "There should probably be exactly one storage manager; found "
19728                    + matches.size() + ": matches=" + matches);
19729            return null;
19730        }
19731    }
19732
19733    @Override
19734    public void setApplicationEnabledSetting(String appPackageName,
19735            int newState, int flags, int userId, String callingPackage) {
19736        if (!sUserManager.exists(userId)) return;
19737        if (callingPackage == null) {
19738            callingPackage = Integer.toString(Binder.getCallingUid());
19739        }
19740        setEnabledSetting(appPackageName, null, newState, flags, userId, callingPackage);
19741    }
19742
19743    @Override
19744    public void setComponentEnabledSetting(ComponentName componentName,
19745            int newState, int flags, int userId) {
19746        if (!sUserManager.exists(userId)) return;
19747        setEnabledSetting(componentName.getPackageName(),
19748                componentName.getClassName(), newState, flags, userId, null);
19749    }
19750
19751    private void setEnabledSetting(final String packageName, String className, int newState,
19752            final int flags, int userId, String callingPackage) {
19753        if (!(newState == COMPONENT_ENABLED_STATE_DEFAULT
19754              || newState == COMPONENT_ENABLED_STATE_ENABLED
19755              || newState == COMPONENT_ENABLED_STATE_DISABLED
19756              || newState == COMPONENT_ENABLED_STATE_DISABLED_USER
19757              || newState == COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED)) {
19758            throw new IllegalArgumentException("Invalid new component state: "
19759                    + newState);
19760        }
19761        PackageSetting pkgSetting;
19762        final int uid = Binder.getCallingUid();
19763        final int permission;
19764        if (uid == Process.SYSTEM_UID) {
19765            permission = PackageManager.PERMISSION_GRANTED;
19766        } else {
19767            permission = mContext.checkCallingOrSelfPermission(
19768                    android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
19769        }
19770        enforceCrossUserPermission(uid, userId,
19771                false /* requireFullPermission */, true /* checkShell */, "set enabled");
19772        final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
19773        boolean sendNow = false;
19774        boolean isApp = (className == null);
19775        String componentName = isApp ? packageName : className;
19776        int packageUid = -1;
19777        ArrayList<String> components;
19778
19779        // writer
19780        synchronized (mPackages) {
19781            pkgSetting = mSettings.mPackages.get(packageName);
19782            if (pkgSetting == null) {
19783                if (className == null) {
19784                    throw new IllegalArgumentException("Unknown package: " + packageName);
19785                }
19786                throw new IllegalArgumentException(
19787                        "Unknown component: " + packageName + "/" + className);
19788            }
19789        }
19790
19791        // Limit who can change which apps
19792        if (!UserHandle.isSameApp(uid, pkgSetting.appId)) {
19793            // Don't allow apps that don't have permission to modify other apps
19794            if (!allowedByPermission) {
19795                throw new SecurityException(
19796                        "Permission Denial: attempt to change component state from pid="
19797                        + Binder.getCallingPid()
19798                        + ", uid=" + uid + ", package uid=" + pkgSetting.appId);
19799            }
19800            // Don't allow changing protected packages.
19801            if (mProtectedPackages.isPackageStateProtected(userId, packageName)) {
19802                throw new SecurityException("Cannot disable a protected package: " + packageName);
19803            }
19804        }
19805
19806        synchronized (mPackages) {
19807            if (uid == Process.SHELL_UID
19808                    && (pkgSetting.pkgFlags & ApplicationInfo.FLAG_TEST_ONLY) == 0) {
19809                // Shell can only change whole packages between ENABLED and DISABLED_USER states
19810                // unless it is a test package.
19811                int oldState = pkgSetting.getEnabled(userId);
19812                if (className == null
19813                    &&
19814                    (oldState == COMPONENT_ENABLED_STATE_DISABLED_USER
19815                     || oldState == COMPONENT_ENABLED_STATE_DEFAULT
19816                     || oldState == COMPONENT_ENABLED_STATE_ENABLED)
19817                    &&
19818                    (newState == COMPONENT_ENABLED_STATE_DISABLED_USER
19819                     || newState == COMPONENT_ENABLED_STATE_DEFAULT
19820                     || newState == COMPONENT_ENABLED_STATE_ENABLED)) {
19821                    // ok
19822                } else {
19823                    throw new SecurityException(
19824                            "Shell cannot change component state for " + packageName + "/"
19825                            + className + " to " + newState);
19826                }
19827            }
19828            if (className == null) {
19829                // We're dealing with an application/package level state change
19830                if (pkgSetting.getEnabled(userId) == newState) {
19831                    // Nothing to do
19832                    return;
19833                }
19834                if (newState == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT
19835                    || newState == PackageManager.COMPONENT_ENABLED_STATE_ENABLED) {
19836                    // Don't care about who enables an app.
19837                    callingPackage = null;
19838                }
19839                pkgSetting.setEnabled(newState, userId, callingPackage);
19840                // pkgSetting.pkg.mSetEnabled = newState;
19841            } else {
19842                // We're dealing with a component level state change
19843                // First, verify that this is a valid class name.
19844                PackageParser.Package pkg = pkgSetting.pkg;
19845                if (pkg == null || !pkg.hasComponentClassName(className)) {
19846                    if (pkg != null &&
19847                            pkg.applicationInfo.targetSdkVersion >=
19848                                    Build.VERSION_CODES.JELLY_BEAN) {
19849                        throw new IllegalArgumentException("Component class " + className
19850                                + " does not exist in " + packageName);
19851                    } else {
19852                        Slog.w(TAG, "Failed setComponentEnabledSetting: component class "
19853                                + className + " does not exist in " + packageName);
19854                    }
19855                }
19856                switch (newState) {
19857                case COMPONENT_ENABLED_STATE_ENABLED:
19858                    if (!pkgSetting.enableComponentLPw(className, userId)) {
19859                        return;
19860                    }
19861                    break;
19862                case COMPONENT_ENABLED_STATE_DISABLED:
19863                    if (!pkgSetting.disableComponentLPw(className, userId)) {
19864                        return;
19865                    }
19866                    break;
19867                case COMPONENT_ENABLED_STATE_DEFAULT:
19868                    if (!pkgSetting.restoreComponentLPw(className, userId)) {
19869                        return;
19870                    }
19871                    break;
19872                default:
19873                    Slog.e(TAG, "Invalid new component state: " + newState);
19874                    return;
19875                }
19876            }
19877            scheduleWritePackageRestrictionsLocked(userId);
19878            updateSequenceNumberLP(packageName, new int[] { userId });
19879            components = mPendingBroadcasts.get(userId, packageName);
19880            final boolean newPackage = components == null;
19881            if (newPackage) {
19882                components = new ArrayList<String>();
19883            }
19884            if (!components.contains(componentName)) {
19885                components.add(componentName);
19886            }
19887            if ((flags&PackageManager.DONT_KILL_APP) == 0) {
19888                sendNow = true;
19889                // Purge entry from pending broadcast list if another one exists already
19890                // since we are sending one right away.
19891                mPendingBroadcasts.remove(userId, packageName);
19892            } else {
19893                if (newPackage) {
19894                    mPendingBroadcasts.put(userId, packageName, components);
19895                }
19896                if (!mHandler.hasMessages(SEND_PENDING_BROADCAST)) {
19897                    // Schedule a message
19898                    mHandler.sendEmptyMessageDelayed(SEND_PENDING_BROADCAST, BROADCAST_DELAY);
19899                }
19900            }
19901        }
19902
19903        long callingId = Binder.clearCallingIdentity();
19904        try {
19905            if (sendNow) {
19906                packageUid = UserHandle.getUid(userId, pkgSetting.appId);
19907                sendPackageChangedBroadcast(packageName,
19908                        (flags&PackageManager.DONT_KILL_APP) != 0, components, packageUid);
19909            }
19910        } finally {
19911            Binder.restoreCallingIdentity(callingId);
19912        }
19913    }
19914
19915    @Override
19916    public void flushPackageRestrictionsAsUser(int userId) {
19917        if (!sUserManager.exists(userId)) {
19918            return;
19919        }
19920        enforceCrossUserPermission(Binder.getCallingUid(), userId, false /* requireFullPermission*/,
19921                false /* checkShell */, "flushPackageRestrictions");
19922        synchronized (mPackages) {
19923            mSettings.writePackageRestrictionsLPr(userId);
19924            mDirtyUsers.remove(userId);
19925            if (mDirtyUsers.isEmpty()) {
19926                mHandler.removeMessages(WRITE_PACKAGE_RESTRICTIONS);
19927            }
19928        }
19929    }
19930
19931    private void sendPackageChangedBroadcast(String packageName,
19932            boolean killFlag, ArrayList<String> componentNames, int packageUid) {
19933        if (DEBUG_INSTALL)
19934            Log.v(TAG, "Sending package changed: package=" + packageName + " components="
19935                    + componentNames);
19936        Bundle extras = new Bundle(4);
19937        extras.putString(Intent.EXTRA_CHANGED_COMPONENT_NAME, componentNames.get(0));
19938        String nameList[] = new String[componentNames.size()];
19939        componentNames.toArray(nameList);
19940        extras.putStringArray(Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST, nameList);
19941        extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, killFlag);
19942        extras.putInt(Intent.EXTRA_UID, packageUid);
19943        // If this is not reporting a change of the overall package, then only send it
19944        // to registered receivers.  We don't want to launch a swath of apps for every
19945        // little component state change.
19946        final int flags = !componentNames.contains(packageName)
19947                ? Intent.FLAG_RECEIVER_REGISTERED_ONLY : 0;
19948        sendPackageBroadcast(Intent.ACTION_PACKAGE_CHANGED,  packageName, extras, flags, null, null,
19949                new int[] {UserHandle.getUserId(packageUid)});
19950    }
19951
19952    @Override
19953    public void setPackageStoppedState(String packageName, boolean stopped, int userId) {
19954        if (!sUserManager.exists(userId)) return;
19955        final int uid = Binder.getCallingUid();
19956        final int permission = mContext.checkCallingOrSelfPermission(
19957                android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
19958        final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
19959        enforceCrossUserPermission(uid, userId,
19960                true /* requireFullPermission */, true /* checkShell */, "stop package");
19961        // writer
19962        synchronized (mPackages) {
19963            if (mSettings.setPackageStoppedStateLPw(this, packageName, stopped,
19964                    allowedByPermission, uid, userId)) {
19965                scheduleWritePackageRestrictionsLocked(userId);
19966            }
19967        }
19968    }
19969
19970    @Override
19971    public String getInstallerPackageName(String packageName) {
19972        // reader
19973        synchronized (mPackages) {
19974            return mSettings.getInstallerPackageNameLPr(packageName);
19975        }
19976    }
19977
19978    public boolean isOrphaned(String packageName) {
19979        // reader
19980        synchronized (mPackages) {
19981            return mSettings.isOrphaned(packageName);
19982        }
19983    }
19984
19985    @Override
19986    public int getApplicationEnabledSetting(String packageName, int userId) {
19987        if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
19988        int uid = Binder.getCallingUid();
19989        enforceCrossUserPermission(uid, userId,
19990                false /* requireFullPermission */, false /* checkShell */, "get enabled");
19991        // reader
19992        synchronized (mPackages) {
19993            return mSettings.getApplicationEnabledSettingLPr(packageName, userId);
19994        }
19995    }
19996
19997    @Override
19998    public int getComponentEnabledSetting(ComponentName componentName, int userId) {
19999        if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
20000        int uid = Binder.getCallingUid();
20001        enforceCrossUserPermission(uid, userId,
20002                false /* requireFullPermission */, false /* checkShell */, "get component enabled");
20003        // reader
20004        synchronized (mPackages) {
20005            return mSettings.getComponentEnabledSettingLPr(componentName, userId);
20006        }
20007    }
20008
20009    @Override
20010    public void enterSafeMode() {
20011        enforceSystemOrRoot("Only the system can request entering safe mode");
20012
20013        if (!mSystemReady) {
20014            mSafeMode = true;
20015        }
20016    }
20017
20018    @Override
20019    public void systemReady() {
20020        mSystemReady = true;
20021
20022        // Disable any carrier apps. We do this very early in boot to prevent the apps from being
20023        // disabled after already being started.
20024        CarrierAppUtils.disableCarrierAppsUntilPrivileged(mContext.getOpPackageName(), this,
20025                mContext.getContentResolver(), UserHandle.USER_SYSTEM);
20026
20027        // Read the compatibilty setting when the system is ready.
20028        boolean compatibilityModeEnabled = android.provider.Settings.Global.getInt(
20029                mContext.getContentResolver(),
20030                android.provider.Settings.Global.COMPATIBILITY_MODE, 1) == 1;
20031        PackageParser.setCompatibilityModeEnabled(compatibilityModeEnabled);
20032        if (DEBUG_SETTINGS) {
20033            Log.d(TAG, "compatibility mode:" + compatibilityModeEnabled);
20034        }
20035
20036        int[] grantPermissionsUserIds = EMPTY_INT_ARRAY;
20037
20038        synchronized (mPackages) {
20039            // Verify that all of the preferred activity components actually
20040            // exist.  It is possible for applications to be updated and at
20041            // that point remove a previously declared activity component that
20042            // had been set as a preferred activity.  We try to clean this up
20043            // the next time we encounter that preferred activity, but it is
20044            // possible for the user flow to never be able to return to that
20045            // situation so here we do a sanity check to make sure we haven't
20046            // left any junk around.
20047            ArrayList<PreferredActivity> removed = new ArrayList<PreferredActivity>();
20048            for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
20049                PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
20050                removed.clear();
20051                for (PreferredActivity pa : pir.filterSet()) {
20052                    if (mActivities.mActivities.get(pa.mPref.mComponent) == null) {
20053                        removed.add(pa);
20054                    }
20055                }
20056                if (removed.size() > 0) {
20057                    for (int r=0; r<removed.size(); r++) {
20058                        PreferredActivity pa = removed.get(r);
20059                        Slog.w(TAG, "Removing dangling preferred activity: "
20060                                + pa.mPref.mComponent);
20061                        pir.removeFilter(pa);
20062                    }
20063                    mSettings.writePackageRestrictionsLPr(
20064                            mSettings.mPreferredActivities.keyAt(i));
20065                }
20066            }
20067
20068            for (int userId : UserManagerService.getInstance().getUserIds()) {
20069                if (!mSettings.areDefaultRuntimePermissionsGrantedLPr(userId)) {
20070                    grantPermissionsUserIds = ArrayUtils.appendInt(
20071                            grantPermissionsUserIds, userId);
20072                }
20073            }
20074        }
20075        sUserManager.systemReady();
20076
20077        // If we upgraded grant all default permissions before kicking off.
20078        for (int userId : grantPermissionsUserIds) {
20079            mDefaultPermissionPolicy.grantDefaultPermissions(userId);
20080        }
20081
20082        // If we did not grant default permissions, we preload from this the
20083        // default permission exceptions lazily to ensure we don't hit the
20084        // disk on a new user creation.
20085        if (grantPermissionsUserIds == EMPTY_INT_ARRAY) {
20086            mDefaultPermissionPolicy.scheduleReadDefaultPermissionExceptions();
20087        }
20088
20089        // Kick off any messages waiting for system ready
20090        if (mPostSystemReadyMessages != null) {
20091            for (Message msg : mPostSystemReadyMessages) {
20092                msg.sendToTarget();
20093            }
20094            mPostSystemReadyMessages = null;
20095        }
20096
20097        // Watch for external volumes that come and go over time
20098        final StorageManager storage = mContext.getSystemService(StorageManager.class);
20099        storage.registerListener(mStorageListener);
20100
20101        mInstallerService.systemReady();
20102        mPackageDexOptimizer.systemReady();
20103
20104        StorageManagerInternal StorageManagerInternal = LocalServices.getService(
20105                StorageManagerInternal.class);
20106        StorageManagerInternal.addExternalStoragePolicy(
20107                new StorageManagerInternal.ExternalStorageMountPolicy() {
20108            @Override
20109            public int getMountMode(int uid, String packageName) {
20110                if (Process.isIsolated(uid)) {
20111                    return Zygote.MOUNT_EXTERNAL_NONE;
20112                }
20113                if (checkUidPermission(WRITE_MEDIA_STORAGE, uid) == PERMISSION_GRANTED) {
20114                    return Zygote.MOUNT_EXTERNAL_DEFAULT;
20115                }
20116                if (checkUidPermission(READ_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) {
20117                    return Zygote.MOUNT_EXTERNAL_DEFAULT;
20118                }
20119                if (checkUidPermission(WRITE_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) {
20120                    return Zygote.MOUNT_EXTERNAL_READ;
20121                }
20122                return Zygote.MOUNT_EXTERNAL_WRITE;
20123            }
20124
20125            @Override
20126            public boolean hasExternalStorage(int uid, String packageName) {
20127                return true;
20128            }
20129        });
20130
20131        // Now that we're mostly running, clean up stale users and apps
20132        sUserManager.reconcileUsers(StorageManager.UUID_PRIVATE_INTERNAL);
20133        reconcileApps(StorageManager.UUID_PRIVATE_INTERNAL);
20134
20135        if (mPrivappPermissionsViolations != null) {
20136            Slog.wtf(TAG,"Signature|privileged permissions not in "
20137                    + "privapp-permissions whitelist: " + mPrivappPermissionsViolations);
20138            mPrivappPermissionsViolations = null;
20139        }
20140    }
20141
20142    public void waitForAppDataPrepared() {
20143        if (mPrepareAppDataFuture == null) {
20144            return;
20145        }
20146        ConcurrentUtils.waitForFutureNoInterrupt(mPrepareAppDataFuture, "wait for prepareAppData");
20147        mPrepareAppDataFuture = null;
20148    }
20149
20150    @Override
20151    public boolean isSafeMode() {
20152        return mSafeMode;
20153    }
20154
20155    @Override
20156    public boolean hasSystemUidErrors() {
20157        return mHasSystemUidErrors;
20158    }
20159
20160    static String arrayToString(int[] array) {
20161        StringBuffer buf = new StringBuffer(128);
20162        buf.append('[');
20163        if (array != null) {
20164            for (int i=0; i<array.length; i++) {
20165                if (i > 0) buf.append(", ");
20166                buf.append(array[i]);
20167            }
20168        }
20169        buf.append(']');
20170        return buf.toString();
20171    }
20172
20173    static class DumpState {
20174        public static final int DUMP_LIBS = 1 << 0;
20175        public static final int DUMP_FEATURES = 1 << 1;
20176        public static final int DUMP_ACTIVITY_RESOLVERS = 1 << 2;
20177        public static final int DUMP_SERVICE_RESOLVERS = 1 << 3;
20178        public static final int DUMP_RECEIVER_RESOLVERS = 1 << 4;
20179        public static final int DUMP_CONTENT_RESOLVERS = 1 << 5;
20180        public static final int DUMP_PERMISSIONS = 1 << 6;
20181        public static final int DUMP_PACKAGES = 1 << 7;
20182        public static final int DUMP_SHARED_USERS = 1 << 8;
20183        public static final int DUMP_MESSAGES = 1 << 9;
20184        public static final int DUMP_PROVIDERS = 1 << 10;
20185        public static final int DUMP_VERIFIERS = 1 << 11;
20186        public static final int DUMP_PREFERRED = 1 << 12;
20187        public static final int DUMP_PREFERRED_XML = 1 << 13;
20188        public static final int DUMP_KEYSETS = 1 << 14;
20189        public static final int DUMP_VERSION = 1 << 15;
20190        public static final int DUMP_INSTALLS = 1 << 16;
20191        public static final int DUMP_INTENT_FILTER_VERIFIERS = 1 << 17;
20192        public static final int DUMP_DOMAIN_PREFERRED = 1 << 18;
20193        public static final int DUMP_FROZEN = 1 << 19;
20194        public static final int DUMP_DEXOPT = 1 << 20;
20195        public static final int DUMP_COMPILER_STATS = 1 << 21;
20196
20197        public static final int OPTION_SHOW_FILTERS = 1 << 0;
20198
20199        private int mTypes;
20200
20201        private int mOptions;
20202
20203        private boolean mTitlePrinted;
20204
20205        private SharedUserSetting mSharedUser;
20206
20207        public boolean isDumping(int type) {
20208            if (mTypes == 0 && type != DUMP_PREFERRED_XML) {
20209                return true;
20210            }
20211
20212            return (mTypes & type) != 0;
20213        }
20214
20215        public void setDump(int type) {
20216            mTypes |= type;
20217        }
20218
20219        public boolean isOptionEnabled(int option) {
20220            return (mOptions & option) != 0;
20221        }
20222
20223        public void setOptionEnabled(int option) {
20224            mOptions |= option;
20225        }
20226
20227        public boolean onTitlePrinted() {
20228            final boolean printed = mTitlePrinted;
20229            mTitlePrinted = true;
20230            return printed;
20231        }
20232
20233        public boolean getTitlePrinted() {
20234            return mTitlePrinted;
20235        }
20236
20237        public void setTitlePrinted(boolean enabled) {
20238            mTitlePrinted = enabled;
20239        }
20240
20241        public SharedUserSetting getSharedUser() {
20242            return mSharedUser;
20243        }
20244
20245        public void setSharedUser(SharedUserSetting user) {
20246            mSharedUser = user;
20247        }
20248    }
20249
20250    @Override
20251    public void onShellCommand(FileDescriptor in, FileDescriptor out,
20252            FileDescriptor err, String[] args, ShellCallback callback,
20253            ResultReceiver resultReceiver) {
20254        (new PackageManagerShellCommand(this)).exec(
20255                this, in, out, err, args, callback, resultReceiver);
20256    }
20257
20258    @Override
20259    protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
20260        if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
20261                != PackageManager.PERMISSION_GRANTED) {
20262            pw.println("Permission Denial: can't dump ActivityManager from from pid="
20263                    + Binder.getCallingPid()
20264                    + ", uid=" + Binder.getCallingUid()
20265                    + " without permission "
20266                    + android.Manifest.permission.DUMP);
20267            return;
20268        }
20269
20270        DumpState dumpState = new DumpState();
20271        boolean fullPreferred = false;
20272        boolean checkin = false;
20273
20274        String packageName = null;
20275        ArraySet<String> permissionNames = null;
20276
20277        int opti = 0;
20278        while (opti < args.length) {
20279            String opt = args[opti];
20280            if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') {
20281                break;
20282            }
20283            opti++;
20284
20285            if ("-a".equals(opt)) {
20286                // Right now we only know how to print all.
20287            } else if ("-h".equals(opt)) {
20288                pw.println("Package manager dump options:");
20289                pw.println("  [-h] [-f] [--checkin] [cmd] ...");
20290                pw.println("    --checkin: dump for a checkin");
20291                pw.println("    -f: print details of intent filters");
20292                pw.println("    -h: print this help");
20293                pw.println("  cmd may be one of:");
20294                pw.println("    l[ibraries]: list known shared libraries");
20295                pw.println("    f[eatures]: list device features");
20296                pw.println("    k[eysets]: print known keysets");
20297                pw.println("    r[esolvers] [activity|service|receiver|content]: dump intent resolvers");
20298                pw.println("    perm[issions]: dump permissions");
20299                pw.println("    permission [name ...]: dump declaration and use of given permission");
20300                pw.println("    pref[erred]: print preferred package settings");
20301                pw.println("    preferred-xml [--full]: print preferred package settings as xml");
20302                pw.println("    prov[iders]: dump content providers");
20303                pw.println("    p[ackages]: dump installed packages");
20304                pw.println("    s[hared-users]: dump shared user IDs");
20305                pw.println("    m[essages]: print collected runtime messages");
20306                pw.println("    v[erifiers]: print package verifier info");
20307                pw.println("    d[omain-preferred-apps]: print domains preferred apps");
20308                pw.println("    i[ntent-filter-verifiers]|ifv: print intent filter verifier info");
20309                pw.println("    version: print database version info");
20310                pw.println("    write: write current settings now");
20311                pw.println("    installs: details about install sessions");
20312                pw.println("    check-permission <permission> <package> [<user>]: does pkg hold perm?");
20313                pw.println("    dexopt: dump dexopt state");
20314                pw.println("    compiler-stats: dump compiler statistics");
20315                pw.println("    <package.name>: info about given package");
20316                return;
20317            } else if ("--checkin".equals(opt)) {
20318                checkin = true;
20319            } else if ("-f".equals(opt)) {
20320                dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS);
20321            } else {
20322                pw.println("Unknown argument: " + opt + "; use -h for help");
20323            }
20324        }
20325
20326        // Is the caller requesting to dump a particular piece of data?
20327        if (opti < args.length) {
20328            String cmd = args[opti];
20329            opti++;
20330            // Is this a package name?
20331            if ("android".equals(cmd) || cmd.contains(".")) {
20332                packageName = cmd;
20333                // When dumping a single package, we always dump all of its
20334                // filter information since the amount of data will be reasonable.
20335                dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS);
20336            } else if ("check-permission".equals(cmd)) {
20337                if (opti >= args.length) {
20338                    pw.println("Error: check-permission missing permission argument");
20339                    return;
20340                }
20341                String perm = args[opti];
20342                opti++;
20343                if (opti >= args.length) {
20344                    pw.println("Error: check-permission missing package argument");
20345                    return;
20346                }
20347
20348                String pkg = args[opti];
20349                opti++;
20350                int user = UserHandle.getUserId(Binder.getCallingUid());
20351                if (opti < args.length) {
20352                    try {
20353                        user = Integer.parseInt(args[opti]);
20354                    } catch (NumberFormatException e) {
20355                        pw.println("Error: check-permission user argument is not a number: "
20356                                + args[opti]);
20357                        return;
20358                    }
20359                }
20360
20361                // Normalize package name to handle renamed packages and static libs
20362                pkg = resolveInternalPackageNameLPr(pkg, PackageManager.VERSION_CODE_HIGHEST);
20363
20364                pw.println(checkPermission(perm, pkg, user));
20365                return;
20366            } else if ("l".equals(cmd) || "libraries".equals(cmd)) {
20367                dumpState.setDump(DumpState.DUMP_LIBS);
20368            } else if ("f".equals(cmd) || "features".equals(cmd)) {
20369                dumpState.setDump(DumpState.DUMP_FEATURES);
20370            } else if ("r".equals(cmd) || "resolvers".equals(cmd)) {
20371                if (opti >= args.length) {
20372                    dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS
20373                            | DumpState.DUMP_SERVICE_RESOLVERS
20374                            | DumpState.DUMP_RECEIVER_RESOLVERS
20375                            | DumpState.DUMP_CONTENT_RESOLVERS);
20376                } else {
20377                    while (opti < args.length) {
20378                        String name = args[opti];
20379                        if ("a".equals(name) || "activity".equals(name)) {
20380                            dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS);
20381                        } else if ("s".equals(name) || "service".equals(name)) {
20382                            dumpState.setDump(DumpState.DUMP_SERVICE_RESOLVERS);
20383                        } else if ("r".equals(name) || "receiver".equals(name)) {
20384                            dumpState.setDump(DumpState.DUMP_RECEIVER_RESOLVERS);
20385                        } else if ("c".equals(name) || "content".equals(name)) {
20386                            dumpState.setDump(DumpState.DUMP_CONTENT_RESOLVERS);
20387                        } else {
20388                            pw.println("Error: unknown resolver table type: " + name);
20389                            return;
20390                        }
20391                        opti++;
20392                    }
20393                }
20394            } else if ("perm".equals(cmd) || "permissions".equals(cmd)) {
20395                dumpState.setDump(DumpState.DUMP_PERMISSIONS);
20396            } else if ("permission".equals(cmd)) {
20397                if (opti >= args.length) {
20398                    pw.println("Error: permission requires permission name");
20399                    return;
20400                }
20401                permissionNames = new ArraySet<>();
20402                while (opti < args.length) {
20403                    permissionNames.add(args[opti]);
20404                    opti++;
20405                }
20406                dumpState.setDump(DumpState.DUMP_PERMISSIONS
20407                        | DumpState.DUMP_PACKAGES | DumpState.DUMP_SHARED_USERS);
20408            } else if ("pref".equals(cmd) || "preferred".equals(cmd)) {
20409                dumpState.setDump(DumpState.DUMP_PREFERRED);
20410            } else if ("preferred-xml".equals(cmd)) {
20411                dumpState.setDump(DumpState.DUMP_PREFERRED_XML);
20412                if (opti < args.length && "--full".equals(args[opti])) {
20413                    fullPreferred = true;
20414                    opti++;
20415                }
20416            } else if ("d".equals(cmd) || "domain-preferred-apps".equals(cmd)) {
20417                dumpState.setDump(DumpState.DUMP_DOMAIN_PREFERRED);
20418            } else if ("p".equals(cmd) || "packages".equals(cmd)) {
20419                dumpState.setDump(DumpState.DUMP_PACKAGES);
20420            } else if ("s".equals(cmd) || "shared-users".equals(cmd)) {
20421                dumpState.setDump(DumpState.DUMP_SHARED_USERS);
20422            } else if ("prov".equals(cmd) || "providers".equals(cmd)) {
20423                dumpState.setDump(DumpState.DUMP_PROVIDERS);
20424            } else if ("m".equals(cmd) || "messages".equals(cmd)) {
20425                dumpState.setDump(DumpState.DUMP_MESSAGES);
20426            } else if ("v".equals(cmd) || "verifiers".equals(cmd)) {
20427                dumpState.setDump(DumpState.DUMP_VERIFIERS);
20428            } else if ("i".equals(cmd) || "ifv".equals(cmd)
20429                    || "intent-filter-verifiers".equals(cmd)) {
20430                dumpState.setDump(DumpState.DUMP_INTENT_FILTER_VERIFIERS);
20431            } else if ("version".equals(cmd)) {
20432                dumpState.setDump(DumpState.DUMP_VERSION);
20433            } else if ("k".equals(cmd) || "keysets".equals(cmd)) {
20434                dumpState.setDump(DumpState.DUMP_KEYSETS);
20435            } else if ("installs".equals(cmd)) {
20436                dumpState.setDump(DumpState.DUMP_INSTALLS);
20437            } else if ("frozen".equals(cmd)) {
20438                dumpState.setDump(DumpState.DUMP_FROZEN);
20439            } else if ("dexopt".equals(cmd)) {
20440                dumpState.setDump(DumpState.DUMP_DEXOPT);
20441            } else if ("compiler-stats".equals(cmd)) {
20442                dumpState.setDump(DumpState.DUMP_COMPILER_STATS);
20443            } else if ("write".equals(cmd)) {
20444                synchronized (mPackages) {
20445                    mSettings.writeLPr();
20446                    pw.println("Settings written.");
20447                    return;
20448                }
20449            }
20450        }
20451
20452        if (checkin) {
20453            pw.println("vers,1");
20454        }
20455
20456        // reader
20457        synchronized (mPackages) {
20458            if (dumpState.isDumping(DumpState.DUMP_VERSION) && packageName == null) {
20459                if (!checkin) {
20460                    if (dumpState.onTitlePrinted())
20461                        pw.println();
20462                    pw.println("Database versions:");
20463                    mSettings.dumpVersionLPr(new IndentingPrintWriter(pw, "  "));
20464                }
20465            }
20466
20467            if (dumpState.isDumping(DumpState.DUMP_VERIFIERS) && packageName == null) {
20468                if (!checkin) {
20469                    if (dumpState.onTitlePrinted())
20470                        pw.println();
20471                    pw.println("Verifiers:");
20472                    pw.print("  Required: ");
20473                    pw.print(mRequiredVerifierPackage);
20474                    pw.print(" (uid=");
20475                    pw.print(getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING,
20476                            UserHandle.USER_SYSTEM));
20477                    pw.println(")");
20478                } else if (mRequiredVerifierPackage != null) {
20479                    pw.print("vrfy,"); pw.print(mRequiredVerifierPackage);
20480                    pw.print(",");
20481                    pw.println(getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING,
20482                            UserHandle.USER_SYSTEM));
20483                }
20484            }
20485
20486            if (dumpState.isDumping(DumpState.DUMP_INTENT_FILTER_VERIFIERS) &&
20487                    packageName == null) {
20488                if (mIntentFilterVerifierComponent != null) {
20489                    String verifierPackageName = mIntentFilterVerifierComponent.getPackageName();
20490                    if (!checkin) {
20491                        if (dumpState.onTitlePrinted())
20492                            pw.println();
20493                        pw.println("Intent Filter Verifier:");
20494                        pw.print("  Using: ");
20495                        pw.print(verifierPackageName);
20496                        pw.print(" (uid=");
20497                        pw.print(getPackageUid(verifierPackageName, MATCH_DEBUG_TRIAGED_MISSING,
20498                                UserHandle.USER_SYSTEM));
20499                        pw.println(")");
20500                    } else if (verifierPackageName != null) {
20501                        pw.print("ifv,"); pw.print(verifierPackageName);
20502                        pw.print(",");
20503                        pw.println(getPackageUid(verifierPackageName, MATCH_DEBUG_TRIAGED_MISSING,
20504                                UserHandle.USER_SYSTEM));
20505                    }
20506                } else {
20507                    pw.println();
20508                    pw.println("No Intent Filter Verifier available!");
20509                }
20510            }
20511
20512            if (dumpState.isDumping(DumpState.DUMP_LIBS) && packageName == null) {
20513                boolean printedHeader = false;
20514                final Iterator<String> it = mSharedLibraries.keySet().iterator();
20515                while (it.hasNext()) {
20516                    String libName = it.next();
20517                    SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(libName);
20518                    if (versionedLib == null) {
20519                        continue;
20520                    }
20521                    final int versionCount = versionedLib.size();
20522                    for (int i = 0; i < versionCount; i++) {
20523                        SharedLibraryEntry libEntry = versionedLib.valueAt(i);
20524                        if (!checkin) {
20525                            if (!printedHeader) {
20526                                if (dumpState.onTitlePrinted())
20527                                    pw.println();
20528                                pw.println("Libraries:");
20529                                printedHeader = true;
20530                            }
20531                            pw.print("  ");
20532                        } else {
20533                            pw.print("lib,");
20534                        }
20535                        pw.print(libEntry.info.getName());
20536                        if (libEntry.info.isStatic()) {
20537                            pw.print(" version=" + libEntry.info.getVersion());
20538                        }
20539                        if (!checkin) {
20540                            pw.print(" -> ");
20541                        }
20542                        if (libEntry.path != null) {
20543                            pw.print(" (jar) ");
20544                            pw.print(libEntry.path);
20545                        } else {
20546                            pw.print(" (apk) ");
20547                            pw.print(libEntry.apk);
20548                        }
20549                        pw.println();
20550                    }
20551                }
20552            }
20553
20554            if (dumpState.isDumping(DumpState.DUMP_FEATURES) && packageName == null) {
20555                if (dumpState.onTitlePrinted())
20556                    pw.println();
20557                if (!checkin) {
20558                    pw.println("Features:");
20559                }
20560
20561                synchronized (mAvailableFeatures) {
20562                    for (FeatureInfo feat : mAvailableFeatures.values()) {
20563                        if (checkin) {
20564                            pw.print("feat,");
20565                            pw.print(feat.name);
20566                            pw.print(",");
20567                            pw.println(feat.version);
20568                        } else {
20569                            pw.print("  ");
20570                            pw.print(feat.name);
20571                            if (feat.version > 0) {
20572                                pw.print(" version=");
20573                                pw.print(feat.version);
20574                            }
20575                            pw.println();
20576                        }
20577                    }
20578                }
20579            }
20580
20581            if (!checkin && dumpState.isDumping(DumpState.DUMP_ACTIVITY_RESOLVERS)) {
20582                if (mActivities.dump(pw, dumpState.getTitlePrinted() ? "\nActivity Resolver Table:"
20583                        : "Activity Resolver Table:", "  ", packageName,
20584                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
20585                    dumpState.setTitlePrinted(true);
20586                }
20587            }
20588            if (!checkin && dumpState.isDumping(DumpState.DUMP_RECEIVER_RESOLVERS)) {
20589                if (mReceivers.dump(pw, dumpState.getTitlePrinted() ? "\nReceiver Resolver Table:"
20590                        : "Receiver Resolver Table:", "  ", packageName,
20591                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
20592                    dumpState.setTitlePrinted(true);
20593                }
20594            }
20595            if (!checkin && dumpState.isDumping(DumpState.DUMP_SERVICE_RESOLVERS)) {
20596                if (mServices.dump(pw, dumpState.getTitlePrinted() ? "\nService Resolver Table:"
20597                        : "Service Resolver Table:", "  ", packageName,
20598                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
20599                    dumpState.setTitlePrinted(true);
20600                }
20601            }
20602            if (!checkin && dumpState.isDumping(DumpState.DUMP_CONTENT_RESOLVERS)) {
20603                if (mProviders.dump(pw, dumpState.getTitlePrinted() ? "\nProvider Resolver Table:"
20604                        : "Provider Resolver Table:", "  ", packageName,
20605                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
20606                    dumpState.setTitlePrinted(true);
20607                }
20608            }
20609
20610            if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED)) {
20611                for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
20612                    PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
20613                    int user = mSettings.mPreferredActivities.keyAt(i);
20614                    if (pir.dump(pw,
20615                            dumpState.getTitlePrinted()
20616                                ? "\nPreferred Activities User " + user + ":"
20617                                : "Preferred Activities User " + user + ":", "  ",
20618                            packageName, true, false)) {
20619                        dumpState.setTitlePrinted(true);
20620                    }
20621                }
20622            }
20623
20624            if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED_XML)) {
20625                pw.flush();
20626                FileOutputStream fout = new FileOutputStream(fd);
20627                BufferedOutputStream str = new BufferedOutputStream(fout);
20628                XmlSerializer serializer = new FastXmlSerializer();
20629                try {
20630                    serializer.setOutput(str, StandardCharsets.UTF_8.name());
20631                    serializer.startDocument(null, true);
20632                    serializer.setFeature(
20633                            "http://xmlpull.org/v1/doc/features.html#indent-output", true);
20634                    mSettings.writePreferredActivitiesLPr(serializer, 0, fullPreferred);
20635                    serializer.endDocument();
20636                    serializer.flush();
20637                } catch (IllegalArgumentException e) {
20638                    pw.println("Failed writing: " + e);
20639                } catch (IllegalStateException e) {
20640                    pw.println("Failed writing: " + e);
20641                } catch (IOException e) {
20642                    pw.println("Failed writing: " + e);
20643                }
20644            }
20645
20646            if (!checkin
20647                    && dumpState.isDumping(DumpState.DUMP_DOMAIN_PREFERRED)
20648                    && packageName == null) {
20649                pw.println();
20650                int count = mSettings.mPackages.size();
20651                if (count == 0) {
20652                    pw.println("No applications!");
20653                    pw.println();
20654                } else {
20655                    final String prefix = "  ";
20656                    Collection<PackageSetting> allPackageSettings = mSettings.mPackages.values();
20657                    if (allPackageSettings.size() == 0) {
20658                        pw.println("No domain preferred apps!");
20659                        pw.println();
20660                    } else {
20661                        pw.println("App verification status:");
20662                        pw.println();
20663                        count = 0;
20664                        for (PackageSetting ps : allPackageSettings) {
20665                            IntentFilterVerificationInfo ivi = ps.getIntentFilterVerificationInfo();
20666                            if (ivi == null || ivi.getPackageName() == null) continue;
20667                            pw.println(prefix + "Package: " + ivi.getPackageName());
20668                            pw.println(prefix + "Domains: " + ivi.getDomainsString());
20669                            pw.println(prefix + "Status:  " + ivi.getStatusString());
20670                            pw.println();
20671                            count++;
20672                        }
20673                        if (count == 0) {
20674                            pw.println(prefix + "No app verification established.");
20675                            pw.println();
20676                        }
20677                        for (int userId : sUserManager.getUserIds()) {
20678                            pw.println("App linkages for user " + userId + ":");
20679                            pw.println();
20680                            count = 0;
20681                            for (PackageSetting ps : allPackageSettings) {
20682                                final long status = ps.getDomainVerificationStatusForUser(userId);
20683                                if (status >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED
20684                                        && !DEBUG_DOMAIN_VERIFICATION) {
20685                                    continue;
20686                                }
20687                                pw.println(prefix + "Package: " + ps.name);
20688                                pw.println(prefix + "Domains: " + dumpDomainString(ps.name));
20689                                String statusStr = IntentFilterVerificationInfo.
20690                                        getStatusStringFromValue(status);
20691                                pw.println(prefix + "Status:  " + statusStr);
20692                                pw.println();
20693                                count++;
20694                            }
20695                            if (count == 0) {
20696                                pw.println(prefix + "No configured app linkages.");
20697                                pw.println();
20698                            }
20699                        }
20700                    }
20701                }
20702            }
20703
20704            if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS)) {
20705                mSettings.dumpPermissionsLPr(pw, packageName, permissionNames, dumpState);
20706                if (packageName == null && permissionNames == null) {
20707                    for (int iperm=0; iperm<mAppOpPermissionPackages.size(); iperm++) {
20708                        if (iperm == 0) {
20709                            if (dumpState.onTitlePrinted())
20710                                pw.println();
20711                            pw.println("AppOp Permissions:");
20712                        }
20713                        pw.print("  AppOp Permission ");
20714                        pw.print(mAppOpPermissionPackages.keyAt(iperm));
20715                        pw.println(":");
20716                        ArraySet<String> pkgs = mAppOpPermissionPackages.valueAt(iperm);
20717                        for (int ipkg=0; ipkg<pkgs.size(); ipkg++) {
20718                            pw.print("    "); pw.println(pkgs.valueAt(ipkg));
20719                        }
20720                    }
20721                }
20722            }
20723
20724            if (!checkin && dumpState.isDumping(DumpState.DUMP_PROVIDERS)) {
20725                boolean printedSomething = false;
20726                for (PackageParser.Provider p : mProviders.mProviders.values()) {
20727                    if (packageName != null && !packageName.equals(p.info.packageName)) {
20728                        continue;
20729                    }
20730                    if (!printedSomething) {
20731                        if (dumpState.onTitlePrinted())
20732                            pw.println();
20733                        pw.println("Registered ContentProviders:");
20734                        printedSomething = true;
20735                    }
20736                    pw.print("  "); p.printComponentShortName(pw); pw.println(":");
20737                    pw.print("    "); pw.println(p.toString());
20738                }
20739                printedSomething = false;
20740                for (Map.Entry<String, PackageParser.Provider> entry :
20741                        mProvidersByAuthority.entrySet()) {
20742                    PackageParser.Provider p = entry.getValue();
20743                    if (packageName != null && !packageName.equals(p.info.packageName)) {
20744                        continue;
20745                    }
20746                    if (!printedSomething) {
20747                        if (dumpState.onTitlePrinted())
20748                            pw.println();
20749                        pw.println("ContentProvider Authorities:");
20750                        printedSomething = true;
20751                    }
20752                    pw.print("  ["); pw.print(entry.getKey()); pw.println("]:");
20753                    pw.print("    "); pw.println(p.toString());
20754                    if (p.info != null && p.info.applicationInfo != null) {
20755                        final String appInfo = p.info.applicationInfo.toString();
20756                        pw.print("      applicationInfo="); pw.println(appInfo);
20757                    }
20758                }
20759            }
20760
20761            if (!checkin && dumpState.isDumping(DumpState.DUMP_KEYSETS)) {
20762                mSettings.mKeySetManagerService.dumpLPr(pw, packageName, dumpState);
20763            }
20764
20765            if (dumpState.isDumping(DumpState.DUMP_PACKAGES)) {
20766                mSettings.dumpPackagesLPr(pw, packageName, permissionNames, dumpState, checkin);
20767            }
20768
20769            if (dumpState.isDumping(DumpState.DUMP_SHARED_USERS)) {
20770                mSettings.dumpSharedUsersLPr(pw, packageName, permissionNames, dumpState, checkin);
20771            }
20772
20773            if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS) && packageName == null) {
20774                mSettings.dumpRestoredPermissionGrantsLPr(pw, dumpState);
20775            }
20776
20777            if (!checkin && dumpState.isDumping(DumpState.DUMP_INSTALLS) && packageName == null) {
20778                // XXX should handle packageName != null by dumping only install data that
20779                // the given package is involved with.
20780                if (dumpState.onTitlePrinted()) pw.println();
20781                mInstallerService.dump(new IndentingPrintWriter(pw, "  ", 120));
20782            }
20783
20784            if (!checkin && dumpState.isDumping(DumpState.DUMP_FROZEN) && packageName == null) {
20785                // XXX should handle packageName != null by dumping only install data that
20786                // the given package is involved with.
20787                if (dumpState.onTitlePrinted()) pw.println();
20788
20789                final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, "  ", 120);
20790                ipw.println();
20791                ipw.println("Frozen packages:");
20792                ipw.increaseIndent();
20793                if (mFrozenPackages.size() == 0) {
20794                    ipw.println("(none)");
20795                } else {
20796                    for (int i = 0; i < mFrozenPackages.size(); i++) {
20797                        ipw.println(mFrozenPackages.valueAt(i));
20798                    }
20799                }
20800                ipw.decreaseIndent();
20801            }
20802
20803            if (!checkin && dumpState.isDumping(DumpState.DUMP_DEXOPT)) {
20804                if (dumpState.onTitlePrinted()) pw.println();
20805                dumpDexoptStateLPr(pw, packageName);
20806            }
20807
20808            if (!checkin && dumpState.isDumping(DumpState.DUMP_COMPILER_STATS)) {
20809                if (dumpState.onTitlePrinted()) pw.println();
20810                dumpCompilerStatsLPr(pw, packageName);
20811            }
20812
20813            if (!checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES) && packageName == null) {
20814                if (dumpState.onTitlePrinted()) pw.println();
20815                mSettings.dumpReadMessagesLPr(pw, dumpState);
20816
20817                pw.println();
20818                pw.println("Package warning messages:");
20819                BufferedReader in = null;
20820                String line = null;
20821                try {
20822                    in = new BufferedReader(new FileReader(getSettingsProblemFile()));
20823                    while ((line = in.readLine()) != null) {
20824                        if (line.contains("ignored: updated version")) continue;
20825                        pw.println(line);
20826                    }
20827                } catch (IOException ignored) {
20828                } finally {
20829                    IoUtils.closeQuietly(in);
20830                }
20831            }
20832
20833            if (checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES)) {
20834                BufferedReader in = null;
20835                String line = null;
20836                try {
20837                    in = new BufferedReader(new FileReader(getSettingsProblemFile()));
20838                    while ((line = in.readLine()) != null) {
20839                        if (line.contains("ignored: updated version")) continue;
20840                        pw.print("msg,");
20841                        pw.println(line);
20842                    }
20843                } catch (IOException ignored) {
20844                } finally {
20845                    IoUtils.closeQuietly(in);
20846                }
20847            }
20848        }
20849    }
20850
20851    private void dumpDexoptStateLPr(PrintWriter pw, String packageName) {
20852        final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, "  ", 120);
20853        ipw.println();
20854        ipw.println("Dexopt state:");
20855        ipw.increaseIndent();
20856        Collection<PackageParser.Package> packages = null;
20857        if (packageName != null) {
20858            PackageParser.Package targetPackage = mPackages.get(packageName);
20859            if (targetPackage != null) {
20860                packages = Collections.singletonList(targetPackage);
20861            } else {
20862                ipw.println("Unable to find package: " + packageName);
20863                return;
20864            }
20865        } else {
20866            packages = mPackages.values();
20867        }
20868
20869        for (PackageParser.Package pkg : packages) {
20870            ipw.println("[" + pkg.packageName + "]");
20871            ipw.increaseIndent();
20872            mPackageDexOptimizer.dumpDexoptState(ipw, pkg);
20873            ipw.decreaseIndent();
20874        }
20875    }
20876
20877    private void dumpCompilerStatsLPr(PrintWriter pw, String packageName) {
20878        final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, "  ", 120);
20879        ipw.println();
20880        ipw.println("Compiler stats:");
20881        ipw.increaseIndent();
20882        Collection<PackageParser.Package> packages = null;
20883        if (packageName != null) {
20884            PackageParser.Package targetPackage = mPackages.get(packageName);
20885            if (targetPackage != null) {
20886                packages = Collections.singletonList(targetPackage);
20887            } else {
20888                ipw.println("Unable to find package: " + packageName);
20889                return;
20890            }
20891        } else {
20892            packages = mPackages.values();
20893        }
20894
20895        for (PackageParser.Package pkg : packages) {
20896            ipw.println("[" + pkg.packageName + "]");
20897            ipw.increaseIndent();
20898
20899            CompilerStats.PackageStats stats = getCompilerPackageStats(pkg.packageName);
20900            if (stats == null) {
20901                ipw.println("(No recorded stats)");
20902            } else {
20903                stats.dump(ipw);
20904            }
20905            ipw.decreaseIndent();
20906        }
20907    }
20908
20909    private String dumpDomainString(String packageName) {
20910        List<IntentFilterVerificationInfo> iviList = getIntentFilterVerifications(packageName)
20911                .getList();
20912        List<IntentFilter> filters = getAllIntentFilters(packageName).getList();
20913
20914        ArraySet<String> result = new ArraySet<>();
20915        if (iviList.size() > 0) {
20916            for (IntentFilterVerificationInfo ivi : iviList) {
20917                for (String host : ivi.getDomains()) {
20918                    result.add(host);
20919                }
20920            }
20921        }
20922        if (filters != null && filters.size() > 0) {
20923            for (IntentFilter filter : filters) {
20924                if (filter.hasCategory(Intent.CATEGORY_BROWSABLE)
20925                        && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) ||
20926                                filter.hasDataScheme(IntentFilter.SCHEME_HTTPS))) {
20927                    result.addAll(filter.getHostsList());
20928                }
20929            }
20930        }
20931
20932        StringBuilder sb = new StringBuilder(result.size() * 16);
20933        for (String domain : result) {
20934            if (sb.length() > 0) sb.append(" ");
20935            sb.append(domain);
20936        }
20937        return sb.toString();
20938    }
20939
20940    // ------- apps on sdcard specific code -------
20941    static final boolean DEBUG_SD_INSTALL = false;
20942
20943    private static final String SD_ENCRYPTION_KEYSTORE_NAME = "AppsOnSD";
20944
20945    private static final String SD_ENCRYPTION_ALGORITHM = "AES";
20946
20947    private boolean mMediaMounted = false;
20948
20949    static String getEncryptKey() {
20950        try {
20951            String sdEncKey = SystemKeyStore.getInstance().retrieveKeyHexString(
20952                    SD_ENCRYPTION_KEYSTORE_NAME);
20953            if (sdEncKey == null) {
20954                sdEncKey = SystemKeyStore.getInstance().generateNewKeyHexString(128,
20955                        SD_ENCRYPTION_ALGORITHM, SD_ENCRYPTION_KEYSTORE_NAME);
20956                if (sdEncKey == null) {
20957                    Slog.e(TAG, "Failed to create encryption keys");
20958                    return null;
20959                }
20960            }
20961            return sdEncKey;
20962        } catch (NoSuchAlgorithmException nsae) {
20963            Slog.e(TAG, "Failed to create encryption keys with exception: " + nsae);
20964            return null;
20965        } catch (IOException ioe) {
20966            Slog.e(TAG, "Failed to retrieve encryption keys with exception: " + ioe);
20967            return null;
20968        }
20969    }
20970
20971    /*
20972     * Update media status on PackageManager.
20973     */
20974    @Override
20975    public void updateExternalMediaStatus(final boolean mediaStatus, final boolean reportStatus) {
20976        int callingUid = Binder.getCallingUid();
20977        if (callingUid != 0 && callingUid != Process.SYSTEM_UID) {
20978            throw new SecurityException("Media status can only be updated by the system");
20979        }
20980        // reader; this apparently protects mMediaMounted, but should probably
20981        // be a different lock in that case.
20982        synchronized (mPackages) {
20983            Log.i(TAG, "Updating external media status from "
20984                    + (mMediaMounted ? "mounted" : "unmounted") + " to "
20985                    + (mediaStatus ? "mounted" : "unmounted"));
20986            if (DEBUG_SD_INSTALL)
20987                Log.i(TAG, "updateExternalMediaStatus:: mediaStatus=" + mediaStatus
20988                        + ", mMediaMounted=" + mMediaMounted);
20989            if (mediaStatus == mMediaMounted) {
20990                final Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1
20991                        : 0, -1);
20992                mHandler.sendMessage(msg);
20993                return;
20994            }
20995            mMediaMounted = mediaStatus;
20996        }
20997        // Queue up an async operation since the package installation may take a
20998        // little while.
20999        mHandler.post(new Runnable() {
21000            public void run() {
21001                updateExternalMediaStatusInner(mediaStatus, reportStatus, true);
21002            }
21003        });
21004    }
21005
21006    /**
21007     * Called by StorageManagerService when the initial ASECs to scan are available.
21008     * Should block until all the ASEC containers are finished being scanned.
21009     */
21010    public void scanAvailableAsecs() {
21011        updateExternalMediaStatusInner(true, false, false);
21012    }
21013
21014    /*
21015     * Collect information of applications on external media, map them against
21016     * existing containers and update information based on current mount status.
21017     * Please note that we always have to report status if reportStatus has been
21018     * set to true especially when unloading packages.
21019     */
21020    private void updateExternalMediaStatusInner(boolean isMounted, boolean reportStatus,
21021            boolean externalStorage) {
21022        ArrayMap<AsecInstallArgs, String> processCids = new ArrayMap<>();
21023        int[] uidArr = EmptyArray.INT;
21024
21025        final String[] list = PackageHelper.getSecureContainerList();
21026        if (ArrayUtils.isEmpty(list)) {
21027            Log.i(TAG, "No secure containers found");
21028        } else {
21029            // Process list of secure containers and categorize them
21030            // as active or stale based on their package internal state.
21031
21032            // reader
21033            synchronized (mPackages) {
21034                for (String cid : list) {
21035                    // Leave stages untouched for now; installer service owns them
21036                    if (PackageInstallerService.isStageName(cid)) continue;
21037
21038                    if (DEBUG_SD_INSTALL)
21039                        Log.i(TAG, "Processing container " + cid);
21040                    String pkgName = getAsecPackageName(cid);
21041                    if (pkgName == null) {
21042                        Slog.i(TAG, "Found stale container " + cid + " with no package name");
21043                        continue;
21044                    }
21045                    if (DEBUG_SD_INSTALL)
21046                        Log.i(TAG, "Looking for pkg : " + pkgName);
21047
21048                    final PackageSetting ps = mSettings.mPackages.get(pkgName);
21049                    if (ps == null) {
21050                        Slog.i(TAG, "Found stale container " + cid + " with no matching settings");
21051                        continue;
21052                    }
21053
21054                    /*
21055                     * Skip packages that are not external if we're unmounting
21056                     * external storage.
21057                     */
21058                    if (externalStorage && !isMounted && !isExternal(ps)) {
21059                        continue;
21060                    }
21061
21062                    final AsecInstallArgs args = new AsecInstallArgs(cid,
21063                            getAppDexInstructionSets(ps), ps.isForwardLocked());
21064                    // The package status is changed only if the code path
21065                    // matches between settings and the container id.
21066                    if (ps.codePathString != null
21067                            && ps.codePathString.startsWith(args.getCodePath())) {
21068                        if (DEBUG_SD_INSTALL) {
21069                            Log.i(TAG, "Container : " + cid + " corresponds to pkg : " + pkgName
21070                                    + " at code path: " + ps.codePathString);
21071                        }
21072
21073                        // We do have a valid package installed on sdcard
21074                        processCids.put(args, ps.codePathString);
21075                        final int uid = ps.appId;
21076                        if (uid != -1) {
21077                            uidArr = ArrayUtils.appendInt(uidArr, uid);
21078                        }
21079                    } else {
21080                        Slog.i(TAG, "Found stale container " + cid + ": expected codePath="
21081                                + ps.codePathString);
21082                    }
21083                }
21084            }
21085
21086            Arrays.sort(uidArr);
21087        }
21088
21089        // Process packages with valid entries.
21090        if (isMounted) {
21091            if (DEBUG_SD_INSTALL)
21092                Log.i(TAG, "Loading packages");
21093            loadMediaPackages(processCids, uidArr, externalStorage);
21094            startCleaningPackages();
21095            mInstallerService.onSecureContainersAvailable();
21096        } else {
21097            if (DEBUG_SD_INSTALL)
21098                Log.i(TAG, "Unloading packages");
21099            unloadMediaPackages(processCids, uidArr, reportStatus);
21100        }
21101    }
21102
21103    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
21104            ArrayList<ApplicationInfo> infos, IIntentReceiver finishedReceiver) {
21105        final int size = infos.size();
21106        final String[] packageNames = new String[size];
21107        final int[] packageUids = new int[size];
21108        for (int i = 0; i < size; i++) {
21109            final ApplicationInfo info = infos.get(i);
21110            packageNames[i] = info.packageName;
21111            packageUids[i] = info.uid;
21112        }
21113        sendResourcesChangedBroadcast(mediaStatus, replacing, packageNames, packageUids,
21114                finishedReceiver);
21115    }
21116
21117    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
21118            ArrayList<String> pkgList, int uidArr[], IIntentReceiver finishedReceiver) {
21119        sendResourcesChangedBroadcast(mediaStatus, replacing,
21120                pkgList.toArray(new String[pkgList.size()]), uidArr, finishedReceiver);
21121    }
21122
21123    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
21124            String[] pkgList, int uidArr[], IIntentReceiver finishedReceiver) {
21125        int size = pkgList.length;
21126        if (size > 0) {
21127            // Send broadcasts here
21128            Bundle extras = new Bundle();
21129            extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList);
21130            if (uidArr != null) {
21131                extras.putIntArray(Intent.EXTRA_CHANGED_UID_LIST, uidArr);
21132            }
21133            if (replacing) {
21134                extras.putBoolean(Intent.EXTRA_REPLACING, replacing);
21135            }
21136            String action = mediaStatus ? Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE
21137                    : Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE;
21138            sendPackageBroadcast(action, null, extras, 0, null, finishedReceiver, null);
21139        }
21140    }
21141
21142   /*
21143     * Look at potentially valid container ids from processCids If package
21144     * information doesn't match the one on record or package scanning fails,
21145     * the cid is added to list of removeCids. We currently don't delete stale
21146     * containers.
21147     */
21148    private void loadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int[] uidArr,
21149            boolean externalStorage) {
21150        ArrayList<String> pkgList = new ArrayList<String>();
21151        Set<AsecInstallArgs> keys = processCids.keySet();
21152
21153        for (AsecInstallArgs args : keys) {
21154            String codePath = processCids.get(args);
21155            if (DEBUG_SD_INSTALL)
21156                Log.i(TAG, "Loading container : " + args.cid);
21157            int retCode = PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
21158            try {
21159                // Make sure there are no container errors first.
21160                if (args.doPreInstall(PackageManager.INSTALL_SUCCEEDED) != PackageManager.INSTALL_SUCCEEDED) {
21161                    Slog.e(TAG, "Failed to mount cid : " + args.cid
21162                            + " when installing from sdcard");
21163                    continue;
21164                }
21165                // Check code path here.
21166                if (codePath == null || !codePath.startsWith(args.getCodePath())) {
21167                    Slog.e(TAG, "Container " + args.cid + " cachepath " + args.getCodePath()
21168                            + " does not match one in settings " + codePath);
21169                    continue;
21170                }
21171                // Parse package
21172                int parseFlags = mDefParseFlags;
21173                if (args.isExternalAsec()) {
21174                    parseFlags |= PackageParser.PARSE_EXTERNAL_STORAGE;
21175                }
21176                if (args.isFwdLocked()) {
21177                    parseFlags |= PackageParser.PARSE_FORWARD_LOCK;
21178                }
21179
21180                synchronized (mInstallLock) {
21181                    PackageParser.Package pkg = null;
21182                    try {
21183                        // Sadly we don't know the package name yet to freeze it
21184                        pkg = scanPackageTracedLI(new File(codePath), parseFlags,
21185                                SCAN_IGNORE_FROZEN, 0, null);
21186                    } catch (PackageManagerException e) {
21187                        Slog.w(TAG, "Failed to scan " + codePath + ": " + e.getMessage());
21188                    }
21189                    // Scan the package
21190                    if (pkg != null) {
21191                        /*
21192                         * TODO why is the lock being held? doPostInstall is
21193                         * called in other places without the lock. This needs
21194                         * to be straightened out.
21195                         */
21196                        // writer
21197                        synchronized (mPackages) {
21198                            retCode = PackageManager.INSTALL_SUCCEEDED;
21199                            pkgList.add(pkg.packageName);
21200                            // Post process args
21201                            args.doPostInstall(PackageManager.INSTALL_SUCCEEDED,
21202                                    pkg.applicationInfo.uid);
21203                        }
21204                    } else {
21205                        Slog.i(TAG, "Failed to install pkg from  " + codePath + " from sdcard");
21206                    }
21207                }
21208
21209            } finally {
21210                if (retCode != PackageManager.INSTALL_SUCCEEDED) {
21211                    Log.w(TAG, "Container " + args.cid + " is stale, retCode=" + retCode);
21212                }
21213            }
21214        }
21215        // writer
21216        synchronized (mPackages) {
21217            // If the platform SDK has changed since the last time we booted,
21218            // we need to re-grant app permission to catch any new ones that
21219            // appear. This is really a hack, and means that apps can in some
21220            // cases get permissions that the user didn't initially explicitly
21221            // allow... it would be nice to have some better way to handle
21222            // this situation.
21223            final VersionInfo ver = externalStorage ? mSettings.getExternalVersion()
21224                    : mSettings.getInternalVersion();
21225            final String volumeUuid = externalStorage ? StorageManager.UUID_PRIMARY_PHYSICAL
21226                    : StorageManager.UUID_PRIVATE_INTERNAL;
21227
21228            int updateFlags = UPDATE_PERMISSIONS_ALL;
21229            if (ver.sdkVersion != mSdkVersion) {
21230                logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to "
21231                        + mSdkVersion + "; regranting permissions for external");
21232                updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL;
21233            }
21234            updatePermissionsLPw(null, null, volumeUuid, updateFlags);
21235
21236            // Yay, everything is now upgraded
21237            ver.forceCurrent();
21238
21239            // can downgrade to reader
21240            // Persist settings
21241            mSettings.writeLPr();
21242        }
21243        // Send a broadcast to let everyone know we are done processing
21244        if (pkgList.size() > 0) {
21245            sendResourcesChangedBroadcast(true, false, pkgList, uidArr, null);
21246        }
21247    }
21248
21249   /*
21250     * Utility method to unload a list of specified containers
21251     */
21252    private void unloadAllContainers(Set<AsecInstallArgs> cidArgs) {
21253        // Just unmount all valid containers.
21254        for (AsecInstallArgs arg : cidArgs) {
21255            synchronized (mInstallLock) {
21256                arg.doPostDeleteLI(false);
21257           }
21258       }
21259   }
21260
21261    /*
21262     * Unload packages mounted on external media. This involves deleting package
21263     * data from internal structures, sending broadcasts about disabled packages,
21264     * gc'ing to free up references, unmounting all secure containers
21265     * corresponding to packages on external media, and posting a
21266     * UPDATED_MEDIA_STATUS message if status has been requested. Please note
21267     * that we always have to post this message if status has been requested no
21268     * matter what.
21269     */
21270    private void unloadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int uidArr[],
21271            final boolean reportStatus) {
21272        if (DEBUG_SD_INSTALL)
21273            Log.i(TAG, "unloading media packages");
21274        ArrayList<String> pkgList = new ArrayList<String>();
21275        ArrayList<AsecInstallArgs> failedList = new ArrayList<AsecInstallArgs>();
21276        final Set<AsecInstallArgs> keys = processCids.keySet();
21277        for (AsecInstallArgs args : keys) {
21278            String pkgName = args.getPackageName();
21279            if (DEBUG_SD_INSTALL)
21280                Log.i(TAG, "Trying to unload pkg : " + pkgName);
21281            // Delete package internally
21282            PackageRemovedInfo outInfo = new PackageRemovedInfo();
21283            synchronized (mInstallLock) {
21284                final int deleteFlags = PackageManager.DELETE_KEEP_DATA;
21285                final boolean res;
21286                try (PackageFreezer freezer = freezePackageForDelete(pkgName, deleteFlags,
21287                        "unloadMediaPackages")) {
21288                    res = deletePackageLIF(pkgName, null, false, null, deleteFlags, outInfo, false,
21289                            null);
21290                }
21291                if (res) {
21292                    pkgList.add(pkgName);
21293                } else {
21294                    Slog.e(TAG, "Failed to delete pkg from sdcard : " + pkgName);
21295                    failedList.add(args);
21296                }
21297            }
21298        }
21299
21300        // reader
21301        synchronized (mPackages) {
21302            // We didn't update the settings after removing each package;
21303            // write them now for all packages.
21304            mSettings.writeLPr();
21305        }
21306
21307        // We have to absolutely send UPDATED_MEDIA_STATUS only
21308        // after confirming that all the receivers processed the ordered
21309        // broadcast when packages get disabled, force a gc to clean things up.
21310        // and unload all the containers.
21311        if (pkgList.size() > 0) {
21312            sendResourcesChangedBroadcast(false, false, pkgList, uidArr,
21313                    new IIntentReceiver.Stub() {
21314                public void performReceive(Intent intent, int resultCode, String data,
21315                        Bundle extras, boolean ordered, boolean sticky,
21316                        int sendingUser) throws RemoteException {
21317                    Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS,
21318                            reportStatus ? 1 : 0, 1, keys);
21319                    mHandler.sendMessage(msg);
21320                }
21321            });
21322        } else {
21323            Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 : 0, -1,
21324                    keys);
21325            mHandler.sendMessage(msg);
21326        }
21327    }
21328
21329    private void loadPrivatePackages(final VolumeInfo vol) {
21330        mHandler.post(new Runnable() {
21331            @Override
21332            public void run() {
21333                loadPrivatePackagesInner(vol);
21334            }
21335        });
21336    }
21337
21338    private void loadPrivatePackagesInner(VolumeInfo vol) {
21339        final String volumeUuid = vol.fsUuid;
21340        if (TextUtils.isEmpty(volumeUuid)) {
21341            Slog.e(TAG, "Loading internal storage is probably a mistake; ignoring");
21342            return;
21343        }
21344
21345        final ArrayList<PackageFreezer> freezers = new ArrayList<>();
21346        final ArrayList<ApplicationInfo> loaded = new ArrayList<>();
21347        final int parseFlags = mDefParseFlags | PackageParser.PARSE_EXTERNAL_STORAGE;
21348
21349        final VersionInfo ver;
21350        final List<PackageSetting> packages;
21351        synchronized (mPackages) {
21352            ver = mSettings.findOrCreateVersion(volumeUuid);
21353            packages = mSettings.getVolumePackagesLPr(volumeUuid);
21354        }
21355
21356        for (PackageSetting ps : packages) {
21357            freezers.add(freezePackage(ps.name, "loadPrivatePackagesInner"));
21358            synchronized (mInstallLock) {
21359                final PackageParser.Package pkg;
21360                try {
21361                    pkg = scanPackageTracedLI(ps.codePath, parseFlags, SCAN_INITIAL, 0, null);
21362                    loaded.add(pkg.applicationInfo);
21363
21364                } catch (PackageManagerException e) {
21365                    Slog.w(TAG, "Failed to scan " + ps.codePath + ": " + e.getMessage());
21366                }
21367
21368                if (!Build.FINGERPRINT.equals(ver.fingerprint)) {
21369                    clearAppDataLIF(ps.pkg, UserHandle.USER_ALL,
21370                            StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE
21371                                    | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
21372                }
21373            }
21374        }
21375
21376        // Reconcile app data for all started/unlocked users
21377        final StorageManager sm = mContext.getSystemService(StorageManager.class);
21378        final UserManager um = mContext.getSystemService(UserManager.class);
21379        UserManagerInternal umInternal = getUserManagerInternal();
21380        for (UserInfo user : um.getUsers()) {
21381            final int flags;
21382            if (umInternal.isUserUnlockingOrUnlocked(user.id)) {
21383                flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
21384            } else if (umInternal.isUserRunning(user.id)) {
21385                flags = StorageManager.FLAG_STORAGE_DE;
21386            } else {
21387                continue;
21388            }
21389
21390            try {
21391                sm.prepareUserStorage(volumeUuid, user.id, user.serialNumber, flags);
21392                synchronized (mInstallLock) {
21393                    reconcileAppsDataLI(volumeUuid, user.id, flags, true /* migrateAppData */);
21394                }
21395            } catch (IllegalStateException e) {
21396                // Device was probably ejected, and we'll process that event momentarily
21397                Slog.w(TAG, "Failed to prepare storage: " + e);
21398            }
21399        }
21400
21401        synchronized (mPackages) {
21402            int updateFlags = UPDATE_PERMISSIONS_ALL;
21403            if (ver.sdkVersion != mSdkVersion) {
21404                logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to "
21405                        + mSdkVersion + "; regranting permissions for " + volumeUuid);
21406                updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL;
21407            }
21408            updatePermissionsLPw(null, null, volumeUuid, updateFlags);
21409
21410            // Yay, everything is now upgraded
21411            ver.forceCurrent();
21412
21413            mSettings.writeLPr();
21414        }
21415
21416        for (PackageFreezer freezer : freezers) {
21417            freezer.close();
21418        }
21419
21420        if (DEBUG_INSTALL) Slog.d(TAG, "Loaded packages " + loaded);
21421        sendResourcesChangedBroadcast(true, false, loaded, null);
21422    }
21423
21424    private void unloadPrivatePackages(final VolumeInfo vol) {
21425        mHandler.post(new Runnable() {
21426            @Override
21427            public void run() {
21428                unloadPrivatePackagesInner(vol);
21429            }
21430        });
21431    }
21432
21433    private void unloadPrivatePackagesInner(VolumeInfo vol) {
21434        final String volumeUuid = vol.fsUuid;
21435        if (TextUtils.isEmpty(volumeUuid)) {
21436            Slog.e(TAG, "Unloading internal storage is probably a mistake; ignoring");
21437            return;
21438        }
21439
21440        final ArrayList<ApplicationInfo> unloaded = new ArrayList<>();
21441        synchronized (mInstallLock) {
21442        synchronized (mPackages) {
21443            final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(volumeUuid);
21444            for (PackageSetting ps : packages) {
21445                if (ps.pkg == null) continue;
21446
21447                final ApplicationInfo info = ps.pkg.applicationInfo;
21448                final int deleteFlags = PackageManager.DELETE_KEEP_DATA;
21449                final PackageRemovedInfo outInfo = new PackageRemovedInfo();
21450
21451                try (PackageFreezer freezer = freezePackageForDelete(ps.name, deleteFlags,
21452                        "unloadPrivatePackagesInner")) {
21453                    if (deletePackageLIF(ps.name, null, false, null, deleteFlags, outInfo,
21454                            false, null)) {
21455                        unloaded.add(info);
21456                    } else {
21457                        Slog.w(TAG, "Failed to unload " + ps.codePath);
21458                    }
21459                }
21460
21461                // Try very hard to release any references to this package
21462                // so we don't risk the system server being killed due to
21463                // open FDs
21464                AttributeCache.instance().removePackage(ps.name);
21465            }
21466
21467            mSettings.writeLPr();
21468        }
21469        }
21470
21471        if (DEBUG_INSTALL) Slog.d(TAG, "Unloaded packages " + unloaded);
21472        sendResourcesChangedBroadcast(false, false, unloaded, null);
21473
21474        // Try very hard to release any references to this path so we don't risk
21475        // the system server being killed due to open FDs
21476        ResourcesManager.getInstance().invalidatePath(vol.getPath().getAbsolutePath());
21477
21478        for (int i = 0; i < 3; i++) {
21479            System.gc();
21480            System.runFinalization();
21481        }
21482    }
21483
21484    private void assertPackageKnown(String volumeUuid, String packageName)
21485            throws PackageManagerException {
21486        synchronized (mPackages) {
21487            // Normalize package name to handle renamed packages
21488            packageName = normalizePackageNameLPr(packageName);
21489
21490            final PackageSetting ps = mSettings.mPackages.get(packageName);
21491            if (ps == null) {
21492                throw new PackageManagerException("Package " + packageName + " is unknown");
21493            } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) {
21494                throw new PackageManagerException(
21495                        "Package " + packageName + " found on unknown volume " + volumeUuid
21496                                + "; expected volume " + ps.volumeUuid);
21497            }
21498        }
21499    }
21500
21501    private void assertPackageKnownAndInstalled(String volumeUuid, String packageName, int userId)
21502            throws PackageManagerException {
21503        synchronized (mPackages) {
21504            // Normalize package name to handle renamed packages
21505            packageName = normalizePackageNameLPr(packageName);
21506
21507            final PackageSetting ps = mSettings.mPackages.get(packageName);
21508            if (ps == null) {
21509                throw new PackageManagerException("Package " + packageName + " is unknown");
21510            } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) {
21511                throw new PackageManagerException(
21512                        "Package " + packageName + " found on unknown volume " + volumeUuid
21513                                + "; expected volume " + ps.volumeUuid);
21514            } else if (!ps.getInstalled(userId)) {
21515                throw new PackageManagerException(
21516                        "Package " + packageName + " not installed for user " + userId);
21517            }
21518        }
21519    }
21520
21521    private List<String> collectAbsoluteCodePaths() {
21522        synchronized (mPackages) {
21523            List<String> codePaths = new ArrayList<>();
21524            final int packageCount = mSettings.mPackages.size();
21525            for (int i = 0; i < packageCount; i++) {
21526                final PackageSetting ps = mSettings.mPackages.valueAt(i);
21527                codePaths.add(ps.codePath.getAbsolutePath());
21528            }
21529            return codePaths;
21530        }
21531    }
21532
21533    /**
21534     * Examine all apps present on given mounted volume, and destroy apps that
21535     * aren't expected, either due to uninstallation or reinstallation on
21536     * another volume.
21537     */
21538    private void reconcileApps(String volumeUuid) {
21539        List<String> absoluteCodePaths = collectAbsoluteCodePaths();
21540        List<File> filesToDelete = null;
21541
21542        final File[] files = FileUtils.listFilesOrEmpty(
21543                Environment.getDataAppDirectory(volumeUuid));
21544        for (File file : files) {
21545            final boolean isPackage = (isApkFile(file) || file.isDirectory())
21546                    && !PackageInstallerService.isStageName(file.getName());
21547            if (!isPackage) {
21548                // Ignore entries which are not packages
21549                continue;
21550            }
21551
21552            String absolutePath = file.getAbsolutePath();
21553
21554            boolean pathValid = false;
21555            final int absoluteCodePathCount = absoluteCodePaths.size();
21556            for (int i = 0; i < absoluteCodePathCount; i++) {
21557                String absoluteCodePath = absoluteCodePaths.get(i);
21558                if (absolutePath.startsWith(absoluteCodePath)) {
21559                    pathValid = true;
21560                    break;
21561                }
21562            }
21563
21564            if (!pathValid) {
21565                if (filesToDelete == null) {
21566                    filesToDelete = new ArrayList<>();
21567                }
21568                filesToDelete.add(file);
21569            }
21570        }
21571
21572        if (filesToDelete != null) {
21573            final int fileToDeleteCount = filesToDelete.size();
21574            for (int i = 0; i < fileToDeleteCount; i++) {
21575                File fileToDelete = filesToDelete.get(i);
21576                logCriticalInfo(Log.WARN, "Destroying orphaned" + fileToDelete);
21577                synchronized (mInstallLock) {
21578                    removeCodePathLI(fileToDelete);
21579                }
21580            }
21581        }
21582    }
21583
21584    /**
21585     * Reconcile all app data for the given user.
21586     * <p>
21587     * Verifies that directories exist and that ownership and labeling is
21588     * correct for all installed apps on all mounted volumes.
21589     */
21590    void reconcileAppsData(int userId, int flags, boolean migrateAppsData) {
21591        final StorageManager storage = mContext.getSystemService(StorageManager.class);
21592        for (VolumeInfo vol : storage.getWritablePrivateVolumes()) {
21593            final String volumeUuid = vol.getFsUuid();
21594            synchronized (mInstallLock) {
21595                reconcileAppsDataLI(volumeUuid, userId, flags, migrateAppsData);
21596            }
21597        }
21598    }
21599
21600    private void reconcileAppsDataLI(String volumeUuid, int userId, int flags,
21601            boolean migrateAppData) {
21602        reconcileAppsDataLI(volumeUuid, userId, flags, migrateAppData, false /* onlyCoreApps */);
21603    }
21604
21605    /**
21606     * Reconcile all app data on given mounted volume.
21607     * <p>
21608     * Destroys app data that isn't expected, either due to uninstallation or
21609     * reinstallation on another volume.
21610     * <p>
21611     * Verifies that directories exist and that ownership and labeling is
21612     * correct for all installed apps.
21613     * @returns list of skipped non-core packages (if {@code onlyCoreApps} is true)
21614     */
21615    private List<String> reconcileAppsDataLI(String volumeUuid, int userId, int flags,
21616            boolean migrateAppData, boolean onlyCoreApps) {
21617        Slog.v(TAG, "reconcileAppsData for " + volumeUuid + " u" + userId + " 0x"
21618                + Integer.toHexString(flags) + " migrateAppData=" + migrateAppData);
21619        List<String> result = onlyCoreApps ? new ArrayList<>() : null;
21620
21621        final File ceDir = Environment.getDataUserCeDirectory(volumeUuid, userId);
21622        final File deDir = Environment.getDataUserDeDirectory(volumeUuid, userId);
21623
21624        // First look for stale data that doesn't belong, and check if things
21625        // have changed since we did our last restorecon
21626        if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) {
21627            if (StorageManager.isFileEncryptedNativeOrEmulated()
21628                    && !StorageManager.isUserKeyUnlocked(userId)) {
21629                throw new RuntimeException(
21630                        "Yikes, someone asked us to reconcile CE storage while " + userId
21631                                + " was still locked; this would have caused massive data loss!");
21632            }
21633
21634            final File[] files = FileUtils.listFilesOrEmpty(ceDir);
21635            for (File file : files) {
21636                final String packageName = file.getName();
21637                try {
21638                    assertPackageKnownAndInstalled(volumeUuid, packageName, userId);
21639                } catch (PackageManagerException e) {
21640                    logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e);
21641                    try {
21642                        mInstaller.destroyAppData(volumeUuid, packageName, userId,
21643                                StorageManager.FLAG_STORAGE_CE, 0);
21644                    } catch (InstallerException e2) {
21645                        logCriticalInfo(Log.WARN, "Failed to destroy: " + e2);
21646                    }
21647                }
21648            }
21649        }
21650        if ((flags & StorageManager.FLAG_STORAGE_DE) != 0) {
21651            final File[] files = FileUtils.listFilesOrEmpty(deDir);
21652            for (File file : files) {
21653                final String packageName = file.getName();
21654                try {
21655                    assertPackageKnownAndInstalled(volumeUuid, packageName, userId);
21656                } catch (PackageManagerException e) {
21657                    logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e);
21658                    try {
21659                        mInstaller.destroyAppData(volumeUuid, packageName, userId,
21660                                StorageManager.FLAG_STORAGE_DE, 0);
21661                    } catch (InstallerException e2) {
21662                        logCriticalInfo(Log.WARN, "Failed to destroy: " + e2);
21663                    }
21664                }
21665            }
21666        }
21667
21668        // Ensure that data directories are ready to roll for all packages
21669        // installed for this volume and user
21670        final List<PackageSetting> packages;
21671        synchronized (mPackages) {
21672            packages = mSettings.getVolumePackagesLPr(volumeUuid);
21673        }
21674        int preparedCount = 0;
21675        for (PackageSetting ps : packages) {
21676            final String packageName = ps.name;
21677            if (ps.pkg == null) {
21678                Slog.w(TAG, "Odd, missing scanned package " + packageName);
21679                // TODO: might be due to legacy ASEC apps; we should circle back
21680                // and reconcile again once they're scanned
21681                continue;
21682            }
21683            // Skip non-core apps if requested
21684            if (onlyCoreApps && !ps.pkg.coreApp) {
21685                result.add(packageName);
21686                continue;
21687            }
21688
21689            if (ps.getInstalled(userId)) {
21690                prepareAppDataAndMigrateLIF(ps.pkg, userId, flags, migrateAppData);
21691                preparedCount++;
21692            }
21693        }
21694
21695        Slog.v(TAG, "reconcileAppsData finished " + preparedCount + " packages");
21696        return result;
21697    }
21698
21699    /**
21700     * Prepare app data for the given app just after it was installed or
21701     * upgraded. This method carefully only touches users that it's installed
21702     * for, and it forces a restorecon to handle any seinfo changes.
21703     * <p>
21704     * Verifies that directories exist and that ownership and labeling is
21705     * correct for all installed apps. If there is an ownership mismatch, it
21706     * will try recovering system apps by wiping data; third-party app data is
21707     * left intact.
21708     * <p>
21709     * <em>Note: To avoid a deadlock, do not call this method with {@code mPackages} lock held</em>
21710     */
21711    private void prepareAppDataAfterInstallLIF(PackageParser.Package pkg) {
21712        final PackageSetting ps;
21713        synchronized (mPackages) {
21714            ps = mSettings.mPackages.get(pkg.packageName);
21715            mSettings.writeKernelMappingLPr(ps);
21716        }
21717
21718        final UserManager um = mContext.getSystemService(UserManager.class);
21719        UserManagerInternal umInternal = getUserManagerInternal();
21720        for (UserInfo user : um.getUsers()) {
21721            final int flags;
21722            if (umInternal.isUserUnlockingOrUnlocked(user.id)) {
21723                flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
21724            } else if (umInternal.isUserRunning(user.id)) {
21725                flags = StorageManager.FLAG_STORAGE_DE;
21726            } else {
21727                continue;
21728            }
21729
21730            if (ps.getInstalled(user.id)) {
21731                // TODO: when user data is locked, mark that we're still dirty
21732                prepareAppDataLIF(pkg, user.id, flags);
21733            }
21734        }
21735    }
21736
21737    /**
21738     * Prepare app data for the given app.
21739     * <p>
21740     * Verifies that directories exist and that ownership and labeling is
21741     * correct for all installed apps. If there is an ownership mismatch, this
21742     * will try recovering system apps by wiping data; third-party app data is
21743     * left intact.
21744     */
21745    private void prepareAppDataLIF(PackageParser.Package pkg, int userId, int flags) {
21746        if (pkg == null) {
21747            Slog.wtf(TAG, "Package was null!", new Throwable());
21748            return;
21749        }
21750        prepareAppDataLeafLIF(pkg, userId, flags);
21751        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
21752        for (int i = 0; i < childCount; i++) {
21753            prepareAppDataLeafLIF(pkg.childPackages.get(i), userId, flags);
21754        }
21755    }
21756
21757    private void prepareAppDataAndMigrateLIF(PackageParser.Package pkg, int userId, int flags,
21758            boolean maybeMigrateAppData) {
21759        prepareAppDataLIF(pkg, userId, flags);
21760
21761        if (maybeMigrateAppData && maybeMigrateAppDataLIF(pkg, userId)) {
21762            // We may have just shuffled around app data directories, so
21763            // prepare them one more time
21764            prepareAppDataLIF(pkg, userId, flags);
21765        }
21766    }
21767
21768    private void prepareAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) {
21769        if (DEBUG_APP_DATA) {
21770            Slog.v(TAG, "prepareAppData for " + pkg.packageName + " u" + userId + " 0x"
21771                    + Integer.toHexString(flags));
21772        }
21773
21774        final String volumeUuid = pkg.volumeUuid;
21775        final String packageName = pkg.packageName;
21776        final ApplicationInfo app = pkg.applicationInfo;
21777        final int appId = UserHandle.getAppId(app.uid);
21778
21779        Preconditions.checkNotNull(app.seInfo);
21780
21781        long ceDataInode = -1;
21782        try {
21783            ceDataInode = mInstaller.createAppData(volumeUuid, packageName, userId, flags,
21784                    appId, app.seInfo, app.targetSdkVersion);
21785        } catch (InstallerException e) {
21786            if (app.isSystemApp()) {
21787                logCriticalInfo(Log.ERROR, "Failed to create app data for " + packageName
21788                        + ", but trying to recover: " + e);
21789                destroyAppDataLeafLIF(pkg, userId, flags);
21790                try {
21791                    ceDataInode = mInstaller.createAppData(volumeUuid, packageName, userId, flags,
21792                            appId, app.seInfo, app.targetSdkVersion);
21793                    logCriticalInfo(Log.DEBUG, "Recovery succeeded!");
21794                } catch (InstallerException e2) {
21795                    logCriticalInfo(Log.DEBUG, "Recovery failed!");
21796                }
21797            } else {
21798                Slog.e(TAG, "Failed to create app data for " + packageName + ": " + e);
21799            }
21800        }
21801
21802        if ((flags & StorageManager.FLAG_STORAGE_CE) != 0 && ceDataInode != -1) {
21803            // TODO: mark this structure as dirty so we persist it!
21804            synchronized (mPackages) {
21805                final PackageSetting ps = mSettings.mPackages.get(packageName);
21806                if (ps != null) {
21807                    ps.setCeDataInode(ceDataInode, userId);
21808                }
21809            }
21810        }
21811
21812        prepareAppDataContentsLeafLIF(pkg, userId, flags);
21813    }
21814
21815    private void prepareAppDataContentsLIF(PackageParser.Package pkg, int userId, int flags) {
21816        if (pkg == null) {
21817            Slog.wtf(TAG, "Package was null!", new Throwable());
21818            return;
21819        }
21820        prepareAppDataContentsLeafLIF(pkg, userId, flags);
21821        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
21822        for (int i = 0; i < childCount; i++) {
21823            prepareAppDataContentsLeafLIF(pkg.childPackages.get(i), userId, flags);
21824        }
21825    }
21826
21827    private void prepareAppDataContentsLeafLIF(PackageParser.Package pkg, int userId, int flags) {
21828        final String volumeUuid = pkg.volumeUuid;
21829        final String packageName = pkg.packageName;
21830        final ApplicationInfo app = pkg.applicationInfo;
21831
21832        if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) {
21833            // Create a native library symlink only if we have native libraries
21834            // and if the native libraries are 32 bit libraries. We do not provide
21835            // this symlink for 64 bit libraries.
21836            if (app.primaryCpuAbi != null && !VMRuntime.is64BitAbi(app.primaryCpuAbi)) {
21837                final String nativeLibPath = app.nativeLibraryDir;
21838                try {
21839                    mInstaller.linkNativeLibraryDirectory(volumeUuid, packageName,
21840                            nativeLibPath, userId);
21841                } catch (InstallerException e) {
21842                    Slog.e(TAG, "Failed to link native for " + packageName + ": " + e);
21843                }
21844            }
21845        }
21846    }
21847
21848    /**
21849     * For system apps on non-FBE devices, this method migrates any existing
21850     * CE/DE data to match the {@code defaultToDeviceProtectedStorage} flag
21851     * requested by the app.
21852     */
21853    private boolean maybeMigrateAppDataLIF(PackageParser.Package pkg, int userId) {
21854        if (pkg.isSystemApp() && !StorageManager.isFileEncryptedNativeOrEmulated()
21855                && PackageManager.APPLY_DEFAULT_TO_DEVICE_PROTECTED_STORAGE) {
21856            final int storageTarget = pkg.applicationInfo.isDefaultToDeviceProtectedStorage()
21857                    ? StorageManager.FLAG_STORAGE_DE : StorageManager.FLAG_STORAGE_CE;
21858            try {
21859                mInstaller.migrateAppData(pkg.volumeUuid, pkg.packageName, userId,
21860                        storageTarget);
21861            } catch (InstallerException e) {
21862                logCriticalInfo(Log.WARN,
21863                        "Failed to migrate " + pkg.packageName + ": " + e.getMessage());
21864            }
21865            return true;
21866        } else {
21867            return false;
21868        }
21869    }
21870
21871    public PackageFreezer freezePackage(String packageName, String killReason) {
21872        return freezePackage(packageName, UserHandle.USER_ALL, killReason);
21873    }
21874
21875    public PackageFreezer freezePackage(String packageName, int userId, String killReason) {
21876        return new PackageFreezer(packageName, userId, killReason);
21877    }
21878
21879    public PackageFreezer freezePackageForInstall(String packageName, int installFlags,
21880            String killReason) {
21881        return freezePackageForInstall(packageName, UserHandle.USER_ALL, installFlags, killReason);
21882    }
21883
21884    public PackageFreezer freezePackageForInstall(String packageName, int userId, int installFlags,
21885            String killReason) {
21886        if ((installFlags & PackageManager.INSTALL_DONT_KILL_APP) != 0) {
21887            return new PackageFreezer();
21888        } else {
21889            return freezePackage(packageName, userId, killReason);
21890        }
21891    }
21892
21893    public PackageFreezer freezePackageForDelete(String packageName, int deleteFlags,
21894            String killReason) {
21895        return freezePackageForDelete(packageName, UserHandle.USER_ALL, deleteFlags, killReason);
21896    }
21897
21898    public PackageFreezer freezePackageForDelete(String packageName, int userId, int deleteFlags,
21899            String killReason) {
21900        if ((deleteFlags & PackageManager.DELETE_DONT_KILL_APP) != 0) {
21901            return new PackageFreezer();
21902        } else {
21903            return freezePackage(packageName, userId, killReason);
21904        }
21905    }
21906
21907    /**
21908     * Class that freezes and kills the given package upon creation, and
21909     * unfreezes it upon closing. This is typically used when doing surgery on
21910     * app code/data to prevent the app from running while you're working.
21911     */
21912    private class PackageFreezer implements AutoCloseable {
21913        private final String mPackageName;
21914        private final PackageFreezer[] mChildren;
21915
21916        private final boolean mWeFroze;
21917
21918        private final AtomicBoolean mClosed = new AtomicBoolean();
21919        private final CloseGuard mCloseGuard = CloseGuard.get();
21920
21921        /**
21922         * Create and return a stub freezer that doesn't actually do anything,
21923         * typically used when someone requested
21924         * {@link PackageManager#INSTALL_DONT_KILL_APP} or
21925         * {@link PackageManager#DELETE_DONT_KILL_APP}.
21926         */
21927        public PackageFreezer() {
21928            mPackageName = null;
21929            mChildren = null;
21930            mWeFroze = false;
21931            mCloseGuard.open("close");
21932        }
21933
21934        public PackageFreezer(String packageName, int userId, String killReason) {
21935            synchronized (mPackages) {
21936                mPackageName = packageName;
21937                mWeFroze = mFrozenPackages.add(mPackageName);
21938
21939                final PackageSetting ps = mSettings.mPackages.get(mPackageName);
21940                if (ps != null) {
21941                    killApplication(ps.name, ps.appId, userId, killReason);
21942                }
21943
21944                final PackageParser.Package p = mPackages.get(packageName);
21945                if (p != null && p.childPackages != null) {
21946                    final int N = p.childPackages.size();
21947                    mChildren = new PackageFreezer[N];
21948                    for (int i = 0; i < N; i++) {
21949                        mChildren[i] = new PackageFreezer(p.childPackages.get(i).packageName,
21950                                userId, killReason);
21951                    }
21952                } else {
21953                    mChildren = null;
21954                }
21955            }
21956            mCloseGuard.open("close");
21957        }
21958
21959        @Override
21960        protected void finalize() throws Throwable {
21961            try {
21962                mCloseGuard.warnIfOpen();
21963                close();
21964            } finally {
21965                super.finalize();
21966            }
21967        }
21968
21969        @Override
21970        public void close() {
21971            mCloseGuard.close();
21972            if (mClosed.compareAndSet(false, true)) {
21973                synchronized (mPackages) {
21974                    if (mWeFroze) {
21975                        mFrozenPackages.remove(mPackageName);
21976                    }
21977
21978                    if (mChildren != null) {
21979                        for (PackageFreezer freezer : mChildren) {
21980                            freezer.close();
21981                        }
21982                    }
21983                }
21984            }
21985        }
21986    }
21987
21988    /**
21989     * Verify that given package is currently frozen.
21990     */
21991    private void checkPackageFrozen(String packageName) {
21992        synchronized (mPackages) {
21993            if (!mFrozenPackages.contains(packageName)) {
21994                Slog.wtf(TAG, "Expected " + packageName + " to be frozen!", new Throwable());
21995            }
21996        }
21997    }
21998
21999    @Override
22000    public int movePackage(final String packageName, final String volumeUuid) {
22001        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null);
22002
22003        final UserHandle user = new UserHandle(UserHandle.getCallingUserId());
22004        final int moveId = mNextMoveId.getAndIncrement();
22005        mHandler.post(new Runnable() {
22006            @Override
22007            public void run() {
22008                try {
22009                    movePackageInternal(packageName, volumeUuid, moveId, user);
22010                } catch (PackageManagerException e) {
22011                    Slog.w(TAG, "Failed to move " + packageName, e);
22012                    mMoveCallbacks.notifyStatusChanged(moveId,
22013                            PackageManager.MOVE_FAILED_INTERNAL_ERROR);
22014                }
22015            }
22016        });
22017        return moveId;
22018    }
22019
22020    private void movePackageInternal(final String packageName, final String volumeUuid,
22021            final int moveId, UserHandle user) throws PackageManagerException {
22022        final StorageManager storage = mContext.getSystemService(StorageManager.class);
22023        final PackageManager pm = mContext.getPackageManager();
22024
22025        final boolean currentAsec;
22026        final String currentVolumeUuid;
22027        final File codeFile;
22028        final String installerPackageName;
22029        final String packageAbiOverride;
22030        final int appId;
22031        final String seinfo;
22032        final String label;
22033        final int targetSdkVersion;
22034        final PackageFreezer freezer;
22035        final int[] installedUserIds;
22036
22037        // reader
22038        synchronized (mPackages) {
22039            final PackageParser.Package pkg = mPackages.get(packageName);
22040            final PackageSetting ps = mSettings.mPackages.get(packageName);
22041            if (pkg == null || ps == null) {
22042                throw new PackageManagerException(MOVE_FAILED_DOESNT_EXIST, "Missing package");
22043            }
22044
22045            if (pkg.applicationInfo.isSystemApp()) {
22046                throw new PackageManagerException(MOVE_FAILED_SYSTEM_PACKAGE,
22047                        "Cannot move system application");
22048            }
22049
22050            final boolean isInternalStorage = VolumeInfo.ID_PRIVATE_INTERNAL.equals(volumeUuid);
22051            final boolean allow3rdPartyOnInternal = mContext.getResources().getBoolean(
22052                    com.android.internal.R.bool.config_allow3rdPartyAppOnInternal);
22053            if (isInternalStorage && !allow3rdPartyOnInternal) {
22054                throw new PackageManagerException(MOVE_FAILED_3RD_PARTY_NOT_ALLOWED_ON_INTERNAL,
22055                        "3rd party apps are not allowed on internal storage");
22056            }
22057
22058            if (pkg.applicationInfo.isExternalAsec()) {
22059                currentAsec = true;
22060                currentVolumeUuid = StorageManager.UUID_PRIMARY_PHYSICAL;
22061            } else if (pkg.applicationInfo.isForwardLocked()) {
22062                currentAsec = true;
22063                currentVolumeUuid = "forward_locked";
22064            } else {
22065                currentAsec = false;
22066                currentVolumeUuid = ps.volumeUuid;
22067
22068                final File probe = new File(pkg.codePath);
22069                final File probeOat = new File(probe, "oat");
22070                if (!probe.isDirectory() || !probeOat.isDirectory()) {
22071                    throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
22072                            "Move only supported for modern cluster style installs");
22073                }
22074            }
22075
22076            if (Objects.equals(currentVolumeUuid, volumeUuid)) {
22077                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
22078                        "Package already moved to " + volumeUuid);
22079            }
22080            if (pkg.applicationInfo.isInternal() && isPackageDeviceAdminOnAnyUser(packageName)) {
22081                throw new PackageManagerException(MOVE_FAILED_DEVICE_ADMIN,
22082                        "Device admin cannot be moved");
22083            }
22084
22085            if (mFrozenPackages.contains(packageName)) {
22086                throw new PackageManagerException(MOVE_FAILED_OPERATION_PENDING,
22087                        "Failed to move already frozen package");
22088            }
22089
22090            codeFile = new File(pkg.codePath);
22091            installerPackageName = ps.installerPackageName;
22092            packageAbiOverride = ps.cpuAbiOverrideString;
22093            appId = UserHandle.getAppId(pkg.applicationInfo.uid);
22094            seinfo = pkg.applicationInfo.seInfo;
22095            label = String.valueOf(pm.getApplicationLabel(pkg.applicationInfo));
22096            targetSdkVersion = pkg.applicationInfo.targetSdkVersion;
22097            freezer = freezePackage(packageName, "movePackageInternal");
22098            installedUserIds = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
22099        }
22100
22101        final Bundle extras = new Bundle();
22102        extras.putString(Intent.EXTRA_PACKAGE_NAME, packageName);
22103        extras.putString(Intent.EXTRA_TITLE, label);
22104        mMoveCallbacks.notifyCreated(moveId, extras);
22105
22106        int installFlags;
22107        final boolean moveCompleteApp;
22108        final File measurePath;
22109
22110        if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, volumeUuid)) {
22111            installFlags = INSTALL_INTERNAL;
22112            moveCompleteApp = !currentAsec;
22113            measurePath = Environment.getDataAppDirectory(volumeUuid);
22114        } else if (Objects.equals(StorageManager.UUID_PRIMARY_PHYSICAL, volumeUuid)) {
22115            installFlags = INSTALL_EXTERNAL;
22116            moveCompleteApp = false;
22117            measurePath = storage.getPrimaryPhysicalVolume().getPath();
22118        } else {
22119            final VolumeInfo volume = storage.findVolumeByUuid(volumeUuid);
22120            if (volume == null || volume.getType() != VolumeInfo.TYPE_PRIVATE
22121                    || !volume.isMountedWritable()) {
22122                freezer.close();
22123                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
22124                        "Move location not mounted private volume");
22125            }
22126
22127            Preconditions.checkState(!currentAsec);
22128
22129            installFlags = INSTALL_INTERNAL;
22130            moveCompleteApp = true;
22131            measurePath = Environment.getDataAppDirectory(volumeUuid);
22132        }
22133
22134        final PackageStats stats = new PackageStats(null, -1);
22135        synchronized (mInstaller) {
22136            for (int userId : installedUserIds) {
22137                if (!getPackageSizeInfoLI(packageName, userId, stats)) {
22138                    freezer.close();
22139                    throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
22140                            "Failed to measure package size");
22141                }
22142            }
22143        }
22144
22145        if (DEBUG_INSTALL) Slog.d(TAG, "Measured code size " + stats.codeSize + ", data size "
22146                + stats.dataSize);
22147
22148        final long startFreeBytes = measurePath.getFreeSpace();
22149        final long sizeBytes;
22150        if (moveCompleteApp) {
22151            sizeBytes = stats.codeSize + stats.dataSize;
22152        } else {
22153            sizeBytes = stats.codeSize;
22154        }
22155
22156        if (sizeBytes > storage.getStorageBytesUntilLow(measurePath)) {
22157            freezer.close();
22158            throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
22159                    "Not enough free space to move");
22160        }
22161
22162        mMoveCallbacks.notifyStatusChanged(moveId, 10);
22163
22164        final CountDownLatch installedLatch = new CountDownLatch(1);
22165        final IPackageInstallObserver2 installObserver = new IPackageInstallObserver2.Stub() {
22166            @Override
22167            public void onUserActionRequired(Intent intent) throws RemoteException {
22168                throw new IllegalStateException();
22169            }
22170
22171            @Override
22172            public void onPackageInstalled(String basePackageName, int returnCode, String msg,
22173                    Bundle extras) throws RemoteException {
22174                if (DEBUG_INSTALL) Slog.d(TAG, "Install result for move: "
22175                        + PackageManager.installStatusToString(returnCode, msg));
22176
22177                installedLatch.countDown();
22178                freezer.close();
22179
22180                final int status = PackageManager.installStatusToPublicStatus(returnCode);
22181                switch (status) {
22182                    case PackageInstaller.STATUS_SUCCESS:
22183                        mMoveCallbacks.notifyStatusChanged(moveId,
22184                                PackageManager.MOVE_SUCCEEDED);
22185                        break;
22186                    case PackageInstaller.STATUS_FAILURE_STORAGE:
22187                        mMoveCallbacks.notifyStatusChanged(moveId,
22188                                PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE);
22189                        break;
22190                    default:
22191                        mMoveCallbacks.notifyStatusChanged(moveId,
22192                                PackageManager.MOVE_FAILED_INTERNAL_ERROR);
22193                        break;
22194                }
22195            }
22196        };
22197
22198        final MoveInfo move;
22199        if (moveCompleteApp) {
22200            // Kick off a thread to report progress estimates
22201            new Thread() {
22202                @Override
22203                public void run() {
22204                    while (true) {
22205                        try {
22206                            if (installedLatch.await(1, TimeUnit.SECONDS)) {
22207                                break;
22208                            }
22209                        } catch (InterruptedException ignored) {
22210                        }
22211
22212                        final long deltaFreeBytes = startFreeBytes - measurePath.getFreeSpace();
22213                        final int progress = 10 + (int) MathUtils.constrain(
22214                                ((deltaFreeBytes * 80) / sizeBytes), 0, 80);
22215                        mMoveCallbacks.notifyStatusChanged(moveId, progress);
22216                    }
22217                }
22218            }.start();
22219
22220            final String dataAppName = codeFile.getName();
22221            move = new MoveInfo(moveId, currentVolumeUuid, volumeUuid, packageName,
22222                    dataAppName, appId, seinfo, targetSdkVersion);
22223        } else {
22224            move = null;
22225        }
22226
22227        installFlags |= PackageManager.INSTALL_REPLACE_EXISTING;
22228
22229        final Message msg = mHandler.obtainMessage(INIT_COPY);
22230        final OriginInfo origin = OriginInfo.fromExistingFile(codeFile);
22231        final InstallParams params = new InstallParams(origin, move, installObserver, installFlags,
22232                installerPackageName, volumeUuid, null /*verificationInfo*/, user,
22233                packageAbiOverride, null /*grantedPermissions*/, null /*certificates*/,
22234                PackageManager.INSTALL_REASON_UNKNOWN);
22235        params.setTraceMethod("movePackage").setTraceCookie(System.identityHashCode(params));
22236        msg.obj = params;
22237
22238        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "movePackage",
22239                System.identityHashCode(msg.obj));
22240        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
22241                System.identityHashCode(msg.obj));
22242
22243        mHandler.sendMessage(msg);
22244    }
22245
22246    @Override
22247    public int movePrimaryStorage(String volumeUuid) throws RemoteException {
22248        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null);
22249
22250        final int realMoveId = mNextMoveId.getAndIncrement();
22251        final Bundle extras = new Bundle();
22252        extras.putString(VolumeRecord.EXTRA_FS_UUID, volumeUuid);
22253        mMoveCallbacks.notifyCreated(realMoveId, extras);
22254
22255        final IPackageMoveObserver callback = new IPackageMoveObserver.Stub() {
22256            @Override
22257            public void onCreated(int moveId, Bundle extras) {
22258                // Ignored
22259            }
22260
22261            @Override
22262            public void onStatusChanged(int moveId, int status, long estMillis) {
22263                mMoveCallbacks.notifyStatusChanged(realMoveId, status, estMillis);
22264            }
22265        };
22266
22267        final StorageManager storage = mContext.getSystemService(StorageManager.class);
22268        storage.setPrimaryStorageUuid(volumeUuid, callback);
22269        return realMoveId;
22270    }
22271
22272    @Override
22273    public int getMoveStatus(int moveId) {
22274        mContext.enforceCallingOrSelfPermission(
22275                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
22276        return mMoveCallbacks.mLastStatus.get(moveId);
22277    }
22278
22279    @Override
22280    public void registerMoveCallback(IPackageMoveObserver callback) {
22281        mContext.enforceCallingOrSelfPermission(
22282                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
22283        mMoveCallbacks.register(callback);
22284    }
22285
22286    @Override
22287    public void unregisterMoveCallback(IPackageMoveObserver callback) {
22288        mContext.enforceCallingOrSelfPermission(
22289                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
22290        mMoveCallbacks.unregister(callback);
22291    }
22292
22293    @Override
22294    public boolean setInstallLocation(int loc) {
22295        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WRITE_SECURE_SETTINGS,
22296                null);
22297        if (getInstallLocation() == loc) {
22298            return true;
22299        }
22300        if (loc == PackageHelper.APP_INSTALL_AUTO || loc == PackageHelper.APP_INSTALL_INTERNAL
22301                || loc == PackageHelper.APP_INSTALL_EXTERNAL) {
22302            android.provider.Settings.Global.putInt(mContext.getContentResolver(),
22303                    android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, loc);
22304            return true;
22305        }
22306        return false;
22307   }
22308
22309    @Override
22310    public int getInstallLocation() {
22311        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
22312                android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION,
22313                PackageHelper.APP_INSTALL_AUTO);
22314    }
22315
22316    /** Called by UserManagerService */
22317    void cleanUpUser(UserManagerService userManager, int userHandle) {
22318        synchronized (mPackages) {
22319            mDirtyUsers.remove(userHandle);
22320            mUserNeedsBadging.delete(userHandle);
22321            mSettings.removeUserLPw(userHandle);
22322            mPendingBroadcasts.remove(userHandle);
22323            mInstantAppRegistry.onUserRemovedLPw(userHandle);
22324            removeUnusedPackagesLPw(userManager, userHandle);
22325        }
22326    }
22327
22328    /**
22329     * We're removing userHandle and would like to remove any downloaded packages
22330     * that are no longer in use by any other user.
22331     * @param userHandle the user being removed
22332     */
22333    private void removeUnusedPackagesLPw(UserManagerService userManager, final int userHandle) {
22334        final boolean DEBUG_CLEAN_APKS = false;
22335        int [] users = userManager.getUserIds();
22336        Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator();
22337        while (psit.hasNext()) {
22338            PackageSetting ps = psit.next();
22339            if (ps.pkg == null) {
22340                continue;
22341            }
22342            final String packageName = ps.pkg.packageName;
22343            // Skip over if system app
22344            if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0) {
22345                continue;
22346            }
22347            if (DEBUG_CLEAN_APKS) {
22348                Slog.i(TAG, "Checking package " + packageName);
22349            }
22350            boolean keep = shouldKeepUninstalledPackageLPr(packageName);
22351            if (keep) {
22352                if (DEBUG_CLEAN_APKS) {
22353                    Slog.i(TAG, "  Keeping package " + packageName + " - requested by DO");
22354                }
22355            } else {
22356                for (int i = 0; i < users.length; i++) {
22357                    if (users[i] != userHandle && ps.getInstalled(users[i])) {
22358                        keep = true;
22359                        if (DEBUG_CLEAN_APKS) {
22360                            Slog.i(TAG, "  Keeping package " + packageName + " for user "
22361                                    + users[i]);
22362                        }
22363                        break;
22364                    }
22365                }
22366            }
22367            if (!keep) {
22368                if (DEBUG_CLEAN_APKS) {
22369                    Slog.i(TAG, "  Removing package " + packageName);
22370                }
22371                mHandler.post(new Runnable() {
22372                    public void run() {
22373                        deletePackageX(packageName, PackageManager.VERSION_CODE_HIGHEST,
22374                                userHandle, 0);
22375                    } //end run
22376                });
22377            }
22378        }
22379    }
22380
22381    /** Called by UserManagerService */
22382    void createNewUser(int userId, String[] disallowedPackages) {
22383        synchronized (mInstallLock) {
22384            mSettings.createNewUserLI(this, mInstaller, userId, disallowedPackages);
22385        }
22386        synchronized (mPackages) {
22387            scheduleWritePackageRestrictionsLocked(userId);
22388            scheduleWritePackageListLocked(userId);
22389            applyFactoryDefaultBrowserLPw(userId);
22390            primeDomainVerificationsLPw(userId);
22391        }
22392    }
22393
22394    void onNewUserCreated(final int userId) {
22395        mDefaultPermissionPolicy.grantDefaultPermissions(userId);
22396        // If permission review for legacy apps is required, we represent
22397        // dagerous permissions for such apps as always granted runtime
22398        // permissions to keep per user flag state whether review is needed.
22399        // Hence, if a new user is added we have to propagate dangerous
22400        // permission grants for these legacy apps.
22401        if (mPermissionReviewRequired) {
22402            updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL
22403                    | UPDATE_PERMISSIONS_REPLACE_ALL);
22404        }
22405    }
22406
22407    @Override
22408    public VerifierDeviceIdentity getVerifierDeviceIdentity() throws RemoteException {
22409        mContext.enforceCallingOrSelfPermission(
22410                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
22411                "Only package verification agents can read the verifier device identity");
22412
22413        synchronized (mPackages) {
22414            return mSettings.getVerifierDeviceIdentityLPw();
22415        }
22416    }
22417
22418    @Override
22419    public void setPermissionEnforced(String permission, boolean enforced) {
22420        // TODO: Now that we no longer change GID for storage, this should to away.
22421        mContext.enforceCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS,
22422                "setPermissionEnforced");
22423        if (READ_EXTERNAL_STORAGE.equals(permission)) {
22424            synchronized (mPackages) {
22425                if (mSettings.mReadExternalStorageEnforced == null
22426                        || mSettings.mReadExternalStorageEnforced != enforced) {
22427                    mSettings.mReadExternalStorageEnforced = enforced;
22428                    mSettings.writeLPr();
22429                }
22430            }
22431            // kill any non-foreground processes so we restart them and
22432            // grant/revoke the GID.
22433            final IActivityManager am = ActivityManager.getService();
22434            if (am != null) {
22435                final long token = Binder.clearCallingIdentity();
22436                try {
22437                    am.killProcessesBelowForeground("setPermissionEnforcement");
22438                } catch (RemoteException e) {
22439                } finally {
22440                    Binder.restoreCallingIdentity(token);
22441                }
22442            }
22443        } else {
22444            throw new IllegalArgumentException("No selective enforcement for " + permission);
22445        }
22446    }
22447
22448    @Override
22449    @Deprecated
22450    public boolean isPermissionEnforced(String permission) {
22451        return true;
22452    }
22453
22454    @Override
22455    public boolean isStorageLow() {
22456        final long token = Binder.clearCallingIdentity();
22457        try {
22458            final DeviceStorageMonitorInternal
22459                    dsm = LocalServices.getService(DeviceStorageMonitorInternal.class);
22460            if (dsm != null) {
22461                return dsm.isMemoryLow();
22462            } else {
22463                return false;
22464            }
22465        } finally {
22466            Binder.restoreCallingIdentity(token);
22467        }
22468    }
22469
22470    @Override
22471    public IPackageInstaller getPackageInstaller() {
22472        return mInstallerService;
22473    }
22474
22475    private boolean userNeedsBadging(int userId) {
22476        int index = mUserNeedsBadging.indexOfKey(userId);
22477        if (index < 0) {
22478            final UserInfo userInfo;
22479            final long token = Binder.clearCallingIdentity();
22480            try {
22481                userInfo = sUserManager.getUserInfo(userId);
22482            } finally {
22483                Binder.restoreCallingIdentity(token);
22484            }
22485            final boolean b;
22486            if (userInfo != null && userInfo.isManagedProfile()) {
22487                b = true;
22488            } else {
22489                b = false;
22490            }
22491            mUserNeedsBadging.put(userId, b);
22492            return b;
22493        }
22494        return mUserNeedsBadging.valueAt(index);
22495    }
22496
22497    @Override
22498    public KeySet getKeySetByAlias(String packageName, String alias) {
22499        if (packageName == null || alias == null) {
22500            return null;
22501        }
22502        synchronized(mPackages) {
22503            final PackageParser.Package pkg = mPackages.get(packageName);
22504            if (pkg == null) {
22505                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
22506                throw new IllegalArgumentException("Unknown package: " + packageName);
22507            }
22508            KeySetManagerService ksms = mSettings.mKeySetManagerService;
22509            return new KeySet(ksms.getKeySetByAliasAndPackageNameLPr(packageName, alias));
22510        }
22511    }
22512
22513    @Override
22514    public KeySet getSigningKeySet(String packageName) {
22515        if (packageName == null) {
22516            return null;
22517        }
22518        synchronized(mPackages) {
22519            final PackageParser.Package pkg = mPackages.get(packageName);
22520            if (pkg == null) {
22521                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
22522                throw new IllegalArgumentException("Unknown package: " + packageName);
22523            }
22524            if (pkg.applicationInfo.uid != Binder.getCallingUid()
22525                    && Process.SYSTEM_UID != Binder.getCallingUid()) {
22526                throw new SecurityException("May not access signing KeySet of other apps.");
22527            }
22528            KeySetManagerService ksms = mSettings.mKeySetManagerService;
22529            return new KeySet(ksms.getSigningKeySetByPackageNameLPr(packageName));
22530        }
22531    }
22532
22533    @Override
22534    public boolean isPackageSignedByKeySet(String packageName, KeySet ks) {
22535        if (packageName == null || ks == null) {
22536            return false;
22537        }
22538        synchronized(mPackages) {
22539            final PackageParser.Package pkg = mPackages.get(packageName);
22540            if (pkg == null) {
22541                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
22542                throw new IllegalArgumentException("Unknown package: " + packageName);
22543            }
22544            IBinder ksh = ks.getToken();
22545            if (ksh instanceof KeySetHandle) {
22546                KeySetManagerService ksms = mSettings.mKeySetManagerService;
22547                return ksms.packageIsSignedByLPr(packageName, (KeySetHandle) ksh);
22548            }
22549            return false;
22550        }
22551    }
22552
22553    @Override
22554    public boolean isPackageSignedByKeySetExactly(String packageName, KeySet ks) {
22555        if (packageName == null || ks == null) {
22556            return false;
22557        }
22558        synchronized(mPackages) {
22559            final PackageParser.Package pkg = mPackages.get(packageName);
22560            if (pkg == null) {
22561                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
22562                throw new IllegalArgumentException("Unknown package: " + packageName);
22563            }
22564            IBinder ksh = ks.getToken();
22565            if (ksh instanceof KeySetHandle) {
22566                KeySetManagerService ksms = mSettings.mKeySetManagerService;
22567                return ksms.packageIsSignedByExactlyLPr(packageName, (KeySetHandle) ksh);
22568            }
22569            return false;
22570        }
22571    }
22572
22573    private void deletePackageIfUnusedLPr(final String packageName) {
22574        PackageSetting ps = mSettings.mPackages.get(packageName);
22575        if (ps == null) {
22576            return;
22577        }
22578        if (!ps.isAnyInstalled(sUserManager.getUserIds())) {
22579            // TODO Implement atomic delete if package is unused
22580            // It is currently possible that the package will be deleted even if it is installed
22581            // after this method returns.
22582            mHandler.post(new Runnable() {
22583                public void run() {
22584                    deletePackageX(packageName, PackageManager.VERSION_CODE_HIGHEST,
22585                            0, PackageManager.DELETE_ALL_USERS);
22586                }
22587            });
22588        }
22589    }
22590
22591    /**
22592     * Check and throw if the given before/after packages would be considered a
22593     * downgrade.
22594     */
22595    private static void checkDowngrade(PackageParser.Package before, PackageInfoLite after)
22596            throws PackageManagerException {
22597        if (after.versionCode < before.mVersionCode) {
22598            throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
22599                    "Update version code " + after.versionCode + " is older than current "
22600                    + before.mVersionCode);
22601        } else if (after.versionCode == before.mVersionCode) {
22602            if (after.baseRevisionCode < before.baseRevisionCode) {
22603                throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
22604                        "Update base revision code " + after.baseRevisionCode
22605                        + " is older than current " + before.baseRevisionCode);
22606            }
22607
22608            if (!ArrayUtils.isEmpty(after.splitNames)) {
22609                for (int i = 0; i < after.splitNames.length; i++) {
22610                    final String splitName = after.splitNames[i];
22611                    final int j = ArrayUtils.indexOf(before.splitNames, splitName);
22612                    if (j != -1) {
22613                        if (after.splitRevisionCodes[i] < before.splitRevisionCodes[j]) {
22614                            throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
22615                                    "Update split " + splitName + " revision code "
22616                                    + after.splitRevisionCodes[i] + " is older than current "
22617                                    + before.splitRevisionCodes[j]);
22618                        }
22619                    }
22620                }
22621            }
22622        }
22623    }
22624
22625    private static class MoveCallbacks extends Handler {
22626        private static final int MSG_CREATED = 1;
22627        private static final int MSG_STATUS_CHANGED = 2;
22628
22629        private final RemoteCallbackList<IPackageMoveObserver>
22630                mCallbacks = new RemoteCallbackList<>();
22631
22632        private final SparseIntArray mLastStatus = new SparseIntArray();
22633
22634        public MoveCallbacks(Looper looper) {
22635            super(looper);
22636        }
22637
22638        public void register(IPackageMoveObserver callback) {
22639            mCallbacks.register(callback);
22640        }
22641
22642        public void unregister(IPackageMoveObserver callback) {
22643            mCallbacks.unregister(callback);
22644        }
22645
22646        @Override
22647        public void handleMessage(Message msg) {
22648            final SomeArgs args = (SomeArgs) msg.obj;
22649            final int n = mCallbacks.beginBroadcast();
22650            for (int i = 0; i < n; i++) {
22651                final IPackageMoveObserver callback = mCallbacks.getBroadcastItem(i);
22652                try {
22653                    invokeCallback(callback, msg.what, args);
22654                } catch (RemoteException ignored) {
22655                }
22656            }
22657            mCallbacks.finishBroadcast();
22658            args.recycle();
22659        }
22660
22661        private void invokeCallback(IPackageMoveObserver callback, int what, SomeArgs args)
22662                throws RemoteException {
22663            switch (what) {
22664                case MSG_CREATED: {
22665                    callback.onCreated(args.argi1, (Bundle) args.arg2);
22666                    break;
22667                }
22668                case MSG_STATUS_CHANGED: {
22669                    callback.onStatusChanged(args.argi1, args.argi2, (long) args.arg3);
22670                    break;
22671                }
22672            }
22673        }
22674
22675        private void notifyCreated(int moveId, Bundle extras) {
22676            Slog.v(TAG, "Move " + moveId + " created " + extras.toString());
22677
22678            final SomeArgs args = SomeArgs.obtain();
22679            args.argi1 = moveId;
22680            args.arg2 = extras;
22681            obtainMessage(MSG_CREATED, args).sendToTarget();
22682        }
22683
22684        private void notifyStatusChanged(int moveId, int status) {
22685            notifyStatusChanged(moveId, status, -1);
22686        }
22687
22688        private void notifyStatusChanged(int moveId, int status, long estMillis) {
22689            Slog.v(TAG, "Move " + moveId + " status " + status);
22690
22691            final SomeArgs args = SomeArgs.obtain();
22692            args.argi1 = moveId;
22693            args.argi2 = status;
22694            args.arg3 = estMillis;
22695            obtainMessage(MSG_STATUS_CHANGED, args).sendToTarget();
22696
22697            synchronized (mLastStatus) {
22698                mLastStatus.put(moveId, status);
22699            }
22700        }
22701    }
22702
22703    private final static class OnPermissionChangeListeners extends Handler {
22704        private static final int MSG_ON_PERMISSIONS_CHANGED = 1;
22705
22706        private final RemoteCallbackList<IOnPermissionsChangeListener> mPermissionListeners =
22707                new RemoteCallbackList<>();
22708
22709        public OnPermissionChangeListeners(Looper looper) {
22710            super(looper);
22711        }
22712
22713        @Override
22714        public void handleMessage(Message msg) {
22715            switch (msg.what) {
22716                case MSG_ON_PERMISSIONS_CHANGED: {
22717                    final int uid = msg.arg1;
22718                    handleOnPermissionsChanged(uid);
22719                } break;
22720            }
22721        }
22722
22723        public void addListenerLocked(IOnPermissionsChangeListener listener) {
22724            mPermissionListeners.register(listener);
22725
22726        }
22727
22728        public void removeListenerLocked(IOnPermissionsChangeListener listener) {
22729            mPermissionListeners.unregister(listener);
22730        }
22731
22732        public void onPermissionsChanged(int uid) {
22733            if (mPermissionListeners.getRegisteredCallbackCount() > 0) {
22734                obtainMessage(MSG_ON_PERMISSIONS_CHANGED, uid, 0).sendToTarget();
22735            }
22736        }
22737
22738        private void handleOnPermissionsChanged(int uid) {
22739            final int count = mPermissionListeners.beginBroadcast();
22740            try {
22741                for (int i = 0; i < count; i++) {
22742                    IOnPermissionsChangeListener callback = mPermissionListeners
22743                            .getBroadcastItem(i);
22744                    try {
22745                        callback.onPermissionsChanged(uid);
22746                    } catch (RemoteException e) {
22747                        Log.e(TAG, "Permission listener is dead", e);
22748                    }
22749                }
22750            } finally {
22751                mPermissionListeners.finishBroadcast();
22752            }
22753        }
22754    }
22755
22756    private class PackageManagerInternalImpl extends PackageManagerInternal {
22757        @Override
22758        public void setLocationPackagesProvider(PackagesProvider provider) {
22759            synchronized (mPackages) {
22760                mDefaultPermissionPolicy.setLocationPackagesProviderLPw(provider);
22761            }
22762        }
22763
22764        @Override
22765        public void setVoiceInteractionPackagesProvider(PackagesProvider provider) {
22766            synchronized (mPackages) {
22767                mDefaultPermissionPolicy.setVoiceInteractionPackagesProviderLPw(provider);
22768            }
22769        }
22770
22771        @Override
22772        public void setSmsAppPackagesProvider(PackagesProvider provider) {
22773            synchronized (mPackages) {
22774                mDefaultPermissionPolicy.setSmsAppPackagesProviderLPw(provider);
22775            }
22776        }
22777
22778        @Override
22779        public void setDialerAppPackagesProvider(PackagesProvider provider) {
22780            synchronized (mPackages) {
22781                mDefaultPermissionPolicy.setDialerAppPackagesProviderLPw(provider);
22782            }
22783        }
22784
22785        @Override
22786        public void setSimCallManagerPackagesProvider(PackagesProvider provider) {
22787            synchronized (mPackages) {
22788                mDefaultPermissionPolicy.setSimCallManagerPackagesProviderLPw(provider);
22789            }
22790        }
22791
22792        @Override
22793        public void setSyncAdapterPackagesprovider(SyncAdapterPackagesProvider provider) {
22794            synchronized (mPackages) {
22795                mDefaultPermissionPolicy.setSyncAdapterPackagesProviderLPw(provider);
22796            }
22797        }
22798
22799        @Override
22800        public void grantDefaultPermissionsToDefaultSmsApp(String packageName, int userId) {
22801            synchronized (mPackages) {
22802                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSmsAppLPr(
22803                        packageName, userId);
22804            }
22805        }
22806
22807        @Override
22808        public void grantDefaultPermissionsToDefaultDialerApp(String packageName, int userId) {
22809            synchronized (mPackages) {
22810                mSettings.setDefaultDialerPackageNameLPw(packageName, userId);
22811                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultDialerAppLPr(
22812                        packageName, userId);
22813            }
22814        }
22815
22816        @Override
22817        public void grantDefaultPermissionsToDefaultSimCallManager(String packageName, int userId) {
22818            synchronized (mPackages) {
22819                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSimCallManagerLPr(
22820                        packageName, userId);
22821            }
22822        }
22823
22824        @Override
22825        public void setKeepUninstalledPackages(final List<String> packageList) {
22826            Preconditions.checkNotNull(packageList);
22827            List<String> removedFromList = null;
22828            synchronized (mPackages) {
22829                if (mKeepUninstalledPackages != null) {
22830                    final int packagesCount = mKeepUninstalledPackages.size();
22831                    for (int i = 0; i < packagesCount; i++) {
22832                        String oldPackage = mKeepUninstalledPackages.get(i);
22833                        if (packageList != null && packageList.contains(oldPackage)) {
22834                            continue;
22835                        }
22836                        if (removedFromList == null) {
22837                            removedFromList = new ArrayList<>();
22838                        }
22839                        removedFromList.add(oldPackage);
22840                    }
22841                }
22842                mKeepUninstalledPackages = new ArrayList<>(packageList);
22843                if (removedFromList != null) {
22844                    final int removedCount = removedFromList.size();
22845                    for (int i = 0; i < removedCount; i++) {
22846                        deletePackageIfUnusedLPr(removedFromList.get(i));
22847                    }
22848                }
22849            }
22850        }
22851
22852        @Override
22853        public boolean isPermissionsReviewRequired(String packageName, int userId) {
22854            synchronized (mPackages) {
22855                // If we do not support permission review, done.
22856                if (!mPermissionReviewRequired) {
22857                    return false;
22858                }
22859
22860                PackageSetting packageSetting = mSettings.mPackages.get(packageName);
22861                if (packageSetting == null) {
22862                    return false;
22863                }
22864
22865                // Permission review applies only to apps not supporting the new permission model.
22866                if (packageSetting.pkg.applicationInfo.targetSdkVersion >= Build.VERSION_CODES.M) {
22867                    return false;
22868                }
22869
22870                // Legacy apps have the permission and get user consent on launch.
22871                PermissionsState permissionsState = packageSetting.getPermissionsState();
22872                return permissionsState.isPermissionReviewRequired(userId);
22873            }
22874        }
22875
22876        @Override
22877        public ApplicationInfo getApplicationInfo(String packageName, int userId) {
22878            return PackageManagerService.this.getApplicationInfo(packageName, 0 /*flags*/, userId);
22879        }
22880
22881        @Override
22882        public ComponentName getHomeActivitiesAsUser(List<ResolveInfo> allHomeCandidates,
22883                int userId) {
22884            return PackageManagerService.this.getHomeActivitiesAsUser(allHomeCandidates, userId);
22885        }
22886
22887        @Override
22888        public void setDeviceAndProfileOwnerPackages(
22889                int deviceOwnerUserId, String deviceOwnerPackage,
22890                SparseArray<String> profileOwnerPackages) {
22891            mProtectedPackages.setDeviceAndProfileOwnerPackages(
22892                    deviceOwnerUserId, deviceOwnerPackage, profileOwnerPackages);
22893        }
22894
22895        @Override
22896        public boolean isPackageDataProtected(int userId, String packageName) {
22897            return mProtectedPackages.isPackageDataProtected(userId, packageName);
22898        }
22899
22900        @Override
22901        public boolean isPackageEphemeral(int userId, String packageName) {
22902            synchronized (mPackages) {
22903                final PackageSetting ps = mSettings.mPackages.get(packageName);
22904                return ps != null ? ps.getInstantApp(userId) : false;
22905            }
22906        }
22907
22908        @Override
22909        public boolean wasPackageEverLaunched(String packageName, int userId) {
22910            synchronized (mPackages) {
22911                return mSettings.wasPackageEverLaunchedLPr(packageName, userId);
22912            }
22913        }
22914
22915        @Override
22916        public void grantRuntimePermission(String packageName, String name, int userId,
22917                boolean overridePolicy) {
22918            PackageManagerService.this.grantRuntimePermission(packageName, name, userId,
22919                    overridePolicy);
22920        }
22921
22922        @Override
22923        public void revokeRuntimePermission(String packageName, String name, int userId,
22924                boolean overridePolicy) {
22925            PackageManagerService.this.revokeRuntimePermission(packageName, name, userId,
22926                    overridePolicy);
22927        }
22928
22929        @Override
22930        public String getNameForUid(int uid) {
22931            return PackageManagerService.this.getNameForUid(uid);
22932        }
22933
22934        @Override
22935        public void requestInstantAppResolutionPhaseTwo(AuxiliaryResolveInfo responseObj,
22936                Intent origIntent, String resolvedType, String callingPackage, int userId) {
22937            PackageManagerService.this.requestInstantAppResolutionPhaseTwo(
22938                    responseObj, origIntent, resolvedType, callingPackage, userId);
22939        }
22940
22941        @Override
22942        public void grantEphemeralAccess(int userId, Intent intent,
22943                int targetAppId, int ephemeralAppId) {
22944            synchronized (mPackages) {
22945                mInstantAppRegistry.grantInstantAccessLPw(userId, intent,
22946                        targetAppId, ephemeralAppId);
22947            }
22948        }
22949
22950        @Override
22951        public void pruneInstantApps() {
22952            synchronized (mPackages) {
22953                mInstantAppRegistry.pruneInstantAppsLPw();
22954            }
22955        }
22956
22957        @Override
22958        public String getSetupWizardPackageName() {
22959            return mSetupWizardPackage;
22960        }
22961
22962        public void setExternalSourcesPolicy(ExternalSourcesPolicy policy) {
22963            if (policy != null) {
22964                mExternalSourcesPolicy = policy;
22965            }
22966        }
22967
22968        @Override
22969        public boolean isPackagePersistent(String packageName) {
22970            synchronized (mPackages) {
22971                PackageParser.Package pkg = mPackages.get(packageName);
22972                return pkg != null
22973                        ? ((pkg.applicationInfo.flags&(ApplicationInfo.FLAG_SYSTEM
22974                                        | ApplicationInfo.FLAG_PERSISTENT)) ==
22975                                (ApplicationInfo.FLAG_SYSTEM | ApplicationInfo.FLAG_PERSISTENT))
22976                        : false;
22977            }
22978        }
22979
22980        @Override
22981        public List<PackageInfo> getOverlayPackages(int userId) {
22982            final ArrayList<PackageInfo> overlayPackages = new ArrayList<PackageInfo>();
22983            synchronized (mPackages) {
22984                for (PackageParser.Package p : mPackages.values()) {
22985                    if (p.mOverlayTarget != null) {
22986                        PackageInfo pkg = generatePackageInfo((PackageSetting)p.mExtras, 0, userId);
22987                        if (pkg != null) {
22988                            overlayPackages.add(pkg);
22989                        }
22990                    }
22991                }
22992            }
22993            return overlayPackages;
22994        }
22995
22996        @Override
22997        public List<String> getTargetPackageNames(int userId) {
22998            List<String> targetPackages = new ArrayList<>();
22999            synchronized (mPackages) {
23000                for (PackageParser.Package p : mPackages.values()) {
23001                    if (p.mOverlayTarget == null) {
23002                        targetPackages.add(p.packageName);
23003                    }
23004                }
23005            }
23006            return targetPackages;
23007        }
23008
23009
23010        @Override
23011        public boolean setEnabledOverlayPackages(int userId, String targetPackageName,
23012                List<String> overlayPackageNames) {
23013            // TODO: implement when we integrate OMS properly
23014            return false;
23015        }
23016    }
23017
23018    @Override
23019    public void grantDefaultPermissionsToEnabledCarrierApps(String[] packageNames, int userId) {
23020        enforceSystemOrPhoneCaller("grantPermissionsToEnabledCarrierApps");
23021        synchronized (mPackages) {
23022            final long identity = Binder.clearCallingIdentity();
23023            try {
23024                mDefaultPermissionPolicy.grantDefaultPermissionsToEnabledCarrierAppsLPr(
23025                        packageNames, userId);
23026            } finally {
23027                Binder.restoreCallingIdentity(identity);
23028            }
23029        }
23030    }
23031
23032    @Override
23033    public void grantDefaultPermissionsToEnabledImsServices(String[] packageNames, int userId) {
23034        enforceSystemOrPhoneCaller("grantDefaultPermissionsToEnabledImsServices");
23035        synchronized (mPackages) {
23036            final long identity = Binder.clearCallingIdentity();
23037            try {
23038                mDefaultPermissionPolicy.grantDefaultPermissionsToEnabledImsServicesLPr(
23039                        packageNames, userId);
23040            } finally {
23041                Binder.restoreCallingIdentity(identity);
23042            }
23043        }
23044    }
23045
23046    private static void enforceSystemOrPhoneCaller(String tag) {
23047        int callingUid = Binder.getCallingUid();
23048        if (callingUid != Process.PHONE_UID && callingUid != Process.SYSTEM_UID) {
23049            throw new SecurityException(
23050                    "Cannot call " + tag + " from UID " + callingUid);
23051        }
23052    }
23053
23054    boolean isHistoricalPackageUsageAvailable() {
23055        return mPackageUsage.isHistoricalPackageUsageAvailable();
23056    }
23057
23058    /**
23059     * Return a <b>copy</b> of the collection of packages known to the package manager.
23060     * @return A copy of the values of mPackages.
23061     */
23062    Collection<PackageParser.Package> getPackages() {
23063        synchronized (mPackages) {
23064            return new ArrayList<>(mPackages.values());
23065        }
23066    }
23067
23068    /**
23069     * Logs process start information (including base APK hash) to the security log.
23070     * @hide
23071     */
23072    public void logAppProcessStartIfNeeded(String processName, int uid, String seinfo,
23073            String apkFile, int pid) {
23074        if (!SecurityLog.isLoggingEnabled()) {
23075            return;
23076        }
23077        Bundle data = new Bundle();
23078        data.putLong("startTimestamp", System.currentTimeMillis());
23079        data.putString("processName", processName);
23080        data.putInt("uid", uid);
23081        data.putString("seinfo", seinfo);
23082        data.putString("apkFile", apkFile);
23083        data.putInt("pid", pid);
23084        Message msg = mProcessLoggingHandler.obtainMessage(
23085                ProcessLoggingHandler.LOG_APP_PROCESS_START_MSG);
23086        msg.setData(data);
23087        mProcessLoggingHandler.sendMessage(msg);
23088    }
23089
23090    public CompilerStats.PackageStats getCompilerPackageStats(String pkgName) {
23091        return mCompilerStats.getPackageStats(pkgName);
23092    }
23093
23094    public CompilerStats.PackageStats getOrCreateCompilerPackageStats(PackageParser.Package pkg) {
23095        return getOrCreateCompilerPackageStats(pkg.packageName);
23096    }
23097
23098    public CompilerStats.PackageStats getOrCreateCompilerPackageStats(String pkgName) {
23099        return mCompilerStats.getOrCreatePackageStats(pkgName);
23100    }
23101
23102    public void deleteCompilerPackageStats(String pkgName) {
23103        mCompilerStats.deletePackageStats(pkgName);
23104    }
23105
23106    @Override
23107    public int getInstallReason(String packageName, int userId) {
23108        enforceCrossUserPermission(Binder.getCallingUid(), userId,
23109                true /* requireFullPermission */, false /* checkShell */,
23110                "get install reason");
23111        synchronized (mPackages) {
23112            final PackageSetting ps = mSettings.mPackages.get(packageName);
23113            if (ps != null) {
23114                return ps.getInstallReason(userId);
23115            }
23116        }
23117        return PackageManager.INSTALL_REASON_UNKNOWN;
23118    }
23119
23120    @Override
23121    public boolean canRequestPackageInstalls(String packageName, int userId) {
23122        int callingUid = Binder.getCallingUid();
23123        int uid = getPackageUid(packageName, 0, userId);
23124        if (callingUid != uid && callingUid != Process.ROOT_UID
23125                && callingUid != Process.SYSTEM_UID) {
23126            throw new SecurityException(
23127                    "Caller uid " + callingUid + " does not own package " + packageName);
23128        }
23129        ApplicationInfo info = getApplicationInfo(packageName, 0, userId);
23130        if (info == null) {
23131            return false;
23132        }
23133        if (info.targetSdkVersion < Build.VERSION_CODES.O) {
23134            throw new UnsupportedOperationException(
23135                    "Operation only supported on apps targeting Android O or higher");
23136        }
23137        String appOpPermission = Manifest.permission.REQUEST_INSTALL_PACKAGES;
23138        String[] packagesDeclaringPermission = getAppOpPermissionPackages(appOpPermission);
23139        if (!ArrayUtils.contains(packagesDeclaringPermission, packageName)) {
23140            throw new SecurityException("Need to declare " + appOpPermission + " to call this api");
23141        }
23142        if (sUserManager.hasUserRestriction(UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES, userId)) {
23143            return false;
23144        }
23145        if (mExternalSourcesPolicy != null) {
23146            int isTrusted = mExternalSourcesPolicy.getPackageTrustedToInstallApps(packageName, uid);
23147            if (isTrusted != PackageManagerInternal.ExternalSourcesPolicy.USER_DEFAULT) {
23148                return isTrusted == PackageManagerInternal.ExternalSourcesPolicy.USER_TRUSTED;
23149            }
23150        }
23151        return checkUidPermission(appOpPermission, uid) == PERMISSION_GRANTED;
23152    }
23153}
23154