PackageManagerService.java revision 2140cd6431266bdb17024c66bb93cf88ff7cc407
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    // List of APK paths to load for each user and package. This data is never
665    // persisted by the package manager. Instead, the overlay manager will
666    // ensure the data is up-to-date in runtime.
667    @GuardedBy("mPackages")
668    final SparseArray<ArrayMap<String, ArrayList<String>>> mEnabledOverlayPaths =
669        new SparseArray<ArrayMap<String, ArrayList<String>>>();
670
671    /**
672     * Tracks new system packages [received in an OTA] that we expect to
673     * find updated user-installed versions. Keys are package name, values
674     * are package location.
675     */
676    final private ArrayMap<String, File> mExpectingBetter = new ArrayMap<>();
677    /**
678     * Tracks high priority intent filters for protected actions. During boot, certain
679     * filter actions are protected and should never be allowed to have a high priority
680     * intent filter for them. However, there is one, and only one exception -- the
681     * setup wizard. It must be able to define a high priority intent filter for these
682     * actions to ensure there are no escapes from the wizard. We need to delay processing
683     * of these during boot as we need to look at all of the system packages in order
684     * to know which component is the setup wizard.
685     */
686    private final List<PackageParser.ActivityIntentInfo> mProtectedFilters = new ArrayList<>();
687    /**
688     * Whether or not processing protected filters should be deferred.
689     */
690    private boolean mDeferProtectedFilters = true;
691
692    /**
693     * Tracks existing system packages prior to receiving an OTA. Keys are package name.
694     */
695    final private ArraySet<String> mExistingSystemPackages = new ArraySet<>();
696    /**
697     * Whether or not system app permissions should be promoted from install to runtime.
698     */
699    boolean mPromoteSystemApps;
700
701    @GuardedBy("mPackages")
702    final Settings mSettings;
703
704    /**
705     * Set of package names that are currently "frozen", which means active
706     * surgery is being done on the code/data for that package. The platform
707     * will refuse to launch frozen packages to avoid race conditions.
708     *
709     * @see PackageFreezer
710     */
711    @GuardedBy("mPackages")
712    final ArraySet<String> mFrozenPackages = new ArraySet<>();
713
714    final ProtectedPackages mProtectedPackages;
715
716    boolean mFirstBoot;
717
718    PackageManagerInternal.ExternalSourcesPolicy mExternalSourcesPolicy;
719
720    // System configuration read by SystemConfig.
721    final int[] mGlobalGids;
722    final SparseArray<ArraySet<String>> mSystemPermissions;
723    @GuardedBy("mAvailableFeatures")
724    final ArrayMap<String, FeatureInfo> mAvailableFeatures;
725
726    // If mac_permissions.xml was found for seinfo labeling.
727    boolean mFoundPolicyFile;
728
729    private final InstantAppRegistry mInstantAppRegistry;
730
731    @GuardedBy("mPackages")
732    int mChangedPackagesSequenceNumber;
733    /**
734     * List of changed [installed, removed or updated] packages.
735     * mapping from user id -> sequence number -> package name
736     */
737    @GuardedBy("mPackages")
738    final SparseArray<SparseArray<String>> mChangedPackages = new SparseArray<>();
739    /**
740     * The sequence number of the last change to a package.
741     * mapping from user id -> package name -> sequence number
742     */
743    @GuardedBy("mPackages")
744    final SparseArray<Map<String, Integer>> mChangedPackagesSequenceNumbers = new SparseArray<>();
745
746    public static final class SharedLibraryEntry {
747        public final String path;
748        public final String apk;
749        public final SharedLibraryInfo info;
750
751        SharedLibraryEntry(String _path, String _apk, String name, int version, int type,
752                String declaringPackageName, int declaringPackageVersionCode) {
753            path = _path;
754            apk = _apk;
755            info = new SharedLibraryInfo(name, version, type, new VersionedPackage(
756                    declaringPackageName, declaringPackageVersionCode), null);
757        }
758    }
759
760    // Currently known shared libraries.
761    final ArrayMap<String, SparseArray<SharedLibraryEntry>> mSharedLibraries = new ArrayMap<>();
762    final ArrayMap<String, SparseArray<SharedLibraryEntry>> mStaticLibsByDeclaringPackage =
763            new ArrayMap<>();
764
765    // All available activities, for your resolving pleasure.
766    final ActivityIntentResolver mActivities =
767            new ActivityIntentResolver();
768
769    // All available receivers, for your resolving pleasure.
770    final ActivityIntentResolver mReceivers =
771            new ActivityIntentResolver();
772
773    // All available services, for your resolving pleasure.
774    final ServiceIntentResolver mServices = new ServiceIntentResolver();
775
776    // All available providers, for your resolving pleasure.
777    final ProviderIntentResolver mProviders = new ProviderIntentResolver();
778
779    // Mapping from provider base names (first directory in content URI codePath)
780    // to the provider information.
781    final ArrayMap<String, PackageParser.Provider> mProvidersByAuthority =
782            new ArrayMap<String, PackageParser.Provider>();
783
784    // Mapping from instrumentation class names to info about them.
785    final ArrayMap<ComponentName, PackageParser.Instrumentation> mInstrumentation =
786            new ArrayMap<ComponentName, PackageParser.Instrumentation>();
787
788    // Mapping from permission names to info about them.
789    final ArrayMap<String, PackageParser.PermissionGroup> mPermissionGroups =
790            new ArrayMap<String, PackageParser.PermissionGroup>();
791
792    // Packages whose data we have transfered into another package, thus
793    // should no longer exist.
794    final ArraySet<String> mTransferedPackages = new ArraySet<String>();
795
796    // Broadcast actions that are only available to the system.
797    final ArraySet<String> mProtectedBroadcasts = new ArraySet<String>();
798
799    /** List of packages waiting for verification. */
800    final SparseArray<PackageVerificationState> mPendingVerification
801            = new SparseArray<PackageVerificationState>();
802
803    /** Set of packages associated with each app op permission. */
804    final ArrayMap<String, ArraySet<String>> mAppOpPermissionPackages = new ArrayMap<>();
805
806    final PackageInstallerService mInstallerService;
807
808    private final PackageDexOptimizer mPackageDexOptimizer;
809    // DexManager handles the usage of dex files (e.g. secondary files, whether or not a package
810    // is used by other apps).
811    private final DexManager mDexManager;
812
813    private AtomicInteger mNextMoveId = new AtomicInteger();
814    private final MoveCallbacks mMoveCallbacks;
815
816    private final OnPermissionChangeListeners mOnPermissionChangeListeners;
817
818    // Cache of users who need badging.
819    SparseBooleanArray mUserNeedsBadging = new SparseBooleanArray();
820
821    /** Token for keys in mPendingVerification. */
822    private int mPendingVerificationToken = 0;
823
824    volatile boolean mSystemReady;
825    volatile boolean mSafeMode;
826    volatile boolean mHasSystemUidErrors;
827
828    ApplicationInfo mAndroidApplication;
829    final ActivityInfo mResolveActivity = new ActivityInfo();
830    final ResolveInfo mResolveInfo = new ResolveInfo();
831    ComponentName mResolveComponentName;
832    PackageParser.Package mPlatformPackage;
833    ComponentName mCustomResolverComponentName;
834
835    boolean mResolverReplaced = false;
836
837    private final @Nullable ComponentName mIntentFilterVerifierComponent;
838    private final @Nullable IntentFilterVerifier<ActivityIntentInfo> mIntentFilterVerifier;
839
840    private int mIntentFilterVerificationToken = 0;
841
842    /** The service connection to the ephemeral resolver */
843    final EphemeralResolverConnection mInstantAppResolverConnection;
844
845    /** Component used to install ephemeral applications */
846    ComponentName mInstantAppInstallerComponent;
847    final ActivityInfo mInstantAppInstallerActivity = new ActivityInfo();
848    final ResolveInfo mInstantAppInstallerInfo = new ResolveInfo();
849
850    final SparseArray<IntentFilterVerificationState> mIntentFilterVerificationStates
851            = new SparseArray<IntentFilterVerificationState>();
852
853    final DefaultPermissionGrantPolicy mDefaultPermissionPolicy;
854
855    // List of packages names to keep cached, even if they are uninstalled for all users
856    private List<String> mKeepUninstalledPackages;
857
858    private UserManagerInternal mUserManagerInternal;
859
860    private DeviceIdleController.LocalService mDeviceIdleController;
861
862    private File mCacheDir;
863
864    private ArraySet<String> mPrivappPermissionsViolations;
865
866    private Future<?> mPrepareAppDataFuture;
867
868    private static class IFVerificationParams {
869        PackageParser.Package pkg;
870        boolean replacing;
871        int userId;
872        int verifierUid;
873
874        public IFVerificationParams(PackageParser.Package _pkg, boolean _replacing,
875                int _userId, int _verifierUid) {
876            pkg = _pkg;
877            replacing = _replacing;
878            userId = _userId;
879            replacing = _replacing;
880            verifierUid = _verifierUid;
881        }
882    }
883
884    private interface IntentFilterVerifier<T extends IntentFilter> {
885        boolean addOneIntentFilterVerification(int verifierId, int userId, int verificationId,
886                                               T filter, String packageName);
887        void startVerifications(int userId);
888        void receiveVerificationResponse(int verificationId);
889    }
890
891    private class IntentVerifierProxy implements IntentFilterVerifier<ActivityIntentInfo> {
892        private Context mContext;
893        private ComponentName mIntentFilterVerifierComponent;
894        private ArrayList<Integer> mCurrentIntentFilterVerifications = new ArrayList<Integer>();
895
896        public IntentVerifierProxy(Context context, ComponentName verifierComponent) {
897            mContext = context;
898            mIntentFilterVerifierComponent = verifierComponent;
899        }
900
901        private String getDefaultScheme() {
902            return IntentFilter.SCHEME_HTTPS;
903        }
904
905        @Override
906        public void startVerifications(int userId) {
907            // Launch verifications requests
908            int count = mCurrentIntentFilterVerifications.size();
909            for (int n=0; n<count; n++) {
910                int verificationId = mCurrentIntentFilterVerifications.get(n);
911                final IntentFilterVerificationState ivs =
912                        mIntentFilterVerificationStates.get(verificationId);
913
914                String packageName = ivs.getPackageName();
915
916                ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters();
917                final int filterCount = filters.size();
918                ArraySet<String> domainsSet = new ArraySet<>();
919                for (int m=0; m<filterCount; m++) {
920                    PackageParser.ActivityIntentInfo filter = filters.get(m);
921                    domainsSet.addAll(filter.getHostsList());
922                }
923                synchronized (mPackages) {
924                    if (mSettings.createIntentFilterVerificationIfNeededLPw(
925                            packageName, domainsSet) != null) {
926                        scheduleWriteSettingsLocked();
927                    }
928                }
929                sendVerificationRequest(userId, verificationId, ivs);
930            }
931            mCurrentIntentFilterVerifications.clear();
932        }
933
934        private void sendVerificationRequest(int userId, int verificationId,
935                IntentFilterVerificationState ivs) {
936
937            Intent verificationIntent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION);
938            verificationIntent.putExtra(
939                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_ID,
940                    verificationId);
941            verificationIntent.putExtra(
942                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_URI_SCHEME,
943                    getDefaultScheme());
944            verificationIntent.putExtra(
945                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_HOSTS,
946                    ivs.getHostsString());
947            verificationIntent.putExtra(
948                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_PACKAGE_NAME,
949                    ivs.getPackageName());
950            verificationIntent.setComponent(mIntentFilterVerifierComponent);
951            verificationIntent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
952
953            UserHandle user = new UserHandle(userId);
954            mContext.sendBroadcastAsUser(verificationIntent, user);
955            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
956                    "Sending IntentFilter verification broadcast");
957        }
958
959        public void receiveVerificationResponse(int verificationId) {
960            IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId);
961
962            final boolean verified = ivs.isVerified();
963
964            ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters();
965            final int count = filters.size();
966            if (DEBUG_DOMAIN_VERIFICATION) {
967                Slog.i(TAG, "Received verification response " + verificationId
968                        + " for " + count + " filters, verified=" + verified);
969            }
970            for (int n=0; n<count; n++) {
971                PackageParser.ActivityIntentInfo filter = filters.get(n);
972                filter.setVerified(verified);
973
974                if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "IntentFilter " + filter.toString()
975                        + " verified with result:" + verified + " and hosts:"
976                        + ivs.getHostsString());
977            }
978
979            mIntentFilterVerificationStates.remove(verificationId);
980
981            final String packageName = ivs.getPackageName();
982            IntentFilterVerificationInfo ivi = null;
983
984            synchronized (mPackages) {
985                ivi = mSettings.getIntentFilterVerificationLPr(packageName);
986            }
987            if (ivi == null) {
988                Slog.w(TAG, "IntentFilterVerificationInfo not found for verificationId:"
989                        + verificationId + " packageName:" + packageName);
990                return;
991            }
992            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
993                    "Updating IntentFilterVerificationInfo for package " + packageName
994                            +" verificationId:" + verificationId);
995
996            synchronized (mPackages) {
997                if (verified) {
998                    ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS);
999                } else {
1000                    ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK);
1001                }
1002                scheduleWriteSettingsLocked();
1003
1004                final int userId = ivs.getUserId();
1005                if (userId != UserHandle.USER_ALL) {
1006                    final int userStatus =
1007                            mSettings.getIntentFilterVerificationStatusLPr(packageName, userId);
1008
1009                    int updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED;
1010                    boolean needUpdate = false;
1011
1012                    // We cannot override the STATUS_ALWAYS / STATUS_NEVER states if they have
1013                    // already been set by the User thru the Disambiguation dialog
1014                    switch (userStatus) {
1015                        case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED:
1016                            if (verified) {
1017                                updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS;
1018                            } else {
1019                                updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK;
1020                            }
1021                            needUpdate = true;
1022                            break;
1023
1024                        case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK:
1025                            if (verified) {
1026                                updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS;
1027                                needUpdate = true;
1028                            }
1029                            break;
1030
1031                        default:
1032                            // Nothing to do
1033                    }
1034
1035                    if (needUpdate) {
1036                        mSettings.updateIntentFilterVerificationStatusLPw(
1037                                packageName, updatedStatus, userId);
1038                        scheduleWritePackageRestrictionsLocked(userId);
1039                    }
1040                }
1041            }
1042        }
1043
1044        @Override
1045        public boolean addOneIntentFilterVerification(int verifierUid, int userId, int verificationId,
1046                    ActivityIntentInfo filter, String packageName) {
1047            if (!hasValidDomains(filter)) {
1048                return false;
1049            }
1050            IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId);
1051            if (ivs == null) {
1052                ivs = createDomainVerificationState(verifierUid, userId, verificationId,
1053                        packageName);
1054            }
1055            if (DEBUG_DOMAIN_VERIFICATION) {
1056                Slog.d(TAG, "Adding verification filter for " + packageName + ": " + filter);
1057            }
1058            ivs.addFilter(filter);
1059            return true;
1060        }
1061
1062        private IntentFilterVerificationState createDomainVerificationState(int verifierUid,
1063                int userId, int verificationId, String packageName) {
1064            IntentFilterVerificationState ivs = new IntentFilterVerificationState(
1065                    verifierUid, userId, packageName);
1066            ivs.setPendingState();
1067            synchronized (mPackages) {
1068                mIntentFilterVerificationStates.append(verificationId, ivs);
1069                mCurrentIntentFilterVerifications.add(verificationId);
1070            }
1071            return ivs;
1072        }
1073    }
1074
1075    private static boolean hasValidDomains(ActivityIntentInfo filter) {
1076        return filter.hasCategory(Intent.CATEGORY_BROWSABLE)
1077                && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) ||
1078                        filter.hasDataScheme(IntentFilter.SCHEME_HTTPS));
1079    }
1080
1081    // Set of pending broadcasts for aggregating enable/disable of components.
1082    static class PendingPackageBroadcasts {
1083        // for each user id, a map of <package name -> components within that package>
1084        final SparseArray<ArrayMap<String, ArrayList<String>>> mUidMap;
1085
1086        public PendingPackageBroadcasts() {
1087            mUidMap = new SparseArray<ArrayMap<String, ArrayList<String>>>(2);
1088        }
1089
1090        public ArrayList<String> get(int userId, String packageName) {
1091            ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId);
1092            return packages.get(packageName);
1093        }
1094
1095        public void put(int userId, String packageName, ArrayList<String> components) {
1096            ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId);
1097            packages.put(packageName, components);
1098        }
1099
1100        public void remove(int userId, String packageName) {
1101            ArrayMap<String, ArrayList<String>> packages = mUidMap.get(userId);
1102            if (packages != null) {
1103                packages.remove(packageName);
1104            }
1105        }
1106
1107        public void remove(int userId) {
1108            mUidMap.remove(userId);
1109        }
1110
1111        public int userIdCount() {
1112            return mUidMap.size();
1113        }
1114
1115        public int userIdAt(int n) {
1116            return mUidMap.keyAt(n);
1117        }
1118
1119        public ArrayMap<String, ArrayList<String>> packagesForUserId(int userId) {
1120            return mUidMap.get(userId);
1121        }
1122
1123        public int size() {
1124            // total number of pending broadcast entries across all userIds
1125            int num = 0;
1126            for (int i = 0; i< mUidMap.size(); i++) {
1127                num += mUidMap.valueAt(i).size();
1128            }
1129            return num;
1130        }
1131
1132        public void clear() {
1133            mUidMap.clear();
1134        }
1135
1136        private ArrayMap<String, ArrayList<String>> getOrAllocate(int userId) {
1137            ArrayMap<String, ArrayList<String>> map = mUidMap.get(userId);
1138            if (map == null) {
1139                map = new ArrayMap<String, ArrayList<String>>();
1140                mUidMap.put(userId, map);
1141            }
1142            return map;
1143        }
1144    }
1145    final PendingPackageBroadcasts mPendingBroadcasts = new PendingPackageBroadcasts();
1146
1147    // Service Connection to remote media container service to copy
1148    // package uri's from external media onto secure containers
1149    // or internal storage.
1150    private IMediaContainerService mContainerService = null;
1151
1152    static final int SEND_PENDING_BROADCAST = 1;
1153    static final int MCS_BOUND = 3;
1154    static final int END_COPY = 4;
1155    static final int INIT_COPY = 5;
1156    static final int MCS_UNBIND = 6;
1157    static final int START_CLEANING_PACKAGE = 7;
1158    static final int FIND_INSTALL_LOC = 8;
1159    static final int POST_INSTALL = 9;
1160    static final int MCS_RECONNECT = 10;
1161    static final int MCS_GIVE_UP = 11;
1162    static final int UPDATED_MEDIA_STATUS = 12;
1163    static final int WRITE_SETTINGS = 13;
1164    static final int WRITE_PACKAGE_RESTRICTIONS = 14;
1165    static final int PACKAGE_VERIFIED = 15;
1166    static final int CHECK_PENDING_VERIFICATION = 16;
1167    static final int START_INTENT_FILTER_VERIFICATIONS = 17;
1168    static final int INTENT_FILTER_VERIFIED = 18;
1169    static final int WRITE_PACKAGE_LIST = 19;
1170    static final int INSTANT_APP_RESOLUTION_PHASE_TWO = 20;
1171
1172    static final int WRITE_SETTINGS_DELAY = 10*1000;  // 10 seconds
1173
1174    // Delay time in millisecs
1175    static final int BROADCAST_DELAY = 10 * 1000;
1176
1177    static UserManagerService sUserManager;
1178
1179    // Stores a list of users whose package restrictions file needs to be updated
1180    private ArraySet<Integer> mDirtyUsers = new ArraySet<Integer>();
1181
1182    final private DefaultContainerConnection mDefContainerConn =
1183            new DefaultContainerConnection();
1184    class DefaultContainerConnection implements ServiceConnection {
1185        public void onServiceConnected(ComponentName name, IBinder service) {
1186            if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceConnected");
1187            final IMediaContainerService imcs = IMediaContainerService.Stub
1188                    .asInterface(Binder.allowBlocking(service));
1189            mHandler.sendMessage(mHandler.obtainMessage(MCS_BOUND, imcs));
1190        }
1191
1192        public void onServiceDisconnected(ComponentName name) {
1193            if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceDisconnected");
1194        }
1195    }
1196
1197    // Recordkeeping of restore-after-install operations that are currently in flight
1198    // between the Package Manager and the Backup Manager
1199    static class PostInstallData {
1200        public InstallArgs args;
1201        public PackageInstalledInfo res;
1202
1203        PostInstallData(InstallArgs _a, PackageInstalledInfo _r) {
1204            args = _a;
1205            res = _r;
1206        }
1207    }
1208
1209    final SparseArray<PostInstallData> mRunningInstalls = new SparseArray<PostInstallData>();
1210    int mNextInstallToken = 1;  // nonzero; will be wrapped back to 1 when ++ overflows
1211
1212    // XML tags for backup/restore of various bits of state
1213    private static final String TAG_PREFERRED_BACKUP = "pa";
1214    private static final String TAG_DEFAULT_APPS = "da";
1215    private static final String TAG_INTENT_FILTER_VERIFICATION = "iv";
1216
1217    private static final String TAG_PERMISSION_BACKUP = "perm-grant-backup";
1218    private static final String TAG_ALL_GRANTS = "rt-grants";
1219    private static final String TAG_GRANT = "grant";
1220    private static final String ATTR_PACKAGE_NAME = "pkg";
1221
1222    private static final String TAG_PERMISSION = "perm";
1223    private static final String ATTR_PERMISSION_NAME = "name";
1224    private static final String ATTR_IS_GRANTED = "g";
1225    private static final String ATTR_USER_SET = "set";
1226    private static final String ATTR_USER_FIXED = "fixed";
1227    private static final String ATTR_REVOKE_ON_UPGRADE = "rou";
1228
1229    // System/policy permission grants are not backed up
1230    private static final int SYSTEM_RUNTIME_GRANT_MASK =
1231            FLAG_PERMISSION_POLICY_FIXED
1232            | FLAG_PERMISSION_SYSTEM_FIXED
1233            | FLAG_PERMISSION_GRANTED_BY_DEFAULT;
1234
1235    // And we back up these user-adjusted states
1236    private static final int USER_RUNTIME_GRANT_MASK =
1237            FLAG_PERMISSION_USER_SET
1238            | FLAG_PERMISSION_USER_FIXED
1239            | FLAG_PERMISSION_REVOKE_ON_UPGRADE;
1240
1241    final @Nullable String mRequiredVerifierPackage;
1242    final @NonNull String mRequiredInstallerPackage;
1243    final @NonNull String mRequiredUninstallerPackage;
1244    final @Nullable String mSetupWizardPackage;
1245    final @Nullable String mStorageManagerPackage;
1246    final @NonNull String mServicesSystemSharedLibraryPackageName;
1247    final @NonNull String mSharedSystemSharedLibraryPackageName;
1248
1249    final boolean mPermissionReviewRequired;
1250
1251    private final PackageUsage mPackageUsage = new PackageUsage();
1252    private final CompilerStats mCompilerStats = new CompilerStats();
1253
1254    class PackageHandler extends Handler {
1255        private boolean mBound = false;
1256        final ArrayList<HandlerParams> mPendingInstalls =
1257            new ArrayList<HandlerParams>();
1258
1259        private boolean connectToService() {
1260            if (DEBUG_SD_INSTALL) Log.i(TAG, "Trying to bind to" +
1261                    " DefaultContainerService");
1262            Intent service = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
1263            Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1264            if (mContext.bindServiceAsUser(service, mDefContainerConn,
1265                    Context.BIND_AUTO_CREATE, UserHandle.SYSTEM)) {
1266                Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1267                mBound = true;
1268                return true;
1269            }
1270            Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1271            return false;
1272        }
1273
1274        private void disconnectService() {
1275            mContainerService = null;
1276            mBound = false;
1277            Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1278            mContext.unbindService(mDefContainerConn);
1279            Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1280        }
1281
1282        PackageHandler(Looper looper) {
1283            super(looper);
1284        }
1285
1286        public void handleMessage(Message msg) {
1287            try {
1288                doHandleMessage(msg);
1289            } finally {
1290                Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1291            }
1292        }
1293
1294        void doHandleMessage(Message msg) {
1295            switch (msg.what) {
1296                case INIT_COPY: {
1297                    HandlerParams params = (HandlerParams) msg.obj;
1298                    int idx = mPendingInstalls.size();
1299                    if (DEBUG_INSTALL) Slog.i(TAG, "init_copy idx=" + idx + ": " + params);
1300                    // If a bind was already initiated we dont really
1301                    // need to do anything. The pending install
1302                    // will be processed later on.
1303                    if (!mBound) {
1304                        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS",
1305                                System.identityHashCode(mHandler));
1306                        // If this is the only one pending we might
1307                        // have to bind to the service again.
1308                        if (!connectToService()) {
1309                            Slog.e(TAG, "Failed to bind to media container service");
1310                            params.serviceError();
1311                            Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS",
1312                                    System.identityHashCode(mHandler));
1313                            if (params.traceMethod != null) {
1314                                Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, params.traceMethod,
1315                                        params.traceCookie);
1316                            }
1317                            return;
1318                        } else {
1319                            // Once we bind to the service, the first
1320                            // pending request will be processed.
1321                            mPendingInstalls.add(idx, params);
1322                        }
1323                    } else {
1324                        mPendingInstalls.add(idx, params);
1325                        // Already bound to the service. Just make
1326                        // sure we trigger off processing the first request.
1327                        if (idx == 0) {
1328                            mHandler.sendEmptyMessage(MCS_BOUND);
1329                        }
1330                    }
1331                    break;
1332                }
1333                case MCS_BOUND: {
1334                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_bound");
1335                    if (msg.obj != null) {
1336                        mContainerService = (IMediaContainerService) msg.obj;
1337                        Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS",
1338                                System.identityHashCode(mHandler));
1339                    }
1340                    if (mContainerService == null) {
1341                        if (!mBound) {
1342                            // Something seriously wrong since we are not bound and we are not
1343                            // waiting for connection. Bail out.
1344                            Slog.e(TAG, "Cannot bind to media container service");
1345                            for (HandlerParams params : mPendingInstalls) {
1346                                // Indicate service bind error
1347                                params.serviceError();
1348                                Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1349                                        System.identityHashCode(params));
1350                                if (params.traceMethod != null) {
1351                                    Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER,
1352                                            params.traceMethod, params.traceCookie);
1353                                }
1354                                return;
1355                            }
1356                            mPendingInstalls.clear();
1357                        } else {
1358                            Slog.w(TAG, "Waiting to connect to media container service");
1359                        }
1360                    } else if (mPendingInstalls.size() > 0) {
1361                        HandlerParams params = mPendingInstalls.get(0);
1362                        if (params != null) {
1363                            Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1364                                    System.identityHashCode(params));
1365                            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "startCopy");
1366                            if (params.startCopy()) {
1367                                // We are done...  look for more work or to
1368                                // go idle.
1369                                if (DEBUG_SD_INSTALL) Log.i(TAG,
1370                                        "Checking for more work or unbind...");
1371                                // Delete pending install
1372                                if (mPendingInstalls.size() > 0) {
1373                                    mPendingInstalls.remove(0);
1374                                }
1375                                if (mPendingInstalls.size() == 0) {
1376                                    if (mBound) {
1377                                        if (DEBUG_SD_INSTALL) Log.i(TAG,
1378                                                "Posting delayed MCS_UNBIND");
1379                                        removeMessages(MCS_UNBIND);
1380                                        Message ubmsg = obtainMessage(MCS_UNBIND);
1381                                        // Unbind after a little delay, to avoid
1382                                        // continual thrashing.
1383                                        sendMessageDelayed(ubmsg, 10000);
1384                                    }
1385                                } else {
1386                                    // There are more pending requests in queue.
1387                                    // Just post MCS_BOUND message to trigger processing
1388                                    // of next pending install.
1389                                    if (DEBUG_SD_INSTALL) Log.i(TAG,
1390                                            "Posting MCS_BOUND for next work");
1391                                    mHandler.sendEmptyMessage(MCS_BOUND);
1392                                }
1393                            }
1394                            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
1395                        }
1396                    } else {
1397                        // Should never happen ideally.
1398                        Slog.w(TAG, "Empty queue");
1399                    }
1400                    break;
1401                }
1402                case MCS_RECONNECT: {
1403                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_reconnect");
1404                    if (mPendingInstalls.size() > 0) {
1405                        if (mBound) {
1406                            disconnectService();
1407                        }
1408                        if (!connectToService()) {
1409                            Slog.e(TAG, "Failed to bind to media container service");
1410                            for (HandlerParams params : mPendingInstalls) {
1411                                // Indicate service bind error
1412                                params.serviceError();
1413                                Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1414                                        System.identityHashCode(params));
1415                            }
1416                            mPendingInstalls.clear();
1417                        }
1418                    }
1419                    break;
1420                }
1421                case MCS_UNBIND: {
1422                    // If there is no actual work left, then time to unbind.
1423                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_unbind");
1424
1425                    if (mPendingInstalls.size() == 0 && mPendingVerification.size() == 0) {
1426                        if (mBound) {
1427                            if (DEBUG_INSTALL) Slog.i(TAG, "calling disconnectService()");
1428
1429                            disconnectService();
1430                        }
1431                    } else if (mPendingInstalls.size() > 0) {
1432                        // There are more pending requests in queue.
1433                        // Just post MCS_BOUND message to trigger processing
1434                        // of next pending install.
1435                        mHandler.sendEmptyMessage(MCS_BOUND);
1436                    }
1437
1438                    break;
1439                }
1440                case MCS_GIVE_UP: {
1441                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_giveup too many retries");
1442                    HandlerParams params = mPendingInstalls.remove(0);
1443                    Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1444                            System.identityHashCode(params));
1445                    break;
1446                }
1447                case SEND_PENDING_BROADCAST: {
1448                    String packages[];
1449                    ArrayList<String> components[];
1450                    int size = 0;
1451                    int uids[];
1452                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1453                    synchronized (mPackages) {
1454                        if (mPendingBroadcasts == null) {
1455                            return;
1456                        }
1457                        size = mPendingBroadcasts.size();
1458                        if (size <= 0) {
1459                            // Nothing to be done. Just return
1460                            return;
1461                        }
1462                        packages = new String[size];
1463                        components = new ArrayList[size];
1464                        uids = new int[size];
1465                        int i = 0;  // filling out the above arrays
1466
1467                        for (int n = 0; n < mPendingBroadcasts.userIdCount(); n++) {
1468                            int packageUserId = mPendingBroadcasts.userIdAt(n);
1469                            Iterator<Map.Entry<String, ArrayList<String>>> it
1470                                    = mPendingBroadcasts.packagesForUserId(packageUserId)
1471                                            .entrySet().iterator();
1472                            while (it.hasNext() && i < size) {
1473                                Map.Entry<String, ArrayList<String>> ent = it.next();
1474                                packages[i] = ent.getKey();
1475                                components[i] = ent.getValue();
1476                                PackageSetting ps = mSettings.mPackages.get(ent.getKey());
1477                                uids[i] = (ps != null)
1478                                        ? UserHandle.getUid(packageUserId, ps.appId)
1479                                        : -1;
1480                                i++;
1481                            }
1482                        }
1483                        size = i;
1484                        mPendingBroadcasts.clear();
1485                    }
1486                    // Send broadcasts
1487                    for (int i = 0; i < size; i++) {
1488                        sendPackageChangedBroadcast(packages[i], true, components[i], uids[i]);
1489                    }
1490                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1491                    break;
1492                }
1493                case START_CLEANING_PACKAGE: {
1494                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1495                    final String packageName = (String)msg.obj;
1496                    final int userId = msg.arg1;
1497                    final boolean andCode = msg.arg2 != 0;
1498                    synchronized (mPackages) {
1499                        if (userId == UserHandle.USER_ALL) {
1500                            int[] users = sUserManager.getUserIds();
1501                            for (int user : users) {
1502                                mSettings.addPackageToCleanLPw(
1503                                        new PackageCleanItem(user, packageName, andCode));
1504                            }
1505                        } else {
1506                            mSettings.addPackageToCleanLPw(
1507                                    new PackageCleanItem(userId, packageName, andCode));
1508                        }
1509                    }
1510                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1511                    startCleaningPackages();
1512                } break;
1513                case POST_INSTALL: {
1514                    if (DEBUG_INSTALL) Log.v(TAG, "Handling post-install for " + msg.arg1);
1515
1516                    PostInstallData data = mRunningInstalls.get(msg.arg1);
1517                    final boolean didRestore = (msg.arg2 != 0);
1518                    mRunningInstalls.delete(msg.arg1);
1519
1520                    if (data != null) {
1521                        InstallArgs args = data.args;
1522                        PackageInstalledInfo parentRes = data.res;
1523
1524                        final boolean grantPermissions = (args.installFlags
1525                                & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0;
1526                        final boolean killApp = (args.installFlags
1527                                & PackageManager.INSTALL_DONT_KILL_APP) == 0;
1528                        final String[] grantedPermissions = args.installGrantPermissions;
1529
1530                        // Handle the parent package
1531                        handlePackagePostInstall(parentRes, grantPermissions, killApp,
1532                                grantedPermissions, didRestore, args.installerPackageName,
1533                                args.observer);
1534
1535                        // Handle the child packages
1536                        final int childCount = (parentRes.addedChildPackages != null)
1537                                ? parentRes.addedChildPackages.size() : 0;
1538                        for (int i = 0; i < childCount; i++) {
1539                            PackageInstalledInfo childRes = parentRes.addedChildPackages.valueAt(i);
1540                            handlePackagePostInstall(childRes, grantPermissions, killApp,
1541                                    grantedPermissions, false, args.installerPackageName,
1542                                    args.observer);
1543                        }
1544
1545                        // Log tracing if needed
1546                        if (args.traceMethod != null) {
1547                            Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, args.traceMethod,
1548                                    args.traceCookie);
1549                        }
1550                    } else {
1551                        Slog.e(TAG, "Bogus post-install token " + msg.arg1);
1552                    }
1553
1554                    Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "postInstall", msg.arg1);
1555                } break;
1556                case UPDATED_MEDIA_STATUS: {
1557                    if (DEBUG_SD_INSTALL) Log.i(TAG, "Got message UPDATED_MEDIA_STATUS");
1558                    boolean reportStatus = msg.arg1 == 1;
1559                    boolean doGc = msg.arg2 == 1;
1560                    if (DEBUG_SD_INSTALL) Log.i(TAG, "reportStatus=" + reportStatus + ", doGc = " + doGc);
1561                    if (doGc) {
1562                        // Force a gc to clear up stale containers.
1563                        Runtime.getRuntime().gc();
1564                    }
1565                    if (msg.obj != null) {
1566                        @SuppressWarnings("unchecked")
1567                        Set<AsecInstallArgs> args = (Set<AsecInstallArgs>) msg.obj;
1568                        if (DEBUG_SD_INSTALL) Log.i(TAG, "Unloading all containers");
1569                        // Unload containers
1570                        unloadAllContainers(args);
1571                    }
1572                    if (reportStatus) {
1573                        try {
1574                            if (DEBUG_SD_INSTALL) Log.i(TAG,
1575                                    "Invoking StorageManagerService call back");
1576                            PackageHelper.getStorageManager().finishMediaUpdate();
1577                        } catch (RemoteException e) {
1578                            Log.e(TAG, "StorageManagerService not running?");
1579                        }
1580                    }
1581                } break;
1582                case WRITE_SETTINGS: {
1583                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1584                    synchronized (mPackages) {
1585                        removeMessages(WRITE_SETTINGS);
1586                        removeMessages(WRITE_PACKAGE_RESTRICTIONS);
1587                        mSettings.writeLPr();
1588                        mDirtyUsers.clear();
1589                    }
1590                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1591                } break;
1592                case WRITE_PACKAGE_RESTRICTIONS: {
1593                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1594                    synchronized (mPackages) {
1595                        removeMessages(WRITE_PACKAGE_RESTRICTIONS);
1596                        for (int userId : mDirtyUsers) {
1597                            mSettings.writePackageRestrictionsLPr(userId);
1598                        }
1599                        mDirtyUsers.clear();
1600                    }
1601                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1602                } break;
1603                case WRITE_PACKAGE_LIST: {
1604                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1605                    synchronized (mPackages) {
1606                        removeMessages(WRITE_PACKAGE_LIST);
1607                        mSettings.writePackageListLPr(msg.arg1);
1608                    }
1609                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1610                } break;
1611                case CHECK_PENDING_VERIFICATION: {
1612                    final int verificationId = msg.arg1;
1613                    final PackageVerificationState state = mPendingVerification.get(verificationId);
1614
1615                    if ((state != null) && !state.timeoutExtended()) {
1616                        final InstallArgs args = state.getInstallArgs();
1617                        final Uri originUri = Uri.fromFile(args.origin.resolvedFile);
1618
1619                        Slog.i(TAG, "Verification timed out for " + originUri);
1620                        mPendingVerification.remove(verificationId);
1621
1622                        int ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
1623
1624                        if (getDefaultVerificationResponse() == PackageManager.VERIFICATION_ALLOW) {
1625                            Slog.i(TAG, "Continuing with installation of " + originUri);
1626                            state.setVerifierResponse(Binder.getCallingUid(),
1627                                    PackageManager.VERIFICATION_ALLOW_WITHOUT_SUFFICIENT);
1628                            broadcastPackageVerified(verificationId, originUri,
1629                                    PackageManager.VERIFICATION_ALLOW,
1630                                    state.getInstallArgs().getUser());
1631                            try {
1632                                ret = args.copyApk(mContainerService, true);
1633                            } catch (RemoteException e) {
1634                                Slog.e(TAG, "Could not contact the ContainerService");
1635                            }
1636                        } else {
1637                            broadcastPackageVerified(verificationId, originUri,
1638                                    PackageManager.VERIFICATION_REJECT,
1639                                    state.getInstallArgs().getUser());
1640                        }
1641
1642                        Trace.asyncTraceEnd(
1643                                TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId);
1644
1645                        processPendingInstall(args, ret);
1646                        mHandler.sendEmptyMessage(MCS_UNBIND);
1647                    }
1648                    break;
1649                }
1650                case PACKAGE_VERIFIED: {
1651                    final int verificationId = msg.arg1;
1652
1653                    final PackageVerificationState state = mPendingVerification.get(verificationId);
1654                    if (state == null) {
1655                        Slog.w(TAG, "Invalid verification token " + verificationId + " received");
1656                        break;
1657                    }
1658
1659                    final PackageVerificationResponse response = (PackageVerificationResponse) msg.obj;
1660
1661                    state.setVerifierResponse(response.callerUid, response.code);
1662
1663                    if (state.isVerificationComplete()) {
1664                        mPendingVerification.remove(verificationId);
1665
1666                        final InstallArgs args = state.getInstallArgs();
1667                        final Uri originUri = Uri.fromFile(args.origin.resolvedFile);
1668
1669                        int ret;
1670                        if (state.isInstallAllowed()) {
1671                            ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
1672                            broadcastPackageVerified(verificationId, originUri,
1673                                    response.code, state.getInstallArgs().getUser());
1674                            try {
1675                                ret = args.copyApk(mContainerService, true);
1676                            } catch (RemoteException e) {
1677                                Slog.e(TAG, "Could not contact the ContainerService");
1678                            }
1679                        } else {
1680                            ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
1681                        }
1682
1683                        Trace.asyncTraceEnd(
1684                                TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId);
1685
1686                        processPendingInstall(args, ret);
1687                        mHandler.sendEmptyMessage(MCS_UNBIND);
1688                    }
1689
1690                    break;
1691                }
1692                case START_INTENT_FILTER_VERIFICATIONS: {
1693                    IFVerificationParams params = (IFVerificationParams) msg.obj;
1694                    verifyIntentFiltersIfNeeded(params.userId, params.verifierUid,
1695                            params.replacing, params.pkg);
1696                    break;
1697                }
1698                case INTENT_FILTER_VERIFIED: {
1699                    final int verificationId = msg.arg1;
1700
1701                    final IntentFilterVerificationState state = mIntentFilterVerificationStates.get(
1702                            verificationId);
1703                    if (state == null) {
1704                        Slog.w(TAG, "Invalid IntentFilter verification token "
1705                                + verificationId + " received");
1706                        break;
1707                    }
1708
1709                    final int userId = state.getUserId();
1710
1711                    if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1712                            "Processing IntentFilter verification with token:"
1713                            + verificationId + " and userId:" + userId);
1714
1715                    final IntentFilterVerificationResponse response =
1716                            (IntentFilterVerificationResponse) msg.obj;
1717
1718                    state.setVerifierResponse(response.callerUid, response.code);
1719
1720                    if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1721                            "IntentFilter verification with token:" + verificationId
1722                            + " and userId:" + userId
1723                            + " is settings verifier response with response code:"
1724                            + response.code);
1725
1726                    if (response.code == PackageManager.INTENT_FILTER_VERIFICATION_FAILURE) {
1727                        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Domains failing verification: "
1728                                + response.getFailedDomainsString());
1729                    }
1730
1731                    if (state.isVerificationComplete()) {
1732                        mIntentFilterVerifier.receiveVerificationResponse(verificationId);
1733                    } else {
1734                        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1735                                "IntentFilter verification with token:" + verificationId
1736                                + " was not said to be complete");
1737                    }
1738
1739                    break;
1740                }
1741                case INSTANT_APP_RESOLUTION_PHASE_TWO: {
1742                    EphemeralResolver.doEphemeralResolutionPhaseTwo(mContext,
1743                            mInstantAppResolverConnection,
1744                            (EphemeralRequest) msg.obj,
1745                            mInstantAppInstallerActivity,
1746                            mHandler);
1747                }
1748            }
1749        }
1750    }
1751
1752    private void handlePackagePostInstall(PackageInstalledInfo res, boolean grantPermissions,
1753            boolean killApp, String[] grantedPermissions,
1754            boolean launchedForRestore, String installerPackage,
1755            IPackageInstallObserver2 installObserver) {
1756        if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
1757            // Send the removed broadcasts
1758            if (res.removedInfo != null) {
1759                res.removedInfo.sendPackageRemovedBroadcasts(killApp);
1760            }
1761
1762            // Now that we successfully installed the package, grant runtime
1763            // permissions if requested before broadcasting the install. Also
1764            // for legacy apps in permission review mode we clear the permission
1765            // review flag which is used to emulate runtime permissions for
1766            // legacy apps.
1767            if (grantPermissions) {
1768                grantRequestedRuntimePermissions(res.pkg, res.newUsers, grantedPermissions);
1769            }
1770
1771            final boolean update = res.removedInfo != null
1772                    && res.removedInfo.removedPackage != null;
1773
1774            // If this is the first time we have child packages for a disabled privileged
1775            // app that had no children, we grant requested runtime permissions to the new
1776            // children if the parent on the system image had them already granted.
1777            if (res.pkg.parentPackage != null) {
1778                synchronized (mPackages) {
1779                    grantRuntimePermissionsGrantedToDisabledPrivSysPackageParentLPw(res.pkg);
1780                }
1781            }
1782
1783            synchronized (mPackages) {
1784                mInstantAppRegistry.onPackageInstalledLPw(res.pkg, res.newUsers);
1785            }
1786
1787            final String packageName = res.pkg.applicationInfo.packageName;
1788
1789            // Determine the set of users who are adding this package for
1790            // the first time vs. those who are seeing an update.
1791            int[] firstUsers = EMPTY_INT_ARRAY;
1792            int[] updateUsers = EMPTY_INT_ARRAY;
1793            final boolean allNewUsers = res.origUsers == null || res.origUsers.length == 0;
1794            final PackageSetting ps = (PackageSetting) res.pkg.mExtras;
1795            for (int newUser : res.newUsers) {
1796                if (ps.getInstantApp(newUser)) {
1797                    continue;
1798                }
1799                if (allNewUsers) {
1800                    firstUsers = ArrayUtils.appendInt(firstUsers, newUser);
1801                    continue;
1802                }
1803                boolean isNew = true;
1804                for (int origUser : res.origUsers) {
1805                    if (origUser == newUser) {
1806                        isNew = false;
1807                        break;
1808                    }
1809                }
1810                if (isNew) {
1811                    firstUsers = ArrayUtils.appendInt(firstUsers, newUser);
1812                } else {
1813                    updateUsers = ArrayUtils.appendInt(updateUsers, newUser);
1814                }
1815            }
1816
1817            // Send installed broadcasts if the package is not a static shared lib.
1818            if (res.pkg.staticSharedLibName == null) {
1819                mProcessLoggingHandler.invalidateProcessLoggingBaseApkHash(res.pkg.baseCodePath);
1820
1821                // Send added for users that see the package for the first time
1822                // sendPackageAddedForNewUsers also deals with system apps
1823                int appId = UserHandle.getAppId(res.uid);
1824                boolean isSystem = res.pkg.applicationInfo.isSystemApp();
1825                sendPackageAddedForNewUsers(packageName, isSystem, appId, firstUsers);
1826
1827                // Send added for users that don't see the package for the first time
1828                Bundle extras = new Bundle(1);
1829                extras.putInt(Intent.EXTRA_UID, res.uid);
1830                if (update) {
1831                    extras.putBoolean(Intent.EXTRA_REPLACING, true);
1832                }
1833                sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName,
1834                        extras, 0 /*flags*/, null /*targetPackage*/,
1835                        null /*finishedReceiver*/, updateUsers);
1836
1837                // Send replaced for users that don't see the package for the first time
1838                if (update) {
1839                    sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED,
1840                            packageName, extras, 0 /*flags*/,
1841                            null /*targetPackage*/, null /*finishedReceiver*/,
1842                            updateUsers);
1843                    sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED,
1844                            null /*package*/, null /*extras*/, 0 /*flags*/,
1845                            packageName /*targetPackage*/,
1846                            null /*finishedReceiver*/, updateUsers);
1847                } else if (launchedForRestore && !isSystemApp(res.pkg)) {
1848                    // First-install and we did a restore, so we're responsible for the
1849                    // first-launch broadcast.
1850                    if (DEBUG_BACKUP) {
1851                        Slog.i(TAG, "Post-restore of " + packageName
1852                                + " sending FIRST_LAUNCH in " + Arrays.toString(firstUsers));
1853                    }
1854                    sendFirstLaunchBroadcast(packageName, installerPackage, firstUsers);
1855                }
1856
1857                // Send broadcast package appeared if forward locked/external for all users
1858                // treat asec-hosted packages like removable media on upgrade
1859                if (res.pkg.isForwardLocked() || isExternal(res.pkg)) {
1860                    if (DEBUG_INSTALL) {
1861                        Slog.i(TAG, "upgrading pkg " + res.pkg
1862                                + " is ASEC-hosted -> AVAILABLE");
1863                    }
1864                    final int[] uidArray = new int[]{res.pkg.applicationInfo.uid};
1865                    ArrayList<String> pkgList = new ArrayList<>(1);
1866                    pkgList.add(packageName);
1867                    sendResourcesChangedBroadcast(true, true, pkgList, uidArray, null);
1868                }
1869            }
1870
1871            // Work that needs to happen on first install within each user
1872            if (firstUsers != null && firstUsers.length > 0) {
1873                synchronized (mPackages) {
1874                    for (int userId : firstUsers) {
1875                        // If this app is a browser and it's newly-installed for some
1876                        // users, clear any default-browser state in those users. The
1877                        // app's nature doesn't depend on the user, so we can just check
1878                        // its browser nature in any user and generalize.
1879                        if (packageIsBrowser(packageName, userId)) {
1880                            mSettings.setDefaultBrowserPackageNameLPw(null, userId);
1881                        }
1882
1883                        // We may also need to apply pending (restored) runtime
1884                        // permission grants within these users.
1885                        mSettings.applyPendingPermissionGrantsLPw(packageName, userId);
1886                    }
1887                }
1888            }
1889
1890            // Log current value of "unknown sources" setting
1891            EventLog.writeEvent(EventLogTags.UNKNOWN_SOURCES_ENABLED,
1892                    getUnknownSourcesSettings());
1893
1894            // Force a gc to clear up things
1895            Runtime.getRuntime().gc();
1896
1897            // Remove the replaced package's older resources safely now
1898            // We delete after a gc for applications  on sdcard.
1899            if (res.removedInfo != null && res.removedInfo.args != null) {
1900                synchronized (mInstallLock) {
1901                    res.removedInfo.args.doPostDeleteLI(true);
1902                }
1903            }
1904
1905            // Notify DexManager that the package was installed for new users.
1906            // The updated users should already be indexed and the package code paths
1907            // should not change.
1908            // Don't notify the manager for ephemeral apps as they are not expected to
1909            // survive long enough to benefit of background optimizations.
1910            for (int userId : firstUsers) {
1911                PackageInfo info = getPackageInfo(packageName, /*flags*/ 0, userId);
1912                mDexManager.notifyPackageInstalled(info, userId);
1913            }
1914        }
1915
1916        // If someone is watching installs - notify them
1917        if (installObserver != null) {
1918            try {
1919                Bundle extras = extrasForInstallResult(res);
1920                installObserver.onPackageInstalled(res.name, res.returnCode,
1921                        res.returnMsg, extras);
1922            } catch (RemoteException e) {
1923                Slog.i(TAG, "Observer no longer exists.");
1924            }
1925        }
1926    }
1927
1928    private void grantRuntimePermissionsGrantedToDisabledPrivSysPackageParentLPw(
1929            PackageParser.Package pkg) {
1930        if (pkg.parentPackage == null) {
1931            return;
1932        }
1933        if (pkg.requestedPermissions == null) {
1934            return;
1935        }
1936        final PackageSetting disabledSysParentPs = mSettings
1937                .getDisabledSystemPkgLPr(pkg.parentPackage.packageName);
1938        if (disabledSysParentPs == null || disabledSysParentPs.pkg == null
1939                || !disabledSysParentPs.isPrivileged()
1940                || (disabledSysParentPs.childPackageNames != null
1941                        && !disabledSysParentPs.childPackageNames.isEmpty())) {
1942            return;
1943        }
1944        final int[] allUserIds = sUserManager.getUserIds();
1945        final int permCount = pkg.requestedPermissions.size();
1946        for (int i = 0; i < permCount; i++) {
1947            String permission = pkg.requestedPermissions.get(i);
1948            BasePermission bp = mSettings.mPermissions.get(permission);
1949            if (bp == null || !(bp.isRuntime() || bp.isDevelopment())) {
1950                continue;
1951            }
1952            for (int userId : allUserIds) {
1953                if (disabledSysParentPs.getPermissionsState().hasRuntimePermission(
1954                        permission, userId)) {
1955                    grantRuntimePermission(pkg.packageName, permission, userId);
1956                }
1957            }
1958        }
1959    }
1960
1961    private StorageEventListener mStorageListener = new StorageEventListener() {
1962        @Override
1963        public void onVolumeStateChanged(VolumeInfo vol, int oldState, int newState) {
1964            if (vol.type == VolumeInfo.TYPE_PRIVATE) {
1965                if (vol.state == VolumeInfo.STATE_MOUNTED) {
1966                    final String volumeUuid = vol.getFsUuid();
1967
1968                    // Clean up any users or apps that were removed or recreated
1969                    // while this volume was missing
1970                    sUserManager.reconcileUsers(volumeUuid);
1971                    reconcileApps(volumeUuid);
1972
1973                    // Clean up any install sessions that expired or were
1974                    // cancelled while this volume was missing
1975                    mInstallerService.onPrivateVolumeMounted(volumeUuid);
1976
1977                    loadPrivatePackages(vol);
1978
1979                } else if (vol.state == VolumeInfo.STATE_EJECTING) {
1980                    unloadPrivatePackages(vol);
1981                }
1982            }
1983
1984            if (vol.type == VolumeInfo.TYPE_PUBLIC && vol.isPrimary()) {
1985                if (vol.state == VolumeInfo.STATE_MOUNTED) {
1986                    updateExternalMediaStatus(true, false);
1987                } else if (vol.state == VolumeInfo.STATE_EJECTING) {
1988                    updateExternalMediaStatus(false, false);
1989                }
1990            }
1991        }
1992
1993        @Override
1994        public void onVolumeForgotten(String fsUuid) {
1995            if (TextUtils.isEmpty(fsUuid)) {
1996                Slog.e(TAG, "Forgetting internal storage is probably a mistake; ignoring");
1997                return;
1998            }
1999
2000            // Remove any apps installed on the forgotten volume
2001            synchronized (mPackages) {
2002                final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(fsUuid);
2003                for (PackageSetting ps : packages) {
2004                    Slog.d(TAG, "Destroying " + ps.name + " because volume was forgotten");
2005                    deletePackageVersioned(new VersionedPackage(ps.name,
2006                            PackageManager.VERSION_CODE_HIGHEST),
2007                            new LegacyPackageDeleteObserver(null).getBinder(),
2008                            UserHandle.USER_SYSTEM, PackageManager.DELETE_ALL_USERS);
2009                    // Try very hard to release any references to this package
2010                    // so we don't risk the system server being killed due to
2011                    // open FDs
2012                    AttributeCache.instance().removePackage(ps.name);
2013                }
2014
2015                mSettings.onVolumeForgotten(fsUuid);
2016                mSettings.writeLPr();
2017            }
2018        }
2019    };
2020
2021    private void grantRequestedRuntimePermissions(PackageParser.Package pkg, int[] userIds,
2022            String[] grantedPermissions) {
2023        for (int userId : userIds) {
2024            grantRequestedRuntimePermissionsForUser(pkg, userId, grantedPermissions);
2025        }
2026    }
2027
2028    private void grantRequestedRuntimePermissionsForUser(PackageParser.Package pkg, int userId,
2029            String[] grantedPermissions) {
2030        SettingBase sb = (SettingBase) pkg.mExtras;
2031        if (sb == null) {
2032            return;
2033        }
2034
2035        PermissionsState permissionsState = sb.getPermissionsState();
2036
2037        final int immutableFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED
2038                | PackageManager.FLAG_PERMISSION_POLICY_FIXED;
2039
2040        final boolean supportsRuntimePermissions = pkg.applicationInfo.targetSdkVersion
2041                >= Build.VERSION_CODES.M;
2042
2043        for (String permission : pkg.requestedPermissions) {
2044            final BasePermission bp;
2045            synchronized (mPackages) {
2046                bp = mSettings.mPermissions.get(permission);
2047            }
2048            if (bp != null && (bp.isRuntime() || bp.isDevelopment())
2049                    && (grantedPermissions == null
2050                           || ArrayUtils.contains(grantedPermissions, permission))) {
2051                final int flags = permissionsState.getPermissionFlags(permission, userId);
2052                if (supportsRuntimePermissions) {
2053                    // Installer cannot change immutable permissions.
2054                    if ((flags & immutableFlags) == 0) {
2055                        grantRuntimePermission(pkg.packageName, permission, userId);
2056                    }
2057                } else if (mPermissionReviewRequired) {
2058                    // In permission review mode we clear the review flag when we
2059                    // are asked to install the app with all permissions granted.
2060                    if ((flags & PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED) != 0) {
2061                        updatePermissionFlags(permission, pkg.packageName,
2062                                PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED, 0, userId);
2063                    }
2064                }
2065            }
2066        }
2067    }
2068
2069    Bundle extrasForInstallResult(PackageInstalledInfo res) {
2070        Bundle extras = null;
2071        switch (res.returnCode) {
2072            case PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION: {
2073                extras = new Bundle();
2074                extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PERMISSION,
2075                        res.origPermission);
2076                extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PACKAGE,
2077                        res.origPackage);
2078                break;
2079            }
2080            case PackageManager.INSTALL_SUCCEEDED: {
2081                extras = new Bundle();
2082                extras.putBoolean(Intent.EXTRA_REPLACING,
2083                        res.removedInfo != null && res.removedInfo.removedPackage != null);
2084                break;
2085            }
2086        }
2087        return extras;
2088    }
2089
2090    void scheduleWriteSettingsLocked() {
2091        if (!mHandler.hasMessages(WRITE_SETTINGS)) {
2092            mHandler.sendEmptyMessageDelayed(WRITE_SETTINGS, WRITE_SETTINGS_DELAY);
2093        }
2094    }
2095
2096    void scheduleWritePackageListLocked(int userId) {
2097        if (!mHandler.hasMessages(WRITE_PACKAGE_LIST)) {
2098            Message msg = mHandler.obtainMessage(WRITE_PACKAGE_LIST);
2099            msg.arg1 = userId;
2100            mHandler.sendMessageDelayed(msg, WRITE_SETTINGS_DELAY);
2101        }
2102    }
2103
2104    void scheduleWritePackageRestrictionsLocked(UserHandle user) {
2105        final int userId = user == null ? UserHandle.USER_ALL : user.getIdentifier();
2106        scheduleWritePackageRestrictionsLocked(userId);
2107    }
2108
2109    void scheduleWritePackageRestrictionsLocked(int userId) {
2110        final int[] userIds = (userId == UserHandle.USER_ALL)
2111                ? sUserManager.getUserIds() : new int[]{userId};
2112        for (int nextUserId : userIds) {
2113            if (!sUserManager.exists(nextUserId)) return;
2114            mDirtyUsers.add(nextUserId);
2115            if (!mHandler.hasMessages(WRITE_PACKAGE_RESTRICTIONS)) {
2116                mHandler.sendEmptyMessageDelayed(WRITE_PACKAGE_RESTRICTIONS, WRITE_SETTINGS_DELAY);
2117            }
2118        }
2119    }
2120
2121    public static PackageManagerService main(Context context, Installer installer,
2122            boolean factoryTest, boolean onlyCore) {
2123        // Self-check for initial settings.
2124        PackageManagerServiceCompilerMapping.checkProperties();
2125
2126        PackageManagerService m = new PackageManagerService(context, installer,
2127                factoryTest, onlyCore);
2128        m.enableSystemUserPackages();
2129        ServiceManager.addService("package", m);
2130        return m;
2131    }
2132
2133    private void enableSystemUserPackages() {
2134        if (!UserManager.isSplitSystemUser()) {
2135            return;
2136        }
2137        // For system user, enable apps based on the following conditions:
2138        // - app is whitelisted or belong to one of these groups:
2139        //   -- system app which has no launcher icons
2140        //   -- system app which has INTERACT_ACROSS_USERS permission
2141        //   -- system IME app
2142        // - app is not in the blacklist
2143        AppsQueryHelper queryHelper = new AppsQueryHelper(this);
2144        Set<String> enableApps = new ArraySet<>();
2145        enableApps.addAll(queryHelper.queryApps(AppsQueryHelper.GET_NON_LAUNCHABLE_APPS
2146                | AppsQueryHelper.GET_APPS_WITH_INTERACT_ACROSS_USERS_PERM
2147                | AppsQueryHelper.GET_IMES, /* systemAppsOnly */ true, UserHandle.SYSTEM));
2148        ArraySet<String> wlApps = SystemConfig.getInstance().getSystemUserWhitelistedApps();
2149        enableApps.addAll(wlApps);
2150        enableApps.addAll(queryHelper.queryApps(AppsQueryHelper.GET_REQUIRED_FOR_SYSTEM_USER,
2151                /* systemAppsOnly */ false, UserHandle.SYSTEM));
2152        ArraySet<String> blApps = SystemConfig.getInstance().getSystemUserBlacklistedApps();
2153        enableApps.removeAll(blApps);
2154        Log.i(TAG, "Applications installed for system user: " + enableApps);
2155        List<String> allAps = queryHelper.queryApps(0, /* systemAppsOnly */ false,
2156                UserHandle.SYSTEM);
2157        final int allAppsSize = allAps.size();
2158        synchronized (mPackages) {
2159            for (int i = 0; i < allAppsSize; i++) {
2160                String pName = allAps.get(i);
2161                PackageSetting pkgSetting = mSettings.mPackages.get(pName);
2162                // Should not happen, but we shouldn't be failing if it does
2163                if (pkgSetting == null) {
2164                    continue;
2165                }
2166                boolean install = enableApps.contains(pName);
2167                if (pkgSetting.getInstalled(UserHandle.USER_SYSTEM) != install) {
2168                    Log.i(TAG, (install ? "Installing " : "Uninstalling ") + pName
2169                            + " for system user");
2170                    pkgSetting.setInstalled(install, UserHandle.USER_SYSTEM);
2171                }
2172            }
2173            scheduleWritePackageRestrictionsLocked(UserHandle.USER_SYSTEM);
2174        }
2175    }
2176
2177    private static void getDefaultDisplayMetrics(Context context, DisplayMetrics metrics) {
2178        DisplayManager displayManager = (DisplayManager) context.getSystemService(
2179                Context.DISPLAY_SERVICE);
2180        displayManager.getDisplay(Display.DEFAULT_DISPLAY).getMetrics(metrics);
2181    }
2182
2183    /**
2184     * Requests that files preopted on a secondary system partition be copied to the data partition
2185     * if possible.  Note that the actual copying of the files is accomplished by init for security
2186     * reasons. This simply requests that the copy takes place and awaits confirmation of its
2187     * completion. See platform/system/extras/cppreopt/ for the implementation of the actual copy.
2188     */
2189    private static void requestCopyPreoptedFiles() {
2190        final int WAIT_TIME_MS = 100;
2191        final String CP_PREOPT_PROPERTY = "sys.cppreopt";
2192        if (SystemProperties.getInt("ro.cp_system_other_odex", 0) == 1) {
2193            SystemProperties.set(CP_PREOPT_PROPERTY, "requested");
2194            // We will wait for up to 100 seconds.
2195            final long timeStart = SystemClock.uptimeMillis();
2196            final long timeEnd = timeStart + 100 * 1000;
2197            long timeNow = timeStart;
2198            while (!SystemProperties.get(CP_PREOPT_PROPERTY).equals("finished")) {
2199                try {
2200                    Thread.sleep(WAIT_TIME_MS);
2201                } catch (InterruptedException e) {
2202                    // Do nothing
2203                }
2204                timeNow = SystemClock.uptimeMillis();
2205                if (timeNow > timeEnd) {
2206                    SystemProperties.set(CP_PREOPT_PROPERTY, "timed-out");
2207                    Slog.wtf(TAG, "cppreopt did not finish!");
2208                    break;
2209                }
2210            }
2211
2212            Slog.i(TAG, "cppreopts took " + (timeNow - timeStart) + " ms");
2213        }
2214    }
2215
2216    public PackageManagerService(Context context, Installer installer,
2217            boolean factoryTest, boolean onlyCore) {
2218        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "create package manager");
2219        EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_START,
2220                SystemClock.uptimeMillis());
2221
2222        if (mSdkVersion <= 0) {
2223            Slog.w(TAG, "**** ro.build.version.sdk not set!");
2224        }
2225
2226        mContext = context;
2227
2228        mPermissionReviewRequired = context.getResources().getBoolean(
2229                R.bool.config_permissionReviewRequired);
2230
2231        mFactoryTest = factoryTest;
2232        mOnlyCore = onlyCore;
2233        mMetrics = new DisplayMetrics();
2234        mSettings = new Settings(mPackages);
2235        mSettings.addSharedUserLPw("android.uid.system", Process.SYSTEM_UID,
2236                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2237        mSettings.addSharedUserLPw("android.uid.phone", RADIO_UID,
2238                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2239        mSettings.addSharedUserLPw("android.uid.log", LOG_UID,
2240                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2241        mSettings.addSharedUserLPw("android.uid.nfc", NFC_UID,
2242                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2243        mSettings.addSharedUserLPw("android.uid.bluetooth", BLUETOOTH_UID,
2244                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2245        mSettings.addSharedUserLPw("android.uid.shell", SHELL_UID,
2246                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2247
2248        String separateProcesses = SystemProperties.get("debug.separate_processes");
2249        if (separateProcesses != null && separateProcesses.length() > 0) {
2250            if ("*".equals(separateProcesses)) {
2251                mDefParseFlags = PackageParser.PARSE_IGNORE_PROCESSES;
2252                mSeparateProcesses = null;
2253                Slog.w(TAG, "Running with debug.separate_processes: * (ALL)");
2254            } else {
2255                mDefParseFlags = 0;
2256                mSeparateProcesses = separateProcesses.split(",");
2257                Slog.w(TAG, "Running with debug.separate_processes: "
2258                        + separateProcesses);
2259            }
2260        } else {
2261            mDefParseFlags = 0;
2262            mSeparateProcesses = null;
2263        }
2264
2265        mInstaller = installer;
2266        mPackageDexOptimizer = new PackageDexOptimizer(installer, mInstallLock, context,
2267                "*dexopt*");
2268        mDexManager = new DexManager(this, mPackageDexOptimizer, installer, mInstallLock);
2269        mMoveCallbacks = new MoveCallbacks(FgThread.get().getLooper());
2270
2271        mOnPermissionChangeListeners = new OnPermissionChangeListeners(
2272                FgThread.get().getLooper());
2273
2274        getDefaultDisplayMetrics(context, mMetrics);
2275
2276        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "get system config");
2277        SystemConfig systemConfig = SystemConfig.getInstance();
2278        mGlobalGids = systemConfig.getGlobalGids();
2279        mSystemPermissions = systemConfig.getSystemPermissions();
2280        mAvailableFeatures = systemConfig.getAvailableFeatures();
2281        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
2282
2283        mProtectedPackages = new ProtectedPackages(mContext);
2284
2285        synchronized (mInstallLock) {
2286        // writer
2287        synchronized (mPackages) {
2288            mHandlerThread = new ServiceThread(TAG,
2289                    Process.THREAD_PRIORITY_BACKGROUND, true /*allowIo*/);
2290            mHandlerThread.start();
2291            mHandler = new PackageHandler(mHandlerThread.getLooper());
2292            mProcessLoggingHandler = new ProcessLoggingHandler();
2293            Watchdog.getInstance().addThread(mHandler, WATCHDOG_TIMEOUT);
2294
2295            mDefaultPermissionPolicy = new DefaultPermissionGrantPolicy(this);
2296            mInstantAppRegistry = new InstantAppRegistry(this);
2297
2298            File dataDir = Environment.getDataDirectory();
2299            mAppInstallDir = new File(dataDir, "app");
2300            mAppLib32InstallDir = new File(dataDir, "app-lib");
2301            mAsecInternalPath = new File(dataDir, "app-asec").getPath();
2302            mDrmAppPrivateInstallDir = new File(dataDir, "app-private");
2303            sUserManager = new UserManagerService(context, this,
2304                    new UserDataPreparer(mInstaller, mInstallLock, mContext, mOnlyCore), mPackages);
2305
2306            // Propagate permission configuration in to package manager.
2307            ArrayMap<String, SystemConfig.PermissionEntry> permConfig
2308                    = systemConfig.getPermissions();
2309            for (int i=0; i<permConfig.size(); i++) {
2310                SystemConfig.PermissionEntry perm = permConfig.valueAt(i);
2311                BasePermission bp = mSettings.mPermissions.get(perm.name);
2312                if (bp == null) {
2313                    bp = new BasePermission(perm.name, "android", BasePermission.TYPE_BUILTIN);
2314                    mSettings.mPermissions.put(perm.name, bp);
2315                }
2316                if (perm.gids != null) {
2317                    bp.setGids(perm.gids, perm.perUser);
2318                }
2319            }
2320
2321            ArrayMap<String, String> libConfig = systemConfig.getSharedLibraries();
2322            final int builtInLibCount = libConfig.size();
2323            for (int i = 0; i < builtInLibCount; i++) {
2324                String name = libConfig.keyAt(i);
2325                String path = libConfig.valueAt(i);
2326                addSharedLibraryLPw(path, null, name, SharedLibraryInfo.VERSION_UNDEFINED,
2327                        SharedLibraryInfo.TYPE_BUILTIN, PLATFORM_PACKAGE_NAME, 0);
2328            }
2329
2330            mFoundPolicyFile = SELinuxMMAC.readInstallPolicy();
2331
2332            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "read user settings");
2333            mFirstBoot = !mSettings.readLPw(sUserManager.getUsers(false));
2334            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
2335
2336            // Clean up orphaned packages for which the code path doesn't exist
2337            // and they are an update to a system app - caused by bug/32321269
2338            final int packageSettingCount = mSettings.mPackages.size();
2339            for (int i = packageSettingCount - 1; i >= 0; i--) {
2340                PackageSetting ps = mSettings.mPackages.valueAt(i);
2341                if (!isExternal(ps) && (ps.codePath == null || !ps.codePath.exists())
2342                        && mSettings.getDisabledSystemPkgLPr(ps.name) != null) {
2343                    mSettings.mPackages.removeAt(i);
2344                    mSettings.enableSystemPackageLPw(ps.name);
2345                }
2346            }
2347
2348            if (mFirstBoot) {
2349                requestCopyPreoptedFiles();
2350            }
2351
2352            String customResolverActivity = Resources.getSystem().getString(
2353                    R.string.config_customResolverActivity);
2354            if (TextUtils.isEmpty(customResolverActivity)) {
2355                customResolverActivity = null;
2356            } else {
2357                mCustomResolverComponentName = ComponentName.unflattenFromString(
2358                        customResolverActivity);
2359            }
2360
2361            long startTime = SystemClock.uptimeMillis();
2362
2363            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SYSTEM_SCAN_START,
2364                    startTime);
2365
2366            final String bootClassPath = System.getenv("BOOTCLASSPATH");
2367            final String systemServerClassPath = System.getenv("SYSTEMSERVERCLASSPATH");
2368
2369            if (bootClassPath == null) {
2370                Slog.w(TAG, "No BOOTCLASSPATH found!");
2371            }
2372
2373            if (systemServerClassPath == null) {
2374                Slog.w(TAG, "No SYSTEMSERVERCLASSPATH found!");
2375            }
2376
2377            final List<String> allInstructionSets = InstructionSets.getAllInstructionSets();
2378            final String[] dexCodeInstructionSets =
2379                    getDexCodeInstructionSets(
2380                            allInstructionSets.toArray(new String[allInstructionSets.size()]));
2381
2382            /**
2383             * Ensure all external libraries have had dexopt run on them.
2384             */
2385            if (mSharedLibraries.size() > 0) {
2386                Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt");
2387                // NOTE: For now, we're compiling these system "shared libraries"
2388                // (and framework jars) into all available architectures. It's possible
2389                // to compile them only when we come across an app that uses them (there's
2390                // already logic for that in scanPackageLI) but that adds some complexity.
2391                for (String dexCodeInstructionSet : dexCodeInstructionSets) {
2392                    final int libCount = mSharedLibraries.size();
2393                    for (int i = 0; i < libCount; i++) {
2394                        SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.valueAt(i);
2395                        final int versionCount = versionedLib.size();
2396                        for (int j = 0; j < versionCount; j++) {
2397                            SharedLibraryEntry libEntry = versionedLib.valueAt(j);
2398                            final String libPath = libEntry.path != null
2399                                    ? libEntry.path : libEntry.apk;
2400                            if (libPath == null) {
2401                                continue;
2402                            }
2403                            try {
2404                                // Shared libraries do not have profiles so we perform a full
2405                                // AOT compilation (if needed).
2406                                int dexoptNeeded = DexFile.getDexOptNeeded(
2407                                        libPath, dexCodeInstructionSet,
2408                                        getCompilerFilterForReason(REASON_SHARED_APK),
2409                                        false /* newProfile */);
2410                                if (dexoptNeeded != DexFile.NO_DEXOPT_NEEDED) {
2411                                    mInstaller.dexopt(libPath, Process.SYSTEM_UID, "*",
2412                                            dexCodeInstructionSet, dexoptNeeded, null,
2413                                            DEXOPT_PUBLIC,
2414                                            getCompilerFilterForReason(REASON_SHARED_APK),
2415                                            StorageManager.UUID_PRIVATE_INTERNAL,
2416                                            PackageDexOptimizer.SKIP_SHARED_LIBRARY_CHECK);
2417                                }
2418                            } catch (FileNotFoundException e) {
2419                                Slog.w(TAG, "Library not found: " + libPath);
2420                            } catch (IOException | InstallerException e) {
2421                                Slog.w(TAG, "Cannot dexopt " + libPath + "; is it an APK or JAR? "
2422                                        + e.getMessage());
2423                            }
2424                        }
2425                    }
2426                }
2427                Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
2428            }
2429
2430            File frameworkDir = new File(Environment.getRootDirectory(), "framework");
2431
2432            final VersionInfo ver = mSettings.getInternalVersion();
2433            mIsUpgrade = !Build.FINGERPRINT.equals(ver.fingerprint);
2434
2435            // when upgrading from pre-M, promote system app permissions from install to runtime
2436            mPromoteSystemApps =
2437                    mIsUpgrade && ver.sdkVersion <= Build.VERSION_CODES.LOLLIPOP_MR1;
2438
2439            // When upgrading from pre-N, we need to handle package extraction like first boot,
2440            // as there is no profiling data available.
2441            mIsPreNUpgrade = mIsUpgrade && ver.sdkVersion < Build.VERSION_CODES.N;
2442
2443            mIsPreNMR1Upgrade = mIsUpgrade && ver.sdkVersion < Build.VERSION_CODES.N_MR1;
2444
2445            // save off the names of pre-existing system packages prior to scanning; we don't
2446            // want to automatically grant runtime permissions for new system apps
2447            if (mPromoteSystemApps) {
2448                Iterator<PackageSetting> pkgSettingIter = mSettings.mPackages.values().iterator();
2449                while (pkgSettingIter.hasNext()) {
2450                    PackageSetting ps = pkgSettingIter.next();
2451                    if (isSystemApp(ps)) {
2452                        mExistingSystemPackages.add(ps.name);
2453                    }
2454                }
2455            }
2456
2457            mCacheDir = preparePackageParserCache(mIsUpgrade);
2458
2459            // Set flag to monitor and not change apk file paths when
2460            // scanning install directories.
2461            int scanFlags = SCAN_BOOTING | SCAN_INITIAL;
2462
2463            if (mIsUpgrade || mFirstBoot) {
2464                scanFlags = scanFlags | SCAN_FIRST_BOOT_OR_UPGRADE;
2465            }
2466
2467            // Collect vendor overlay packages. (Do this before scanning any apps.)
2468            // For security and version matching reason, only consider
2469            // overlay packages if they reside in the right directory.
2470            String overlayThemeDir = SystemProperties.get(VENDOR_OVERLAY_THEME_PERSIST_PROPERTY);
2471            if (overlayThemeDir.isEmpty()) {
2472                overlayThemeDir = SystemProperties.get(VENDOR_OVERLAY_THEME_PROPERTY);
2473            }
2474            if (!overlayThemeDir.isEmpty()) {
2475                scanDirTracedLI(new File(VENDOR_OVERLAY_DIR, overlayThemeDir), mDefParseFlags
2476                        | PackageParser.PARSE_IS_SYSTEM
2477                        | PackageParser.PARSE_IS_SYSTEM_DIR
2478                        | PackageParser.PARSE_TRUSTED_OVERLAY, scanFlags | SCAN_TRUSTED_OVERLAY, 0);
2479            }
2480            scanDirTracedLI(new File(VENDOR_OVERLAY_DIR), mDefParseFlags
2481                    | PackageParser.PARSE_IS_SYSTEM
2482                    | PackageParser.PARSE_IS_SYSTEM_DIR
2483                    | PackageParser.PARSE_TRUSTED_OVERLAY, scanFlags | SCAN_TRUSTED_OVERLAY, 0);
2484
2485            // Find base frameworks (resource packages without code).
2486            scanDirTracedLI(frameworkDir, mDefParseFlags
2487                    | PackageParser.PARSE_IS_SYSTEM
2488                    | PackageParser.PARSE_IS_SYSTEM_DIR
2489                    | PackageParser.PARSE_IS_PRIVILEGED,
2490                    scanFlags | SCAN_NO_DEX, 0);
2491
2492            // Collected privileged system packages.
2493            final File privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app");
2494            scanDirTracedLI(privilegedAppDir, mDefParseFlags
2495                    | PackageParser.PARSE_IS_SYSTEM
2496                    | PackageParser.PARSE_IS_SYSTEM_DIR
2497                    | PackageParser.PARSE_IS_PRIVILEGED, scanFlags, 0);
2498
2499            // Collect ordinary system packages.
2500            final File systemAppDir = new File(Environment.getRootDirectory(), "app");
2501            scanDirTracedLI(systemAppDir, mDefParseFlags
2502                    | PackageParser.PARSE_IS_SYSTEM
2503                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
2504
2505            // Collect all vendor packages.
2506            File vendorAppDir = new File("/vendor/app");
2507            try {
2508                vendorAppDir = vendorAppDir.getCanonicalFile();
2509            } catch (IOException e) {
2510                // failed to look up canonical path, continue with original one
2511            }
2512            scanDirTracedLI(vendorAppDir, mDefParseFlags
2513                    | PackageParser.PARSE_IS_SYSTEM
2514                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
2515
2516            // Collect all OEM packages.
2517            final File oemAppDir = new File(Environment.getOemDirectory(), "app");
2518            scanDirTracedLI(oemAppDir, mDefParseFlags
2519                    | PackageParser.PARSE_IS_SYSTEM
2520                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
2521
2522            // Prune any system packages that no longer exist.
2523            final List<String> possiblyDeletedUpdatedSystemApps = new ArrayList<String>();
2524            if (!mOnlyCore) {
2525                Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator();
2526                while (psit.hasNext()) {
2527                    PackageSetting ps = psit.next();
2528
2529                    /*
2530                     * If this is not a system app, it can't be a
2531                     * disable system app.
2532                     */
2533                    if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0) {
2534                        continue;
2535                    }
2536
2537                    /*
2538                     * If the package is scanned, it's not erased.
2539                     */
2540                    final PackageParser.Package scannedPkg = mPackages.get(ps.name);
2541                    if (scannedPkg != null) {
2542                        /*
2543                         * If the system app is both scanned and in the
2544                         * disabled packages list, then it must have been
2545                         * added via OTA. Remove it from the currently
2546                         * scanned package so the previously user-installed
2547                         * application can be scanned.
2548                         */
2549                        if (mSettings.isDisabledSystemPackageLPr(ps.name)) {
2550                            logCriticalInfo(Log.WARN, "Expecting better updated system app for "
2551                                    + ps.name + "; removing system app.  Last known codePath="
2552                                    + ps.codePathString + ", installStatus=" + ps.installStatus
2553                                    + ", versionCode=" + ps.versionCode + "; scanned versionCode="
2554                                    + scannedPkg.mVersionCode);
2555                            removePackageLI(scannedPkg, true);
2556                            mExpectingBetter.put(ps.name, ps.codePath);
2557                        }
2558
2559                        continue;
2560                    }
2561
2562                    if (!mSettings.isDisabledSystemPackageLPr(ps.name)) {
2563                        psit.remove();
2564                        logCriticalInfo(Log.WARN, "System package " + ps.name
2565                                + " no longer exists; it's data will be wiped");
2566                        // Actual deletion of code and data will be handled by later
2567                        // reconciliation step
2568                    } else {
2569                        final PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(ps.name);
2570                        if (disabledPs.codePath == null || !disabledPs.codePath.exists()) {
2571                            possiblyDeletedUpdatedSystemApps.add(ps.name);
2572                        }
2573                    }
2574                }
2575            }
2576
2577            //look for any incomplete package installations
2578            ArrayList<PackageSetting> deletePkgsList = mSettings.getListOfIncompleteInstallPackagesLPr();
2579            for (int i = 0; i < deletePkgsList.size(); i++) {
2580                // Actual deletion of code and data will be handled by later
2581                // reconciliation step
2582                final String packageName = deletePkgsList.get(i).name;
2583                logCriticalInfo(Log.WARN, "Cleaning up incompletely installed app: " + packageName);
2584                synchronized (mPackages) {
2585                    mSettings.removePackageLPw(packageName);
2586                }
2587            }
2588
2589            //delete tmp files
2590            deleteTempPackageFiles();
2591
2592            // Remove any shared userIDs that have no associated packages
2593            mSettings.pruneSharedUsersLPw();
2594
2595            if (!mOnlyCore) {
2596                EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_DATA_SCAN_START,
2597                        SystemClock.uptimeMillis());
2598                scanDirTracedLI(mAppInstallDir, 0, scanFlags | SCAN_REQUIRE_KNOWN, 0);
2599
2600                scanDirTracedLI(mDrmAppPrivateInstallDir, mDefParseFlags
2601                        | PackageParser.PARSE_FORWARD_LOCK,
2602                        scanFlags | SCAN_REQUIRE_KNOWN, 0);
2603
2604                /**
2605                 * Remove disable package settings for any updated system
2606                 * apps that were removed via an OTA. If they're not a
2607                 * previously-updated app, remove them completely.
2608                 * Otherwise, just revoke their system-level permissions.
2609                 */
2610                for (String deletedAppName : possiblyDeletedUpdatedSystemApps) {
2611                    PackageParser.Package deletedPkg = mPackages.get(deletedAppName);
2612                    mSettings.removeDisabledSystemPackageLPw(deletedAppName);
2613
2614                    String msg;
2615                    if (deletedPkg == null) {
2616                        msg = "Updated system package " + deletedAppName
2617                                + " no longer exists; it's data will be wiped";
2618                        // Actual deletion of code and data will be handled by later
2619                        // reconciliation step
2620                    } else {
2621                        msg = "Updated system app + " + deletedAppName
2622                                + " no longer present; removing system privileges for "
2623                                + deletedAppName;
2624
2625                        deletedPkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_SYSTEM;
2626
2627                        PackageSetting deletedPs = mSettings.mPackages.get(deletedAppName);
2628                        deletedPs.pkgFlags &= ~ApplicationInfo.FLAG_SYSTEM;
2629                    }
2630                    logCriticalInfo(Log.WARN, msg);
2631                }
2632
2633                /**
2634                 * Make sure all system apps that we expected to appear on
2635                 * the userdata partition actually showed up. If they never
2636                 * appeared, crawl back and revive the system version.
2637                 */
2638                for (int i = 0; i < mExpectingBetter.size(); i++) {
2639                    final String packageName = mExpectingBetter.keyAt(i);
2640                    if (!mPackages.containsKey(packageName)) {
2641                        final File scanFile = mExpectingBetter.valueAt(i);
2642
2643                        logCriticalInfo(Log.WARN, "Expected better " + packageName
2644                                + " but never showed up; reverting to system");
2645
2646                        int reparseFlags = mDefParseFlags;
2647                        if (FileUtils.contains(privilegedAppDir, scanFile)) {
2648                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2649                                    | PackageParser.PARSE_IS_SYSTEM_DIR
2650                                    | PackageParser.PARSE_IS_PRIVILEGED;
2651                        } else if (FileUtils.contains(systemAppDir, scanFile)) {
2652                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2653                                    | PackageParser.PARSE_IS_SYSTEM_DIR;
2654                        } else if (FileUtils.contains(vendorAppDir, scanFile)) {
2655                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2656                                    | PackageParser.PARSE_IS_SYSTEM_DIR;
2657                        } else if (FileUtils.contains(oemAppDir, scanFile)) {
2658                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2659                                    | PackageParser.PARSE_IS_SYSTEM_DIR;
2660                        } else {
2661                            Slog.e(TAG, "Ignoring unexpected fallback path " + scanFile);
2662                            continue;
2663                        }
2664
2665                        mSettings.enableSystemPackageLPw(packageName);
2666
2667                        try {
2668                            scanPackageTracedLI(scanFile, reparseFlags, scanFlags, 0, null);
2669                        } catch (PackageManagerException e) {
2670                            Slog.e(TAG, "Failed to parse original system package: "
2671                                    + e.getMessage());
2672                        }
2673                    }
2674                }
2675            }
2676            mExpectingBetter.clear();
2677
2678            // Resolve the storage manager.
2679            mStorageManagerPackage = getStorageManagerPackageName();
2680
2681            // Resolve protected action filters. Only the setup wizard is allowed to
2682            // have a high priority filter for these actions.
2683            mSetupWizardPackage = getSetupWizardPackageName();
2684            if (mProtectedFilters.size() > 0) {
2685                if (DEBUG_FILTERS && mSetupWizardPackage == null) {
2686                    Slog.i(TAG, "No setup wizard;"
2687                        + " All protected intents capped to priority 0");
2688                }
2689                for (ActivityIntentInfo filter : mProtectedFilters) {
2690                    if (filter.activity.info.packageName.equals(mSetupWizardPackage)) {
2691                        if (DEBUG_FILTERS) {
2692                            Slog.i(TAG, "Found setup wizard;"
2693                                + " allow priority " + filter.getPriority() + ";"
2694                                + " package: " + filter.activity.info.packageName
2695                                + " activity: " + filter.activity.className
2696                                + " priority: " + filter.getPriority());
2697                        }
2698                        // skip setup wizard; allow it to keep the high priority filter
2699                        continue;
2700                    }
2701                    Slog.w(TAG, "Protected action; cap priority to 0;"
2702                            + " package: " + filter.activity.info.packageName
2703                            + " activity: " + filter.activity.className
2704                            + " origPrio: " + filter.getPriority());
2705                    filter.setPriority(0);
2706                }
2707            }
2708            mDeferProtectedFilters = false;
2709            mProtectedFilters.clear();
2710
2711            // Now that we know all of the shared libraries, update all clients to have
2712            // the correct library paths.
2713            updateAllSharedLibrariesLPw(null);
2714
2715            for (SharedUserSetting setting : mSettings.getAllSharedUsersLPw()) {
2716                // NOTE: We ignore potential failures here during a system scan (like
2717                // the rest of the commands above) because there's precious little we
2718                // can do about it. A settings error is reported, though.
2719                adjustCpuAbisForSharedUserLPw(setting.packages, null /*scannedPackage*/);
2720            }
2721
2722            // Now that we know all the packages we are keeping,
2723            // read and update their last usage times.
2724            mPackageUsage.read(mPackages);
2725            mCompilerStats.read();
2726
2727            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SCAN_END,
2728                    SystemClock.uptimeMillis());
2729            Slog.i(TAG, "Time to scan packages: "
2730                    + ((SystemClock.uptimeMillis()-startTime)/1000f)
2731                    + " seconds");
2732
2733            // If the platform SDK has changed since the last time we booted,
2734            // we need to re-grant app permission to catch any new ones that
2735            // appear.  This is really a hack, and means that apps can in some
2736            // cases get permissions that the user didn't initially explicitly
2737            // allow...  it would be nice to have some better way to handle
2738            // this situation.
2739            int updateFlags = UPDATE_PERMISSIONS_ALL;
2740            if (ver.sdkVersion != mSdkVersion) {
2741                Slog.i(TAG, "Platform changed from " + ver.sdkVersion + " to "
2742                        + mSdkVersion + "; regranting permissions for internal storage");
2743                updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL;
2744            }
2745            updatePermissionsLPw(null, null, StorageManager.UUID_PRIVATE_INTERNAL, updateFlags);
2746            ver.sdkVersion = mSdkVersion;
2747
2748            // If this is the first boot or an update from pre-M, and it is a normal
2749            // boot, then we need to initialize the default preferred apps across
2750            // all defined users.
2751            if (!onlyCore && (mPromoteSystemApps || mFirstBoot)) {
2752                for (UserInfo user : sUserManager.getUsers(true)) {
2753                    mSettings.applyDefaultPreferredAppsLPw(this, user.id);
2754                    applyFactoryDefaultBrowserLPw(user.id);
2755                    primeDomainVerificationsLPw(user.id);
2756                }
2757            }
2758
2759            // Prepare storage for system user really early during boot,
2760            // since core system apps like SettingsProvider and SystemUI
2761            // can't wait for user to start
2762            final int storageFlags;
2763            if (StorageManager.isFileEncryptedNativeOrEmulated()) {
2764                storageFlags = StorageManager.FLAG_STORAGE_DE;
2765            } else {
2766                storageFlags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
2767            }
2768            List<String> deferPackages = reconcileAppsDataLI(StorageManager.UUID_PRIVATE_INTERNAL,
2769                    UserHandle.USER_SYSTEM, storageFlags, true /* migrateAppData */,
2770                    true /* onlyCoreApps */);
2771            mPrepareAppDataFuture = SystemServerInitThreadPool.get().submit(() -> {
2772                if (deferPackages == null || deferPackages.isEmpty()) {
2773                    return;
2774                }
2775                int count = 0;
2776                for (String pkgName : deferPackages) {
2777                    PackageParser.Package pkg = null;
2778                    synchronized (mPackages) {
2779                        PackageSetting ps = mSettings.getPackageLPr(pkgName);
2780                        if (ps != null && ps.getInstalled(UserHandle.USER_SYSTEM)) {
2781                            pkg = ps.pkg;
2782                        }
2783                    }
2784                    if (pkg != null) {
2785                        synchronized (mInstallLock) {
2786                            prepareAppDataAndMigrateLIF(pkg, UserHandle.USER_SYSTEM, storageFlags,
2787                                    true /* maybeMigrateAppData */);
2788                        }
2789                        count++;
2790                    }
2791                }
2792                Slog.i(TAG, "Deferred reconcileAppsData finished " + count + " packages");
2793            }, "prepareAppData");
2794
2795            // If this is first boot after an OTA, and a normal boot, then
2796            // we need to clear code cache directories.
2797            // Note that we do *not* clear the application profiles. These remain valid
2798            // across OTAs and are used to drive profile verification (post OTA) and
2799            // profile compilation (without waiting to collect a fresh set of profiles).
2800            if (mIsUpgrade && !onlyCore) {
2801                Slog.i(TAG, "Build fingerprint changed; clearing code caches");
2802                for (int i = 0; i < mSettings.mPackages.size(); i++) {
2803                    final PackageSetting ps = mSettings.mPackages.valueAt(i);
2804                    if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, ps.volumeUuid)) {
2805                        // No apps are running this early, so no need to freeze
2806                        clearAppDataLIF(ps.pkg, UserHandle.USER_ALL,
2807                                StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE
2808                                        | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
2809                    }
2810                }
2811                ver.fingerprint = Build.FINGERPRINT;
2812            }
2813
2814            checkDefaultBrowser();
2815
2816            // clear only after permissions and other defaults have been updated
2817            mExistingSystemPackages.clear();
2818            mPromoteSystemApps = false;
2819
2820            // All the changes are done during package scanning.
2821            ver.databaseVersion = Settings.CURRENT_DATABASE_VERSION;
2822
2823            // can downgrade to reader
2824            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "write settings");
2825            mSettings.writeLPr();
2826            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
2827
2828            // Perform dexopt on all apps that mark themselves as coreApps. We do this pretty
2829            // early on (before the package manager declares itself as early) because other
2830            // components in the system server might ask for package contexts for these apps.
2831            //
2832            // Note that "onlyCore" in this context means the system is encrypted or encrypting
2833            // (i.e, that the data partition is unavailable).
2834            if ((isFirstBoot() || isUpgrade() || VMRuntime.didPruneDalvikCache()) && !onlyCore) {
2835                long start = System.nanoTime();
2836                List<PackageParser.Package> coreApps = new ArrayList<>();
2837                for (PackageParser.Package pkg : mPackages.values()) {
2838                    if (pkg.coreApp) {
2839                        coreApps.add(pkg);
2840                    }
2841                }
2842
2843                int[] stats = performDexOptUpgrade(coreApps, false,
2844                        getCompilerFilterForReason(REASON_CORE_APP));
2845
2846                final int elapsedTimeSeconds =
2847                        (int) TimeUnit.NANOSECONDS.toSeconds(System.nanoTime() - start);
2848                MetricsLogger.histogram(mContext, "opt_coreapps_time_s", elapsedTimeSeconds);
2849
2850                if (DEBUG_DEXOPT) {
2851                    Slog.i(TAG, "Dex-opt core apps took : " + elapsedTimeSeconds + " seconds (" +
2852                            stats[0] + ", " + stats[1] + ", " + stats[2] + ")");
2853                }
2854
2855
2856                // TODO: Should we log these stats to tron too ?
2857                // MetricsLogger.histogram(mContext, "opt_coreapps_num_dexopted", stats[0]);
2858                // MetricsLogger.histogram(mContext, "opt_coreapps_num_skipped", stats[1]);
2859                // MetricsLogger.histogram(mContext, "opt_coreapps_num_failed", stats[2]);
2860                // MetricsLogger.histogram(mContext, "opt_coreapps_num_total", coreApps.size());
2861            }
2862
2863            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_READY,
2864                    SystemClock.uptimeMillis());
2865
2866            if (!mOnlyCore) {
2867                mRequiredVerifierPackage = getRequiredButNotReallyRequiredVerifierLPr();
2868                mRequiredInstallerPackage = getRequiredInstallerLPr();
2869                mRequiredUninstallerPackage = getRequiredUninstallerLPr();
2870                mIntentFilterVerifierComponent = getIntentFilterVerifierComponentNameLPr();
2871                mIntentFilterVerifier = new IntentVerifierProxy(mContext,
2872                        mIntentFilterVerifierComponent);
2873                mServicesSystemSharedLibraryPackageName = getRequiredSharedLibraryLPr(
2874                        PackageManager.SYSTEM_SHARED_LIBRARY_SERVICES,
2875                        SharedLibraryInfo.VERSION_UNDEFINED);
2876                mSharedSystemSharedLibraryPackageName = getRequiredSharedLibraryLPr(
2877                        PackageManager.SYSTEM_SHARED_LIBRARY_SHARED,
2878                        SharedLibraryInfo.VERSION_UNDEFINED);
2879            } else {
2880                mRequiredVerifierPackage = null;
2881                mRequiredInstallerPackage = null;
2882                mRequiredUninstallerPackage = null;
2883                mIntentFilterVerifierComponent = null;
2884                mIntentFilterVerifier = null;
2885                mServicesSystemSharedLibraryPackageName = null;
2886                mSharedSystemSharedLibraryPackageName = null;
2887            }
2888
2889            mInstallerService = new PackageInstallerService(context, this);
2890
2891            final ComponentName ephemeralResolverComponent = getEphemeralResolverLPr();
2892            if (ephemeralResolverComponent != null) {
2893                if (DEBUG_EPHEMERAL) {
2894                    Slog.i(TAG, "Ephemeral resolver: " + ephemeralResolverComponent);
2895                }
2896                mInstantAppResolverConnection =
2897                        new EphemeralResolverConnection(mContext, ephemeralResolverComponent);
2898            } else {
2899                mInstantAppResolverConnection = null;
2900            }
2901            mInstantAppInstallerComponent = getEphemeralInstallerLPr();
2902            if (mInstantAppInstallerComponent != null) {
2903                if (DEBUG_EPHEMERAL) {
2904                    Slog.i(TAG, "Ephemeral installer: " + mInstantAppInstallerComponent);
2905                }
2906                setUpInstantAppInstallerActivityLP(mInstantAppInstallerComponent);
2907            }
2908
2909            // Read and update the usage of dex files.
2910            // Do this at the end of PM init so that all the packages have their
2911            // data directory reconciled.
2912            // At this point we know the code paths of the packages, so we can validate
2913            // the disk file and build the internal cache.
2914            // The usage file is expected to be small so loading and verifying it
2915            // should take a fairly small time compare to the other activities (e.g. package
2916            // scanning).
2917            final Map<Integer, List<PackageInfo>> userPackages = new HashMap<>();
2918            final int[] currentUserIds = UserManagerService.getInstance().getUserIds();
2919            for (int userId : currentUserIds) {
2920                userPackages.put(userId, getInstalledPackages(/*flags*/ 0, userId).getList());
2921            }
2922            mDexManager.load(userPackages);
2923        } // synchronized (mPackages)
2924        } // synchronized (mInstallLock)
2925
2926        // Now after opening every single application zip, make sure they
2927        // are all flushed.  Not really needed, but keeps things nice and
2928        // tidy.
2929        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "GC");
2930        Runtime.getRuntime().gc();
2931        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
2932
2933        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "loadFallbacks");
2934        FallbackCategoryProvider.loadFallbacks();
2935        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
2936
2937        // The initial scanning above does many calls into installd while
2938        // holding the mPackages lock, but we're mostly interested in yelling
2939        // once we have a booted system.
2940        mInstaller.setWarnIfHeld(mPackages);
2941
2942        // Expose private service for system components to use.
2943        LocalServices.addService(PackageManagerInternal.class, new PackageManagerInternalImpl());
2944        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
2945    }
2946
2947    private static File preparePackageParserCache(boolean isUpgrade) {
2948        if (!DEFAULT_PACKAGE_PARSER_CACHE_ENABLED) {
2949            return null;
2950        }
2951
2952        // Disable package parsing on eng builds to allow for faster incremental development.
2953        if ("eng".equals(Build.TYPE)) {
2954            return null;
2955        }
2956
2957        if (SystemProperties.getBoolean("pm.boot.disable_package_cache", false)) {
2958            Slog.i(TAG, "Disabling package parser cache due to system property.");
2959            return null;
2960        }
2961
2962        // The base directory for the package parser cache lives under /data/system/.
2963        final File cacheBaseDir = FileUtils.createDir(Environment.getDataSystemDirectory(),
2964                "package_cache");
2965        if (cacheBaseDir == null) {
2966            return null;
2967        }
2968
2969        // If this is a system upgrade scenario, delete the contents of the package cache dir.
2970        // This also serves to "GC" unused entries when the package cache version changes (which
2971        // can only happen during upgrades).
2972        if (isUpgrade) {
2973            FileUtils.deleteContents(cacheBaseDir);
2974        }
2975
2976
2977        // Return the versioned package cache directory. This is something like
2978        // "/data/system/package_cache/1"
2979        File cacheDir = FileUtils.createDir(cacheBaseDir, PACKAGE_PARSER_CACHE_VERSION);
2980
2981        // The following is a workaround to aid development on non-numbered userdebug
2982        // builds or cases where "adb sync" is used on userdebug builds. If we detect that
2983        // the system partition is newer.
2984        //
2985        // NOTE: When no BUILD_NUMBER is set by the build system, it defaults to a build
2986        // that starts with "eng." to signify that this is an engineering build and not
2987        // destined for release.
2988        if ("userdebug".equals(Build.TYPE) && Build.VERSION.INCREMENTAL.startsWith("eng.")) {
2989            Slog.w(TAG, "Wiping cache directory because the system partition changed.");
2990
2991            // Heuristic: If the /system directory has been modified recently due to an "adb sync"
2992            // or a regular make, then blow away the cache. Note that mtimes are *NOT* reliable
2993            // in general and should not be used for production changes. In this specific case,
2994            // we know that they will work.
2995            File frameworkDir = new File(Environment.getRootDirectory(), "framework");
2996            if (cacheDir.lastModified() < frameworkDir.lastModified()) {
2997                FileUtils.deleteContents(cacheBaseDir);
2998                cacheDir = FileUtils.createDir(cacheBaseDir, PACKAGE_PARSER_CACHE_VERSION);
2999            }
3000        }
3001
3002        return cacheDir;
3003    }
3004
3005    @Override
3006    public boolean isFirstBoot() {
3007        return mFirstBoot;
3008    }
3009
3010    @Override
3011    public boolean isOnlyCoreApps() {
3012        return mOnlyCore;
3013    }
3014
3015    @Override
3016    public boolean isUpgrade() {
3017        return mIsUpgrade;
3018    }
3019
3020    private @Nullable String getRequiredButNotReallyRequiredVerifierLPr() {
3021        final Intent intent = new Intent(Intent.ACTION_PACKAGE_NEEDS_VERIFICATION);
3022
3023        final List<ResolveInfo> matches = queryIntentReceiversInternal(intent, PACKAGE_MIME_TYPE,
3024                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
3025                UserHandle.USER_SYSTEM);
3026        if (matches.size() == 1) {
3027            return matches.get(0).getComponentInfo().packageName;
3028        } else if (matches.size() == 0) {
3029            Log.e(TAG, "There should probably be a verifier, but, none were found");
3030            return null;
3031        }
3032        throw new RuntimeException("There must be exactly one verifier; found " + matches);
3033    }
3034
3035    private @NonNull String getRequiredSharedLibraryLPr(String name, int version) {
3036        synchronized (mPackages) {
3037            SharedLibraryEntry libraryEntry = getSharedLibraryEntryLPr(name, version);
3038            if (libraryEntry == null) {
3039                throw new IllegalStateException("Missing required shared library:" + name);
3040            }
3041            return libraryEntry.apk;
3042        }
3043    }
3044
3045    private @NonNull String getRequiredInstallerLPr() {
3046        final Intent intent = new Intent(Intent.ACTION_INSTALL_PACKAGE);
3047        intent.addCategory(Intent.CATEGORY_DEFAULT);
3048        intent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE);
3049
3050        final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, PACKAGE_MIME_TYPE,
3051                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
3052                UserHandle.USER_SYSTEM);
3053        if (matches.size() == 1) {
3054            ResolveInfo resolveInfo = matches.get(0);
3055            if (!resolveInfo.activityInfo.applicationInfo.isPrivilegedApp()) {
3056                throw new RuntimeException("The installer must be a privileged app");
3057            }
3058            return matches.get(0).getComponentInfo().packageName;
3059        } else {
3060            throw new RuntimeException("There must be exactly one installer; found " + matches);
3061        }
3062    }
3063
3064    private @NonNull String getRequiredUninstallerLPr() {
3065        final Intent intent = new Intent(Intent.ACTION_UNINSTALL_PACKAGE);
3066        intent.addCategory(Intent.CATEGORY_DEFAULT);
3067        intent.setData(Uri.fromParts(PACKAGE_SCHEME, "foo.bar", null));
3068
3069        final ResolveInfo resolveInfo = resolveIntent(intent, null,
3070                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
3071                UserHandle.USER_SYSTEM);
3072        if (resolveInfo == null ||
3073                mResolveActivity.name.equals(resolveInfo.getComponentInfo().name)) {
3074            throw new RuntimeException("There must be exactly one uninstaller; found "
3075                    + resolveInfo);
3076        }
3077        return resolveInfo.getComponentInfo().packageName;
3078    }
3079
3080    private @NonNull ComponentName getIntentFilterVerifierComponentNameLPr() {
3081        final Intent intent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION);
3082
3083        final List<ResolveInfo> matches = queryIntentReceiversInternal(intent, PACKAGE_MIME_TYPE,
3084                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
3085                UserHandle.USER_SYSTEM);
3086        ResolveInfo best = null;
3087        final int N = matches.size();
3088        for (int i = 0; i < N; i++) {
3089            final ResolveInfo cur = matches.get(i);
3090            final String packageName = cur.getComponentInfo().packageName;
3091            if (checkPermission(android.Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT,
3092                    packageName, UserHandle.USER_SYSTEM) != PackageManager.PERMISSION_GRANTED) {
3093                continue;
3094            }
3095
3096            if (best == null || cur.priority > best.priority) {
3097                best = cur;
3098            }
3099        }
3100
3101        if (best != null) {
3102            return best.getComponentInfo().getComponentName();
3103        } else {
3104            throw new RuntimeException("There must be at least one intent filter verifier");
3105        }
3106    }
3107
3108    private @Nullable ComponentName getEphemeralResolverLPr() {
3109        final String[] packageArray =
3110                mContext.getResources().getStringArray(R.array.config_ephemeralResolverPackage);
3111        if (packageArray.length == 0 && !Build.IS_DEBUGGABLE) {
3112            if (DEBUG_EPHEMERAL) {
3113                Slog.d(TAG, "Ephemeral resolver NOT found; empty package list");
3114            }
3115            return null;
3116        }
3117
3118        final int resolveFlags =
3119                MATCH_DIRECT_BOOT_AWARE
3120                | MATCH_DIRECT_BOOT_UNAWARE
3121                | (!Build.IS_DEBUGGABLE ? MATCH_SYSTEM_ONLY : 0);
3122        final Intent resolverIntent = new Intent(Intent.ACTION_RESOLVE_EPHEMERAL_PACKAGE);
3123        final List<ResolveInfo> resolvers = queryIntentServicesInternal(resolverIntent, null,
3124                resolveFlags, UserHandle.USER_SYSTEM);
3125
3126        final int N = resolvers.size();
3127        if (N == 0) {
3128            if (DEBUG_EPHEMERAL) {
3129                Slog.d(TAG, "Ephemeral resolver NOT found; no matching intent filters");
3130            }
3131            return null;
3132        }
3133
3134        final Set<String> possiblePackages = new ArraySet<>(Arrays.asList(packageArray));
3135        for (int i = 0; i < N; i++) {
3136            final ResolveInfo info = resolvers.get(i);
3137
3138            if (info.serviceInfo == null) {
3139                continue;
3140            }
3141
3142            final String packageName = info.serviceInfo.packageName;
3143            if (!possiblePackages.contains(packageName) && !Build.IS_DEBUGGABLE) {
3144                if (DEBUG_EPHEMERAL) {
3145                    Slog.d(TAG, "Ephemeral resolver not in allowed package list;"
3146                            + " pkg: " + packageName + ", info:" + info);
3147                }
3148                continue;
3149            }
3150
3151            if (DEBUG_EPHEMERAL) {
3152                Slog.v(TAG, "Ephemeral resolver found;"
3153                        + " pkg: " + packageName + ", info:" + info);
3154            }
3155            return new ComponentName(packageName, info.serviceInfo.name);
3156        }
3157        if (DEBUG_EPHEMERAL) {
3158            Slog.v(TAG, "Ephemeral resolver NOT found");
3159        }
3160        return null;
3161    }
3162
3163    private @Nullable ComponentName getEphemeralInstallerLPr() {
3164        final Intent intent = new Intent(Intent.ACTION_INSTALL_EPHEMERAL_PACKAGE);
3165        intent.addCategory(Intent.CATEGORY_DEFAULT);
3166        intent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE);
3167
3168        final int resolveFlags =
3169                MATCH_DIRECT_BOOT_AWARE
3170                | MATCH_DIRECT_BOOT_UNAWARE
3171                | (!Build.IS_DEBUGGABLE ? MATCH_SYSTEM_ONLY : 0);
3172        final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, PACKAGE_MIME_TYPE,
3173                resolveFlags, UserHandle.USER_SYSTEM);
3174        Iterator<ResolveInfo> iter = matches.iterator();
3175        while (iter.hasNext()) {
3176            final ResolveInfo rInfo = iter.next();
3177            final PackageSetting ps = mSettings.mPackages.get(rInfo.activityInfo.packageName);
3178            if (ps != null) {
3179                final PermissionsState permissionsState = ps.getPermissionsState();
3180                if (permissionsState.hasPermission(Manifest.permission.INSTALL_PACKAGES, 0)) {
3181                    continue;
3182                }
3183            }
3184            iter.remove();
3185        }
3186        if (matches.size() == 0) {
3187            return null;
3188        } else if (matches.size() == 1) {
3189            return matches.get(0).getComponentInfo().getComponentName();
3190        } else {
3191            throw new RuntimeException(
3192                    "There must be at most one ephemeral installer; found " + matches);
3193        }
3194    }
3195
3196    private void primeDomainVerificationsLPw(int userId) {
3197        if (DEBUG_DOMAIN_VERIFICATION) {
3198            Slog.d(TAG, "Priming domain verifications in user " + userId);
3199        }
3200
3201        SystemConfig systemConfig = SystemConfig.getInstance();
3202        ArraySet<String> packages = systemConfig.getLinkedApps();
3203
3204        for (String packageName : packages) {
3205            PackageParser.Package pkg = mPackages.get(packageName);
3206            if (pkg != null) {
3207                if (!pkg.isSystemApp()) {
3208                    Slog.w(TAG, "Non-system app '" + packageName + "' in sysconfig <app-link>");
3209                    continue;
3210                }
3211
3212                ArraySet<String> domains = null;
3213                for (PackageParser.Activity a : pkg.activities) {
3214                    for (ActivityIntentInfo filter : a.intents) {
3215                        if (hasValidDomains(filter)) {
3216                            if (domains == null) {
3217                                domains = new ArraySet<String>();
3218                            }
3219                            domains.addAll(filter.getHostsList());
3220                        }
3221                    }
3222                }
3223
3224                if (domains != null && domains.size() > 0) {
3225                    if (DEBUG_DOMAIN_VERIFICATION) {
3226                        Slog.v(TAG, "      + " + packageName);
3227                    }
3228                    // 'Undefined' in the global IntentFilterVerificationInfo, i.e. the usual
3229                    // state w.r.t. the formal app-linkage "no verification attempted" state;
3230                    // and then 'always' in the per-user state actually used for intent resolution.
3231                    final IntentFilterVerificationInfo ivi;
3232                    ivi = mSettings.createIntentFilterVerificationIfNeededLPw(packageName, domains);
3233                    ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED);
3234                    mSettings.updateIntentFilterVerificationStatusLPw(packageName,
3235                            INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS, userId);
3236                } else {
3237                    Slog.w(TAG, "Sysconfig <app-link> package '" + packageName
3238                            + "' does not handle web links");
3239                }
3240            } else {
3241                Slog.w(TAG, "Unknown package " + packageName + " in sysconfig <app-link>");
3242            }
3243        }
3244
3245        scheduleWritePackageRestrictionsLocked(userId);
3246        scheduleWriteSettingsLocked();
3247    }
3248
3249    private void applyFactoryDefaultBrowserLPw(int userId) {
3250        // The default browser app's package name is stored in a string resource,
3251        // with a product-specific overlay used for vendor customization.
3252        String browserPkg = mContext.getResources().getString(
3253                com.android.internal.R.string.default_browser);
3254        if (!TextUtils.isEmpty(browserPkg)) {
3255            // non-empty string => required to be a known package
3256            PackageSetting ps = mSettings.mPackages.get(browserPkg);
3257            if (ps == null) {
3258                Slog.e(TAG, "Product default browser app does not exist: " + browserPkg);
3259                browserPkg = null;
3260            } else {
3261                mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId);
3262            }
3263        }
3264
3265        // Nothing valid explicitly set? Make the factory-installed browser the explicit
3266        // default.  If there's more than one, just leave everything alone.
3267        if (browserPkg == null) {
3268            calculateDefaultBrowserLPw(userId);
3269        }
3270    }
3271
3272    private void calculateDefaultBrowserLPw(int userId) {
3273        List<String> allBrowsers = resolveAllBrowserApps(userId);
3274        final String browserPkg = (allBrowsers.size() == 1) ? allBrowsers.get(0) : null;
3275        mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId);
3276    }
3277
3278    private List<String> resolveAllBrowserApps(int userId) {
3279        // Resolve the canonical browser intent and check that the handleAllWebDataURI boolean is set
3280        List<ResolveInfo> list = queryIntentActivitiesInternal(sBrowserIntent, null,
3281                PackageManager.MATCH_ALL, userId);
3282
3283        final int count = list.size();
3284        List<String> result = new ArrayList<String>(count);
3285        for (int i=0; i<count; i++) {
3286            ResolveInfo info = list.get(i);
3287            if (info.activityInfo == null
3288                    || !info.handleAllWebDataURI
3289                    || (info.activityInfo.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) == 0
3290                    || result.contains(info.activityInfo.packageName)) {
3291                continue;
3292            }
3293            result.add(info.activityInfo.packageName);
3294        }
3295
3296        return result;
3297    }
3298
3299    private boolean packageIsBrowser(String packageName, int userId) {
3300        List<ResolveInfo> list = queryIntentActivitiesInternal(sBrowserIntent, null,
3301                PackageManager.MATCH_ALL, userId);
3302        final int N = list.size();
3303        for (int i = 0; i < N; i++) {
3304            ResolveInfo info = list.get(i);
3305            if (packageName.equals(info.activityInfo.packageName)) {
3306                return true;
3307            }
3308        }
3309        return false;
3310    }
3311
3312    private void checkDefaultBrowser() {
3313        final int myUserId = UserHandle.myUserId();
3314        final String packageName = getDefaultBrowserPackageName(myUserId);
3315        if (packageName != null) {
3316            PackageInfo info = getPackageInfo(packageName, 0, myUserId);
3317            if (info == null) {
3318                Slog.w(TAG, "Default browser no longer installed: " + packageName);
3319                synchronized (mPackages) {
3320                    applyFactoryDefaultBrowserLPw(myUserId);    // leaves ambiguous when > 1
3321                }
3322            }
3323        }
3324    }
3325
3326    @Override
3327    public boolean onTransact(int code, Parcel data, Parcel reply, int flags)
3328            throws RemoteException {
3329        try {
3330            return super.onTransact(code, data, reply, flags);
3331        } catch (RuntimeException e) {
3332            if (!(e instanceof SecurityException) && !(e instanceof IllegalArgumentException)) {
3333                Slog.wtf(TAG, "Package Manager Crash", e);
3334            }
3335            throw e;
3336        }
3337    }
3338
3339    static int[] appendInts(int[] cur, int[] add) {
3340        if (add == null) return cur;
3341        if (cur == null) return add;
3342        final int N = add.length;
3343        for (int i=0; i<N; i++) {
3344            cur = appendInt(cur, add[i]);
3345        }
3346        return cur;
3347    }
3348
3349    private PackageInfo generatePackageInfo(PackageSetting ps, int flags, int userId) {
3350        if (!sUserManager.exists(userId)) return null;
3351        if (ps == null) {
3352            return null;
3353        }
3354        final PackageParser.Package p = ps.pkg;
3355        if (p == null) {
3356            return null;
3357        }
3358        // Filter out ephemeral app metadata:
3359        //   * The system/shell/root can see metadata for any app
3360        //   * An installed app can see metadata for 1) other installed apps
3361        //     and 2) ephemeral apps that have explicitly interacted with it
3362        //   * Ephemeral apps can only see their own metadata
3363        //   * Holding a signature permission allows seeing instant apps
3364        final int callingAppId = UserHandle.getAppId(Binder.getCallingUid());
3365        if (callingAppId != Process.SYSTEM_UID
3366                && callingAppId != Process.SHELL_UID
3367                && callingAppId != Process.ROOT_UID
3368                && checkUidPermission(Manifest.permission.ACCESS_INSTANT_APPS,
3369                        Binder.getCallingUid()) != PackageManager.PERMISSION_GRANTED) {
3370            final String instantAppPackageName = getInstantAppPackageName(Binder.getCallingUid());
3371            if (instantAppPackageName != null) {
3372                // ephemeral apps can only get information on themselves
3373                if (!instantAppPackageName.equals(p.packageName)) {
3374                    return null;
3375                }
3376            } else {
3377                if (ps.getInstantApp(userId)) {
3378                    // only get access to the ephemeral app if we've been granted access
3379                    if (!mInstantAppRegistry.isInstantAccessGranted(
3380                            userId, callingAppId, ps.appId)) {
3381                        return null;
3382                    }
3383                }
3384            }
3385        }
3386
3387        final PermissionsState permissionsState = ps.getPermissionsState();
3388
3389        // Compute GIDs only if requested
3390        final int[] gids = (flags & PackageManager.GET_GIDS) == 0
3391                ? EMPTY_INT_ARRAY : permissionsState.computeGids(userId);
3392        // Compute granted permissions only if package has requested permissions
3393        final Set<String> permissions = ArrayUtils.isEmpty(p.requestedPermissions)
3394                ? Collections.<String>emptySet() : permissionsState.getPermissions(userId);
3395        final PackageUserState state = ps.readUserState(userId);
3396
3397        if ((flags & MATCH_UNINSTALLED_PACKAGES) != 0
3398                && ps.isSystem()) {
3399            flags |= MATCH_ANY_USER;
3400        }
3401
3402        PackageInfo packageInfo = PackageParser.generatePackageInfo(p, gids, flags,
3403                ps.firstInstallTime, ps.lastUpdateTime, permissions, state, userId);
3404
3405        if (packageInfo == null) {
3406            return null;
3407        }
3408
3409        packageInfo.packageName = packageInfo.applicationInfo.packageName =
3410                resolveExternalPackageNameLPr(p);
3411
3412        return packageInfo;
3413    }
3414
3415    @Override
3416    public void checkPackageStartable(String packageName, int userId) {
3417        final boolean userKeyUnlocked = StorageManager.isUserKeyUnlocked(userId);
3418
3419        synchronized (mPackages) {
3420            final PackageSetting ps = mSettings.mPackages.get(packageName);
3421            if (ps == null) {
3422                throw new SecurityException("Package " + packageName + " was not found!");
3423            }
3424
3425            if (!ps.getInstalled(userId)) {
3426                throw new SecurityException(
3427                        "Package " + packageName + " was not installed for user " + userId + "!");
3428            }
3429
3430            if (mSafeMode && !ps.isSystem()) {
3431                throw new SecurityException("Package " + packageName + " not a system app!");
3432            }
3433
3434            if (mFrozenPackages.contains(packageName)) {
3435                throw new SecurityException("Package " + packageName + " is currently frozen!");
3436            }
3437
3438            if (!userKeyUnlocked && !(ps.pkg.applicationInfo.isDirectBootAware()
3439                    || ps.pkg.applicationInfo.isPartiallyDirectBootAware())) {
3440                throw new SecurityException("Package " + packageName + " is not encryption aware!");
3441            }
3442        }
3443    }
3444
3445    @Override
3446    public boolean isPackageAvailable(String packageName, int userId) {
3447        if (!sUserManager.exists(userId)) return false;
3448        enforceCrossUserPermission(Binder.getCallingUid(), userId,
3449                false /* requireFullPermission */, false /* checkShell */, "is package available");
3450        synchronized (mPackages) {
3451            PackageParser.Package p = mPackages.get(packageName);
3452            if (p != null) {
3453                final PackageSetting ps = (PackageSetting) p.mExtras;
3454                if (ps != null) {
3455                    final PackageUserState state = ps.readUserState(userId);
3456                    if (state != null) {
3457                        return PackageParser.isAvailable(state);
3458                    }
3459                }
3460            }
3461        }
3462        return false;
3463    }
3464
3465    @Override
3466    public PackageInfo getPackageInfo(String packageName, int flags, int userId) {
3467        return getPackageInfoInternal(packageName, PackageManager.VERSION_CODE_HIGHEST,
3468                flags, userId);
3469    }
3470
3471    @Override
3472    public PackageInfo getPackageInfoVersioned(VersionedPackage versionedPackage,
3473            int flags, int userId) {
3474        return getPackageInfoInternal(versionedPackage.getPackageName(),
3475                // TODO: We will change version code to long, so in the new API it is long
3476                (int) versionedPackage.getVersionCode(), flags, userId);
3477    }
3478
3479    private PackageInfo getPackageInfoInternal(String packageName, int versionCode,
3480            int flags, int userId) {
3481        if (!sUserManager.exists(userId)) return null;
3482        flags = updateFlagsForPackage(flags, userId, packageName);
3483        enforceCrossUserPermission(Binder.getCallingUid(), userId,
3484                false /* requireFullPermission */, false /* checkShell */, "get package info");
3485
3486        // reader
3487        synchronized (mPackages) {
3488            // Normalize package name to handle renamed packages and static libs
3489            packageName = resolveInternalPackageNameLPr(packageName, versionCode);
3490
3491            final boolean matchFactoryOnly = (flags & MATCH_FACTORY_ONLY) != 0;
3492            if (matchFactoryOnly) {
3493                final PackageSetting ps = mSettings.getDisabledSystemPkgLPr(packageName);
3494                if (ps != null) {
3495                    if (filterSharedLibPackageLPr(ps, Binder.getCallingUid(), userId)) {
3496                        return null;
3497                    }
3498                    return generatePackageInfo(ps, flags, userId);
3499                }
3500            }
3501
3502            PackageParser.Package p = mPackages.get(packageName);
3503            if (matchFactoryOnly && p != null && !isSystemApp(p)) {
3504                return null;
3505            }
3506            if (DEBUG_PACKAGE_INFO)
3507                Log.v(TAG, "getPackageInfo " + packageName + ": " + p);
3508            if (p != null) {
3509                if (filterSharedLibPackageLPr((PackageSetting) p.mExtras,
3510                        Binder.getCallingUid(), userId)) {
3511                    return null;
3512                }
3513                return generatePackageInfo((PackageSetting)p.mExtras, flags, userId);
3514            }
3515            if (!matchFactoryOnly && (flags & MATCH_KNOWN_PACKAGES) != 0) {
3516                final PackageSetting ps = mSettings.mPackages.get(packageName);
3517                if (filterSharedLibPackageLPr(ps, Binder.getCallingUid(), userId)) {
3518                    return null;
3519                }
3520                return generatePackageInfo(ps, flags, userId);
3521            }
3522        }
3523        return null;
3524    }
3525
3526
3527    private boolean filterSharedLibPackageLPr(@Nullable PackageSetting ps, int uid, int userId) {
3528        // System/shell/root get to see all static libs
3529        final int appId = UserHandle.getAppId(uid);
3530        if (appId == Process.SYSTEM_UID || appId == Process.SHELL_UID
3531                || appId == Process.ROOT_UID) {
3532            return false;
3533        }
3534
3535        // No package means no static lib as it is always on internal storage
3536        if (ps == null || ps.pkg == null || !ps.pkg.applicationInfo.isStaticSharedLibrary()) {
3537            return false;
3538        }
3539
3540        final SharedLibraryEntry libEntry = getSharedLibraryEntryLPr(ps.pkg.staticSharedLibName,
3541                ps.pkg.staticSharedLibVersion);
3542        if (libEntry == null) {
3543            return false;
3544        }
3545
3546        final int resolvedUid = UserHandle.getUid(userId, UserHandle.getAppId(uid));
3547        final String[] uidPackageNames = getPackagesForUid(resolvedUid);
3548        if (uidPackageNames == null) {
3549            return true;
3550        }
3551
3552        for (String uidPackageName : uidPackageNames) {
3553            if (ps.name.equals(uidPackageName)) {
3554                return false;
3555            }
3556            PackageSetting uidPs = mSettings.getPackageLPr(uidPackageName);
3557            if (uidPs != null) {
3558                final int index = ArrayUtils.indexOf(uidPs.usesStaticLibraries,
3559                        libEntry.info.getName());
3560                if (index < 0) {
3561                    continue;
3562                }
3563                if (uidPs.pkg.usesStaticLibrariesVersions[index] == libEntry.info.getVersion()) {
3564                    return false;
3565                }
3566            }
3567        }
3568        return true;
3569    }
3570
3571    @Override
3572    public String[] currentToCanonicalPackageNames(String[] names) {
3573        String[] out = new String[names.length];
3574        // reader
3575        synchronized (mPackages) {
3576            for (int i=names.length-1; i>=0; i--) {
3577                PackageSetting ps = mSettings.mPackages.get(names[i]);
3578                out[i] = ps != null && ps.realName != null ? ps.realName : names[i];
3579            }
3580        }
3581        return out;
3582    }
3583
3584    @Override
3585    public String[] canonicalToCurrentPackageNames(String[] names) {
3586        String[] out = new String[names.length];
3587        // reader
3588        synchronized (mPackages) {
3589            for (int i=names.length-1; i>=0; i--) {
3590                String cur = mSettings.getRenamedPackageLPr(names[i]);
3591                out[i] = cur != null ? cur : names[i];
3592            }
3593        }
3594        return out;
3595    }
3596
3597    @Override
3598    public int getPackageUid(String packageName, int flags, int userId) {
3599        if (!sUserManager.exists(userId)) return -1;
3600        flags = updateFlagsForPackage(flags, userId, packageName);
3601        enforceCrossUserPermission(Binder.getCallingUid(), userId,
3602                false /* requireFullPermission */, false /* checkShell */, "get package uid");
3603
3604        // reader
3605        synchronized (mPackages) {
3606            final PackageParser.Package p = mPackages.get(packageName);
3607            if (p != null && p.isMatch(flags)) {
3608                return UserHandle.getUid(userId, p.applicationInfo.uid);
3609            }
3610            if ((flags & MATCH_KNOWN_PACKAGES) != 0) {
3611                final PackageSetting ps = mSettings.mPackages.get(packageName);
3612                if (ps != null && ps.isMatch(flags)) {
3613                    return UserHandle.getUid(userId, ps.appId);
3614                }
3615            }
3616        }
3617
3618        return -1;
3619    }
3620
3621    @Override
3622    public int[] getPackageGids(String packageName, int flags, int userId) {
3623        if (!sUserManager.exists(userId)) return null;
3624        flags = updateFlagsForPackage(flags, userId, packageName);
3625        enforceCrossUserPermission(Binder.getCallingUid(), userId,
3626                false /* requireFullPermission */, false /* checkShell */,
3627                "getPackageGids");
3628
3629        // reader
3630        synchronized (mPackages) {
3631            final PackageParser.Package p = mPackages.get(packageName);
3632            if (p != null && p.isMatch(flags)) {
3633                PackageSetting ps = (PackageSetting) p.mExtras;
3634                // TODO: Shouldn't this be checking for package installed state for userId and
3635                // return null?
3636                return ps.getPermissionsState().computeGids(userId);
3637            }
3638            if ((flags & MATCH_KNOWN_PACKAGES) != 0) {
3639                final PackageSetting ps = mSettings.mPackages.get(packageName);
3640                if (ps != null && ps.isMatch(flags)) {
3641                    return ps.getPermissionsState().computeGids(userId);
3642                }
3643            }
3644        }
3645
3646        return null;
3647    }
3648
3649    static PermissionInfo generatePermissionInfo(BasePermission bp, int flags) {
3650        if (bp.perm != null) {
3651            return PackageParser.generatePermissionInfo(bp.perm, flags);
3652        }
3653        PermissionInfo pi = new PermissionInfo();
3654        pi.name = bp.name;
3655        pi.packageName = bp.sourcePackage;
3656        pi.nonLocalizedLabel = bp.name;
3657        pi.protectionLevel = bp.protectionLevel;
3658        return pi;
3659    }
3660
3661    @Override
3662    public PermissionInfo getPermissionInfo(String name, int flags) {
3663        // reader
3664        synchronized (mPackages) {
3665            final BasePermission p = mSettings.mPermissions.get(name);
3666            if (p != null) {
3667                return generatePermissionInfo(p, flags);
3668            }
3669            return null;
3670        }
3671    }
3672
3673    @Override
3674    public @Nullable ParceledListSlice<PermissionInfo> queryPermissionsByGroup(String group,
3675            int flags) {
3676        // reader
3677        synchronized (mPackages) {
3678            if (group != null && !mPermissionGroups.containsKey(group)) {
3679                // This is thrown as NameNotFoundException
3680                return null;
3681            }
3682
3683            ArrayList<PermissionInfo> out = new ArrayList<PermissionInfo>(10);
3684            for (BasePermission p : mSettings.mPermissions.values()) {
3685                if (group == null) {
3686                    if (p.perm == null || p.perm.info.group == null) {
3687                        out.add(generatePermissionInfo(p, flags));
3688                    }
3689                } else {
3690                    if (p.perm != null && group.equals(p.perm.info.group)) {
3691                        out.add(PackageParser.generatePermissionInfo(p.perm, flags));
3692                    }
3693                }
3694            }
3695            return new ParceledListSlice<>(out);
3696        }
3697    }
3698
3699    @Override
3700    public PermissionGroupInfo getPermissionGroupInfo(String name, int flags) {
3701        // reader
3702        synchronized (mPackages) {
3703            return PackageParser.generatePermissionGroupInfo(
3704                    mPermissionGroups.get(name), flags);
3705        }
3706    }
3707
3708    @Override
3709    public @NonNull ParceledListSlice<PermissionGroupInfo> getAllPermissionGroups(int flags) {
3710        // reader
3711        synchronized (mPackages) {
3712            final int N = mPermissionGroups.size();
3713            ArrayList<PermissionGroupInfo> out
3714                    = new ArrayList<PermissionGroupInfo>(N);
3715            for (PackageParser.PermissionGroup pg : mPermissionGroups.values()) {
3716                out.add(PackageParser.generatePermissionGroupInfo(pg, flags));
3717            }
3718            return new ParceledListSlice<>(out);
3719        }
3720    }
3721
3722    private ApplicationInfo generateApplicationInfoFromSettingsLPw(String packageName, int flags,
3723            int uid, int userId) {
3724        if (!sUserManager.exists(userId)) return null;
3725        PackageSetting ps = mSettings.mPackages.get(packageName);
3726        if (ps != null) {
3727            if (filterSharedLibPackageLPr(ps, uid, userId)) {
3728                return null;
3729            }
3730            if (ps.pkg == null) {
3731                final PackageInfo pInfo = generatePackageInfo(ps, flags, userId);
3732                if (pInfo != null) {
3733                    return pInfo.applicationInfo;
3734                }
3735                return null;
3736            }
3737            ApplicationInfo ai = PackageParser.generateApplicationInfo(ps.pkg, flags,
3738                    ps.readUserState(userId), userId);
3739            if (ai != null) {
3740                rebaseEnabledOverlays(ai, userId);
3741                ai.packageName = resolveExternalPackageNameLPr(ps.pkg);
3742            }
3743            return ai;
3744        }
3745        return null;
3746    }
3747
3748    @Override
3749    public ApplicationInfo getApplicationInfo(String packageName, int flags, int userId) {
3750        if (!sUserManager.exists(userId)) return null;
3751        flags = updateFlagsForApplication(flags, userId, packageName);
3752        enforceCrossUserPermission(Binder.getCallingUid(), userId,
3753                false /* requireFullPermission */, false /* checkShell */, "get application info");
3754
3755        // writer
3756        synchronized (mPackages) {
3757            // Normalize package name to handle renamed packages and static libs
3758            packageName = resolveInternalPackageNameLPr(packageName,
3759                    PackageManager.VERSION_CODE_HIGHEST);
3760
3761            PackageParser.Package p = mPackages.get(packageName);
3762            if (DEBUG_PACKAGE_INFO) Log.v(
3763                    TAG, "getApplicationInfo " + packageName
3764                    + ": " + p);
3765            if (p != null) {
3766                PackageSetting ps = mSettings.mPackages.get(packageName);
3767                if (ps == null) return null;
3768                if (filterSharedLibPackageLPr(ps, Binder.getCallingUid(), userId)) {
3769                    return null;
3770                }
3771                // Note: isEnabledLP() does not apply here - always return info
3772                ApplicationInfo ai = PackageParser.generateApplicationInfo(
3773                        p, flags, ps.readUserState(userId), userId);
3774                if (ai != null) {
3775                    rebaseEnabledOverlays(ai, userId);
3776                    ai.packageName = resolveExternalPackageNameLPr(p);
3777                }
3778                return ai;
3779            }
3780            if ("android".equals(packageName)||"system".equals(packageName)) {
3781                return mAndroidApplication;
3782            }
3783            if ((flags & MATCH_KNOWN_PACKAGES) != 0) {
3784                // Already generates the external package name
3785                return generateApplicationInfoFromSettingsLPw(packageName,
3786                        Binder.getCallingUid(), flags, userId);
3787            }
3788        }
3789        return null;
3790    }
3791
3792    private void rebaseEnabledOverlays(@NonNull ApplicationInfo ai, int userId) {
3793        List<String> paths = new ArrayList<>();
3794        ArrayMap<String, ArrayList<String>> userSpecificOverlays =
3795            mEnabledOverlayPaths.get(userId);
3796        if (userSpecificOverlays != null) {
3797            if (!"android".equals(ai.packageName)) {
3798                ArrayList<String> frameworkOverlays = userSpecificOverlays.get("android");
3799                if (frameworkOverlays != null) {
3800                    paths.addAll(frameworkOverlays);
3801                }
3802            }
3803
3804            ArrayList<String> appOverlays = userSpecificOverlays.get(ai.packageName);
3805            if (appOverlays != null) {
3806                paths.addAll(appOverlays);
3807            }
3808        }
3809        ai.resourceDirs = paths.size() > 0 ? paths.toArray(new String[paths.size()]) : null;
3810    }
3811
3812    private String normalizePackageNameLPr(String packageName) {
3813        String normalizedPackageName = mSettings.getRenamedPackageLPr(packageName);
3814        return normalizedPackageName != null ? normalizedPackageName : packageName;
3815    }
3816
3817    @Override
3818    public void freeStorageAndNotify(final String volumeUuid, final long freeStorageSize,
3819            final IPackageDataObserver observer) {
3820        mContext.enforceCallingOrSelfPermission(
3821                android.Manifest.permission.CLEAR_APP_CACHE, null);
3822        mHandler.post(() -> {
3823            boolean success = false;
3824            try {
3825                freeStorage(volumeUuid, freeStorageSize, 0);
3826                success = true;
3827            } catch (IOException e) {
3828                Slog.w(TAG, e);
3829            }
3830            if (observer != null) {
3831                try {
3832                    observer.onRemoveCompleted(null, success);
3833                } catch (RemoteException e) {
3834                    Slog.w(TAG, e);
3835                }
3836            }
3837        });
3838    }
3839
3840    @Override
3841    public void freeStorage(final String volumeUuid, final long freeStorageSize,
3842            final IntentSender pi) {
3843        mContext.enforceCallingOrSelfPermission(
3844                android.Manifest.permission.CLEAR_APP_CACHE, TAG);
3845        mHandler.post(() -> {
3846            boolean success = false;
3847            try {
3848                freeStorage(volumeUuid, freeStorageSize, 0);
3849                success = true;
3850            } catch (IOException e) {
3851                Slog.w(TAG, e);
3852            }
3853            if (pi != null) {
3854                try {
3855                    pi.sendIntent(null, success ? 1 : 0, null, null, null);
3856                } catch (SendIntentException e) {
3857                    Slog.w(TAG, e);
3858                }
3859            }
3860        });
3861    }
3862
3863    /**
3864     * Blocking call to clear various types of cached data across the system
3865     * until the requested bytes are available.
3866     */
3867    public void freeStorage(String volumeUuid, long bytes, int storageFlags) throws IOException {
3868        final StorageManager storage = mContext.getSystemService(StorageManager.class);
3869        final File file = storage.findPathForUuid(volumeUuid);
3870
3871        if (ENABLE_FREE_CACHE_V2) {
3872            final boolean aggressive = (storageFlags
3873                    & StorageManager.FLAG_ALLOCATE_AGGRESSIVE) != 0;
3874
3875            // 1. Pre-flight to determine if we have any chance to succeed
3876            // 2. Consider preloaded data (after 1w honeymoon, unless aggressive)
3877
3878            // 3. Consider parsed APK data (aggressive only)
3879            if (aggressive) {
3880                FileUtils.deleteContents(mCacheDir);
3881            }
3882            if (file.getUsableSpace() >= bytes) return;
3883
3884            // 4. Consider cached app data (above quotas)
3885            try {
3886                mInstaller.freeCache(volumeUuid, bytes, Installer.FLAG_FREE_CACHE_V2);
3887            } catch (InstallerException ignored) {
3888            }
3889            if (file.getUsableSpace() >= bytes) return;
3890
3891            // 5. Consider shared libraries with refcount=0 and age>2h
3892            // 6. Consider dexopt output (aggressive only)
3893            // 7. Consider ephemeral apps not used in last week
3894
3895            // 8. Consider cached app data (below quotas)
3896            try {
3897                mInstaller.freeCache(volumeUuid, bytes, Installer.FLAG_FREE_CACHE_V2
3898                        | Installer.FLAG_FREE_CACHE_V2_DEFY_QUOTA);
3899            } catch (InstallerException ignored) {
3900            }
3901            if (file.getUsableSpace() >= bytes) return;
3902
3903            // 9. Consider DropBox entries
3904            // 10. Consider ephemeral cookies
3905
3906        } else {
3907            try {
3908                mInstaller.freeCache(volumeUuid, bytes, 0);
3909            } catch (InstallerException ignored) {
3910            }
3911            if (file.getUsableSpace() >= bytes) return;
3912        }
3913
3914        throw new IOException("Failed to free " + bytes + " on storage device at " + file);
3915    }
3916
3917    /**
3918     * Update given flags based on encryption status of current user.
3919     */
3920    private int updateFlags(int flags, int userId) {
3921        if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE
3922                | PackageManager.MATCH_DIRECT_BOOT_AWARE)) != 0) {
3923            // Caller expressed an explicit opinion about what encryption
3924            // aware/unaware components they want to see, so fall through and
3925            // give them what they want
3926        } else {
3927            // Caller expressed no opinion, so match based on user state
3928            if (getUserManagerInternal().isUserUnlockingOrUnlocked(userId)) {
3929                flags |= PackageManager.MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE;
3930            } else {
3931                flags |= PackageManager.MATCH_DIRECT_BOOT_AWARE;
3932            }
3933        }
3934        return flags;
3935    }
3936
3937    private UserManagerInternal getUserManagerInternal() {
3938        if (mUserManagerInternal == null) {
3939            mUserManagerInternal = LocalServices.getService(UserManagerInternal.class);
3940        }
3941        return mUserManagerInternal;
3942    }
3943
3944    private DeviceIdleController.LocalService getDeviceIdleController() {
3945        if (mDeviceIdleController == null) {
3946            mDeviceIdleController =
3947                    LocalServices.getService(DeviceIdleController.LocalService.class);
3948        }
3949        return mDeviceIdleController;
3950    }
3951
3952    /**
3953     * Update given flags when being used to request {@link PackageInfo}.
3954     */
3955    private int updateFlagsForPackage(int flags, int userId, Object cookie) {
3956        final boolean isCallerSystemUser = UserHandle.getCallingUserId() == UserHandle.USER_SYSTEM;
3957        boolean triaged = true;
3958        if ((flags & (PackageManager.GET_ACTIVITIES | PackageManager.GET_RECEIVERS
3959                | PackageManager.GET_SERVICES | PackageManager.GET_PROVIDERS)) != 0) {
3960            // Caller is asking for component details, so they'd better be
3961            // asking for specific encryption matching behavior, or be triaged
3962            if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE
3963                    | PackageManager.MATCH_DIRECT_BOOT_AWARE
3964                    | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) {
3965                triaged = false;
3966            }
3967        }
3968        if ((flags & (PackageManager.MATCH_UNINSTALLED_PACKAGES
3969                | PackageManager.MATCH_SYSTEM_ONLY
3970                | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) {
3971            triaged = false;
3972        }
3973        if ((flags & PackageManager.MATCH_ANY_USER) != 0) {
3974            enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false,
3975                    "MATCH_ANY_USER flag requires INTERACT_ACROSS_USERS permission at "
3976                    + Debug.getCallers(5));
3977        } else if ((flags & PackageManager.MATCH_UNINSTALLED_PACKAGES) != 0 && isCallerSystemUser
3978                && sUserManager.hasManagedProfile(UserHandle.USER_SYSTEM)) {
3979            // If the caller wants all packages and has a restricted profile associated with it,
3980            // then match all users. This is to make sure that launchers that need to access work
3981            // profile apps don't start breaking. TODO: Remove this hack when launchers stop using
3982            // MATCH_UNINSTALLED_PACKAGES to query apps in other profiles. b/31000380
3983            flags |= PackageManager.MATCH_ANY_USER;
3984        }
3985        if (DEBUG_TRIAGED_MISSING && (Binder.getCallingUid() == Process.SYSTEM_UID) && !triaged) {
3986            Log.w(TAG, "Caller hasn't been triaged for missing apps; they asked about " + cookie
3987                    + " with flags 0x" + Integer.toHexString(flags), new Throwable());
3988        }
3989        return updateFlags(flags, userId);
3990    }
3991
3992    /**
3993     * Update given flags when being used to request {@link ApplicationInfo}.
3994     */
3995    private int updateFlagsForApplication(int flags, int userId, Object cookie) {
3996        return updateFlagsForPackage(flags, userId, cookie);
3997    }
3998
3999    /**
4000     * Update given flags when being used to request {@link ComponentInfo}.
4001     */
4002    private int updateFlagsForComponent(int flags, int userId, Object cookie) {
4003        if (cookie instanceof Intent) {
4004            if ((((Intent) cookie).getFlags() & Intent.FLAG_DEBUG_TRIAGED_MISSING) != 0) {
4005                flags |= PackageManager.MATCH_DEBUG_TRIAGED_MISSING;
4006            }
4007        }
4008
4009        boolean triaged = true;
4010        // Caller is asking for component details, so they'd better be
4011        // asking for specific encryption matching behavior, or be triaged
4012        if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE
4013                | PackageManager.MATCH_DIRECT_BOOT_AWARE
4014                | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) {
4015            triaged = false;
4016        }
4017        if (DEBUG_TRIAGED_MISSING && (Binder.getCallingUid() == Process.SYSTEM_UID) && !triaged) {
4018            Log.w(TAG, "Caller hasn't been triaged for missing apps; they asked about " + cookie
4019                    + " with flags 0x" + Integer.toHexString(flags), new Throwable());
4020        }
4021
4022        return updateFlags(flags, userId);
4023    }
4024
4025    /**
4026     * Update given intent when being used to request {@link ResolveInfo}.
4027     */
4028    private Intent updateIntentForResolve(Intent intent) {
4029        if (intent.getSelector() != null) {
4030            intent = intent.getSelector();
4031        }
4032        if (DEBUG_PREFERRED) {
4033            intent.addFlags(Intent.FLAG_DEBUG_LOG_RESOLUTION);
4034        }
4035        return intent;
4036    }
4037
4038    /**
4039     * Update given flags when being used to request {@link ResolveInfo}.
4040     * <p>Instant apps are resolved specially, depending upon context. Minimally,
4041     * {@code}flags{@code} must have the {@link PackageManager#MATCH_INSTANT}
4042     * flag set. However, this flag is only honoured in three circumstances:
4043     * <ul>
4044     * <li>when called from a system process</li>
4045     * <li>when the caller holds the permission {@code android.permission.ACCESS_INSTANT_APPS}</li>
4046     * <li>when resolution occurs to start an activity with a {@code android.intent.action.VIEW}
4047     * action and a {@code android.intent.category.BROWSABLE} category</li>
4048     * </ul>
4049     */
4050    int updateFlagsForResolve(int flags, int userId, Intent intent, boolean includeInstantApp) {
4051        // Safe mode means we shouldn't match any third-party components
4052        if (mSafeMode) {
4053            flags |= PackageManager.MATCH_SYSTEM_ONLY;
4054        }
4055        final int callingUid = Binder.getCallingUid();
4056        if (getInstantAppPackageName(callingUid) != null) {
4057            // But, ephemeral apps see both ephemeral and exposed, non-ephemeral components
4058            flags |= PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY;
4059            flags |= PackageManager.MATCH_INSTANT;
4060        } else {
4061            // Otherwise, prevent leaking ephemeral components
4062            final boolean isSpecialProcess =
4063                    callingUid == Process.SYSTEM_UID
4064                    || callingUid == Process.SHELL_UID
4065                    || callingUid == 0;
4066            final boolean allowMatchInstant =
4067                    (includeInstantApp
4068                            && Intent.ACTION_VIEW.equals(intent.getAction())
4069                            && intent.hasCategory(Intent.CATEGORY_BROWSABLE)
4070                            && hasWebURI(intent))
4071                    || isSpecialProcess
4072                    || mContext.checkCallingOrSelfPermission(
4073                            android.Manifest.permission.ACCESS_INSTANT_APPS) == PERMISSION_GRANTED;
4074            flags &= ~PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY;
4075            if (!allowMatchInstant) {
4076                flags &= ~PackageManager.MATCH_INSTANT;
4077            }
4078        }
4079        return updateFlagsForComponent(flags, userId, intent /*cookie*/);
4080    }
4081
4082    @Override
4083    public ActivityInfo getActivityInfo(ComponentName component, int flags, int userId) {
4084        if (!sUserManager.exists(userId)) return null;
4085        flags = updateFlagsForComponent(flags, userId, component);
4086        enforceCrossUserPermission(Binder.getCallingUid(), userId,
4087                false /* requireFullPermission */, false /* checkShell */, "get activity info");
4088        synchronized (mPackages) {
4089            PackageParser.Activity a = mActivities.mActivities.get(component);
4090
4091            if (DEBUG_PACKAGE_INFO) Log.v(TAG, "getActivityInfo " + component + ": " + a);
4092            if (a != null && mSettings.isEnabledAndMatchLPr(a.info, flags, userId)) {
4093                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
4094                if (ps == null) return null;
4095                return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId),
4096                        userId);
4097            }
4098            if (mResolveComponentName.equals(component)) {
4099                return PackageParser.generateActivityInfo(mResolveActivity, flags,
4100                        new PackageUserState(), userId);
4101            }
4102        }
4103        return null;
4104    }
4105
4106    @Override
4107    public boolean activitySupportsIntent(ComponentName component, Intent intent,
4108            String resolvedType) {
4109        synchronized (mPackages) {
4110            if (component.equals(mResolveComponentName)) {
4111                // The resolver supports EVERYTHING!
4112                return true;
4113            }
4114            PackageParser.Activity a = mActivities.mActivities.get(component);
4115            if (a == null) {
4116                return false;
4117            }
4118            for (int i=0; i<a.intents.size(); i++) {
4119                if (a.intents.get(i).match(intent.getAction(), resolvedType, intent.getScheme(),
4120                        intent.getData(), intent.getCategories(), TAG) >= 0) {
4121                    return true;
4122                }
4123            }
4124            return false;
4125        }
4126    }
4127
4128    @Override
4129    public ActivityInfo getReceiverInfo(ComponentName component, int flags, int userId) {
4130        if (!sUserManager.exists(userId)) return null;
4131        flags = updateFlagsForComponent(flags, userId, component);
4132        enforceCrossUserPermission(Binder.getCallingUid(), userId,
4133                false /* requireFullPermission */, false /* checkShell */, "get receiver info");
4134        synchronized (mPackages) {
4135            PackageParser.Activity a = mReceivers.mActivities.get(component);
4136            if (DEBUG_PACKAGE_INFO) Log.v(
4137                TAG, "getReceiverInfo " + component + ": " + a);
4138            if (a != null && mSettings.isEnabledAndMatchLPr(a.info, flags, userId)) {
4139                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
4140                if (ps == null) return null;
4141                return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId),
4142                        userId);
4143            }
4144        }
4145        return null;
4146    }
4147
4148    @Override
4149    public ParceledListSlice<SharedLibraryInfo> getSharedLibraries(int flags, int userId) {
4150        if (!sUserManager.exists(userId)) return null;
4151        Preconditions.checkArgumentNonnegative(userId, "userId must be >= 0");
4152
4153        flags = updateFlagsForPackage(flags, userId, null);
4154
4155        final boolean canSeeStaticLibraries =
4156                mContext.checkCallingOrSelfPermission(INSTALL_PACKAGES)
4157                        == PERMISSION_GRANTED
4158                || mContext.checkCallingOrSelfPermission(DELETE_PACKAGES)
4159                        == PERMISSION_GRANTED
4160                || mContext.checkCallingOrSelfPermission(REQUEST_INSTALL_PACKAGES)
4161                        == PERMISSION_GRANTED
4162                || mContext.checkCallingOrSelfPermission(REQUEST_DELETE_PACKAGES)
4163                        == PERMISSION_GRANTED;
4164
4165        synchronized (mPackages) {
4166            List<SharedLibraryInfo> result = null;
4167
4168            final int libCount = mSharedLibraries.size();
4169            for (int i = 0; i < libCount; i++) {
4170                SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.valueAt(i);
4171                if (versionedLib == null) {
4172                    continue;
4173                }
4174
4175                final int versionCount = versionedLib.size();
4176                for (int j = 0; j < versionCount; j++) {
4177                    SharedLibraryInfo libInfo = versionedLib.valueAt(j).info;
4178                    if (!canSeeStaticLibraries && libInfo.isStatic()) {
4179                        break;
4180                    }
4181                    final long identity = Binder.clearCallingIdentity();
4182                    try {
4183                        // TODO: We will change version code to long, so in the new API it is long
4184                        PackageInfo packageInfo = getPackageInfoVersioned(
4185                                libInfo.getDeclaringPackage(), flags, userId);
4186                        if (packageInfo == null) {
4187                            continue;
4188                        }
4189                    } finally {
4190                        Binder.restoreCallingIdentity(identity);
4191                    }
4192
4193                    SharedLibraryInfo resLibInfo = new SharedLibraryInfo(libInfo.getName(),
4194                            libInfo.getVersion(), libInfo.getType(), libInfo.getDeclaringPackage(),
4195                            getPackagesUsingSharedLibraryLPr(libInfo, flags, userId));
4196
4197                    if (result == null) {
4198                        result = new ArrayList<>();
4199                    }
4200                    result.add(resLibInfo);
4201                }
4202            }
4203
4204            return result != null ? new ParceledListSlice<>(result) : null;
4205        }
4206    }
4207
4208    private List<VersionedPackage> getPackagesUsingSharedLibraryLPr(
4209            SharedLibraryInfo libInfo, int flags, int userId) {
4210        List<VersionedPackage> versionedPackages = null;
4211        final int packageCount = mSettings.mPackages.size();
4212        for (int i = 0; i < packageCount; i++) {
4213            PackageSetting ps = mSettings.mPackages.valueAt(i);
4214
4215            if (ps == null) {
4216                continue;
4217            }
4218
4219            if (!ps.getUserState().get(userId).isAvailable(flags)) {
4220                continue;
4221            }
4222
4223            final String libName = libInfo.getName();
4224            if (libInfo.isStatic()) {
4225                final int libIdx = ArrayUtils.indexOf(ps.usesStaticLibraries, libName);
4226                if (libIdx < 0) {
4227                    continue;
4228                }
4229                if (ps.usesStaticLibrariesVersions[libIdx] != libInfo.getVersion()) {
4230                    continue;
4231                }
4232                if (versionedPackages == null) {
4233                    versionedPackages = new ArrayList<>();
4234                }
4235                // If the dependent is a static shared lib, use the public package name
4236                String dependentPackageName = ps.name;
4237                if (ps.pkg != null && ps.pkg.applicationInfo.isStaticSharedLibrary()) {
4238                    dependentPackageName = ps.pkg.manifestPackageName;
4239                }
4240                versionedPackages.add(new VersionedPackage(dependentPackageName, ps.versionCode));
4241            } else if (ps.pkg != null) {
4242                if (ArrayUtils.contains(ps.pkg.usesLibraries, libName)
4243                        || ArrayUtils.contains(ps.pkg.usesOptionalLibraries, libName)) {
4244                    if (versionedPackages == null) {
4245                        versionedPackages = new ArrayList<>();
4246                    }
4247                    versionedPackages.add(new VersionedPackage(ps.name, ps.versionCode));
4248                }
4249            }
4250        }
4251
4252        return versionedPackages;
4253    }
4254
4255    @Override
4256    public ServiceInfo getServiceInfo(ComponentName component, int flags, int userId) {
4257        if (!sUserManager.exists(userId)) return null;
4258        flags = updateFlagsForComponent(flags, userId, component);
4259        enforceCrossUserPermission(Binder.getCallingUid(), userId,
4260                false /* requireFullPermission */, false /* checkShell */, "get service info");
4261        synchronized (mPackages) {
4262            PackageParser.Service s = mServices.mServices.get(component);
4263            if (DEBUG_PACKAGE_INFO) Log.v(
4264                TAG, "getServiceInfo " + component + ": " + s);
4265            if (s != null && mSettings.isEnabledAndMatchLPr(s.info, flags, userId)) {
4266                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
4267                if (ps == null) return null;
4268                return PackageParser.generateServiceInfo(s, flags, ps.readUserState(userId),
4269                        userId);
4270            }
4271        }
4272        return null;
4273    }
4274
4275    @Override
4276    public ProviderInfo getProviderInfo(ComponentName component, int flags, int userId) {
4277        if (!sUserManager.exists(userId)) return null;
4278        flags = updateFlagsForComponent(flags, userId, component);
4279        enforceCrossUserPermission(Binder.getCallingUid(), userId,
4280                false /* requireFullPermission */, false /* checkShell */, "get provider info");
4281        synchronized (mPackages) {
4282            PackageParser.Provider p = mProviders.mProviders.get(component);
4283            if (DEBUG_PACKAGE_INFO) Log.v(
4284                TAG, "getProviderInfo " + component + ": " + p);
4285            if (p != null && mSettings.isEnabledAndMatchLPr(p.info, flags, userId)) {
4286                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
4287                if (ps == null) return null;
4288                return PackageParser.generateProviderInfo(p, flags, ps.readUserState(userId),
4289                        userId);
4290            }
4291        }
4292        return null;
4293    }
4294
4295    @Override
4296    public String[] getSystemSharedLibraryNames() {
4297        synchronized (mPackages) {
4298            Set<String> libs = null;
4299            final int libCount = mSharedLibraries.size();
4300            for (int i = 0; i < libCount; i++) {
4301                SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.valueAt(i);
4302                if (versionedLib == null) {
4303                    continue;
4304                }
4305                final int versionCount = versionedLib.size();
4306                for (int j = 0; j < versionCount; j++) {
4307                    SharedLibraryEntry libEntry = versionedLib.valueAt(j);
4308                    if (!libEntry.info.isStatic()) {
4309                        if (libs == null) {
4310                            libs = new ArraySet<>();
4311                        }
4312                        libs.add(libEntry.info.getName());
4313                        break;
4314                    }
4315                    PackageSetting ps = mSettings.getPackageLPr(libEntry.apk);
4316                    if (ps != null && !filterSharedLibPackageLPr(ps, Binder.getCallingUid(),
4317                            UserHandle.getUserId(Binder.getCallingUid()))) {
4318                        if (libs == null) {
4319                            libs = new ArraySet<>();
4320                        }
4321                        libs.add(libEntry.info.getName());
4322                        break;
4323                    }
4324                }
4325            }
4326
4327            if (libs != null) {
4328                String[] libsArray = new String[libs.size()];
4329                libs.toArray(libsArray);
4330                return libsArray;
4331            }
4332
4333            return null;
4334        }
4335    }
4336
4337    @Override
4338    public @NonNull String getServicesSystemSharedLibraryPackageName() {
4339        synchronized (mPackages) {
4340            return mServicesSystemSharedLibraryPackageName;
4341        }
4342    }
4343
4344    @Override
4345    public @NonNull String getSharedSystemSharedLibraryPackageName() {
4346        synchronized (mPackages) {
4347            return mSharedSystemSharedLibraryPackageName;
4348        }
4349    }
4350
4351    private void updateSequenceNumberLP(String packageName, int[] userList) {
4352        for (int i = userList.length - 1; i >= 0; --i) {
4353            final int userId = userList[i];
4354            SparseArray<String> changedPackages = mChangedPackages.get(userId);
4355            if (changedPackages == null) {
4356                changedPackages = new SparseArray<>();
4357                mChangedPackages.put(userId, changedPackages);
4358            }
4359            Map<String, Integer> sequenceNumbers = mChangedPackagesSequenceNumbers.get(userId);
4360            if (sequenceNumbers == null) {
4361                sequenceNumbers = new HashMap<>();
4362                mChangedPackagesSequenceNumbers.put(userId, sequenceNumbers);
4363            }
4364            final Integer sequenceNumber = sequenceNumbers.get(packageName);
4365            if (sequenceNumber != null) {
4366                changedPackages.remove(sequenceNumber);
4367            }
4368            changedPackages.put(mChangedPackagesSequenceNumber, packageName);
4369            sequenceNumbers.put(packageName, mChangedPackagesSequenceNumber);
4370        }
4371        mChangedPackagesSequenceNumber++;
4372    }
4373
4374    @Override
4375    public ChangedPackages getChangedPackages(int sequenceNumber, int userId) {
4376        synchronized (mPackages) {
4377            if (sequenceNumber >= mChangedPackagesSequenceNumber) {
4378                return null;
4379            }
4380            final SparseArray<String> changedPackages = mChangedPackages.get(userId);
4381            if (changedPackages == null) {
4382                return null;
4383            }
4384            final List<String> packageNames =
4385                    new ArrayList<>(mChangedPackagesSequenceNumber - sequenceNumber);
4386            for (int i = sequenceNumber; i < mChangedPackagesSequenceNumber; i++) {
4387                final String packageName = changedPackages.get(i);
4388                if (packageName != null) {
4389                    packageNames.add(packageName);
4390                }
4391            }
4392            return packageNames.isEmpty()
4393                    ? null : new ChangedPackages(mChangedPackagesSequenceNumber, packageNames);
4394        }
4395    }
4396
4397    @Override
4398    public @NonNull ParceledListSlice<FeatureInfo> getSystemAvailableFeatures() {
4399        ArrayList<FeatureInfo> res;
4400        synchronized (mAvailableFeatures) {
4401            res = new ArrayList<>(mAvailableFeatures.size() + 1);
4402            res.addAll(mAvailableFeatures.values());
4403        }
4404        final FeatureInfo fi = new FeatureInfo();
4405        fi.reqGlEsVersion = SystemProperties.getInt("ro.opengles.version",
4406                FeatureInfo.GL_ES_VERSION_UNDEFINED);
4407        res.add(fi);
4408
4409        return new ParceledListSlice<>(res);
4410    }
4411
4412    @Override
4413    public boolean hasSystemFeature(String name, int version) {
4414        synchronized (mAvailableFeatures) {
4415            final FeatureInfo feat = mAvailableFeatures.get(name);
4416            if (feat == null) {
4417                return false;
4418            } else {
4419                return feat.version >= version;
4420            }
4421        }
4422    }
4423
4424    @Override
4425    public int checkPermission(String permName, String pkgName, int userId) {
4426        if (!sUserManager.exists(userId)) {
4427            return PackageManager.PERMISSION_DENIED;
4428        }
4429
4430        synchronized (mPackages) {
4431            final PackageParser.Package p = mPackages.get(pkgName);
4432            if (p != null && p.mExtras != null) {
4433                final PackageSetting ps = (PackageSetting) p.mExtras;
4434                final PermissionsState permissionsState = ps.getPermissionsState();
4435                if (permissionsState.hasPermission(permName, userId)) {
4436                    return PackageManager.PERMISSION_GRANTED;
4437                }
4438                // Special case: ACCESS_FINE_LOCATION permission includes ACCESS_COARSE_LOCATION
4439                if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && permissionsState
4440                        .hasPermission(Manifest.permission.ACCESS_FINE_LOCATION, userId)) {
4441                    return PackageManager.PERMISSION_GRANTED;
4442                }
4443            }
4444        }
4445
4446        return PackageManager.PERMISSION_DENIED;
4447    }
4448
4449    @Override
4450    public int checkUidPermission(String permName, int uid) {
4451        final int userId = UserHandle.getUserId(uid);
4452
4453        if (!sUserManager.exists(userId)) {
4454            return PackageManager.PERMISSION_DENIED;
4455        }
4456
4457        synchronized (mPackages) {
4458            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
4459            if (obj != null) {
4460                final SettingBase ps = (SettingBase) obj;
4461                final PermissionsState permissionsState = ps.getPermissionsState();
4462                if (permissionsState.hasPermission(permName, userId)) {
4463                    return PackageManager.PERMISSION_GRANTED;
4464                }
4465                // Special case: ACCESS_FINE_LOCATION permission includes ACCESS_COARSE_LOCATION
4466                if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && permissionsState
4467                        .hasPermission(Manifest.permission.ACCESS_FINE_LOCATION, userId)) {
4468                    return PackageManager.PERMISSION_GRANTED;
4469                }
4470            } else {
4471                ArraySet<String> perms = mSystemPermissions.get(uid);
4472                if (perms != null) {
4473                    if (perms.contains(permName)) {
4474                        return PackageManager.PERMISSION_GRANTED;
4475                    }
4476                    if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && perms
4477                            .contains(Manifest.permission.ACCESS_FINE_LOCATION)) {
4478                        return PackageManager.PERMISSION_GRANTED;
4479                    }
4480                }
4481            }
4482        }
4483
4484        return PackageManager.PERMISSION_DENIED;
4485    }
4486
4487    @Override
4488    public boolean isPermissionRevokedByPolicy(String permission, String packageName, int userId) {
4489        if (UserHandle.getCallingUserId() != userId) {
4490            mContext.enforceCallingPermission(
4491                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
4492                    "isPermissionRevokedByPolicy for user " + userId);
4493        }
4494
4495        if (checkPermission(permission, packageName, userId)
4496                == PackageManager.PERMISSION_GRANTED) {
4497            return false;
4498        }
4499
4500        final long identity = Binder.clearCallingIdentity();
4501        try {
4502            final int flags = getPermissionFlags(permission, packageName, userId);
4503            return (flags & PackageManager.FLAG_PERMISSION_POLICY_FIXED) != 0;
4504        } finally {
4505            Binder.restoreCallingIdentity(identity);
4506        }
4507    }
4508
4509    @Override
4510    public String getPermissionControllerPackageName() {
4511        synchronized (mPackages) {
4512            return mRequiredInstallerPackage;
4513        }
4514    }
4515
4516    /**
4517     * Checks if the request is from the system or an app that has INTERACT_ACROSS_USERS
4518     * or INTERACT_ACROSS_USERS_FULL permissions, if the userid is not for the caller.
4519     * @param checkShell whether to prevent shell from access if there's a debugging restriction
4520     * @param message the message to log on security exception
4521     */
4522    void enforceCrossUserPermission(int callingUid, int userId, boolean requireFullPermission,
4523            boolean checkShell, String message) {
4524        if (userId < 0) {
4525            throw new IllegalArgumentException("Invalid userId " + userId);
4526        }
4527        if (checkShell) {
4528            enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, userId);
4529        }
4530        if (userId == UserHandle.getUserId(callingUid)) return;
4531        if (callingUid != Process.SYSTEM_UID && callingUid != 0) {
4532            if (requireFullPermission) {
4533                mContext.enforceCallingOrSelfPermission(
4534                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message);
4535            } else {
4536                try {
4537                    mContext.enforceCallingOrSelfPermission(
4538                            android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message);
4539                } catch (SecurityException se) {
4540                    mContext.enforceCallingOrSelfPermission(
4541                            android.Manifest.permission.INTERACT_ACROSS_USERS, message);
4542                }
4543            }
4544        }
4545    }
4546
4547    void enforceShellRestriction(String restriction, int callingUid, int userHandle) {
4548        if (callingUid == Process.SHELL_UID) {
4549            if (userHandle >= 0
4550                    && sUserManager.hasUserRestriction(restriction, userHandle)) {
4551                throw new SecurityException("Shell does not have permission to access user "
4552                        + userHandle);
4553            } else if (userHandle < 0) {
4554                Slog.e(TAG, "Unable to check shell permission for user " + userHandle + "\n\t"
4555                        + Debug.getCallers(3));
4556            }
4557        }
4558    }
4559
4560    private BasePermission findPermissionTreeLP(String permName) {
4561        for(BasePermission bp : mSettings.mPermissionTrees.values()) {
4562            if (permName.startsWith(bp.name) &&
4563                    permName.length() > bp.name.length() &&
4564                    permName.charAt(bp.name.length()) == '.') {
4565                return bp;
4566            }
4567        }
4568        return null;
4569    }
4570
4571    private BasePermission checkPermissionTreeLP(String permName) {
4572        if (permName != null) {
4573            BasePermission bp = findPermissionTreeLP(permName);
4574            if (bp != null) {
4575                if (bp.uid == UserHandle.getAppId(Binder.getCallingUid())) {
4576                    return bp;
4577                }
4578                throw new SecurityException("Calling uid "
4579                        + Binder.getCallingUid()
4580                        + " is not allowed to add to permission tree "
4581                        + bp.name + " owned by uid " + bp.uid);
4582            }
4583        }
4584        throw new SecurityException("No permission tree found for " + permName);
4585    }
4586
4587    static boolean compareStrings(CharSequence s1, CharSequence s2) {
4588        if (s1 == null) {
4589            return s2 == null;
4590        }
4591        if (s2 == null) {
4592            return false;
4593        }
4594        if (s1.getClass() != s2.getClass()) {
4595            return false;
4596        }
4597        return s1.equals(s2);
4598    }
4599
4600    static boolean comparePermissionInfos(PermissionInfo pi1, PermissionInfo pi2) {
4601        if (pi1.icon != pi2.icon) return false;
4602        if (pi1.logo != pi2.logo) return false;
4603        if (pi1.protectionLevel != pi2.protectionLevel) return false;
4604        if (!compareStrings(pi1.name, pi2.name)) return false;
4605        if (!compareStrings(pi1.nonLocalizedLabel, pi2.nonLocalizedLabel)) return false;
4606        // We'll take care of setting this one.
4607        if (!compareStrings(pi1.packageName, pi2.packageName)) return false;
4608        // These are not currently stored in settings.
4609        //if (!compareStrings(pi1.group, pi2.group)) return false;
4610        //if (!compareStrings(pi1.nonLocalizedDescription, pi2.nonLocalizedDescription)) return false;
4611        //if (pi1.labelRes != pi2.labelRes) return false;
4612        //if (pi1.descriptionRes != pi2.descriptionRes) return false;
4613        return true;
4614    }
4615
4616    int permissionInfoFootprint(PermissionInfo info) {
4617        int size = info.name.length();
4618        if (info.nonLocalizedLabel != null) size += info.nonLocalizedLabel.length();
4619        if (info.nonLocalizedDescription != null) size += info.nonLocalizedDescription.length();
4620        return size;
4621    }
4622
4623    int calculateCurrentPermissionFootprintLocked(BasePermission tree) {
4624        int size = 0;
4625        for (BasePermission perm : mSettings.mPermissions.values()) {
4626            if (perm.uid == tree.uid) {
4627                size += perm.name.length() + permissionInfoFootprint(perm.perm.info);
4628            }
4629        }
4630        return size;
4631    }
4632
4633    void enforcePermissionCapLocked(PermissionInfo info, BasePermission tree) {
4634        // We calculate the max size of permissions defined by this uid and throw
4635        // if that plus the size of 'info' would exceed our stated maximum.
4636        if (tree.uid != Process.SYSTEM_UID) {
4637            final int curTreeSize = calculateCurrentPermissionFootprintLocked(tree);
4638            if (curTreeSize + permissionInfoFootprint(info) > MAX_PERMISSION_TREE_FOOTPRINT) {
4639                throw new SecurityException("Permission tree size cap exceeded");
4640            }
4641        }
4642    }
4643
4644    boolean addPermissionLocked(PermissionInfo info, boolean async) {
4645        if (info.labelRes == 0 && info.nonLocalizedLabel == null) {
4646            throw new SecurityException("Label must be specified in permission");
4647        }
4648        BasePermission tree = checkPermissionTreeLP(info.name);
4649        BasePermission bp = mSettings.mPermissions.get(info.name);
4650        boolean added = bp == null;
4651        boolean changed = true;
4652        int fixedLevel = PermissionInfo.fixProtectionLevel(info.protectionLevel);
4653        if (added) {
4654            enforcePermissionCapLocked(info, tree);
4655            bp = new BasePermission(info.name, tree.sourcePackage,
4656                    BasePermission.TYPE_DYNAMIC);
4657        } else if (bp.type != BasePermission.TYPE_DYNAMIC) {
4658            throw new SecurityException(
4659                    "Not allowed to modify non-dynamic permission "
4660                    + info.name);
4661        } else {
4662            if (bp.protectionLevel == fixedLevel
4663                    && bp.perm.owner.equals(tree.perm.owner)
4664                    && bp.uid == tree.uid
4665                    && comparePermissionInfos(bp.perm.info, info)) {
4666                changed = false;
4667            }
4668        }
4669        bp.protectionLevel = fixedLevel;
4670        info = new PermissionInfo(info);
4671        info.protectionLevel = fixedLevel;
4672        bp.perm = new PackageParser.Permission(tree.perm.owner, info);
4673        bp.perm.info.packageName = tree.perm.info.packageName;
4674        bp.uid = tree.uid;
4675        if (added) {
4676            mSettings.mPermissions.put(info.name, bp);
4677        }
4678        if (changed) {
4679            if (!async) {
4680                mSettings.writeLPr();
4681            } else {
4682                scheduleWriteSettingsLocked();
4683            }
4684        }
4685        return added;
4686    }
4687
4688    @Override
4689    public boolean addPermission(PermissionInfo info) {
4690        synchronized (mPackages) {
4691            return addPermissionLocked(info, false);
4692        }
4693    }
4694
4695    @Override
4696    public boolean addPermissionAsync(PermissionInfo info) {
4697        synchronized (mPackages) {
4698            return addPermissionLocked(info, true);
4699        }
4700    }
4701
4702    @Override
4703    public void removePermission(String name) {
4704        synchronized (mPackages) {
4705            checkPermissionTreeLP(name);
4706            BasePermission bp = mSettings.mPermissions.get(name);
4707            if (bp != null) {
4708                if (bp.type != BasePermission.TYPE_DYNAMIC) {
4709                    throw new SecurityException(
4710                            "Not allowed to modify non-dynamic permission "
4711                            + name);
4712                }
4713                mSettings.mPermissions.remove(name);
4714                mSettings.writeLPr();
4715            }
4716        }
4717    }
4718
4719    private static void enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(PackageParser.Package pkg,
4720            BasePermission bp) {
4721        int index = pkg.requestedPermissions.indexOf(bp.name);
4722        if (index == -1) {
4723            throw new SecurityException("Package " + pkg.packageName
4724                    + " has not requested permission " + bp.name);
4725        }
4726        if (!bp.isRuntime() && !bp.isDevelopment()) {
4727            throw new SecurityException("Permission " + bp.name
4728                    + " is not a changeable permission type");
4729        }
4730    }
4731
4732    @Override
4733    public void grantRuntimePermission(String packageName, String name, final int userId) {
4734        grantRuntimePermission(packageName, name, userId, false /* Only if not fixed by policy */);
4735    }
4736
4737    private void grantRuntimePermission(String packageName, String name, final int userId,
4738            boolean overridePolicy) {
4739        if (!sUserManager.exists(userId)) {
4740            Log.e(TAG, "No such user:" + userId);
4741            return;
4742        }
4743
4744        mContext.enforceCallingOrSelfPermission(
4745                android.Manifest.permission.GRANT_RUNTIME_PERMISSIONS,
4746                "grantRuntimePermission");
4747
4748        enforceCrossUserPermission(Binder.getCallingUid(), userId,
4749                true /* requireFullPermission */, true /* checkShell */,
4750                "grantRuntimePermission");
4751
4752        final int uid;
4753        final SettingBase sb;
4754
4755        synchronized (mPackages) {
4756            final PackageParser.Package pkg = mPackages.get(packageName);
4757            if (pkg == null) {
4758                throw new IllegalArgumentException("Unknown package: " + packageName);
4759            }
4760
4761            final BasePermission bp = mSettings.mPermissions.get(name);
4762            if (bp == null) {
4763                throw new IllegalArgumentException("Unknown permission: " + name);
4764            }
4765
4766            enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(pkg, bp);
4767
4768            // If a permission review is required for legacy apps we represent
4769            // their permissions as always granted runtime ones since we need
4770            // to keep the review required permission flag per user while an
4771            // install permission's state is shared across all users.
4772            if (mPermissionReviewRequired
4773                    && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M
4774                    && bp.isRuntime()) {
4775                return;
4776            }
4777
4778            uid = UserHandle.getUid(userId, pkg.applicationInfo.uid);
4779            sb = (SettingBase) pkg.mExtras;
4780            if (sb == null) {
4781                throw new IllegalArgumentException("Unknown package: " + packageName);
4782            }
4783
4784            final PermissionsState permissionsState = sb.getPermissionsState();
4785
4786            final int flags = permissionsState.getPermissionFlags(name, userId);
4787            if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) {
4788                throw new SecurityException("Cannot grant system fixed permission "
4789                        + name + " for package " + packageName);
4790            }
4791            if (!overridePolicy && (flags & PackageManager.FLAG_PERMISSION_POLICY_FIXED) != 0) {
4792                throw new SecurityException("Cannot grant policy fixed permission "
4793                        + name + " for package " + packageName);
4794            }
4795
4796            if (bp.isDevelopment()) {
4797                // Development permissions must be handled specially, since they are not
4798                // normal runtime permissions.  For now they apply to all users.
4799                if (permissionsState.grantInstallPermission(bp) !=
4800                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
4801                    scheduleWriteSettingsLocked();
4802                }
4803                return;
4804            }
4805
4806            final PackageSetting ps = mSettings.mPackages.get(packageName);
4807            if (ps.getInstantApp(userId) && !bp.isInstant()) {
4808                throw new SecurityException("Cannot grant non-ephemeral permission"
4809                        + name + " for package " + packageName);
4810            }
4811
4812            if (pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) {
4813                Slog.w(TAG, "Cannot grant runtime permission to a legacy app");
4814                return;
4815            }
4816
4817            final int result = permissionsState.grantRuntimePermission(bp, userId);
4818            switch (result) {
4819                case PermissionsState.PERMISSION_OPERATION_FAILURE: {
4820                    return;
4821                }
4822
4823                case PermissionsState.PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: {
4824                    final int appId = UserHandle.getAppId(pkg.applicationInfo.uid);
4825                    mHandler.post(new Runnable() {
4826                        @Override
4827                        public void run() {
4828                            killUid(appId, userId, KILL_APP_REASON_GIDS_CHANGED);
4829                        }
4830                    });
4831                }
4832                break;
4833            }
4834
4835            if (bp.isRuntime()) {
4836                logPermissionGranted(mContext, name, packageName);
4837            }
4838
4839            mOnPermissionChangeListeners.onPermissionsChanged(uid);
4840
4841            // Not critical if that is lost - app has to request again.
4842            mSettings.writeRuntimePermissionsForUserLPr(userId, false);
4843        }
4844
4845        // Only need to do this if user is initialized. Otherwise it's a new user
4846        // and there are no processes running as the user yet and there's no need
4847        // to make an expensive call to remount processes for the changed permissions.
4848        if (READ_EXTERNAL_STORAGE.equals(name)
4849                || WRITE_EXTERNAL_STORAGE.equals(name)) {
4850            final long token = Binder.clearCallingIdentity();
4851            try {
4852                if (sUserManager.isInitialized(userId)) {
4853                    StorageManagerInternal storageManagerInternal = LocalServices.getService(
4854                            StorageManagerInternal.class);
4855                    storageManagerInternal.onExternalStoragePolicyChanged(uid, packageName);
4856                }
4857            } finally {
4858                Binder.restoreCallingIdentity(token);
4859            }
4860        }
4861    }
4862
4863    @Override
4864    public void revokeRuntimePermission(String packageName, String name, int userId) {
4865        revokeRuntimePermission(packageName, name, userId, false /* Only if not fixed by policy */);
4866    }
4867
4868    private void revokeRuntimePermission(String packageName, String name, int userId,
4869            boolean overridePolicy) {
4870        if (!sUserManager.exists(userId)) {
4871            Log.e(TAG, "No such user:" + userId);
4872            return;
4873        }
4874
4875        mContext.enforceCallingOrSelfPermission(
4876                android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS,
4877                "revokeRuntimePermission");
4878
4879        enforceCrossUserPermission(Binder.getCallingUid(), userId,
4880                true /* requireFullPermission */, true /* checkShell */,
4881                "revokeRuntimePermission");
4882
4883        final int appId;
4884
4885        synchronized (mPackages) {
4886            final PackageParser.Package pkg = mPackages.get(packageName);
4887            if (pkg == null) {
4888                throw new IllegalArgumentException("Unknown package: " + packageName);
4889            }
4890
4891            final BasePermission bp = mSettings.mPermissions.get(name);
4892            if (bp == null) {
4893                throw new IllegalArgumentException("Unknown permission: " + name);
4894            }
4895
4896            enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(pkg, bp);
4897
4898            // If a permission review is required for legacy apps we represent
4899            // their permissions as always granted runtime ones since we need
4900            // to keep the review required permission flag per user while an
4901            // install permission's state is shared across all users.
4902            if (mPermissionReviewRequired
4903                    && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M
4904                    && bp.isRuntime()) {
4905                return;
4906            }
4907
4908            SettingBase sb = (SettingBase) pkg.mExtras;
4909            if (sb == null) {
4910                throw new IllegalArgumentException("Unknown package: " + packageName);
4911            }
4912
4913            final PermissionsState permissionsState = sb.getPermissionsState();
4914
4915            final int flags = permissionsState.getPermissionFlags(name, userId);
4916            if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) {
4917                throw new SecurityException("Cannot revoke system fixed permission "
4918                        + name + " for package " + packageName);
4919            }
4920            if (!overridePolicy && (flags & PackageManager.FLAG_PERMISSION_POLICY_FIXED) != 0) {
4921                throw new SecurityException("Cannot revoke policy fixed permission "
4922                        + name + " for package " + packageName);
4923            }
4924
4925            if (bp.isDevelopment()) {
4926                // Development permissions must be handled specially, since they are not
4927                // normal runtime permissions.  For now they apply to all users.
4928                if (permissionsState.revokeInstallPermission(bp) !=
4929                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
4930                    scheduleWriteSettingsLocked();
4931                }
4932                return;
4933            }
4934
4935            if (permissionsState.revokeRuntimePermission(bp, userId) ==
4936                    PermissionsState.PERMISSION_OPERATION_FAILURE) {
4937                return;
4938            }
4939
4940            if (bp.isRuntime()) {
4941                logPermissionRevoked(mContext, name, packageName);
4942            }
4943
4944            mOnPermissionChangeListeners.onPermissionsChanged(pkg.applicationInfo.uid);
4945
4946            // Critical, after this call app should never have the permission.
4947            mSettings.writeRuntimePermissionsForUserLPr(userId, true);
4948
4949            appId = UserHandle.getAppId(pkg.applicationInfo.uid);
4950        }
4951
4952        killUid(appId, userId, KILL_APP_REASON_PERMISSIONS_REVOKED);
4953    }
4954
4955    /**
4956     * Get the first event id for the permission.
4957     *
4958     * <p>There are four events for each permission: <ul>
4959     *     <li>Request permission: first id + 0</li>
4960     *     <li>Grant permission: first id + 1</li>
4961     *     <li>Request for permission denied: first id + 2</li>
4962     *     <li>Revoke permission: first id + 3</li>
4963     * </ul></p>
4964     *
4965     * @param name name of the permission
4966     *
4967     * @return The first event id for the permission
4968     */
4969    private static int getBaseEventId(@NonNull String name) {
4970        int eventIdIndex = ALL_DANGEROUS_PERMISSIONS.indexOf(name);
4971
4972        if (eventIdIndex == -1) {
4973            if (AppOpsManager.permissionToOpCode(name) == AppOpsManager.OP_NONE
4974                    || "user".equals(Build.TYPE)) {
4975                Log.i(TAG, "Unknown permission " + name);
4976
4977                return MetricsEvent.ACTION_PERMISSION_REQUEST_UNKNOWN;
4978            } else {
4979                // Most likely #ALL_DANGEROUS_PERMISSIONS needs to be updated.
4980                //
4981                // Also update
4982                // - EventLogger#ALL_DANGEROUS_PERMISSIONS
4983                // - metrics_constants.proto
4984                throw new IllegalStateException("Unknown permission " + name);
4985            }
4986        }
4987
4988        return MetricsEvent.ACTION_PERMISSION_REQUEST_READ_CALENDAR + eventIdIndex * 4;
4989    }
4990
4991    /**
4992     * Log that a permission was revoked.
4993     *
4994     * @param context Context of the caller
4995     * @param name name of the permission
4996     * @param packageName package permission if for
4997     */
4998    private static void logPermissionRevoked(@NonNull Context context, @NonNull String name,
4999            @NonNull String packageName) {
5000        MetricsLogger.action(context, getBaseEventId(name) + 3, packageName);
5001    }
5002
5003    /**
5004     * Log that a permission request was granted.
5005     *
5006     * @param context Context of the caller
5007     * @param name name of the permission
5008     * @param packageName package permission if for
5009     */
5010    private static void logPermissionGranted(@NonNull Context context, @NonNull String name,
5011            @NonNull String packageName) {
5012        MetricsLogger.action(context, getBaseEventId(name) + 1, packageName);
5013    }
5014
5015    @Override
5016    public void resetRuntimePermissions() {
5017        mContext.enforceCallingOrSelfPermission(
5018                android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS,
5019                "revokeRuntimePermission");
5020
5021        int callingUid = Binder.getCallingUid();
5022        if (callingUid != Process.SYSTEM_UID && callingUid != 0) {
5023            mContext.enforceCallingOrSelfPermission(
5024                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
5025                    "resetRuntimePermissions");
5026        }
5027
5028        synchronized (mPackages) {
5029            updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL);
5030            for (int userId : UserManagerService.getInstance().getUserIds()) {
5031                final int packageCount = mPackages.size();
5032                for (int i = 0; i < packageCount; i++) {
5033                    PackageParser.Package pkg = mPackages.valueAt(i);
5034                    if (!(pkg.mExtras instanceof PackageSetting)) {
5035                        continue;
5036                    }
5037                    PackageSetting ps = (PackageSetting) pkg.mExtras;
5038                    resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
5039                }
5040            }
5041        }
5042    }
5043
5044    @Override
5045    public int getPermissionFlags(String name, String packageName, int userId) {
5046        if (!sUserManager.exists(userId)) {
5047            return 0;
5048        }
5049
5050        enforceGrantRevokeRuntimePermissionPermissions("getPermissionFlags");
5051
5052        enforceCrossUserPermission(Binder.getCallingUid(), userId,
5053                true /* requireFullPermission */, false /* checkShell */,
5054                "getPermissionFlags");
5055
5056        synchronized (mPackages) {
5057            final PackageParser.Package pkg = mPackages.get(packageName);
5058            if (pkg == null) {
5059                return 0;
5060            }
5061
5062            final BasePermission bp = mSettings.mPermissions.get(name);
5063            if (bp == null) {
5064                return 0;
5065            }
5066
5067            SettingBase sb = (SettingBase) pkg.mExtras;
5068            if (sb == null) {
5069                return 0;
5070            }
5071
5072            PermissionsState permissionsState = sb.getPermissionsState();
5073            return permissionsState.getPermissionFlags(name, userId);
5074        }
5075    }
5076
5077    @Override
5078    public void updatePermissionFlags(String name, String packageName, int flagMask,
5079            int flagValues, int userId) {
5080        if (!sUserManager.exists(userId)) {
5081            return;
5082        }
5083
5084        enforceGrantRevokeRuntimePermissionPermissions("updatePermissionFlags");
5085
5086        enforceCrossUserPermission(Binder.getCallingUid(), userId,
5087                true /* requireFullPermission */, true /* checkShell */,
5088                "updatePermissionFlags");
5089
5090        // Only the system can change these flags and nothing else.
5091        if (getCallingUid() != Process.SYSTEM_UID) {
5092            flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
5093            flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
5094            flagMask &= ~PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT;
5095            flagValues &= ~PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT;
5096            flagValues &= ~PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED;
5097        }
5098
5099        synchronized (mPackages) {
5100            final PackageParser.Package pkg = mPackages.get(packageName);
5101            if (pkg == null) {
5102                throw new IllegalArgumentException("Unknown package: " + packageName);
5103            }
5104
5105            final BasePermission bp = mSettings.mPermissions.get(name);
5106            if (bp == null) {
5107                throw new IllegalArgumentException("Unknown permission: " + name);
5108            }
5109
5110            SettingBase sb = (SettingBase) pkg.mExtras;
5111            if (sb == null) {
5112                throw new IllegalArgumentException("Unknown package: " + packageName);
5113            }
5114
5115            PermissionsState permissionsState = sb.getPermissionsState();
5116
5117            boolean hadState = permissionsState.getRuntimePermissionState(name, userId) != null;
5118
5119            if (permissionsState.updatePermissionFlags(bp, userId, flagMask, flagValues)) {
5120                // Install and runtime permissions are stored in different places,
5121                // so figure out what permission changed and persist the change.
5122                if (permissionsState.getInstallPermissionState(name) != null) {
5123                    scheduleWriteSettingsLocked();
5124                } else if (permissionsState.getRuntimePermissionState(name, userId) != null
5125                        || hadState) {
5126                    mSettings.writeRuntimePermissionsForUserLPr(userId, false);
5127                }
5128            }
5129        }
5130    }
5131
5132    /**
5133     * Update the permission flags for all packages and runtime permissions of a user in order
5134     * to allow device or profile owner to remove POLICY_FIXED.
5135     */
5136    @Override
5137    public void updatePermissionFlagsForAllApps(int flagMask, int flagValues, int userId) {
5138        if (!sUserManager.exists(userId)) {
5139            return;
5140        }
5141
5142        enforceGrantRevokeRuntimePermissionPermissions("updatePermissionFlagsForAllApps");
5143
5144        enforceCrossUserPermission(Binder.getCallingUid(), userId,
5145                true /* requireFullPermission */, true /* checkShell */,
5146                "updatePermissionFlagsForAllApps");
5147
5148        // Only the system can change system fixed flags.
5149        if (getCallingUid() != Process.SYSTEM_UID) {
5150            flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
5151            flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
5152        }
5153
5154        synchronized (mPackages) {
5155            boolean changed = false;
5156            final int packageCount = mPackages.size();
5157            for (int pkgIndex = 0; pkgIndex < packageCount; pkgIndex++) {
5158                final PackageParser.Package pkg = mPackages.valueAt(pkgIndex);
5159                SettingBase sb = (SettingBase) pkg.mExtras;
5160                if (sb == null) {
5161                    continue;
5162                }
5163                PermissionsState permissionsState = sb.getPermissionsState();
5164                changed |= permissionsState.updatePermissionFlagsForAllPermissions(
5165                        userId, flagMask, flagValues);
5166            }
5167            if (changed) {
5168                mSettings.writeRuntimePermissionsForUserLPr(userId, false);
5169            }
5170        }
5171    }
5172
5173    private void enforceGrantRevokeRuntimePermissionPermissions(String message) {
5174        if (mContext.checkCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS)
5175                != PackageManager.PERMISSION_GRANTED
5176            && mContext.checkCallingOrSelfPermission(Manifest.permission.REVOKE_RUNTIME_PERMISSIONS)
5177                != PackageManager.PERMISSION_GRANTED) {
5178            throw new SecurityException(message + " requires "
5179                    + Manifest.permission.GRANT_RUNTIME_PERMISSIONS + " or "
5180                    + Manifest.permission.REVOKE_RUNTIME_PERMISSIONS);
5181        }
5182    }
5183
5184    @Override
5185    public boolean shouldShowRequestPermissionRationale(String permissionName,
5186            String packageName, int userId) {
5187        if (UserHandle.getCallingUserId() != userId) {
5188            mContext.enforceCallingPermission(
5189                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
5190                    "canShowRequestPermissionRationale for user " + userId);
5191        }
5192
5193        final int uid = getPackageUid(packageName, MATCH_DEBUG_TRIAGED_MISSING, userId);
5194        if (UserHandle.getAppId(getCallingUid()) != UserHandle.getAppId(uid)) {
5195            return false;
5196        }
5197
5198        if (checkPermission(permissionName, packageName, userId)
5199                == PackageManager.PERMISSION_GRANTED) {
5200            return false;
5201        }
5202
5203        final int flags;
5204
5205        final long identity = Binder.clearCallingIdentity();
5206        try {
5207            flags = getPermissionFlags(permissionName,
5208                    packageName, userId);
5209        } finally {
5210            Binder.restoreCallingIdentity(identity);
5211        }
5212
5213        final int fixedFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED
5214                | PackageManager.FLAG_PERMISSION_POLICY_FIXED
5215                | PackageManager.FLAG_PERMISSION_USER_FIXED;
5216
5217        if ((flags & fixedFlags) != 0) {
5218            return false;
5219        }
5220
5221        return (flags & PackageManager.FLAG_PERMISSION_USER_SET) != 0;
5222    }
5223
5224    @Override
5225    public void addOnPermissionsChangeListener(IOnPermissionsChangeListener listener) {
5226        mContext.enforceCallingOrSelfPermission(
5227                Manifest.permission.OBSERVE_GRANT_REVOKE_PERMISSIONS,
5228                "addOnPermissionsChangeListener");
5229
5230        synchronized (mPackages) {
5231            mOnPermissionChangeListeners.addListenerLocked(listener);
5232        }
5233    }
5234
5235    @Override
5236    public void removeOnPermissionsChangeListener(IOnPermissionsChangeListener listener) {
5237        synchronized (mPackages) {
5238            mOnPermissionChangeListeners.removeListenerLocked(listener);
5239        }
5240    }
5241
5242    @Override
5243    public boolean isProtectedBroadcast(String actionName) {
5244        synchronized (mPackages) {
5245            if (mProtectedBroadcasts.contains(actionName)) {
5246                return true;
5247            } else if (actionName != null) {
5248                // TODO: remove these terrible hacks
5249                if (actionName.startsWith("android.net.netmon.lingerExpired")
5250                        || actionName.startsWith("com.android.server.sip.SipWakeupTimer")
5251                        || actionName.startsWith("com.android.internal.telephony.data-reconnect")
5252                        || actionName.startsWith("android.net.netmon.launchCaptivePortalApp")) {
5253                    return true;
5254                }
5255            }
5256        }
5257        return false;
5258    }
5259
5260    @Override
5261    public int checkSignatures(String pkg1, String pkg2) {
5262        synchronized (mPackages) {
5263            final PackageParser.Package p1 = mPackages.get(pkg1);
5264            final PackageParser.Package p2 = mPackages.get(pkg2);
5265            if (p1 == null || p1.mExtras == null
5266                    || p2 == null || p2.mExtras == null) {
5267                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5268            }
5269            return compareSignatures(p1.mSignatures, p2.mSignatures);
5270        }
5271    }
5272
5273    @Override
5274    public int checkUidSignatures(int uid1, int uid2) {
5275        // Map to base uids.
5276        uid1 = UserHandle.getAppId(uid1);
5277        uid2 = UserHandle.getAppId(uid2);
5278        // reader
5279        synchronized (mPackages) {
5280            Signature[] s1;
5281            Signature[] s2;
5282            Object obj = mSettings.getUserIdLPr(uid1);
5283            if (obj != null) {
5284                if (obj instanceof SharedUserSetting) {
5285                    s1 = ((SharedUserSetting)obj).signatures.mSignatures;
5286                } else if (obj instanceof PackageSetting) {
5287                    s1 = ((PackageSetting)obj).signatures.mSignatures;
5288                } else {
5289                    return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5290                }
5291            } else {
5292                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5293            }
5294            obj = mSettings.getUserIdLPr(uid2);
5295            if (obj != null) {
5296                if (obj instanceof SharedUserSetting) {
5297                    s2 = ((SharedUserSetting)obj).signatures.mSignatures;
5298                } else if (obj instanceof PackageSetting) {
5299                    s2 = ((PackageSetting)obj).signatures.mSignatures;
5300                } else {
5301                    return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5302                }
5303            } else {
5304                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5305            }
5306            return compareSignatures(s1, s2);
5307        }
5308    }
5309
5310    /**
5311     * This method should typically only be used when granting or revoking
5312     * permissions, since the app may immediately restart after this call.
5313     * <p>
5314     * If you're doing surgery on app code/data, use {@link PackageFreezer} to
5315     * guard your work against the app being relaunched.
5316     */
5317    private void killUid(int appId, int userId, String reason) {
5318        final long identity = Binder.clearCallingIdentity();
5319        try {
5320            IActivityManager am = ActivityManager.getService();
5321            if (am != null) {
5322                try {
5323                    am.killUid(appId, userId, reason);
5324                } catch (RemoteException e) {
5325                    /* ignore - same process */
5326                }
5327            }
5328        } finally {
5329            Binder.restoreCallingIdentity(identity);
5330        }
5331    }
5332
5333    /**
5334     * Compares two sets of signatures. Returns:
5335     * <br />
5336     * {@link PackageManager#SIGNATURE_NEITHER_SIGNED}: if both signature sets are null,
5337     * <br />
5338     * {@link PackageManager#SIGNATURE_FIRST_NOT_SIGNED}: if the first signature set is null,
5339     * <br />
5340     * {@link PackageManager#SIGNATURE_SECOND_NOT_SIGNED}: if the second signature set is null,
5341     * <br />
5342     * {@link PackageManager#SIGNATURE_MATCH}: if the two signature sets are identical,
5343     * <br />
5344     * {@link PackageManager#SIGNATURE_NO_MATCH}: if the two signature sets differ.
5345     */
5346    static int compareSignatures(Signature[] s1, Signature[] s2) {
5347        if (s1 == null) {
5348            return s2 == null
5349                    ? PackageManager.SIGNATURE_NEITHER_SIGNED
5350                    : PackageManager.SIGNATURE_FIRST_NOT_SIGNED;
5351        }
5352
5353        if (s2 == null) {
5354            return PackageManager.SIGNATURE_SECOND_NOT_SIGNED;
5355        }
5356
5357        if (s1.length != s2.length) {
5358            return PackageManager.SIGNATURE_NO_MATCH;
5359        }
5360
5361        // Since both signature sets are of size 1, we can compare without HashSets.
5362        if (s1.length == 1) {
5363            return s1[0].equals(s2[0]) ?
5364                    PackageManager.SIGNATURE_MATCH :
5365                    PackageManager.SIGNATURE_NO_MATCH;
5366        }
5367
5368        ArraySet<Signature> set1 = new ArraySet<Signature>();
5369        for (Signature sig : s1) {
5370            set1.add(sig);
5371        }
5372        ArraySet<Signature> set2 = new ArraySet<Signature>();
5373        for (Signature sig : s2) {
5374            set2.add(sig);
5375        }
5376        // Make sure s2 contains all signatures in s1.
5377        if (set1.equals(set2)) {
5378            return PackageManager.SIGNATURE_MATCH;
5379        }
5380        return PackageManager.SIGNATURE_NO_MATCH;
5381    }
5382
5383    /**
5384     * If the database version for this type of package (internal storage or
5385     * external storage) is less than the version where package signatures
5386     * were updated, return true.
5387     */
5388    private boolean isCompatSignatureUpdateNeeded(PackageParser.Package scannedPkg) {
5389        final VersionInfo ver = getSettingsVersionForPackage(scannedPkg);
5390        return ver.databaseVersion < DatabaseVersion.SIGNATURE_END_ENTITY;
5391    }
5392
5393    /**
5394     * Used for backward compatibility to make sure any packages with
5395     * certificate chains get upgraded to the new style. {@code existingSigs}
5396     * will be in the old format (since they were stored on disk from before the
5397     * system upgrade) and {@code scannedSigs} will be in the newer format.
5398     */
5399    private int compareSignaturesCompat(PackageSignatures existingSigs,
5400            PackageParser.Package scannedPkg) {
5401        if (!isCompatSignatureUpdateNeeded(scannedPkg)) {
5402            return PackageManager.SIGNATURE_NO_MATCH;
5403        }
5404
5405        ArraySet<Signature> existingSet = new ArraySet<Signature>();
5406        for (Signature sig : existingSigs.mSignatures) {
5407            existingSet.add(sig);
5408        }
5409        ArraySet<Signature> scannedCompatSet = new ArraySet<Signature>();
5410        for (Signature sig : scannedPkg.mSignatures) {
5411            try {
5412                Signature[] chainSignatures = sig.getChainSignatures();
5413                for (Signature chainSig : chainSignatures) {
5414                    scannedCompatSet.add(chainSig);
5415                }
5416            } catch (CertificateEncodingException e) {
5417                scannedCompatSet.add(sig);
5418            }
5419        }
5420        /*
5421         * Make sure the expanded scanned set contains all signatures in the
5422         * existing one.
5423         */
5424        if (scannedCompatSet.equals(existingSet)) {
5425            // Migrate the old signatures to the new scheme.
5426            existingSigs.assignSignatures(scannedPkg.mSignatures);
5427            // The new KeySets will be re-added later in the scanning process.
5428            synchronized (mPackages) {
5429                mSettings.mKeySetManagerService.removeAppKeySetDataLPw(scannedPkg.packageName);
5430            }
5431            return PackageManager.SIGNATURE_MATCH;
5432        }
5433        return PackageManager.SIGNATURE_NO_MATCH;
5434    }
5435
5436    private boolean isRecoverSignatureUpdateNeeded(PackageParser.Package scannedPkg) {
5437        final VersionInfo ver = getSettingsVersionForPackage(scannedPkg);
5438        return ver.databaseVersion < DatabaseVersion.SIGNATURE_MALFORMED_RECOVER;
5439    }
5440
5441    private int compareSignaturesRecover(PackageSignatures existingSigs,
5442            PackageParser.Package scannedPkg) {
5443        if (!isRecoverSignatureUpdateNeeded(scannedPkg)) {
5444            return PackageManager.SIGNATURE_NO_MATCH;
5445        }
5446
5447        String msg = null;
5448        try {
5449            if (Signature.areEffectiveMatch(existingSigs.mSignatures, scannedPkg.mSignatures)) {
5450                logCriticalInfo(Log.INFO, "Recovered effectively matching certificates for "
5451                        + scannedPkg.packageName);
5452                return PackageManager.SIGNATURE_MATCH;
5453            }
5454        } catch (CertificateException e) {
5455            msg = e.getMessage();
5456        }
5457
5458        logCriticalInfo(Log.INFO,
5459                "Failed to recover certificates for " + scannedPkg.packageName + ": " + msg);
5460        return PackageManager.SIGNATURE_NO_MATCH;
5461    }
5462
5463    @Override
5464    public List<String> getAllPackages() {
5465        synchronized (mPackages) {
5466            return new ArrayList<String>(mPackages.keySet());
5467        }
5468    }
5469
5470    @Override
5471    public String[] getPackagesForUid(int uid) {
5472        final int userId = UserHandle.getUserId(uid);
5473        uid = UserHandle.getAppId(uid);
5474        // reader
5475        synchronized (mPackages) {
5476            Object obj = mSettings.getUserIdLPr(uid);
5477            if (obj instanceof SharedUserSetting) {
5478                final SharedUserSetting sus = (SharedUserSetting) obj;
5479                final int N = sus.packages.size();
5480                String[] res = new String[N];
5481                final Iterator<PackageSetting> it = sus.packages.iterator();
5482                int i = 0;
5483                while (it.hasNext()) {
5484                    PackageSetting ps = it.next();
5485                    if (ps.getInstalled(userId)) {
5486                        res[i++] = ps.name;
5487                    } else {
5488                        res = ArrayUtils.removeElement(String.class, res, res[i]);
5489                    }
5490                }
5491                return res;
5492            } else if (obj instanceof PackageSetting) {
5493                final PackageSetting ps = (PackageSetting) obj;
5494                if (ps.getInstalled(userId)) {
5495                    return new String[]{ps.name};
5496                }
5497            }
5498        }
5499        return null;
5500    }
5501
5502    @Override
5503    public String getNameForUid(int uid) {
5504        // reader
5505        synchronized (mPackages) {
5506            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
5507            if (obj instanceof SharedUserSetting) {
5508                final SharedUserSetting sus = (SharedUserSetting) obj;
5509                return sus.name + ":" + sus.userId;
5510            } else if (obj instanceof PackageSetting) {
5511                final PackageSetting ps = (PackageSetting) obj;
5512                return ps.name;
5513            }
5514        }
5515        return null;
5516    }
5517
5518    @Override
5519    public int getUidForSharedUser(String sharedUserName) {
5520        if(sharedUserName == null) {
5521            return -1;
5522        }
5523        // reader
5524        synchronized (mPackages) {
5525            SharedUserSetting suid;
5526            try {
5527                suid = mSettings.getSharedUserLPw(sharedUserName, 0, 0, false);
5528                if (suid != null) {
5529                    return suid.userId;
5530                }
5531            } catch (PackageManagerException ignore) {
5532                // can't happen, but, still need to catch it
5533            }
5534            return -1;
5535        }
5536    }
5537
5538    @Override
5539    public int getFlagsForUid(int uid) {
5540        synchronized (mPackages) {
5541            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
5542            if (obj instanceof SharedUserSetting) {
5543                final SharedUserSetting sus = (SharedUserSetting) obj;
5544                return sus.pkgFlags;
5545            } else if (obj instanceof PackageSetting) {
5546                final PackageSetting ps = (PackageSetting) obj;
5547                return ps.pkgFlags;
5548            }
5549        }
5550        return 0;
5551    }
5552
5553    @Override
5554    public int getPrivateFlagsForUid(int uid) {
5555        synchronized (mPackages) {
5556            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
5557            if (obj instanceof SharedUserSetting) {
5558                final SharedUserSetting sus = (SharedUserSetting) obj;
5559                return sus.pkgPrivateFlags;
5560            } else if (obj instanceof PackageSetting) {
5561                final PackageSetting ps = (PackageSetting) obj;
5562                return ps.pkgPrivateFlags;
5563            }
5564        }
5565        return 0;
5566    }
5567
5568    @Override
5569    public boolean isUidPrivileged(int uid) {
5570        uid = UserHandle.getAppId(uid);
5571        // reader
5572        synchronized (mPackages) {
5573            Object obj = mSettings.getUserIdLPr(uid);
5574            if (obj instanceof SharedUserSetting) {
5575                final SharedUserSetting sus = (SharedUserSetting) obj;
5576                final Iterator<PackageSetting> it = sus.packages.iterator();
5577                while (it.hasNext()) {
5578                    if (it.next().isPrivileged()) {
5579                        return true;
5580                    }
5581                }
5582            } else if (obj instanceof PackageSetting) {
5583                final PackageSetting ps = (PackageSetting) obj;
5584                return ps.isPrivileged();
5585            }
5586        }
5587        return false;
5588    }
5589
5590    @Override
5591    public String[] getAppOpPermissionPackages(String permissionName) {
5592        synchronized (mPackages) {
5593            ArraySet<String> pkgs = mAppOpPermissionPackages.get(permissionName);
5594            if (pkgs == null) {
5595                return null;
5596            }
5597            return pkgs.toArray(new String[pkgs.size()]);
5598        }
5599    }
5600
5601    @Override
5602    public ResolveInfo resolveIntent(Intent intent, String resolvedType,
5603            int flags, int userId) {
5604        return resolveIntentInternal(
5605                intent, resolvedType, flags, userId, false /*includeInstantApp*/);
5606    }
5607
5608    private ResolveInfo resolveIntentInternal(Intent intent, String resolvedType,
5609            int flags, int userId, boolean includeInstantApp) {
5610        try {
5611            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "resolveIntent");
5612
5613            if (!sUserManager.exists(userId)) return null;
5614            flags = updateFlagsForResolve(flags, userId, intent, includeInstantApp);
5615            enforceCrossUserPermission(Binder.getCallingUid(), userId,
5616                    false /*requireFullPermission*/, false /*checkShell*/, "resolve intent");
5617
5618            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "queryIntentActivities");
5619            final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType,
5620                    flags, userId, includeInstantApp);
5621            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
5622
5623            final ResolveInfo bestChoice =
5624                    chooseBestActivity(intent, resolvedType, flags, query, userId);
5625            return bestChoice;
5626        } finally {
5627            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
5628        }
5629    }
5630
5631    @Override
5632    public ResolveInfo findPersistentPreferredActivity(Intent intent, int userId) {
5633        if (!UserHandle.isSameApp(Binder.getCallingUid(), Process.SYSTEM_UID)) {
5634            throw new SecurityException(
5635                    "findPersistentPreferredActivity can only be run by the system");
5636        }
5637        if (!sUserManager.exists(userId)) {
5638            return null;
5639        }
5640        intent = updateIntentForResolve(intent);
5641        final String resolvedType = intent.resolveTypeIfNeeded(mContext.getContentResolver());
5642        final int flags = updateFlagsForResolve(0, userId, intent, false);
5643        final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags,
5644                userId);
5645        synchronized (mPackages) {
5646            return findPersistentPreferredActivityLP(intent, resolvedType, flags, query, false,
5647                    userId);
5648        }
5649    }
5650
5651    @Override
5652    public void setLastChosenActivity(Intent intent, String resolvedType, int flags,
5653            IntentFilter filter, int match, ComponentName activity) {
5654        final int userId = UserHandle.getCallingUserId();
5655        if (DEBUG_PREFERRED) {
5656            Log.v(TAG, "setLastChosenActivity intent=" + intent
5657                + " resolvedType=" + resolvedType
5658                + " flags=" + flags
5659                + " filter=" + filter
5660                + " match=" + match
5661                + " activity=" + activity);
5662            filter.dump(new PrintStreamPrinter(System.out), "    ");
5663        }
5664        intent.setComponent(null);
5665        final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags,
5666                userId);
5667        // Find any earlier preferred or last chosen entries and nuke them
5668        findPreferredActivity(intent, resolvedType,
5669                flags, query, 0, false, true, false, userId);
5670        // Add the new activity as the last chosen for this filter
5671        addPreferredActivityInternal(filter, match, null, activity, false, userId,
5672                "Setting last chosen");
5673    }
5674
5675    @Override
5676    public ResolveInfo getLastChosenActivity(Intent intent, String resolvedType, int flags) {
5677        final int userId = UserHandle.getCallingUserId();
5678        if (DEBUG_PREFERRED) Log.v(TAG, "Querying last chosen activity for " + intent);
5679        final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags,
5680                userId);
5681        return findPreferredActivity(intent, resolvedType, flags, query, 0,
5682                false, false, false, userId);
5683    }
5684
5685    private boolean isEphemeralDisabled() {
5686        // ephemeral apps have been disabled across the board
5687        if (DISABLE_EPHEMERAL_APPS) {
5688            return true;
5689        }
5690        // system isn't up yet; can't read settings, so, assume no ephemeral apps
5691        if (!mSystemReady) {
5692            return true;
5693        }
5694        // we can't get a content resolver until the system is ready; these checks must happen last
5695        final ContentResolver resolver = mContext.getContentResolver();
5696        if (Global.getInt(resolver, Global.ENABLE_EPHEMERAL_FEATURE, 1) == 0) {
5697            return true;
5698        }
5699        return Secure.getInt(resolver, Secure.WEB_ACTION_ENABLED, 1) == 0;
5700    }
5701
5702    private boolean isEphemeralAllowed(
5703            Intent intent, List<ResolveInfo> resolvedActivities, int userId,
5704            boolean skipPackageCheck) {
5705        // Short circuit and return early if possible.
5706        if (isEphemeralDisabled()) {
5707            return false;
5708        }
5709        final int callingUser = UserHandle.getCallingUserId();
5710        if (callingUser != UserHandle.USER_SYSTEM) {
5711            return false;
5712        }
5713        if (mInstantAppResolverConnection == null) {
5714            return false;
5715        }
5716        if (mInstantAppInstallerComponent == null) {
5717            return false;
5718        }
5719        if (intent.getComponent() != null) {
5720            return false;
5721        }
5722        if ((intent.getFlags() & Intent.FLAG_IGNORE_EPHEMERAL) != 0) {
5723            return false;
5724        }
5725        if (!skipPackageCheck && intent.getPackage() != null) {
5726            return false;
5727        }
5728        final boolean isWebUri = hasWebURI(intent);
5729        if (!isWebUri || intent.getData().getHost() == null) {
5730            return false;
5731        }
5732        // Deny ephemeral apps if the user chose _ALWAYS or _ALWAYS_ASK for intent resolution.
5733        // Or if there's already an ephemeral app installed that handles the action
5734        synchronized (mPackages) {
5735            final int count = (resolvedActivities == null ? 0 : resolvedActivities.size());
5736            for (int n = 0; n < count; n++) {
5737                ResolveInfo info = resolvedActivities.get(n);
5738                String packageName = info.activityInfo.packageName;
5739                PackageSetting ps = mSettings.mPackages.get(packageName);
5740                if (ps != null) {
5741                    // Try to get the status from User settings first
5742                    long packedStatus = getDomainVerificationStatusLPr(ps, userId);
5743                    int status = (int) (packedStatus >> 32);
5744                    if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS
5745                            || status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) {
5746                        if (DEBUG_EPHEMERAL) {
5747                            Slog.v(TAG, "DENY ephemeral apps;"
5748                                + " pkg: " + packageName + ", status: " + status);
5749                        }
5750                        return false;
5751                    }
5752                    if (ps.getInstantApp(userId)) {
5753                        return false;
5754                    }
5755                }
5756            }
5757        }
5758        // We've exhausted all ways to deny ephemeral application; let the system look for them.
5759        return true;
5760    }
5761
5762    private void requestInstantAppResolutionPhaseTwo(AuxiliaryResolveInfo responseObj,
5763            Intent origIntent, String resolvedType, String callingPackage,
5764            int userId) {
5765        final Message msg = mHandler.obtainMessage(INSTANT_APP_RESOLUTION_PHASE_TWO,
5766                new EphemeralRequest(responseObj, origIntent, resolvedType,
5767                        callingPackage, userId));
5768        mHandler.sendMessage(msg);
5769    }
5770
5771    private ResolveInfo chooseBestActivity(Intent intent, String resolvedType,
5772            int flags, List<ResolveInfo> query, int userId) {
5773        if (query != null) {
5774            final int N = query.size();
5775            if (N == 1) {
5776                return query.get(0);
5777            } else if (N > 1) {
5778                final boolean debug = ((intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0);
5779                // If there is more than one activity with the same priority,
5780                // then let the user decide between them.
5781                ResolveInfo r0 = query.get(0);
5782                ResolveInfo r1 = query.get(1);
5783                if (DEBUG_INTENT_MATCHING || debug) {
5784                    Slog.v(TAG, r0.activityInfo.name + "=" + r0.priority + " vs "
5785                            + r1.activityInfo.name + "=" + r1.priority);
5786                }
5787                // If the first activity has a higher priority, or a different
5788                // default, then it is always desirable to pick it.
5789                if (r0.priority != r1.priority
5790                        || r0.preferredOrder != r1.preferredOrder
5791                        || r0.isDefault != r1.isDefault) {
5792                    return query.get(0);
5793                }
5794                // If we have saved a preference for a preferred activity for
5795                // this Intent, use that.
5796                ResolveInfo ri = findPreferredActivity(intent, resolvedType,
5797                        flags, query, r0.priority, true, false, debug, userId);
5798                if (ri != null) {
5799                    return ri;
5800                }
5801                // If we have an ephemeral app, use it
5802                for (int i = 0; i < N; i++) {
5803                    ri = query.get(i);
5804                    if (ri.activityInfo.applicationInfo.isInstantApp()) {
5805                        return ri;
5806                    }
5807                }
5808                ri = new ResolveInfo(mResolveInfo);
5809                ri.activityInfo = new ActivityInfo(ri.activityInfo);
5810                ri.activityInfo.labelRes = ResolverActivity.getLabelRes(intent.getAction());
5811                // If all of the options come from the same package, show the application's
5812                // label and icon instead of the generic resolver's.
5813                // Some calls like Intent.resolveActivityInfo query the ResolveInfo from here
5814                // and then throw away the ResolveInfo itself, meaning that the caller loses
5815                // the resolvePackageName. Therefore the activityInfo.labelRes above provides
5816                // a fallback for this case; we only set the target package's resources on
5817                // the ResolveInfo, not the ActivityInfo.
5818                final String intentPackage = intent.getPackage();
5819                if (!TextUtils.isEmpty(intentPackage) && allHavePackage(query, intentPackage)) {
5820                    final ApplicationInfo appi = query.get(0).activityInfo.applicationInfo;
5821                    ri.resolvePackageName = intentPackage;
5822                    if (userNeedsBadging(userId)) {
5823                        ri.noResourceId = true;
5824                    } else {
5825                        ri.icon = appi.icon;
5826                    }
5827                    ri.iconResourceId = appi.icon;
5828                    ri.labelRes = appi.labelRes;
5829                }
5830                ri.activityInfo.applicationInfo = new ApplicationInfo(
5831                        ri.activityInfo.applicationInfo);
5832                if (userId != 0) {
5833                    ri.activityInfo.applicationInfo.uid = UserHandle.getUid(userId,
5834                            UserHandle.getAppId(ri.activityInfo.applicationInfo.uid));
5835                }
5836                // Make sure that the resolver is displayable in car mode
5837                if (ri.activityInfo.metaData == null) ri.activityInfo.metaData = new Bundle();
5838                ri.activityInfo.metaData.putBoolean(Intent.METADATA_DOCK_HOME, true);
5839                return ri;
5840            }
5841        }
5842        return null;
5843    }
5844
5845    /**
5846     * Return true if the given list is not empty and all of its contents have
5847     * an activityInfo with the given package name.
5848     */
5849    private boolean allHavePackage(List<ResolveInfo> list, String packageName) {
5850        if (ArrayUtils.isEmpty(list)) {
5851            return false;
5852        }
5853        for (int i = 0, N = list.size(); i < N; i++) {
5854            final ResolveInfo ri = list.get(i);
5855            final ActivityInfo ai = ri != null ? ri.activityInfo : null;
5856            if (ai == null || !packageName.equals(ai.packageName)) {
5857                return false;
5858            }
5859        }
5860        return true;
5861    }
5862
5863    private ResolveInfo findPersistentPreferredActivityLP(Intent intent, String resolvedType,
5864            int flags, List<ResolveInfo> query, boolean debug, int userId) {
5865        final int N = query.size();
5866        PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities
5867                .get(userId);
5868        // Get the list of persistent preferred activities that handle the intent
5869        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for presistent preferred activities...");
5870        List<PersistentPreferredActivity> pprefs = ppir != null
5871                ? ppir.queryIntent(intent, resolvedType,
5872                        (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0,
5873                        userId)
5874                : null;
5875        if (pprefs != null && pprefs.size() > 0) {
5876            final int M = pprefs.size();
5877            for (int i=0; i<M; i++) {
5878                final PersistentPreferredActivity ppa = pprefs.get(i);
5879                if (DEBUG_PREFERRED || debug) {
5880                    Slog.v(TAG, "Checking PersistentPreferredActivity ds="
5881                            + (ppa.countDataSchemes() > 0 ? ppa.getDataScheme(0) : "<none>")
5882                            + "\n  component=" + ppa.mComponent);
5883                    ppa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
5884                }
5885                final ActivityInfo ai = getActivityInfo(ppa.mComponent,
5886                        flags | MATCH_DISABLED_COMPONENTS, userId);
5887                if (DEBUG_PREFERRED || debug) {
5888                    Slog.v(TAG, "Found persistent preferred activity:");
5889                    if (ai != null) {
5890                        ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
5891                    } else {
5892                        Slog.v(TAG, "  null");
5893                    }
5894                }
5895                if (ai == null) {
5896                    // This previously registered persistent preferred activity
5897                    // component is no longer known. Ignore it and do NOT remove it.
5898                    continue;
5899                }
5900                for (int j=0; j<N; j++) {
5901                    final ResolveInfo ri = query.get(j);
5902                    if (!ri.activityInfo.applicationInfo.packageName
5903                            .equals(ai.applicationInfo.packageName)) {
5904                        continue;
5905                    }
5906                    if (!ri.activityInfo.name.equals(ai.name)) {
5907                        continue;
5908                    }
5909                    //  Found a persistent preference that can handle the intent.
5910                    if (DEBUG_PREFERRED || debug) {
5911                        Slog.v(TAG, "Returning persistent preferred activity: " +
5912                                ri.activityInfo.packageName + "/" + ri.activityInfo.name);
5913                    }
5914                    return ri;
5915                }
5916            }
5917        }
5918        return null;
5919    }
5920
5921    // TODO: handle preferred activities missing while user has amnesia
5922    ResolveInfo findPreferredActivity(Intent intent, String resolvedType, int flags,
5923            List<ResolveInfo> query, int priority, boolean always,
5924            boolean removeMatches, boolean debug, int userId) {
5925        if (!sUserManager.exists(userId)) return null;
5926        flags = updateFlagsForResolve(flags, userId, intent, false);
5927        intent = updateIntentForResolve(intent);
5928        // writer
5929        synchronized (mPackages) {
5930            // Try to find a matching persistent preferred activity.
5931            ResolveInfo pri = findPersistentPreferredActivityLP(intent, resolvedType, flags, query,
5932                    debug, userId);
5933
5934            // If a persistent preferred activity matched, use it.
5935            if (pri != null) {
5936                return pri;
5937            }
5938
5939            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
5940            // Get the list of preferred activities that handle the intent
5941            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for preferred activities...");
5942            List<PreferredActivity> prefs = pir != null
5943                    ? pir.queryIntent(intent, resolvedType,
5944                            (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0,
5945                            userId)
5946                    : null;
5947            if (prefs != null && prefs.size() > 0) {
5948                boolean changed = false;
5949                try {
5950                    // First figure out how good the original match set is.
5951                    // We will only allow preferred activities that came
5952                    // from the same match quality.
5953                    int match = 0;
5954
5955                    if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Figuring out best match...");
5956
5957                    final int N = query.size();
5958                    for (int j=0; j<N; j++) {
5959                        final ResolveInfo ri = query.get(j);
5960                        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Match for " + ri.activityInfo
5961                                + ": 0x" + Integer.toHexString(match));
5962                        if (ri.match > match) {
5963                            match = ri.match;
5964                        }
5965                    }
5966
5967                    if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Best match: 0x"
5968                            + Integer.toHexString(match));
5969
5970                    match &= IntentFilter.MATCH_CATEGORY_MASK;
5971                    final int M = prefs.size();
5972                    for (int i=0; i<M; i++) {
5973                        final PreferredActivity pa = prefs.get(i);
5974                        if (DEBUG_PREFERRED || debug) {
5975                            Slog.v(TAG, "Checking PreferredActivity ds="
5976                                    + (pa.countDataSchemes() > 0 ? pa.getDataScheme(0) : "<none>")
5977                                    + "\n  component=" + pa.mPref.mComponent);
5978                            pa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
5979                        }
5980                        if (pa.mPref.mMatch != match) {
5981                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping bad match "
5982                                    + Integer.toHexString(pa.mPref.mMatch));
5983                            continue;
5984                        }
5985                        // If it's not an "always" type preferred activity and that's what we're
5986                        // looking for, skip it.
5987                        if (always && !pa.mPref.mAlways) {
5988                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping mAlways=false entry");
5989                            continue;
5990                        }
5991                        final ActivityInfo ai = getActivityInfo(
5992                                pa.mPref.mComponent, flags | MATCH_DISABLED_COMPONENTS
5993                                        | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
5994                                userId);
5995                        if (DEBUG_PREFERRED || debug) {
5996                            Slog.v(TAG, "Found preferred activity:");
5997                            if (ai != null) {
5998                                ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
5999                            } else {
6000                                Slog.v(TAG, "  null");
6001                            }
6002                        }
6003                        if (ai == null) {
6004                            // This previously registered preferred activity
6005                            // component is no longer known.  Most likely an update
6006                            // to the app was installed and in the new version this
6007                            // component no longer exists.  Clean it up by removing
6008                            // it from the preferred activities list, and skip it.
6009                            Slog.w(TAG, "Removing dangling preferred activity: "
6010                                    + pa.mPref.mComponent);
6011                            pir.removeFilter(pa);
6012                            changed = true;
6013                            continue;
6014                        }
6015                        for (int j=0; j<N; j++) {
6016                            final ResolveInfo ri = query.get(j);
6017                            if (!ri.activityInfo.applicationInfo.packageName
6018                                    .equals(ai.applicationInfo.packageName)) {
6019                                continue;
6020                            }
6021                            if (!ri.activityInfo.name.equals(ai.name)) {
6022                                continue;
6023                            }
6024
6025                            if (removeMatches) {
6026                                pir.removeFilter(pa);
6027                                changed = true;
6028                                if (DEBUG_PREFERRED) {
6029                                    Slog.v(TAG, "Removing match " + pa.mPref.mComponent);
6030                                }
6031                                break;
6032                            }
6033
6034                            // Okay we found a previously set preferred or last chosen app.
6035                            // If the result set is different from when this
6036                            // was created, we need to clear it and re-ask the
6037                            // user their preference, if we're looking for an "always" type entry.
6038                            if (always && !pa.mPref.sameSet(query)) {
6039                                Slog.i(TAG, "Result set changed, dropping preferred activity for "
6040                                        + intent + " type " + resolvedType);
6041                                if (DEBUG_PREFERRED) {
6042                                    Slog.v(TAG, "Removing preferred activity since set changed "
6043                                            + pa.mPref.mComponent);
6044                                }
6045                                pir.removeFilter(pa);
6046                                // Re-add the filter as a "last chosen" entry (!always)
6047                                PreferredActivity lastChosen = new PreferredActivity(
6048                                        pa, pa.mPref.mMatch, null, pa.mPref.mComponent, false);
6049                                pir.addFilter(lastChosen);
6050                                changed = true;
6051                                return null;
6052                            }
6053
6054                            // Yay! Either the set matched or we're looking for the last chosen
6055                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Returning preferred activity: "
6056                                    + ri.activityInfo.packageName + "/" + ri.activityInfo.name);
6057                            return ri;
6058                        }
6059                    }
6060                } finally {
6061                    if (changed) {
6062                        if (DEBUG_PREFERRED) {
6063                            Slog.v(TAG, "Preferred activity bookkeeping changed; writing restrictions");
6064                        }
6065                        scheduleWritePackageRestrictionsLocked(userId);
6066                    }
6067                }
6068            }
6069        }
6070        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "No preferred activity to return");
6071        return null;
6072    }
6073
6074    /*
6075     * Returns if intent can be forwarded from the sourceUserId to the targetUserId
6076     */
6077    @Override
6078    public boolean canForwardTo(Intent intent, String resolvedType, int sourceUserId,
6079            int targetUserId) {
6080        mContext.enforceCallingOrSelfPermission(
6081                android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
6082        List<CrossProfileIntentFilter> matches =
6083                getMatchingCrossProfileIntentFilters(intent, resolvedType, sourceUserId);
6084        if (matches != null) {
6085            int size = matches.size();
6086            for (int i = 0; i < size; i++) {
6087                if (matches.get(i).getTargetUserId() == targetUserId) return true;
6088            }
6089        }
6090        if (hasWebURI(intent)) {
6091            // cross-profile app linking works only towards the parent.
6092            final UserInfo parent = getProfileParent(sourceUserId);
6093            synchronized(mPackages) {
6094                int flags = updateFlagsForResolve(0, parent.id, intent, false);
6095                CrossProfileDomainInfo xpDomainInfo = getCrossProfileDomainPreferredLpr(
6096                        intent, resolvedType, flags, sourceUserId, parent.id);
6097                return xpDomainInfo != null;
6098            }
6099        }
6100        return false;
6101    }
6102
6103    private UserInfo getProfileParent(int userId) {
6104        final long identity = Binder.clearCallingIdentity();
6105        try {
6106            return sUserManager.getProfileParent(userId);
6107        } finally {
6108            Binder.restoreCallingIdentity(identity);
6109        }
6110    }
6111
6112    private List<CrossProfileIntentFilter> getMatchingCrossProfileIntentFilters(Intent intent,
6113            String resolvedType, int userId) {
6114        CrossProfileIntentResolver resolver = mSettings.mCrossProfileIntentResolvers.get(userId);
6115        if (resolver != null) {
6116            return resolver.queryIntent(intent, resolvedType, false /*defaultOnly*/, userId);
6117        }
6118        return null;
6119    }
6120
6121    @Override
6122    public @NonNull ParceledListSlice<ResolveInfo> queryIntentActivities(Intent intent,
6123            String resolvedType, int flags, int userId) {
6124        try {
6125            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "queryIntentActivities");
6126
6127            return new ParceledListSlice<>(
6128                    queryIntentActivitiesInternal(intent, resolvedType, flags, userId));
6129        } finally {
6130            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
6131        }
6132    }
6133
6134    /**
6135     * Returns the package name of the calling Uid if it's an instant app. If it isn't
6136     * instant, returns {@code null}.
6137     */
6138    private String getInstantAppPackageName(int callingUid) {
6139        final int appId = UserHandle.getAppId(callingUid);
6140        synchronized (mPackages) {
6141            final Object obj = mSettings.getUserIdLPr(appId);
6142            if (obj instanceof PackageSetting) {
6143                final PackageSetting ps = (PackageSetting) obj;
6144                final boolean isInstantApp = ps.getInstantApp(UserHandle.getUserId(callingUid));
6145                return isInstantApp ? ps.pkg.packageName : null;
6146            }
6147        }
6148        return null;
6149    }
6150
6151    private @NonNull List<ResolveInfo> queryIntentActivitiesInternal(Intent intent,
6152            String resolvedType, int flags, int userId) {
6153        return queryIntentActivitiesInternal(intent, resolvedType, flags, userId, false);
6154    }
6155
6156    private @NonNull List<ResolveInfo> queryIntentActivitiesInternal(Intent intent,
6157            String resolvedType, int flags, int userId, boolean includeInstantApp) {
6158        if (!sUserManager.exists(userId)) return Collections.emptyList();
6159        final String instantAppPkgName = getInstantAppPackageName(Binder.getCallingUid());
6160        flags = updateFlagsForResolve(flags, userId, intent, includeInstantApp);
6161        enforceCrossUserPermission(Binder.getCallingUid(), userId,
6162                false /* requireFullPermission */, false /* checkShell */,
6163                "query intent activities");
6164        ComponentName comp = intent.getComponent();
6165        if (comp == null) {
6166            if (intent.getSelector() != null) {
6167                intent = intent.getSelector();
6168                comp = intent.getComponent();
6169            }
6170        }
6171
6172        if (comp != null) {
6173            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
6174            final ActivityInfo ai = getActivityInfo(comp, flags, userId);
6175            if (ai != null) {
6176                // When specifying an explicit component, we prevent the activity from being
6177                // used when either 1) the calling package is normal and the activity is within
6178                // an ephemeral application or 2) the calling package is ephemeral and the
6179                // activity is not visible to ephemeral applications.
6180                final boolean matchInstantApp =
6181                        (flags & PackageManager.MATCH_INSTANT) != 0;
6182                final boolean matchVisibleToInstantAppOnly =
6183                        (flags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
6184                final boolean isCallerInstantApp =
6185                        instantAppPkgName != null;
6186                final boolean isTargetSameInstantApp =
6187                        comp.getPackageName().equals(instantAppPkgName);
6188                final boolean isTargetInstantApp =
6189                        (ai.applicationInfo.privateFlags
6190                                & ApplicationInfo.PRIVATE_FLAG_INSTANT) != 0;
6191                final boolean isTargetHiddenFromInstantApp =
6192                        (ai.flags & ActivityInfo.FLAG_VISIBLE_TO_EPHEMERAL) == 0;
6193                final boolean blockResolution =
6194                        !isTargetSameInstantApp
6195                        && ((!matchInstantApp && !isCallerInstantApp && isTargetInstantApp)
6196                                || (matchVisibleToInstantAppOnly && isCallerInstantApp
6197                                        && isTargetHiddenFromInstantApp));
6198                if (!blockResolution) {
6199                    final ResolveInfo ri = new ResolveInfo();
6200                    ri.activityInfo = ai;
6201                    list.add(ri);
6202                }
6203            }
6204            return applyPostResolutionFilter(list, instantAppPkgName);
6205        }
6206
6207        // reader
6208        boolean sortResult = false;
6209        boolean addEphemeral = false;
6210        List<ResolveInfo> result;
6211        final String pkgName = intent.getPackage();
6212        synchronized (mPackages) {
6213            if (pkgName == null) {
6214                List<CrossProfileIntentFilter> matchingFilters =
6215                        getMatchingCrossProfileIntentFilters(intent, resolvedType, userId);
6216                // Check for results that need to skip the current profile.
6217                ResolveInfo xpResolveInfo  = querySkipCurrentProfileIntents(matchingFilters, intent,
6218                        resolvedType, flags, userId);
6219                if (xpResolveInfo != null) {
6220                    List<ResolveInfo> xpResult = new ArrayList<ResolveInfo>(1);
6221                    xpResult.add(xpResolveInfo);
6222                    return applyPostResolutionFilter(
6223                            filterIfNotSystemUser(xpResult, userId), instantAppPkgName);
6224                }
6225
6226                // Check for results in the current profile.
6227                result = filterIfNotSystemUser(mActivities.queryIntent(
6228                        intent, resolvedType, flags, userId), userId);
6229                addEphemeral =
6230                        isEphemeralAllowed(intent, result, userId, false /*skipPackageCheck*/);
6231
6232                // Check for cross profile results.
6233                boolean hasNonNegativePriorityResult = hasNonNegativePriority(result);
6234                xpResolveInfo = queryCrossProfileIntents(
6235                        matchingFilters, intent, resolvedType, flags, userId,
6236                        hasNonNegativePriorityResult);
6237                if (xpResolveInfo != null && isUserEnabled(xpResolveInfo.targetUserId)) {
6238                    boolean isVisibleToUser = filterIfNotSystemUser(
6239                            Collections.singletonList(xpResolveInfo), userId).size() > 0;
6240                    if (isVisibleToUser) {
6241                        result.add(xpResolveInfo);
6242                        sortResult = true;
6243                    }
6244                }
6245                if (hasWebURI(intent)) {
6246                    CrossProfileDomainInfo xpDomainInfo = null;
6247                    final UserInfo parent = getProfileParent(userId);
6248                    if (parent != null) {
6249                        xpDomainInfo = getCrossProfileDomainPreferredLpr(intent, resolvedType,
6250                                flags, userId, parent.id);
6251                    }
6252                    if (xpDomainInfo != null) {
6253                        if (xpResolveInfo != null) {
6254                            // If we didn't remove it, the cross-profile ResolveInfo would be twice
6255                            // in the result.
6256                            result.remove(xpResolveInfo);
6257                        }
6258                        if (result.size() == 0 && !addEphemeral) {
6259                            // No result in current profile, but found candidate in parent user.
6260                            // And we are not going to add emphemeral app, so we can return the
6261                            // result straight away.
6262                            result.add(xpDomainInfo.resolveInfo);
6263                            return applyPostResolutionFilter(result, instantAppPkgName);
6264                        }
6265                    } else if (result.size() <= 1 && !addEphemeral) {
6266                        // No result in parent user and <= 1 result in current profile, and we
6267                        // are not going to add emphemeral app, so we can return the result without
6268                        // further processing.
6269                        return applyPostResolutionFilter(result, instantAppPkgName);
6270                    }
6271                    // We have more than one candidate (combining results from current and parent
6272                    // profile), so we need filtering and sorting.
6273                    result = filterCandidatesWithDomainPreferredActivitiesLPr(
6274                            intent, flags, result, xpDomainInfo, userId);
6275                    sortResult = true;
6276                }
6277            } else {
6278                final PackageParser.Package pkg = mPackages.get(pkgName);
6279                if (pkg != null) {
6280                    result = applyPostResolutionFilter(filterIfNotSystemUser(
6281                            mActivities.queryIntentForPackage(
6282                                    intent, resolvedType, flags, pkg.activities, userId),
6283                            userId), instantAppPkgName);
6284                } else {
6285                    // the caller wants to resolve for a particular package; however, there
6286                    // were no installed results, so, try to find an ephemeral result
6287                    addEphemeral = isEphemeralAllowed(
6288                            intent, null /*result*/, userId, true /*skipPackageCheck*/);
6289                    result = new ArrayList<ResolveInfo>();
6290                }
6291            }
6292        }
6293        if (addEphemeral) {
6294            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "resolveEphemeral");
6295            final EphemeralRequest requestObject = new EphemeralRequest(
6296                    null /*responseObj*/, intent /*origIntent*/, resolvedType,
6297                    null /*callingPackage*/, userId);
6298            final AuxiliaryResolveInfo auxiliaryResponse =
6299                    EphemeralResolver.doEphemeralResolutionPhaseOne(
6300                            mContext, mInstantAppResolverConnection, requestObject);
6301            if (auxiliaryResponse != null) {
6302                if (DEBUG_EPHEMERAL) {
6303                    Slog.v(TAG, "Adding ephemeral installer to the ResolveInfo list");
6304                }
6305                final ResolveInfo ephemeralInstaller = new ResolveInfo(mInstantAppInstallerInfo);
6306                ephemeralInstaller.auxiliaryInfo = auxiliaryResponse;
6307                // make sure this resolver is the default
6308                ephemeralInstaller.isDefault = true;
6309                ephemeralInstaller.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART
6310                        | IntentFilter.MATCH_ADJUSTMENT_NORMAL;
6311                // add a non-generic filter
6312                ephemeralInstaller.filter = new IntentFilter(intent.getAction());
6313                ephemeralInstaller.filter.addDataPath(
6314                        intent.getData().getPath(), PatternMatcher.PATTERN_LITERAL);
6315                result.add(ephemeralInstaller);
6316            }
6317            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
6318        }
6319        if (sortResult) {
6320            Collections.sort(result, mResolvePrioritySorter);
6321        }
6322        return applyPostResolutionFilter(result, instantAppPkgName);
6323    }
6324
6325    private static class CrossProfileDomainInfo {
6326        /* ResolveInfo for IntentForwarderActivity to send the intent to the other profile */
6327        ResolveInfo resolveInfo;
6328        /* Best domain verification status of the activities found in the other profile */
6329        int bestDomainVerificationStatus;
6330    }
6331
6332    private CrossProfileDomainInfo getCrossProfileDomainPreferredLpr(Intent intent,
6333            String resolvedType, int flags, int sourceUserId, int parentUserId) {
6334        if (!sUserManager.hasUserRestriction(UserManager.ALLOW_PARENT_PROFILE_APP_LINKING,
6335                sourceUserId)) {
6336            return null;
6337        }
6338        List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent,
6339                resolvedType, flags, parentUserId);
6340
6341        if (resultTargetUser == null || resultTargetUser.isEmpty()) {
6342            return null;
6343        }
6344        CrossProfileDomainInfo result = null;
6345        int size = resultTargetUser.size();
6346        for (int i = 0; i < size; i++) {
6347            ResolveInfo riTargetUser = resultTargetUser.get(i);
6348            // Intent filter verification is only for filters that specify a host. So don't return
6349            // those that handle all web uris.
6350            if (riTargetUser.handleAllWebDataURI) {
6351                continue;
6352            }
6353            String packageName = riTargetUser.activityInfo.packageName;
6354            PackageSetting ps = mSettings.mPackages.get(packageName);
6355            if (ps == null) {
6356                continue;
6357            }
6358            long verificationState = getDomainVerificationStatusLPr(ps, parentUserId);
6359            int status = (int)(verificationState >> 32);
6360            if (result == null) {
6361                result = new CrossProfileDomainInfo();
6362                result.resolveInfo = createForwardingResolveInfoUnchecked(new IntentFilter(),
6363                        sourceUserId, parentUserId);
6364                result.bestDomainVerificationStatus = status;
6365            } else {
6366                result.bestDomainVerificationStatus = bestDomainVerificationStatus(status,
6367                        result.bestDomainVerificationStatus);
6368            }
6369        }
6370        // Don't consider matches with status NEVER across profiles.
6371        if (result != null && result.bestDomainVerificationStatus
6372                == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
6373            return null;
6374        }
6375        return result;
6376    }
6377
6378    /**
6379     * Verification statuses are ordered from the worse to the best, except for
6380     * INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER, which is the worse.
6381     */
6382    private int bestDomainVerificationStatus(int status1, int status2) {
6383        if (status1 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
6384            return status2;
6385        }
6386        if (status2 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
6387            return status1;
6388        }
6389        return (int) MathUtils.max(status1, status2);
6390    }
6391
6392    private boolean isUserEnabled(int userId) {
6393        long callingId = Binder.clearCallingIdentity();
6394        try {
6395            UserInfo userInfo = sUserManager.getUserInfo(userId);
6396            return userInfo != null && userInfo.isEnabled();
6397        } finally {
6398            Binder.restoreCallingIdentity(callingId);
6399        }
6400    }
6401
6402    /**
6403     * Filter out activities with systemUserOnly flag set, when current user is not System.
6404     *
6405     * @return filtered list
6406     */
6407    private List<ResolveInfo> filterIfNotSystemUser(List<ResolveInfo> resolveInfos, int userId) {
6408        if (userId == UserHandle.USER_SYSTEM) {
6409            return resolveInfos;
6410        }
6411        for (int i = resolveInfos.size() - 1; i >= 0; i--) {
6412            ResolveInfo info = resolveInfos.get(i);
6413            if ((info.activityInfo.flags & ActivityInfo.FLAG_SYSTEM_USER_ONLY) != 0) {
6414                resolveInfos.remove(i);
6415            }
6416        }
6417        return resolveInfos;
6418    }
6419
6420    /**
6421     * Filters out ephemeral activities.
6422     * <p>When resolving for an ephemeral app, only activities that 1) are defined in the
6423     * ephemeral app or 2) marked with {@code visibleToEphemeral} are returned.
6424     *
6425     * @param resolveInfos The pre-filtered list of resolved activities
6426     * @param ephemeralPkgName The ephemeral package name. If {@code null}, no filtering
6427     *          is performed.
6428     * @return A filtered list of resolved activities.
6429     */
6430    private List<ResolveInfo> applyPostResolutionFilter(List<ResolveInfo> resolveInfos,
6431            String ephemeralPkgName) {
6432        // TODO: When adding on-demand split support for non-instant apps, remove this check
6433        // and always apply post filtering
6434        if (ephemeralPkgName == null) {
6435            return resolveInfos;
6436        }
6437        for (int i = resolveInfos.size() - 1; i >= 0; i--) {
6438            final ResolveInfo info = resolveInfos.get(i);
6439            final boolean isEphemeralApp = info.activityInfo.applicationInfo.isInstantApp();
6440            // allow activities that are defined in the provided package
6441            if (isEphemeralApp && ephemeralPkgName.equals(info.activityInfo.packageName)) {
6442                if (info.activityInfo.splitName != null
6443                        && !ArrayUtils.contains(info.activityInfo.applicationInfo.splitNames,
6444                                info.activityInfo.splitName)) {
6445                    // requested activity is defined in a split that hasn't been installed yet.
6446                    // add the installer to the resolve list
6447                    if (DEBUG_EPHEMERAL) {
6448                        Slog.v(TAG, "Adding ephemeral installer to the ResolveInfo list");
6449                    }
6450                    final ResolveInfo installerInfo = new ResolveInfo(mInstantAppInstallerInfo);
6451                    installerInfo.auxiliaryInfo = new AuxiliaryResolveInfo(
6452                            info.activityInfo.packageName, info.activityInfo.splitName,
6453                            info.activityInfo.applicationInfo.versionCode);
6454                    // make sure this resolver is the default
6455                    installerInfo.isDefault = true;
6456                    installerInfo.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART
6457                            | IntentFilter.MATCH_ADJUSTMENT_NORMAL;
6458                    // add a non-generic filter
6459                    installerInfo.filter = new IntentFilter();
6460                    // load resources from the correct package
6461                    installerInfo.resolvePackageName = info.getComponentInfo().packageName;
6462                    resolveInfos.set(i, installerInfo);
6463                }
6464                continue;
6465            }
6466            // allow activities that have been explicitly exposed to ephemeral apps
6467            if (!isEphemeralApp
6468                    && ((info.activityInfo.flags & ActivityInfo.FLAG_VISIBLE_TO_EPHEMERAL) != 0)) {
6469                continue;
6470            }
6471            resolveInfos.remove(i);
6472        }
6473        return resolveInfos;
6474    }
6475
6476    /**
6477     * @param resolveInfos list of resolve infos in descending priority order
6478     * @return if the list contains a resolve info with non-negative priority
6479     */
6480    private boolean hasNonNegativePriority(List<ResolveInfo> resolveInfos) {
6481        return resolveInfos.size() > 0 && resolveInfos.get(0).priority >= 0;
6482    }
6483
6484    private static boolean hasWebURI(Intent intent) {
6485        if (intent.getData() == null) {
6486            return false;
6487        }
6488        final String scheme = intent.getScheme();
6489        if (TextUtils.isEmpty(scheme)) {
6490            return false;
6491        }
6492        return scheme.equals(IntentFilter.SCHEME_HTTP) || scheme.equals(IntentFilter.SCHEME_HTTPS);
6493    }
6494
6495    private List<ResolveInfo> filterCandidatesWithDomainPreferredActivitiesLPr(Intent intent,
6496            int matchFlags, List<ResolveInfo> candidates, CrossProfileDomainInfo xpDomainInfo,
6497            int userId) {
6498        final boolean debug = (intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0;
6499
6500        if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) {
6501            Slog.v(TAG, "Filtering results with preferred activities. Candidates count: " +
6502                    candidates.size());
6503        }
6504
6505        ArrayList<ResolveInfo> result = new ArrayList<ResolveInfo>();
6506        ArrayList<ResolveInfo> alwaysList = new ArrayList<ResolveInfo>();
6507        ArrayList<ResolveInfo> undefinedList = new ArrayList<ResolveInfo>();
6508        ArrayList<ResolveInfo> alwaysAskList = new ArrayList<ResolveInfo>();
6509        ArrayList<ResolveInfo> neverList = new ArrayList<ResolveInfo>();
6510        ArrayList<ResolveInfo> matchAllList = new ArrayList<ResolveInfo>();
6511
6512        synchronized (mPackages) {
6513            final int count = candidates.size();
6514            // First, try to use linked apps. Partition the candidates into four lists:
6515            // one for the final results, one for the "do not use ever", one for "undefined status"
6516            // and finally one for "browser app type".
6517            for (int n=0; n<count; n++) {
6518                ResolveInfo info = candidates.get(n);
6519                String packageName = info.activityInfo.packageName;
6520                PackageSetting ps = mSettings.mPackages.get(packageName);
6521                if (ps != null) {
6522                    // Add to the special match all list (Browser use case)
6523                    if (info.handleAllWebDataURI) {
6524                        matchAllList.add(info);
6525                        continue;
6526                    }
6527                    // Try to get the status from User settings first
6528                    long packedStatus = getDomainVerificationStatusLPr(ps, userId);
6529                    int status = (int)(packedStatus >> 32);
6530                    int linkGeneration = (int)(packedStatus & 0xFFFFFFFF);
6531                    if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS) {
6532                        if (DEBUG_DOMAIN_VERIFICATION || debug) {
6533                            Slog.i(TAG, "  + always: " + info.activityInfo.packageName
6534                                    + " : linkgen=" + linkGeneration);
6535                        }
6536                        // Use link-enabled generation as preferredOrder, i.e.
6537                        // prefer newly-enabled over earlier-enabled.
6538                        info.preferredOrder = linkGeneration;
6539                        alwaysList.add(info);
6540                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
6541                        if (DEBUG_DOMAIN_VERIFICATION || debug) {
6542                            Slog.i(TAG, "  + never: " + info.activityInfo.packageName);
6543                        }
6544                        neverList.add(info);
6545                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) {
6546                        if (DEBUG_DOMAIN_VERIFICATION || debug) {
6547                            Slog.i(TAG, "  + always-ask: " + info.activityInfo.packageName);
6548                        }
6549                        alwaysAskList.add(info);
6550                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED ||
6551                            status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK) {
6552                        if (DEBUG_DOMAIN_VERIFICATION || debug) {
6553                            Slog.i(TAG, "  + ask: " + info.activityInfo.packageName);
6554                        }
6555                        undefinedList.add(info);
6556                    }
6557                }
6558            }
6559
6560            // We'll want to include browser possibilities in a few cases
6561            boolean includeBrowser = false;
6562
6563            // First try to add the "always" resolution(s) for the current user, if any
6564            if (alwaysList.size() > 0) {
6565                result.addAll(alwaysList);
6566            } else {
6567                // Add all undefined apps as we want them to appear in the disambiguation dialog.
6568                result.addAll(undefinedList);
6569                // Maybe add one for the other profile.
6570                if (xpDomainInfo != null && (
6571                        xpDomainInfo.bestDomainVerificationStatus
6572                        != INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER)) {
6573                    result.add(xpDomainInfo.resolveInfo);
6574                }
6575                includeBrowser = true;
6576            }
6577
6578            // The presence of any 'always ask' alternatives means we'll also offer browsers.
6579            // If there were 'always' entries their preferred order has been set, so we also
6580            // back that off to make the alternatives equivalent
6581            if (alwaysAskList.size() > 0) {
6582                for (ResolveInfo i : result) {
6583                    i.preferredOrder = 0;
6584                }
6585                result.addAll(alwaysAskList);
6586                includeBrowser = true;
6587            }
6588
6589            if (includeBrowser) {
6590                // Also add browsers (all of them or only the default one)
6591                if (DEBUG_DOMAIN_VERIFICATION) {
6592                    Slog.v(TAG, "   ...including browsers in candidate set");
6593                }
6594                if ((matchFlags & MATCH_ALL) != 0) {
6595                    result.addAll(matchAllList);
6596                } else {
6597                    // Browser/generic handling case.  If there's a default browser, go straight
6598                    // to that (but only if there is no other higher-priority match).
6599                    final String defaultBrowserPackageName = getDefaultBrowserPackageName(userId);
6600                    int maxMatchPrio = 0;
6601                    ResolveInfo defaultBrowserMatch = null;
6602                    final int numCandidates = matchAllList.size();
6603                    for (int n = 0; n < numCandidates; n++) {
6604                        ResolveInfo info = matchAllList.get(n);
6605                        // track the highest overall match priority...
6606                        if (info.priority > maxMatchPrio) {
6607                            maxMatchPrio = info.priority;
6608                        }
6609                        // ...and the highest-priority default browser match
6610                        if (info.activityInfo.packageName.equals(defaultBrowserPackageName)) {
6611                            if (defaultBrowserMatch == null
6612                                    || (defaultBrowserMatch.priority < info.priority)) {
6613                                if (debug) {
6614                                    Slog.v(TAG, "Considering default browser match " + info);
6615                                }
6616                                defaultBrowserMatch = info;
6617                            }
6618                        }
6619                    }
6620                    if (defaultBrowserMatch != null
6621                            && defaultBrowserMatch.priority >= maxMatchPrio
6622                            && !TextUtils.isEmpty(defaultBrowserPackageName))
6623                    {
6624                        if (debug) {
6625                            Slog.v(TAG, "Default browser match " + defaultBrowserMatch);
6626                        }
6627                        result.add(defaultBrowserMatch);
6628                    } else {
6629                        result.addAll(matchAllList);
6630                    }
6631                }
6632
6633                // If there is nothing selected, add all candidates and remove the ones that the user
6634                // has explicitly put into the INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER state
6635                if (result.size() == 0) {
6636                    result.addAll(candidates);
6637                    result.removeAll(neverList);
6638                }
6639            }
6640        }
6641        if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) {
6642            Slog.v(TAG, "Filtered results with preferred activities. New candidates count: " +
6643                    result.size());
6644            for (ResolveInfo info : result) {
6645                Slog.v(TAG, "  + " + info.activityInfo);
6646            }
6647        }
6648        return result;
6649    }
6650
6651    // Returns a packed value as a long:
6652    //
6653    // high 'int'-sized word: link status: undefined/ask/never/always.
6654    // low 'int'-sized word: relative priority among 'always' results.
6655    private long getDomainVerificationStatusLPr(PackageSetting ps, int userId) {
6656        long result = ps.getDomainVerificationStatusForUser(userId);
6657        // if none available, get the master status
6658        if (result >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) {
6659            if (ps.getIntentFilterVerificationInfo() != null) {
6660                result = ((long)ps.getIntentFilterVerificationInfo().getStatus()) << 32;
6661            }
6662        }
6663        return result;
6664    }
6665
6666    private ResolveInfo querySkipCurrentProfileIntents(
6667            List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType,
6668            int flags, int sourceUserId) {
6669        if (matchingFilters != null) {
6670            int size = matchingFilters.size();
6671            for (int i = 0; i < size; i ++) {
6672                CrossProfileIntentFilter filter = matchingFilters.get(i);
6673                if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0) {
6674                    // Checking if there are activities in the target user that can handle the
6675                    // intent.
6676                    ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent,
6677                            resolvedType, flags, sourceUserId);
6678                    if (resolveInfo != null) {
6679                        return resolveInfo;
6680                    }
6681                }
6682            }
6683        }
6684        return null;
6685    }
6686
6687    // Return matching ResolveInfo in target user if any.
6688    private ResolveInfo queryCrossProfileIntents(
6689            List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType,
6690            int flags, int sourceUserId, boolean matchInCurrentProfile) {
6691        if (matchingFilters != null) {
6692            // Two {@link CrossProfileIntentFilter}s can have the same targetUserId and
6693            // match the same intent. For performance reasons, it is better not to
6694            // run queryIntent twice for the same userId
6695            SparseBooleanArray alreadyTriedUserIds = new SparseBooleanArray();
6696            int size = matchingFilters.size();
6697            for (int i = 0; i < size; i++) {
6698                CrossProfileIntentFilter filter = matchingFilters.get(i);
6699                int targetUserId = filter.getTargetUserId();
6700                boolean skipCurrentProfile =
6701                        (filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0;
6702                boolean skipCurrentProfileIfNoMatchFound =
6703                        (filter.getFlags() & PackageManager.ONLY_IF_NO_MATCH_FOUND) != 0;
6704                if (!skipCurrentProfile && !alreadyTriedUserIds.get(targetUserId)
6705                        && (!skipCurrentProfileIfNoMatchFound || !matchInCurrentProfile)) {
6706                    // Checking if there are activities in the target user that can handle the
6707                    // intent.
6708                    ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent,
6709                            resolvedType, flags, sourceUserId);
6710                    if (resolveInfo != null) return resolveInfo;
6711                    alreadyTriedUserIds.put(targetUserId, true);
6712                }
6713            }
6714        }
6715        return null;
6716    }
6717
6718    /**
6719     * If the filter's target user can handle the intent and is enabled: returns a ResolveInfo that
6720     * will forward the intent to the filter's target user.
6721     * Otherwise, returns null.
6722     */
6723    private ResolveInfo createForwardingResolveInfo(CrossProfileIntentFilter filter, Intent intent,
6724            String resolvedType, int flags, int sourceUserId) {
6725        int targetUserId = filter.getTargetUserId();
6726        List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent,
6727                resolvedType, flags, targetUserId);
6728        if (resultTargetUser != null && isUserEnabled(targetUserId)) {
6729            // If all the matches in the target profile are suspended, return null.
6730            for (int i = resultTargetUser.size() - 1; i >= 0; i--) {
6731                if ((resultTargetUser.get(i).activityInfo.applicationInfo.flags
6732                        & ApplicationInfo.FLAG_SUSPENDED) == 0) {
6733                    return createForwardingResolveInfoUnchecked(filter, sourceUserId,
6734                            targetUserId);
6735                }
6736            }
6737        }
6738        return null;
6739    }
6740
6741    private ResolveInfo createForwardingResolveInfoUnchecked(IntentFilter filter,
6742            int sourceUserId, int targetUserId) {
6743        ResolveInfo forwardingResolveInfo = new ResolveInfo();
6744        long ident = Binder.clearCallingIdentity();
6745        boolean targetIsProfile;
6746        try {
6747            targetIsProfile = sUserManager.getUserInfo(targetUserId).isManagedProfile();
6748        } finally {
6749            Binder.restoreCallingIdentity(ident);
6750        }
6751        String className;
6752        if (targetIsProfile) {
6753            className = FORWARD_INTENT_TO_MANAGED_PROFILE;
6754        } else {
6755            className = FORWARD_INTENT_TO_PARENT;
6756        }
6757        ComponentName forwardingActivityComponentName = new ComponentName(
6758                mAndroidApplication.packageName, className);
6759        ActivityInfo forwardingActivityInfo = getActivityInfo(forwardingActivityComponentName, 0,
6760                sourceUserId);
6761        if (!targetIsProfile) {
6762            forwardingActivityInfo.showUserIcon = targetUserId;
6763            forwardingResolveInfo.noResourceId = true;
6764        }
6765        forwardingResolveInfo.activityInfo = forwardingActivityInfo;
6766        forwardingResolveInfo.priority = 0;
6767        forwardingResolveInfo.preferredOrder = 0;
6768        forwardingResolveInfo.match = 0;
6769        forwardingResolveInfo.isDefault = true;
6770        forwardingResolveInfo.filter = filter;
6771        forwardingResolveInfo.targetUserId = targetUserId;
6772        return forwardingResolveInfo;
6773    }
6774
6775    @Override
6776    public @NonNull ParceledListSlice<ResolveInfo> queryIntentActivityOptions(ComponentName caller,
6777            Intent[] specifics, String[] specificTypes, Intent intent,
6778            String resolvedType, int flags, int userId) {
6779        return new ParceledListSlice<>(queryIntentActivityOptionsInternal(caller, specifics,
6780                specificTypes, intent, resolvedType, flags, userId));
6781    }
6782
6783    private @NonNull List<ResolveInfo> queryIntentActivityOptionsInternal(ComponentName caller,
6784            Intent[] specifics, String[] specificTypes, Intent intent,
6785            String resolvedType, int flags, int userId) {
6786        if (!sUserManager.exists(userId)) return Collections.emptyList();
6787        flags = updateFlagsForResolve(flags, userId, intent, false);
6788        enforceCrossUserPermission(Binder.getCallingUid(), userId,
6789                false /* requireFullPermission */, false /* checkShell */,
6790                "query intent activity options");
6791        final String resultsAction = intent.getAction();
6792
6793        final List<ResolveInfo> results = queryIntentActivitiesInternal(intent, resolvedType, flags
6794                | PackageManager.GET_RESOLVED_FILTER, userId);
6795
6796        if (DEBUG_INTENT_MATCHING) {
6797            Log.v(TAG, "Query " + intent + ": " + results);
6798        }
6799
6800        int specificsPos = 0;
6801        int N;
6802
6803        // todo: note that the algorithm used here is O(N^2).  This
6804        // isn't a problem in our current environment, but if we start running
6805        // into situations where we have more than 5 or 10 matches then this
6806        // should probably be changed to something smarter...
6807
6808        // First we go through and resolve each of the specific items
6809        // that were supplied, taking care of removing any corresponding
6810        // duplicate items in the generic resolve list.
6811        if (specifics != null) {
6812            for (int i=0; i<specifics.length; i++) {
6813                final Intent sintent = specifics[i];
6814                if (sintent == null) {
6815                    continue;
6816                }
6817
6818                if (DEBUG_INTENT_MATCHING) {
6819                    Log.v(TAG, "Specific #" + i + ": " + sintent);
6820                }
6821
6822                String action = sintent.getAction();
6823                if (resultsAction != null && resultsAction.equals(action)) {
6824                    // If this action was explicitly requested, then don't
6825                    // remove things that have it.
6826                    action = null;
6827                }
6828
6829                ResolveInfo ri = null;
6830                ActivityInfo ai = null;
6831
6832                ComponentName comp = sintent.getComponent();
6833                if (comp == null) {
6834                    ri = resolveIntent(
6835                        sintent,
6836                        specificTypes != null ? specificTypes[i] : null,
6837                            flags, userId);
6838                    if (ri == null) {
6839                        continue;
6840                    }
6841                    if (ri == mResolveInfo) {
6842                        // ACK!  Must do something better with this.
6843                    }
6844                    ai = ri.activityInfo;
6845                    comp = new ComponentName(ai.applicationInfo.packageName,
6846                            ai.name);
6847                } else {
6848                    ai = getActivityInfo(comp, flags, userId);
6849                    if (ai == null) {
6850                        continue;
6851                    }
6852                }
6853
6854                // Look for any generic query activities that are duplicates
6855                // of this specific one, and remove them from the results.
6856                if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Specific #" + i + ": " + ai);
6857                N = results.size();
6858                int j;
6859                for (j=specificsPos; j<N; j++) {
6860                    ResolveInfo sri = results.get(j);
6861                    if ((sri.activityInfo.name.equals(comp.getClassName())
6862                            && sri.activityInfo.applicationInfo.packageName.equals(
6863                                    comp.getPackageName()))
6864                        || (action != null && sri.filter.matchAction(action))) {
6865                        results.remove(j);
6866                        if (DEBUG_INTENT_MATCHING) Log.v(
6867                            TAG, "Removing duplicate item from " + j
6868                            + " due to specific " + specificsPos);
6869                        if (ri == null) {
6870                            ri = sri;
6871                        }
6872                        j--;
6873                        N--;
6874                    }
6875                }
6876
6877                // Add this specific item to its proper place.
6878                if (ri == null) {
6879                    ri = new ResolveInfo();
6880                    ri.activityInfo = ai;
6881                }
6882                results.add(specificsPos, ri);
6883                ri.specificIndex = i;
6884                specificsPos++;
6885            }
6886        }
6887
6888        // Now we go through the remaining generic results and remove any
6889        // duplicate actions that are found here.
6890        N = results.size();
6891        for (int i=specificsPos; i<N-1; i++) {
6892            final ResolveInfo rii = results.get(i);
6893            if (rii.filter == null) {
6894                continue;
6895            }
6896
6897            // Iterate over all of the actions of this result's intent
6898            // filter...  typically this should be just one.
6899            final Iterator<String> it = rii.filter.actionsIterator();
6900            if (it == null) {
6901                continue;
6902            }
6903            while (it.hasNext()) {
6904                final String action = it.next();
6905                if (resultsAction != null && resultsAction.equals(action)) {
6906                    // If this action was explicitly requested, then don't
6907                    // remove things that have it.
6908                    continue;
6909                }
6910                for (int j=i+1; j<N; j++) {
6911                    final ResolveInfo rij = results.get(j);
6912                    if (rij.filter != null && rij.filter.hasAction(action)) {
6913                        results.remove(j);
6914                        if (DEBUG_INTENT_MATCHING) Log.v(
6915                            TAG, "Removing duplicate item from " + j
6916                            + " due to action " + action + " at " + i);
6917                        j--;
6918                        N--;
6919                    }
6920                }
6921            }
6922
6923            // If the caller didn't request filter information, drop it now
6924            // so we don't have to marshall/unmarshall it.
6925            if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
6926                rii.filter = null;
6927            }
6928        }
6929
6930        // Filter out the caller activity if so requested.
6931        if (caller != null) {
6932            N = results.size();
6933            for (int i=0; i<N; i++) {
6934                ActivityInfo ainfo = results.get(i).activityInfo;
6935                if (caller.getPackageName().equals(ainfo.applicationInfo.packageName)
6936                        && caller.getClassName().equals(ainfo.name)) {
6937                    results.remove(i);
6938                    break;
6939                }
6940            }
6941        }
6942
6943        // If the caller didn't request filter information,
6944        // drop them now so we don't have to
6945        // marshall/unmarshall it.
6946        if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
6947            N = results.size();
6948            for (int i=0; i<N; i++) {
6949                results.get(i).filter = null;
6950            }
6951        }
6952
6953        if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Result: " + results);
6954        return results;
6955    }
6956
6957    @Override
6958    public @NonNull ParceledListSlice<ResolveInfo> queryIntentReceivers(Intent intent,
6959            String resolvedType, int flags, int userId) {
6960        return new ParceledListSlice<>(
6961                queryIntentReceiversInternal(intent, resolvedType, flags, userId));
6962    }
6963
6964    private @NonNull List<ResolveInfo> queryIntentReceiversInternal(Intent intent,
6965            String resolvedType, int flags, int userId) {
6966        if (!sUserManager.exists(userId)) return Collections.emptyList();
6967        flags = updateFlagsForResolve(flags, userId, intent, false);
6968        ComponentName comp = intent.getComponent();
6969        if (comp == null) {
6970            if (intent.getSelector() != null) {
6971                intent = intent.getSelector();
6972                comp = intent.getComponent();
6973            }
6974        }
6975        if (comp != null) {
6976            List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
6977            ActivityInfo ai = getReceiverInfo(comp, flags, userId);
6978            if (ai != null) {
6979                ResolveInfo ri = new ResolveInfo();
6980                ri.activityInfo = ai;
6981                list.add(ri);
6982            }
6983            return list;
6984        }
6985
6986        // reader
6987        synchronized (mPackages) {
6988            String pkgName = intent.getPackage();
6989            if (pkgName == null) {
6990                return mReceivers.queryIntent(intent, resolvedType, flags, userId);
6991            }
6992            final PackageParser.Package pkg = mPackages.get(pkgName);
6993            if (pkg != null) {
6994                return mReceivers.queryIntentForPackage(intent, resolvedType, flags, pkg.receivers,
6995                        userId);
6996            }
6997            return Collections.emptyList();
6998        }
6999    }
7000
7001    @Override
7002    public ResolveInfo resolveService(Intent intent, String resolvedType, int flags, int userId) {
7003        if (!sUserManager.exists(userId)) return null;
7004        flags = updateFlagsForResolve(flags, userId, intent, false);
7005        List<ResolveInfo> query = queryIntentServicesInternal(intent, resolvedType, flags, userId);
7006        if (query != null) {
7007            if (query.size() >= 1) {
7008                // If there is more than one service with the same priority,
7009                // just arbitrarily pick the first one.
7010                return query.get(0);
7011            }
7012        }
7013        return null;
7014    }
7015
7016    @Override
7017    public @NonNull ParceledListSlice<ResolveInfo> queryIntentServices(Intent intent,
7018            String resolvedType, int flags, int userId) {
7019        return new ParceledListSlice<>(
7020                queryIntentServicesInternal(intent, resolvedType, flags, userId));
7021    }
7022
7023    private @NonNull List<ResolveInfo> queryIntentServicesInternal(Intent intent,
7024            String resolvedType, int flags, int userId) {
7025        if (!sUserManager.exists(userId)) return Collections.emptyList();
7026        flags = updateFlagsForResolve(flags, userId, intent, false);
7027        ComponentName comp = intent.getComponent();
7028        if (comp == null) {
7029            if (intent.getSelector() != null) {
7030                intent = intent.getSelector();
7031                comp = intent.getComponent();
7032            }
7033        }
7034        if (comp != null) {
7035            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
7036            final ServiceInfo si = getServiceInfo(comp, flags, userId);
7037            if (si != null) {
7038                final ResolveInfo ri = new ResolveInfo();
7039                ri.serviceInfo = si;
7040                list.add(ri);
7041            }
7042            return list;
7043        }
7044
7045        // reader
7046        synchronized (mPackages) {
7047            String pkgName = intent.getPackage();
7048            if (pkgName == null) {
7049                return mServices.queryIntent(intent, resolvedType, flags, userId);
7050            }
7051            final PackageParser.Package pkg = mPackages.get(pkgName);
7052            if (pkg != null) {
7053                return mServices.queryIntentForPackage(intent, resolvedType, flags, pkg.services,
7054                        userId);
7055            }
7056            return Collections.emptyList();
7057        }
7058    }
7059
7060    @Override
7061    public @NonNull ParceledListSlice<ResolveInfo> queryIntentContentProviders(Intent intent,
7062            String resolvedType, int flags, int userId) {
7063        return new ParceledListSlice<>(
7064                queryIntentContentProvidersInternal(intent, resolvedType, flags, userId));
7065    }
7066
7067    private @NonNull List<ResolveInfo> queryIntentContentProvidersInternal(
7068            Intent intent, String resolvedType, int flags, int userId) {
7069        if (!sUserManager.exists(userId)) return Collections.emptyList();
7070        flags = updateFlagsForResolve(flags, userId, intent, false);
7071        ComponentName comp = intent.getComponent();
7072        if (comp == null) {
7073            if (intent.getSelector() != null) {
7074                intent = intent.getSelector();
7075                comp = intent.getComponent();
7076            }
7077        }
7078        if (comp != null) {
7079            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
7080            final ProviderInfo pi = getProviderInfo(comp, flags, userId);
7081            if (pi != null) {
7082                final ResolveInfo ri = new ResolveInfo();
7083                ri.providerInfo = pi;
7084                list.add(ri);
7085            }
7086            return list;
7087        }
7088
7089        // reader
7090        synchronized (mPackages) {
7091            String pkgName = intent.getPackage();
7092            if (pkgName == null) {
7093                return mProviders.queryIntent(intent, resolvedType, flags, userId);
7094            }
7095            final PackageParser.Package pkg = mPackages.get(pkgName);
7096            if (pkg != null) {
7097                return mProviders.queryIntentForPackage(
7098                        intent, resolvedType, flags, pkg.providers, userId);
7099            }
7100            return Collections.emptyList();
7101        }
7102    }
7103
7104    @Override
7105    public ParceledListSlice<PackageInfo> getInstalledPackages(int flags, int userId) {
7106        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
7107        flags = updateFlagsForPackage(flags, userId, null);
7108        final boolean listUninstalled = (flags & MATCH_KNOWN_PACKAGES) != 0;
7109        enforceCrossUserPermission(Binder.getCallingUid(), userId,
7110                true /* requireFullPermission */, false /* checkShell */,
7111                "get installed packages");
7112
7113        // writer
7114        synchronized (mPackages) {
7115            ArrayList<PackageInfo> list;
7116            if (listUninstalled) {
7117                list = new ArrayList<>(mSettings.mPackages.size());
7118                for (PackageSetting ps : mSettings.mPackages.values()) {
7119                    if (filterSharedLibPackageLPr(ps, Binder.getCallingUid(), userId)) {
7120                        continue;
7121                    }
7122                    final PackageInfo pi = generatePackageInfo(ps, flags, userId);
7123                    if (pi != null) {
7124                        list.add(pi);
7125                    }
7126                }
7127            } else {
7128                list = new ArrayList<>(mPackages.size());
7129                for (PackageParser.Package p : mPackages.values()) {
7130                    if (filterSharedLibPackageLPr((PackageSetting) p.mExtras,
7131                            Binder.getCallingUid(), userId)) {
7132                        continue;
7133                    }
7134                    final PackageInfo pi = generatePackageInfo((PackageSetting)
7135                            p.mExtras, flags, userId);
7136                    if (pi != null) {
7137                        list.add(pi);
7138                    }
7139                }
7140            }
7141
7142            return new ParceledListSlice<>(list);
7143        }
7144    }
7145
7146    private void addPackageHoldingPermissions(ArrayList<PackageInfo> list, PackageSetting ps,
7147            String[] permissions, boolean[] tmp, int flags, int userId) {
7148        int numMatch = 0;
7149        final PermissionsState permissionsState = ps.getPermissionsState();
7150        for (int i=0; i<permissions.length; i++) {
7151            final String permission = permissions[i];
7152            if (permissionsState.hasPermission(permission, userId)) {
7153                tmp[i] = true;
7154                numMatch++;
7155            } else {
7156                tmp[i] = false;
7157            }
7158        }
7159        if (numMatch == 0) {
7160            return;
7161        }
7162        final PackageInfo pi = generatePackageInfo(ps, flags, userId);
7163
7164        // The above might return null in cases of uninstalled apps or install-state
7165        // skew across users/profiles.
7166        if (pi != null) {
7167            if ((flags&PackageManager.GET_PERMISSIONS) == 0) {
7168                if (numMatch == permissions.length) {
7169                    pi.requestedPermissions = permissions;
7170                } else {
7171                    pi.requestedPermissions = new String[numMatch];
7172                    numMatch = 0;
7173                    for (int i=0; i<permissions.length; i++) {
7174                        if (tmp[i]) {
7175                            pi.requestedPermissions[numMatch] = permissions[i];
7176                            numMatch++;
7177                        }
7178                    }
7179                }
7180            }
7181            list.add(pi);
7182        }
7183    }
7184
7185    @Override
7186    public ParceledListSlice<PackageInfo> getPackagesHoldingPermissions(
7187            String[] permissions, int flags, int userId) {
7188        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
7189        flags = updateFlagsForPackage(flags, userId, permissions);
7190        enforceCrossUserPermission(Binder.getCallingUid(), userId,
7191                true /* requireFullPermission */, false /* checkShell */,
7192                "get packages holding permissions");
7193        final boolean listUninstalled = (flags & MATCH_KNOWN_PACKAGES) != 0;
7194
7195        // writer
7196        synchronized (mPackages) {
7197            ArrayList<PackageInfo> list = new ArrayList<PackageInfo>();
7198            boolean[] tmpBools = new boolean[permissions.length];
7199            if (listUninstalled) {
7200                for (PackageSetting ps : mSettings.mPackages.values()) {
7201                    addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags,
7202                            userId);
7203                }
7204            } else {
7205                for (PackageParser.Package pkg : mPackages.values()) {
7206                    PackageSetting ps = (PackageSetting)pkg.mExtras;
7207                    if (ps != null) {
7208                        addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags,
7209                                userId);
7210                    }
7211                }
7212            }
7213
7214            return new ParceledListSlice<PackageInfo>(list);
7215        }
7216    }
7217
7218    @Override
7219    public ParceledListSlice<ApplicationInfo> getInstalledApplications(int flags, int userId) {
7220        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
7221        flags = updateFlagsForApplication(flags, userId, null);
7222        final boolean listUninstalled = (flags & MATCH_KNOWN_PACKAGES) != 0;
7223
7224        // writer
7225        synchronized (mPackages) {
7226            ArrayList<ApplicationInfo> list;
7227            if (listUninstalled) {
7228                list = new ArrayList<>(mSettings.mPackages.size());
7229                for (PackageSetting ps : mSettings.mPackages.values()) {
7230                    ApplicationInfo ai;
7231                    int effectiveFlags = flags;
7232                    if (ps.isSystem()) {
7233                        effectiveFlags |= PackageManager.MATCH_ANY_USER;
7234                    }
7235                    if (ps.pkg != null) {
7236                        if (filterSharedLibPackageLPr(ps, Binder.getCallingUid(), userId)) {
7237                            continue;
7238                        }
7239                        ai = PackageParser.generateApplicationInfo(ps.pkg, effectiveFlags,
7240                                ps.readUserState(userId), userId);
7241                        if (ai != null) {
7242                            rebaseEnabledOverlays(ai, userId);
7243                            ai.packageName = resolveExternalPackageNameLPr(ps.pkg);
7244                        }
7245                    } else {
7246                        // Shared lib filtering done in generateApplicationInfoFromSettingsLPw
7247                        // and already converts to externally visible package name
7248                        ai = generateApplicationInfoFromSettingsLPw(ps.name,
7249                                Binder.getCallingUid(), effectiveFlags, userId);
7250                    }
7251                    if (ai != null) {
7252                        list.add(ai);
7253                    }
7254                }
7255            } else {
7256                list = new ArrayList<>(mPackages.size());
7257                for (PackageParser.Package p : mPackages.values()) {
7258                    if (p.mExtras != null) {
7259                        PackageSetting ps = (PackageSetting) p.mExtras;
7260                        if (filterSharedLibPackageLPr(ps, Binder.getCallingUid(), userId)) {
7261                            continue;
7262                        }
7263                        ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags,
7264                                ps.readUserState(userId), userId);
7265                        if (ai != null) {
7266                            rebaseEnabledOverlays(ai, userId);
7267                            ai.packageName = resolveExternalPackageNameLPr(p);
7268                            list.add(ai);
7269                        }
7270                    }
7271                }
7272            }
7273
7274            return new ParceledListSlice<>(list);
7275        }
7276    }
7277
7278    @Override
7279    public ParceledListSlice<InstantAppInfo> getInstantApps(int userId) {
7280        if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) {
7281            return null;
7282        }
7283
7284        mContext.enforceCallingOrSelfPermission(Manifest.permission.ACCESS_INSTANT_APPS,
7285                "getEphemeralApplications");
7286        enforceCrossUserPermission(Binder.getCallingUid(), userId,
7287                true /* requireFullPermission */, false /* checkShell */,
7288                "getEphemeralApplications");
7289        synchronized (mPackages) {
7290            List<InstantAppInfo> instantApps = mInstantAppRegistry
7291                    .getInstantAppsLPr(userId);
7292            if (instantApps != null) {
7293                return new ParceledListSlice<>(instantApps);
7294            }
7295        }
7296        return null;
7297    }
7298
7299    @Override
7300    public boolean isInstantApp(String packageName, int userId) {
7301        enforceCrossUserPermission(Binder.getCallingUid(), userId,
7302                true /* requireFullPermission */, false /* checkShell */,
7303                "isInstantApp");
7304        if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) {
7305            return false;
7306        }
7307
7308        if (!isCallerSameApp(packageName)) {
7309            return false;
7310        }
7311        synchronized (mPackages) {
7312            final PackageSetting ps = mSettings.mPackages.get(packageName);
7313            if (ps != null) {
7314                return ps.getInstantApp(userId);
7315            }
7316        }
7317        return false;
7318    }
7319
7320    @Override
7321    public byte[] getInstantAppCookie(String packageName, int userId) {
7322        if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) {
7323            return null;
7324        }
7325
7326        enforceCrossUserPermission(Binder.getCallingUid(), userId,
7327                true /* requireFullPermission */, false /* checkShell */,
7328                "getInstantAppCookie");
7329        if (!isCallerSameApp(packageName)) {
7330            return null;
7331        }
7332        synchronized (mPackages) {
7333            return mInstantAppRegistry.getInstantAppCookieLPw(
7334                    packageName, userId);
7335        }
7336    }
7337
7338    @Override
7339    public boolean setInstantAppCookie(String packageName, byte[] cookie, int userId) {
7340        if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) {
7341            return true;
7342        }
7343
7344        enforceCrossUserPermission(Binder.getCallingUid(), userId,
7345                true /* requireFullPermission */, true /* checkShell */,
7346                "setInstantAppCookie");
7347        if (!isCallerSameApp(packageName)) {
7348            return false;
7349        }
7350        synchronized (mPackages) {
7351            return mInstantAppRegistry.setInstantAppCookieLPw(
7352                    packageName, cookie, userId);
7353        }
7354    }
7355
7356    @Override
7357    public Bitmap getInstantAppIcon(String packageName, int userId) {
7358        if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) {
7359            return null;
7360        }
7361
7362        mContext.enforceCallingOrSelfPermission(Manifest.permission.ACCESS_INSTANT_APPS,
7363                "getInstantAppIcon");
7364
7365        enforceCrossUserPermission(Binder.getCallingUid(), userId,
7366                true /* requireFullPermission */, false /* checkShell */,
7367                "getInstantAppIcon");
7368
7369        synchronized (mPackages) {
7370            return mInstantAppRegistry.getInstantAppIconLPw(
7371                    packageName, userId);
7372        }
7373    }
7374
7375    private boolean isCallerSameApp(String packageName) {
7376        PackageParser.Package pkg = mPackages.get(packageName);
7377        return pkg != null
7378                && UserHandle.getAppId(Binder.getCallingUid()) == pkg.applicationInfo.uid;
7379    }
7380
7381    @Override
7382    public @NonNull ParceledListSlice<ApplicationInfo> getPersistentApplications(int flags) {
7383        return new ParceledListSlice<>(getPersistentApplicationsInternal(flags));
7384    }
7385
7386    private @NonNull List<ApplicationInfo> getPersistentApplicationsInternal(int flags) {
7387        final ArrayList<ApplicationInfo> finalList = new ArrayList<ApplicationInfo>();
7388
7389        // reader
7390        synchronized (mPackages) {
7391            final Iterator<PackageParser.Package> i = mPackages.values().iterator();
7392            final int userId = UserHandle.getCallingUserId();
7393            while (i.hasNext()) {
7394                final PackageParser.Package p = i.next();
7395                if (p.applicationInfo == null) continue;
7396
7397                final boolean matchesUnaware = ((flags & MATCH_DIRECT_BOOT_UNAWARE) != 0)
7398                        && !p.applicationInfo.isDirectBootAware();
7399                final boolean matchesAware = ((flags & MATCH_DIRECT_BOOT_AWARE) != 0)
7400                        && p.applicationInfo.isDirectBootAware();
7401
7402                if ((p.applicationInfo.flags & ApplicationInfo.FLAG_PERSISTENT) != 0
7403                        && (!mSafeMode || isSystemApp(p))
7404                        && (matchesUnaware || matchesAware)) {
7405                    PackageSetting ps = mSettings.mPackages.get(p.packageName);
7406                    if (ps != null) {
7407                        ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags,
7408                                ps.readUserState(userId), userId);
7409                        if (ai != null) {
7410                            rebaseEnabledOverlays(ai, userId);
7411                            finalList.add(ai);
7412                        }
7413                    }
7414                }
7415            }
7416        }
7417
7418        return finalList;
7419    }
7420
7421    @Override
7422    public ProviderInfo resolveContentProvider(String name, int flags, int userId) {
7423        if (!sUserManager.exists(userId)) return null;
7424        flags = updateFlagsForComponent(flags, userId, name);
7425        // reader
7426        synchronized (mPackages) {
7427            final PackageParser.Provider provider = mProvidersByAuthority.get(name);
7428            PackageSetting ps = provider != null
7429                    ? mSettings.mPackages.get(provider.owner.packageName)
7430                    : null;
7431            return ps != null
7432                    && mSettings.isEnabledAndMatchLPr(provider.info, flags, userId)
7433                    ? PackageParser.generateProviderInfo(provider, flags,
7434                            ps.readUserState(userId), userId)
7435                    : null;
7436        }
7437    }
7438
7439    /**
7440     * @deprecated
7441     */
7442    @Deprecated
7443    public void querySyncProviders(List<String> outNames, List<ProviderInfo> outInfo) {
7444        // reader
7445        synchronized (mPackages) {
7446            final Iterator<Map.Entry<String, PackageParser.Provider>> i = mProvidersByAuthority
7447                    .entrySet().iterator();
7448            final int userId = UserHandle.getCallingUserId();
7449            while (i.hasNext()) {
7450                Map.Entry<String, PackageParser.Provider> entry = i.next();
7451                PackageParser.Provider p = entry.getValue();
7452                PackageSetting ps = mSettings.mPackages.get(p.owner.packageName);
7453
7454                if (ps != null && p.syncable
7455                        && (!mSafeMode || (p.info.applicationInfo.flags
7456                                &ApplicationInfo.FLAG_SYSTEM) != 0)) {
7457                    ProviderInfo info = PackageParser.generateProviderInfo(p, 0,
7458                            ps.readUserState(userId), userId);
7459                    if (info != null) {
7460                        outNames.add(entry.getKey());
7461                        outInfo.add(info);
7462                    }
7463                }
7464            }
7465        }
7466    }
7467
7468    @Override
7469    public @NonNull ParceledListSlice<ProviderInfo> queryContentProviders(String processName,
7470            int uid, int flags) {
7471        final int userId = processName != null ? UserHandle.getUserId(uid)
7472                : UserHandle.getCallingUserId();
7473        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
7474        flags = updateFlagsForComponent(flags, userId, processName);
7475
7476        ArrayList<ProviderInfo> finalList = null;
7477        // reader
7478        synchronized (mPackages) {
7479            final Iterator<PackageParser.Provider> i = mProviders.mProviders.values().iterator();
7480            while (i.hasNext()) {
7481                final PackageParser.Provider p = i.next();
7482                PackageSetting ps = mSettings.mPackages.get(p.owner.packageName);
7483                if (ps != null && p.info.authority != null
7484                        && (processName == null
7485                                || (p.info.processName.equals(processName)
7486                                        && UserHandle.isSameApp(p.info.applicationInfo.uid, uid)))
7487                        && mSettings.isEnabledAndMatchLPr(p.info, flags, userId)) {
7488                    if (finalList == null) {
7489                        finalList = new ArrayList<ProviderInfo>(3);
7490                    }
7491                    ProviderInfo info = PackageParser.generateProviderInfo(p, flags,
7492                            ps.readUserState(userId), userId);
7493                    if (info != null) {
7494                        finalList.add(info);
7495                    }
7496                }
7497            }
7498        }
7499
7500        if (finalList != null) {
7501            Collections.sort(finalList, mProviderInitOrderSorter);
7502            return new ParceledListSlice<ProviderInfo>(finalList);
7503        }
7504
7505        return ParceledListSlice.emptyList();
7506    }
7507
7508    @Override
7509    public InstrumentationInfo getInstrumentationInfo(ComponentName name, int flags) {
7510        // reader
7511        synchronized (mPackages) {
7512            final PackageParser.Instrumentation i = mInstrumentation.get(name);
7513            return PackageParser.generateInstrumentationInfo(i, flags);
7514        }
7515    }
7516
7517    @Override
7518    public @NonNull ParceledListSlice<InstrumentationInfo> queryInstrumentation(
7519            String targetPackage, int flags) {
7520        return new ParceledListSlice<>(queryInstrumentationInternal(targetPackage, flags));
7521    }
7522
7523    private @NonNull List<InstrumentationInfo> queryInstrumentationInternal(String targetPackage,
7524            int flags) {
7525        ArrayList<InstrumentationInfo> finalList = new ArrayList<InstrumentationInfo>();
7526
7527        // reader
7528        synchronized (mPackages) {
7529            final Iterator<PackageParser.Instrumentation> i = mInstrumentation.values().iterator();
7530            while (i.hasNext()) {
7531                final PackageParser.Instrumentation p = i.next();
7532                if (targetPackage == null
7533                        || targetPackage.equals(p.info.targetPackage)) {
7534                    InstrumentationInfo ii = PackageParser.generateInstrumentationInfo(p,
7535                            flags);
7536                    if (ii != null) {
7537                        finalList.add(ii);
7538                    }
7539                }
7540            }
7541        }
7542
7543        return finalList;
7544    }
7545
7546    private void scanDirTracedLI(File dir, final int parseFlags, int scanFlags, long currentTime) {
7547        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanDir [" + dir.getAbsolutePath() + "]");
7548        try {
7549            scanDirLI(dir, parseFlags, scanFlags, currentTime);
7550        } finally {
7551            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
7552        }
7553    }
7554
7555    private void scanDirLI(File dir, int parseFlags, int scanFlags, long currentTime) {
7556        final File[] files = dir.listFiles();
7557        if (ArrayUtils.isEmpty(files)) {
7558            Log.d(TAG, "No files in app dir " + dir);
7559            return;
7560        }
7561
7562        if (DEBUG_PACKAGE_SCANNING) {
7563            Log.d(TAG, "Scanning app dir " + dir + " scanFlags=" + scanFlags
7564                    + " flags=0x" + Integer.toHexString(parseFlags));
7565        }
7566        ParallelPackageParser parallelPackageParser = new ParallelPackageParser(
7567                mSeparateProcesses, mOnlyCore, mMetrics, mCacheDir);
7568
7569        // Submit files for parsing in parallel
7570        int fileCount = 0;
7571        for (File file : files) {
7572            final boolean isPackage = (isApkFile(file) || file.isDirectory())
7573                    && !PackageInstallerService.isStageName(file.getName());
7574            if (!isPackage) {
7575                // Ignore entries which are not packages
7576                continue;
7577            }
7578            parallelPackageParser.submit(file, parseFlags);
7579            fileCount++;
7580        }
7581
7582        // Process results one by one
7583        for (; fileCount > 0; fileCount--) {
7584            ParallelPackageParser.ParseResult parseResult = parallelPackageParser.take();
7585            Throwable throwable = parseResult.throwable;
7586            int errorCode = PackageManager.INSTALL_SUCCEEDED;
7587
7588            if (throwable == null) {
7589                // Static shared libraries have synthetic package names
7590                if (parseResult.pkg.applicationInfo.isStaticSharedLibrary()) {
7591                    renameStaticSharedLibraryPackage(parseResult.pkg);
7592                }
7593                try {
7594                    if (errorCode == PackageManager.INSTALL_SUCCEEDED) {
7595                        scanPackageLI(parseResult.pkg, parseResult.scanFile, parseFlags, scanFlags,
7596                                currentTime, null);
7597                    }
7598                } catch (PackageManagerException e) {
7599                    errorCode = e.error;
7600                    Slog.w(TAG, "Failed to scan " + parseResult.scanFile + ": " + e.getMessage());
7601                }
7602            } else if (throwable instanceof PackageParser.PackageParserException) {
7603                PackageParser.PackageParserException e = (PackageParser.PackageParserException)
7604                        throwable;
7605                errorCode = e.error;
7606                Slog.w(TAG, "Failed to parse " + parseResult.scanFile + ": " + e.getMessage());
7607            } else {
7608                throw new IllegalStateException("Unexpected exception occurred while parsing "
7609                        + parseResult.scanFile, throwable);
7610            }
7611
7612            // Delete invalid userdata apps
7613            if ((parseFlags & PackageParser.PARSE_IS_SYSTEM) == 0 &&
7614                    errorCode == PackageManager.INSTALL_FAILED_INVALID_APK) {
7615                logCriticalInfo(Log.WARN,
7616                        "Deleting invalid package at " + parseResult.scanFile);
7617                removeCodePathLI(parseResult.scanFile);
7618            }
7619        }
7620        parallelPackageParser.close();
7621    }
7622
7623    private static File getSettingsProblemFile() {
7624        File dataDir = Environment.getDataDirectory();
7625        File systemDir = new File(dataDir, "system");
7626        File fname = new File(systemDir, "uiderrors.txt");
7627        return fname;
7628    }
7629
7630    static void reportSettingsProblem(int priority, String msg) {
7631        logCriticalInfo(priority, msg);
7632    }
7633
7634    static void logCriticalInfo(int priority, String msg) {
7635        Slog.println(priority, TAG, msg);
7636        EventLogTags.writePmCriticalInfo(msg);
7637        try {
7638            File fname = getSettingsProblemFile();
7639            FileOutputStream out = new FileOutputStream(fname, true);
7640            PrintWriter pw = new FastPrintWriter(out);
7641            SimpleDateFormat formatter = new SimpleDateFormat();
7642            String dateString = formatter.format(new Date(System.currentTimeMillis()));
7643            pw.println(dateString + ": " + msg);
7644            pw.close();
7645            FileUtils.setPermissions(
7646                    fname.toString(),
7647                    FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IROTH,
7648                    -1, -1);
7649        } catch (java.io.IOException e) {
7650        }
7651    }
7652
7653    private long getLastModifiedTime(PackageParser.Package pkg, File srcFile) {
7654        if (srcFile.isDirectory()) {
7655            final File baseFile = new File(pkg.baseCodePath);
7656            long maxModifiedTime = baseFile.lastModified();
7657            if (pkg.splitCodePaths != null) {
7658                for (int i = pkg.splitCodePaths.length - 1; i >=0; --i) {
7659                    final File splitFile = new File(pkg.splitCodePaths[i]);
7660                    maxModifiedTime = Math.max(maxModifiedTime, splitFile.lastModified());
7661                }
7662            }
7663            return maxModifiedTime;
7664        }
7665        return srcFile.lastModified();
7666    }
7667
7668    private void collectCertificatesLI(PackageSetting ps, PackageParser.Package pkg, File srcFile,
7669            final int policyFlags) throws PackageManagerException {
7670        // When upgrading from pre-N MR1, verify the package time stamp using the package
7671        // directory and not the APK file.
7672        final long lastModifiedTime = mIsPreNMR1Upgrade
7673                ? new File(pkg.codePath).lastModified() : getLastModifiedTime(pkg, srcFile);
7674        if (ps != null
7675                && ps.codePath.equals(srcFile)
7676                && ps.timeStamp == lastModifiedTime
7677                && !isCompatSignatureUpdateNeeded(pkg)
7678                && !isRecoverSignatureUpdateNeeded(pkg)) {
7679            long mSigningKeySetId = ps.keySetData.getProperSigningKeySet();
7680            KeySetManagerService ksms = mSettings.mKeySetManagerService;
7681            ArraySet<PublicKey> signingKs;
7682            synchronized (mPackages) {
7683                signingKs = ksms.getPublicKeysFromKeySetLPr(mSigningKeySetId);
7684            }
7685            if (ps.signatures.mSignatures != null
7686                    && ps.signatures.mSignatures.length != 0
7687                    && signingKs != null) {
7688                // Optimization: reuse the existing cached certificates
7689                // if the package appears to be unchanged.
7690                pkg.mSignatures = ps.signatures.mSignatures;
7691                pkg.mSigningKeys = signingKs;
7692                return;
7693            }
7694
7695            Slog.w(TAG, "PackageSetting for " + ps.name
7696                    + " is missing signatures.  Collecting certs again to recover them.");
7697        } else {
7698            Slog.i(TAG, srcFile.toString() + " changed; collecting certs");
7699        }
7700
7701        try {
7702            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "collectCertificates");
7703            PackageParser.collectCertificates(pkg, policyFlags);
7704        } catch (PackageParserException e) {
7705            throw PackageManagerException.from(e);
7706        } finally {
7707            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
7708        }
7709    }
7710
7711    /**
7712     *  Traces a package scan.
7713     *  @see #scanPackageLI(File, int, int, long, UserHandle)
7714     */
7715    private PackageParser.Package scanPackageTracedLI(File scanFile, final int parseFlags,
7716            int scanFlags, long currentTime, UserHandle user) throws PackageManagerException {
7717        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage [" + scanFile.toString() + "]");
7718        try {
7719            return scanPackageLI(scanFile, parseFlags, scanFlags, currentTime, user);
7720        } finally {
7721            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
7722        }
7723    }
7724
7725    /**
7726     *  Scans a package and returns the newly parsed package.
7727     *  Returns {@code null} in case of errors and the error code is stored in mLastScanError
7728     */
7729    private PackageParser.Package scanPackageLI(File scanFile, int parseFlags, int scanFlags,
7730            long currentTime, UserHandle user) throws PackageManagerException {
7731        if (DEBUG_INSTALL) Slog.d(TAG, "Parsing: " + scanFile);
7732        PackageParser pp = new PackageParser();
7733        pp.setSeparateProcesses(mSeparateProcesses);
7734        pp.setOnlyCoreApps(mOnlyCore);
7735        pp.setDisplayMetrics(mMetrics);
7736
7737        if ((scanFlags & SCAN_TRUSTED_OVERLAY) != 0) {
7738            parseFlags |= PackageParser.PARSE_TRUSTED_OVERLAY;
7739        }
7740
7741        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "parsePackage");
7742        final PackageParser.Package pkg;
7743        try {
7744            pkg = pp.parsePackage(scanFile, parseFlags);
7745        } catch (PackageParserException e) {
7746            throw PackageManagerException.from(e);
7747        } finally {
7748            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
7749        }
7750
7751        // Static shared libraries have synthetic package names
7752        if (pkg.applicationInfo.isStaticSharedLibrary()) {
7753            renameStaticSharedLibraryPackage(pkg);
7754        }
7755
7756        return scanPackageLI(pkg, scanFile, parseFlags, scanFlags, currentTime, user);
7757    }
7758
7759    /**
7760     *  Scans a package and returns the newly parsed package.
7761     *  @throws PackageManagerException on a parse error.
7762     */
7763    private PackageParser.Package scanPackageLI(PackageParser.Package pkg, File scanFile,
7764            final int policyFlags, int scanFlags, long currentTime, @Nullable UserHandle user)
7765            throws PackageManagerException {
7766        // If the package has children and this is the first dive in the function
7767        // we scan the package with the SCAN_CHECK_ONLY flag set to see whether all
7768        // packages (parent and children) would be successfully scanned before the
7769        // actual scan since scanning mutates internal state and we want to atomically
7770        // install the package and its children.
7771        if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
7772            if (pkg.childPackages != null && pkg.childPackages.size() > 0) {
7773                scanFlags |= SCAN_CHECK_ONLY;
7774            }
7775        } else {
7776            scanFlags &= ~SCAN_CHECK_ONLY;
7777        }
7778
7779        // Scan the parent
7780        PackageParser.Package scannedPkg = scanPackageInternalLI(pkg, scanFile, policyFlags,
7781                scanFlags, currentTime, user);
7782
7783        // Scan the children
7784        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
7785        for (int i = 0; i < childCount; i++) {
7786            PackageParser.Package childPackage = pkg.childPackages.get(i);
7787            scanPackageInternalLI(childPackage, scanFile, policyFlags, scanFlags,
7788                    currentTime, user);
7789        }
7790
7791
7792        if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
7793            return scanPackageLI(pkg, scanFile, policyFlags, scanFlags, currentTime, user);
7794        }
7795
7796        return scannedPkg;
7797    }
7798
7799    /**
7800     *  Scans a package and returns the newly parsed package.
7801     *  @throws PackageManagerException on a parse error.
7802     */
7803    private PackageParser.Package scanPackageInternalLI(PackageParser.Package pkg, File scanFile,
7804            int policyFlags, int scanFlags, long currentTime, @Nullable UserHandle user)
7805            throws PackageManagerException {
7806        PackageSetting ps = null;
7807        PackageSetting updatedPkg;
7808        // reader
7809        synchronized (mPackages) {
7810            // Look to see if we already know about this package.
7811            String oldName = mSettings.getRenamedPackageLPr(pkg.packageName);
7812            if (pkg.mOriginalPackages != null && pkg.mOriginalPackages.contains(oldName)) {
7813                // This package has been renamed to its original name.  Let's
7814                // use that.
7815                ps = mSettings.getPackageLPr(oldName);
7816            }
7817            // If there was no original package, see one for the real package name.
7818            if (ps == null) {
7819                ps = mSettings.getPackageLPr(pkg.packageName);
7820            }
7821            // Check to see if this package could be hiding/updating a system
7822            // package.  Must look for it either under the original or real
7823            // package name depending on our state.
7824            updatedPkg = mSettings.getDisabledSystemPkgLPr(ps != null ? ps.name : pkg.packageName);
7825            if (DEBUG_INSTALL && updatedPkg != null) Slog.d(TAG, "updatedPkg = " + updatedPkg);
7826
7827            // If this is a package we don't know about on the system partition, we
7828            // may need to remove disabled child packages on the system partition
7829            // or may need to not add child packages if the parent apk is updated
7830            // on the data partition and no longer defines this child package.
7831            if ((policyFlags & PackageParser.PARSE_IS_SYSTEM) != 0) {
7832                // If this is a parent package for an updated system app and this system
7833                // app got an OTA update which no longer defines some of the child packages
7834                // we have to prune them from the disabled system packages.
7835                PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(pkg.packageName);
7836                if (disabledPs != null) {
7837                    final int scannedChildCount = (pkg.childPackages != null)
7838                            ? pkg.childPackages.size() : 0;
7839                    final int disabledChildCount = disabledPs.childPackageNames != null
7840                            ? disabledPs.childPackageNames.size() : 0;
7841                    for (int i = 0; i < disabledChildCount; i++) {
7842                        String disabledChildPackageName = disabledPs.childPackageNames.get(i);
7843                        boolean disabledPackageAvailable = false;
7844                        for (int j = 0; j < scannedChildCount; j++) {
7845                            PackageParser.Package childPkg = pkg.childPackages.get(j);
7846                            if (childPkg.packageName.equals(disabledChildPackageName)) {
7847                                disabledPackageAvailable = true;
7848                                break;
7849                            }
7850                         }
7851                         if (!disabledPackageAvailable) {
7852                             mSettings.removeDisabledSystemPackageLPw(disabledChildPackageName);
7853                         }
7854                    }
7855                }
7856            }
7857        }
7858
7859        boolean updatedPkgBetter = false;
7860        // First check if this is a system package that may involve an update
7861        if (updatedPkg != null && (policyFlags & PackageParser.PARSE_IS_SYSTEM) != 0) {
7862            // If new package is not located in "/system/priv-app" (e.g. due to an OTA),
7863            // it needs to drop FLAG_PRIVILEGED.
7864            if (locationIsPrivileged(scanFile)) {
7865                updatedPkg.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
7866            } else {
7867                updatedPkg.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
7868            }
7869
7870            if (ps != null && !ps.codePath.equals(scanFile)) {
7871                // The path has changed from what was last scanned...  check the
7872                // version of the new path against what we have stored to determine
7873                // what to do.
7874                if (DEBUG_INSTALL) Slog.d(TAG, "Path changing from " + ps.codePath);
7875                if (pkg.mVersionCode <= ps.versionCode) {
7876                    // The system package has been updated and the code path does not match
7877                    // Ignore entry. Skip it.
7878                    if (DEBUG_INSTALL) Slog.i(TAG, "Package " + ps.name + " at " + scanFile
7879                            + " ignored: updated version " + ps.versionCode
7880                            + " better than this " + pkg.mVersionCode);
7881                    if (!updatedPkg.codePath.equals(scanFile)) {
7882                        Slog.w(PackageManagerService.TAG, "Code path for hidden system pkg "
7883                                + ps.name + " changing from " + updatedPkg.codePathString
7884                                + " to " + scanFile);
7885                        updatedPkg.codePath = scanFile;
7886                        updatedPkg.codePathString = scanFile.toString();
7887                        updatedPkg.resourcePath = scanFile;
7888                        updatedPkg.resourcePathString = scanFile.toString();
7889                    }
7890                    updatedPkg.pkg = pkg;
7891                    updatedPkg.versionCode = pkg.mVersionCode;
7892
7893                    // Update the disabled system child packages to point to the package too.
7894                    final int childCount = updatedPkg.childPackageNames != null
7895                            ? updatedPkg.childPackageNames.size() : 0;
7896                    for (int i = 0; i < childCount; i++) {
7897                        String childPackageName = updatedPkg.childPackageNames.get(i);
7898                        PackageSetting updatedChildPkg = mSettings.getDisabledSystemPkgLPr(
7899                                childPackageName);
7900                        if (updatedChildPkg != null) {
7901                            updatedChildPkg.pkg = pkg;
7902                            updatedChildPkg.versionCode = pkg.mVersionCode;
7903                        }
7904                    }
7905
7906                    throw new PackageManagerException(Log.WARN, "Package " + ps.name + " at "
7907                            + scanFile + " ignored: updated version " + ps.versionCode
7908                            + " better than this " + pkg.mVersionCode);
7909                } else {
7910                    // The current app on the system partition is better than
7911                    // what we have updated to on the data partition; switch
7912                    // back to the system partition version.
7913                    // At this point, its safely assumed that package installation for
7914                    // apps in system partition will go through. If not there won't be a working
7915                    // version of the app
7916                    // writer
7917                    synchronized (mPackages) {
7918                        // Just remove the loaded entries from package lists.
7919                        mPackages.remove(ps.name);
7920                    }
7921
7922                    logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile
7923                            + " reverting from " + ps.codePathString
7924                            + ": new version " + pkg.mVersionCode
7925                            + " better than installed " + ps.versionCode);
7926
7927                    InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
7928                            ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
7929                    synchronized (mInstallLock) {
7930                        args.cleanUpResourcesLI();
7931                    }
7932                    synchronized (mPackages) {
7933                        mSettings.enableSystemPackageLPw(ps.name);
7934                    }
7935                    updatedPkgBetter = true;
7936                }
7937            }
7938        }
7939
7940        if (updatedPkg != null) {
7941            // An updated system app will not have the PARSE_IS_SYSTEM flag set
7942            // initially
7943            policyFlags |= PackageParser.PARSE_IS_SYSTEM;
7944
7945            // An updated privileged app will not have the PARSE_IS_PRIVILEGED
7946            // flag set initially
7947            if ((updatedPkg.pkgPrivateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0) {
7948                policyFlags |= PackageParser.PARSE_IS_PRIVILEGED;
7949            }
7950        }
7951
7952        // Verify certificates against what was last scanned
7953        collectCertificatesLI(ps, pkg, scanFile, policyFlags);
7954
7955        /*
7956         * A new system app appeared, but we already had a non-system one of the
7957         * same name installed earlier.
7958         */
7959        boolean shouldHideSystemApp = false;
7960        if (updatedPkg == null && ps != null
7961                && (policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0 && !isSystemApp(ps)) {
7962            /*
7963             * Check to make sure the signatures match first. If they don't,
7964             * wipe the installed application and its data.
7965             */
7966            if (compareSignatures(ps.signatures.mSignatures, pkg.mSignatures)
7967                    != PackageManager.SIGNATURE_MATCH) {
7968                logCriticalInfo(Log.WARN, "Package " + ps.name + " appeared on system, but"
7969                        + " signatures don't match existing userdata copy; removing");
7970                try (PackageFreezer freezer = freezePackage(pkg.packageName,
7971                        "scanPackageInternalLI")) {
7972                    deletePackageLIF(pkg.packageName, null, true, null, 0, null, false, null);
7973                }
7974                ps = null;
7975            } else {
7976                /*
7977                 * If the newly-added system app is an older version than the
7978                 * already installed version, hide it. It will be scanned later
7979                 * and re-added like an update.
7980                 */
7981                if (pkg.mVersionCode <= ps.versionCode) {
7982                    shouldHideSystemApp = true;
7983                    logCriticalInfo(Log.INFO, "Package " + ps.name + " appeared at " + scanFile
7984                            + " but new version " + pkg.mVersionCode + " better than installed "
7985                            + ps.versionCode + "; hiding system");
7986                } else {
7987                    /*
7988                     * The newly found system app is a newer version that the
7989                     * one previously installed. Simply remove the
7990                     * already-installed application and replace it with our own
7991                     * while keeping the application data.
7992                     */
7993                    logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile
7994                            + " reverting from " + ps.codePathString + ": new version "
7995                            + pkg.mVersionCode + " better than installed " + ps.versionCode);
7996                    InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
7997                            ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
7998                    synchronized (mInstallLock) {
7999                        args.cleanUpResourcesLI();
8000                    }
8001                }
8002            }
8003        }
8004
8005        // The apk is forward locked (not public) if its code and resources
8006        // are kept in different files. (except for app in either system or
8007        // vendor path).
8008        // TODO grab this value from PackageSettings
8009        if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
8010            if (ps != null && !ps.codePath.equals(ps.resourcePath)) {
8011                policyFlags |= PackageParser.PARSE_FORWARD_LOCK;
8012            }
8013        }
8014
8015        // TODO: extend to support forward-locked splits
8016        String resourcePath = null;
8017        String baseResourcePath = null;
8018        if ((policyFlags & PackageParser.PARSE_FORWARD_LOCK) != 0 && !updatedPkgBetter) {
8019            if (ps != null && ps.resourcePathString != null) {
8020                resourcePath = ps.resourcePathString;
8021                baseResourcePath = ps.resourcePathString;
8022            } else {
8023                // Should not happen at all. Just log an error.
8024                Slog.e(TAG, "Resource path not set for package " + pkg.packageName);
8025            }
8026        } else {
8027            resourcePath = pkg.codePath;
8028            baseResourcePath = pkg.baseCodePath;
8029        }
8030
8031        // Set application objects path explicitly.
8032        pkg.setApplicationVolumeUuid(pkg.volumeUuid);
8033        pkg.setApplicationInfoCodePath(pkg.codePath);
8034        pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
8035        pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
8036        pkg.setApplicationInfoResourcePath(resourcePath);
8037        pkg.setApplicationInfoBaseResourcePath(baseResourcePath);
8038        pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
8039
8040        final int userId = ((user == null) ? 0 : user.getIdentifier());
8041        if (ps != null && ps.getInstantApp(userId)) {
8042            scanFlags |= SCAN_AS_INSTANT_APP;
8043        }
8044
8045        // Note that we invoke the following method only if we are about to unpack an application
8046        PackageParser.Package scannedPkg = scanPackageLI(pkg, policyFlags, scanFlags
8047                | SCAN_UPDATE_SIGNATURE, currentTime, user);
8048
8049        /*
8050         * If the system app should be overridden by a previously installed
8051         * data, hide the system app now and let the /data/app scan pick it up
8052         * again.
8053         */
8054        if (shouldHideSystemApp) {
8055            synchronized (mPackages) {
8056                mSettings.disableSystemPackageLPw(pkg.packageName, true);
8057            }
8058        }
8059
8060        return scannedPkg;
8061    }
8062
8063    private void renameStaticSharedLibraryPackage(PackageParser.Package pkg) {
8064        // Derive the new package synthetic package name
8065        pkg.setPackageName(pkg.packageName + STATIC_SHARED_LIB_DELIMITER
8066                + pkg.staticSharedLibVersion);
8067    }
8068
8069    private static String fixProcessName(String defProcessName,
8070            String processName) {
8071        if (processName == null) {
8072            return defProcessName;
8073        }
8074        return processName;
8075    }
8076
8077    private void verifySignaturesLP(PackageSetting pkgSetting, PackageParser.Package pkg)
8078            throws PackageManagerException {
8079        if (pkgSetting.signatures.mSignatures != null) {
8080            // Already existing package. Make sure signatures match
8081            boolean match = compareSignatures(pkgSetting.signatures.mSignatures, pkg.mSignatures)
8082                    == PackageManager.SIGNATURE_MATCH;
8083            if (!match) {
8084                match = compareSignaturesCompat(pkgSetting.signatures, pkg)
8085                        == PackageManager.SIGNATURE_MATCH;
8086            }
8087            if (!match) {
8088                match = compareSignaturesRecover(pkgSetting.signatures, pkg)
8089                        == PackageManager.SIGNATURE_MATCH;
8090            }
8091            if (!match) {
8092                throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package "
8093                        + pkg.packageName + " signatures do not match the "
8094                        + "previously installed version; ignoring!");
8095            }
8096        }
8097
8098        // Check for shared user signatures
8099        if (pkgSetting.sharedUser != null && pkgSetting.sharedUser.signatures.mSignatures != null) {
8100            // Already existing package. Make sure signatures match
8101            boolean match = compareSignatures(pkgSetting.sharedUser.signatures.mSignatures,
8102                    pkg.mSignatures) == PackageManager.SIGNATURE_MATCH;
8103            if (!match) {
8104                match = compareSignaturesCompat(pkgSetting.sharedUser.signatures, pkg)
8105                        == PackageManager.SIGNATURE_MATCH;
8106            }
8107            if (!match) {
8108                match = compareSignaturesRecover(pkgSetting.sharedUser.signatures, pkg)
8109                        == PackageManager.SIGNATURE_MATCH;
8110            }
8111            if (!match) {
8112                throw new PackageManagerException(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE,
8113                        "Package " + pkg.packageName
8114                        + " has no signatures that match those in shared user "
8115                        + pkgSetting.sharedUser.name + "; ignoring!");
8116            }
8117        }
8118    }
8119
8120    /**
8121     * Enforces that only the system UID or root's UID can call a method exposed
8122     * via Binder.
8123     *
8124     * @param message used as message if SecurityException is thrown
8125     * @throws SecurityException if the caller is not system or root
8126     */
8127    private static final void enforceSystemOrRoot(String message) {
8128        final int uid = Binder.getCallingUid();
8129        if (uid != Process.SYSTEM_UID && uid != 0) {
8130            throw new SecurityException(message);
8131        }
8132    }
8133
8134    @Override
8135    public void performFstrimIfNeeded() {
8136        enforceSystemOrRoot("Only the system can request fstrim");
8137
8138        // Before everything else, see whether we need to fstrim.
8139        try {
8140            IStorageManager sm = PackageHelper.getStorageManager();
8141            if (sm != null) {
8142                boolean doTrim = false;
8143                final long interval = android.provider.Settings.Global.getLong(
8144                        mContext.getContentResolver(),
8145                        android.provider.Settings.Global.FSTRIM_MANDATORY_INTERVAL,
8146                        DEFAULT_MANDATORY_FSTRIM_INTERVAL);
8147                if (interval > 0) {
8148                    final long timeSinceLast = System.currentTimeMillis() - sm.lastMaintenance();
8149                    if (timeSinceLast > interval) {
8150                        doTrim = true;
8151                        Slog.w(TAG, "No disk maintenance in " + timeSinceLast
8152                                + "; running immediately");
8153                    }
8154                }
8155                if (doTrim) {
8156                    final boolean dexOptDialogShown;
8157                    synchronized (mPackages) {
8158                        dexOptDialogShown = mDexOptDialogShown;
8159                    }
8160                    if (!isFirstBoot() && dexOptDialogShown) {
8161                        try {
8162                            ActivityManager.getService().showBootMessage(
8163                                    mContext.getResources().getString(
8164                                            R.string.android_upgrading_fstrim), true);
8165                        } catch (RemoteException e) {
8166                        }
8167                    }
8168                    sm.runMaintenance();
8169                }
8170            } else {
8171                Slog.e(TAG, "storageManager service unavailable!");
8172            }
8173        } catch (RemoteException e) {
8174            // Can't happen; StorageManagerService is local
8175        }
8176    }
8177
8178    @Override
8179    public void updatePackagesIfNeeded() {
8180        enforceSystemOrRoot("Only the system can request package update");
8181
8182        // We need to re-extract after an OTA.
8183        boolean causeUpgrade = isUpgrade();
8184
8185        // First boot or factory reset.
8186        // Note: we also handle devices that are upgrading to N right now as if it is their
8187        //       first boot, as they do not have profile data.
8188        boolean causeFirstBoot = isFirstBoot() || mIsPreNUpgrade;
8189
8190        // We need to re-extract after a pruned cache, as AoT-ed files will be out of date.
8191        boolean causePrunedCache = VMRuntime.didPruneDalvikCache();
8192
8193        if (!causeUpgrade && !causeFirstBoot && !causePrunedCache) {
8194            return;
8195        }
8196
8197        List<PackageParser.Package> pkgs;
8198        synchronized (mPackages) {
8199            pkgs = PackageManagerServiceUtils.getPackagesForDexopt(mPackages.values(), this);
8200        }
8201
8202        final long startTime = System.nanoTime();
8203        final int[] stats = performDexOptUpgrade(pkgs, mIsPreNUpgrade /* showDialog */,
8204                    getCompilerFilterForReason(causeFirstBoot ? REASON_FIRST_BOOT : REASON_BOOT));
8205
8206        final int elapsedTimeSeconds =
8207                (int) TimeUnit.NANOSECONDS.toSeconds(System.nanoTime() - startTime);
8208
8209        MetricsLogger.histogram(mContext, "opt_dialog_num_dexopted", stats[0]);
8210        MetricsLogger.histogram(mContext, "opt_dialog_num_skipped", stats[1]);
8211        MetricsLogger.histogram(mContext, "opt_dialog_num_failed", stats[2]);
8212        MetricsLogger.histogram(mContext, "opt_dialog_num_total", getOptimizablePackages().size());
8213        MetricsLogger.histogram(mContext, "opt_dialog_time_s", elapsedTimeSeconds);
8214    }
8215
8216    /**
8217     * Performs dexopt on the set of packages in {@code packages} and returns an int array
8218     * containing statistics about the invocation. The array consists of three elements,
8219     * which are (in order) {@code numberOfPackagesOptimized}, {@code numberOfPackagesSkipped}
8220     * and {@code numberOfPackagesFailed}.
8221     */
8222    private int[] performDexOptUpgrade(List<PackageParser.Package> pkgs, boolean showDialog,
8223            String compilerFilter) {
8224
8225        int numberOfPackagesVisited = 0;
8226        int numberOfPackagesOptimized = 0;
8227        int numberOfPackagesSkipped = 0;
8228        int numberOfPackagesFailed = 0;
8229        final int numberOfPackagesToDexopt = pkgs.size();
8230
8231        for (PackageParser.Package pkg : pkgs) {
8232            numberOfPackagesVisited++;
8233
8234            if (!PackageDexOptimizer.canOptimizePackage(pkg)) {
8235                if (DEBUG_DEXOPT) {
8236                    Log.i(TAG, "Skipping update of of non-optimizable app " + pkg.packageName);
8237                }
8238                numberOfPackagesSkipped++;
8239                continue;
8240            }
8241
8242            if (DEBUG_DEXOPT) {
8243                Log.i(TAG, "Updating app " + numberOfPackagesVisited + " of " +
8244                        numberOfPackagesToDexopt + ": " + pkg.packageName);
8245            }
8246
8247            if (showDialog) {
8248                try {
8249                    ActivityManager.getService().showBootMessage(
8250                            mContext.getResources().getString(R.string.android_upgrading_apk,
8251                                    numberOfPackagesVisited, numberOfPackagesToDexopt), true);
8252                } catch (RemoteException e) {
8253                }
8254                synchronized (mPackages) {
8255                    mDexOptDialogShown = true;
8256                }
8257            }
8258
8259            // If the OTA updates a system app which was previously preopted to a non-preopted state
8260            // the app might end up being verified at runtime. That's because by default the apps
8261            // are verify-profile but for preopted apps there's no profile.
8262            // Do a hacky check to ensure that if we have no profiles (a reasonable indication
8263            // that before the OTA the app was preopted) the app gets compiled with a non-profile
8264            // filter (by default interpret-only).
8265            // Note that at this stage unused apps are already filtered.
8266            if (isSystemApp(pkg) &&
8267                    DexFile.isProfileGuidedCompilerFilter(compilerFilter) &&
8268                    !Environment.getReferenceProfile(pkg.packageName).exists()) {
8269                compilerFilter = getNonProfileGuidedCompilerFilter(compilerFilter);
8270            }
8271
8272            // checkProfiles is false to avoid merging profiles during boot which
8273            // might interfere with background compilation (b/28612421).
8274            // Unfortunately this will also means that "pm.dexopt.boot=speed-profile" will
8275            // behave differently than "pm.dexopt.bg-dexopt=speed-profile" but that's a
8276            // trade-off worth doing to save boot time work.
8277            int dexOptStatus = performDexOptTraced(pkg.packageName,
8278                    false /* checkProfiles */,
8279                    compilerFilter,
8280                    false /* force */);
8281            switch (dexOptStatus) {
8282                case PackageDexOptimizer.DEX_OPT_PERFORMED:
8283                    numberOfPackagesOptimized++;
8284                    break;
8285                case PackageDexOptimizer.DEX_OPT_SKIPPED:
8286                    numberOfPackagesSkipped++;
8287                    break;
8288                case PackageDexOptimizer.DEX_OPT_FAILED:
8289                    numberOfPackagesFailed++;
8290                    break;
8291                default:
8292                    Log.e(TAG, "Unexpected dexopt return code " + dexOptStatus);
8293                    break;
8294            }
8295        }
8296
8297        return new int[] { numberOfPackagesOptimized, numberOfPackagesSkipped,
8298                numberOfPackagesFailed };
8299    }
8300
8301    @Override
8302    public void notifyPackageUse(String packageName, int reason) {
8303        synchronized (mPackages) {
8304            PackageParser.Package p = mPackages.get(packageName);
8305            if (p == null) {
8306                return;
8307            }
8308            p.mLastPackageUsageTimeInMills[reason] = System.currentTimeMillis();
8309        }
8310    }
8311
8312    @Override
8313    public void notifyDexLoad(String loadingPackageName, List<String> dexPaths, String loaderIsa) {
8314        int userId = UserHandle.getCallingUserId();
8315        ApplicationInfo ai = getApplicationInfo(loadingPackageName, /*flags*/ 0, userId);
8316        if (ai == null) {
8317            Slog.w(TAG, "Loading a package that does not exist for the calling user. package="
8318                + loadingPackageName + ", user=" + userId);
8319            return;
8320        }
8321        mDexManager.notifyDexLoad(ai, dexPaths, loaderIsa, userId);
8322    }
8323
8324    // TODO: this is not used nor needed. Delete it.
8325    @Override
8326    public boolean performDexOptIfNeeded(String packageName) {
8327        int dexOptStatus = performDexOptTraced(packageName,
8328                false /* checkProfiles */, getFullCompilerFilter(), false /* force */);
8329        return dexOptStatus != PackageDexOptimizer.DEX_OPT_FAILED;
8330    }
8331
8332    @Override
8333    public boolean performDexOpt(String packageName,
8334            boolean checkProfiles, int compileReason, boolean force) {
8335        int dexOptStatus = performDexOptTraced(packageName, checkProfiles,
8336                getCompilerFilterForReason(compileReason), force);
8337        return dexOptStatus != PackageDexOptimizer.DEX_OPT_FAILED;
8338    }
8339
8340    @Override
8341    public boolean performDexOptMode(String packageName,
8342            boolean checkProfiles, String targetCompilerFilter, boolean force) {
8343        int dexOptStatus = performDexOptTraced(packageName, checkProfiles,
8344                targetCompilerFilter, force);
8345        return dexOptStatus != PackageDexOptimizer.DEX_OPT_FAILED;
8346    }
8347
8348    private int performDexOptTraced(String packageName,
8349                boolean checkProfiles, String targetCompilerFilter, boolean force) {
8350        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt");
8351        try {
8352            return performDexOptInternal(packageName, checkProfiles,
8353                    targetCompilerFilter, force);
8354        } finally {
8355            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
8356        }
8357    }
8358
8359    // Run dexopt on a given package. Returns true if dexopt did not fail, i.e.
8360    // if the package can now be considered up to date for the given filter.
8361    private int performDexOptInternal(String packageName,
8362                boolean checkProfiles, String targetCompilerFilter, boolean force) {
8363        PackageParser.Package p;
8364        synchronized (mPackages) {
8365            p = mPackages.get(packageName);
8366            if (p == null) {
8367                // Package could not be found. Report failure.
8368                return PackageDexOptimizer.DEX_OPT_FAILED;
8369            }
8370            mPackageUsage.maybeWriteAsync(mPackages);
8371            mCompilerStats.maybeWriteAsync();
8372        }
8373        long callingId = Binder.clearCallingIdentity();
8374        try {
8375            synchronized (mInstallLock) {
8376                return performDexOptInternalWithDependenciesLI(p, checkProfiles,
8377                        targetCompilerFilter, force);
8378            }
8379        } finally {
8380            Binder.restoreCallingIdentity(callingId);
8381        }
8382    }
8383
8384    public ArraySet<String> getOptimizablePackages() {
8385        ArraySet<String> pkgs = new ArraySet<String>();
8386        synchronized (mPackages) {
8387            for (PackageParser.Package p : mPackages.values()) {
8388                if (PackageDexOptimizer.canOptimizePackage(p)) {
8389                    pkgs.add(p.packageName);
8390                }
8391            }
8392        }
8393        return pkgs;
8394    }
8395
8396    private int performDexOptInternalWithDependenciesLI(PackageParser.Package p,
8397            boolean checkProfiles, String targetCompilerFilter,
8398            boolean force) {
8399        // Select the dex optimizer based on the force parameter.
8400        // Note: The force option is rarely used (cmdline input for testing, mostly), so it's OK to
8401        //       allocate an object here.
8402        PackageDexOptimizer pdo = force
8403                ? new PackageDexOptimizer.ForcedUpdatePackageDexOptimizer(mPackageDexOptimizer)
8404                : mPackageDexOptimizer;
8405
8406        // Optimize all dependencies first. Note: we ignore the return value and march on
8407        // on errors.
8408        Collection<PackageParser.Package> deps = findSharedNonSystemLibraries(p);
8409        final String[] instructionSets = getAppDexInstructionSets(p.applicationInfo);
8410        if (!deps.isEmpty()) {
8411            for (PackageParser.Package depPackage : deps) {
8412                // TODO: Analyze and investigate if we (should) profile libraries.
8413                // Currently this will do a full compilation of the library by default.
8414                pdo.performDexOpt(depPackage, null /* sharedLibraries */, instructionSets,
8415                        false /* checkProfiles */,
8416                        getCompilerFilterForReason(REASON_NON_SYSTEM_LIBRARY),
8417                        getOrCreateCompilerPackageStats(depPackage));
8418            }
8419        }
8420        return pdo.performDexOpt(p, p.usesLibraryFiles, instructionSets, checkProfiles,
8421                targetCompilerFilter, getOrCreateCompilerPackageStats(p));
8422    }
8423
8424    // Performs dexopt on the used secondary dex files belonging to the given package.
8425    // Returns true if all dex files were process successfully (which could mean either dexopt or
8426    // skip). Returns false if any of the files caused errors.
8427    @Override
8428    public boolean performDexOptSecondary(String packageName, String compilerFilter,
8429            boolean force) {
8430        return mDexManager.dexoptSecondaryDex(packageName, compilerFilter, force);
8431    }
8432
8433    /**
8434     * Reconcile the information we have about the secondary dex files belonging to
8435     * {@code packagName} and the actual dex files. For all dex files that were
8436     * deleted, update the internal records and delete the generated oat files.
8437     */
8438    @Override
8439    public void reconcileSecondaryDexFiles(String packageName) {
8440        mDexManager.reconcileSecondaryDexFiles(packageName);
8441    }
8442
8443    // TODO(calin): this is only needed for BackgroundDexOptService. Find a cleaner way to inject
8444    // a reference there.
8445    /*package*/ DexManager getDexManager() {
8446        return mDexManager;
8447    }
8448
8449    /**
8450     * Execute the background dexopt job immediately.
8451     */
8452    @Override
8453    public boolean runBackgroundDexoptJob() {
8454        return BackgroundDexOptService.runIdleOptimizationsNow(this, mContext);
8455    }
8456
8457    List<PackageParser.Package> findSharedNonSystemLibraries(PackageParser.Package p) {
8458        if (p.usesLibraries != null || p.usesOptionalLibraries != null
8459                || p.usesStaticLibraries != null) {
8460            ArrayList<PackageParser.Package> retValue = new ArrayList<>();
8461            Set<String> collectedNames = new HashSet<>();
8462            findSharedNonSystemLibrariesRecursive(p, retValue, collectedNames);
8463
8464            retValue.remove(p);
8465
8466            return retValue;
8467        } else {
8468            return Collections.emptyList();
8469        }
8470    }
8471
8472    private void findSharedNonSystemLibrariesRecursive(PackageParser.Package p,
8473            ArrayList<PackageParser.Package> collected, Set<String> collectedNames) {
8474        if (!collectedNames.contains(p.packageName)) {
8475            collectedNames.add(p.packageName);
8476            collected.add(p);
8477
8478            if (p.usesLibraries != null) {
8479                findSharedNonSystemLibrariesRecursive(p.usesLibraries,
8480                        null, collected, collectedNames);
8481            }
8482            if (p.usesOptionalLibraries != null) {
8483                findSharedNonSystemLibrariesRecursive(p.usesOptionalLibraries,
8484                        null, collected, collectedNames);
8485            }
8486            if (p.usesStaticLibraries != null) {
8487                findSharedNonSystemLibrariesRecursive(p.usesStaticLibraries,
8488                        p.usesStaticLibrariesVersions, collected, collectedNames);
8489            }
8490        }
8491    }
8492
8493    private void findSharedNonSystemLibrariesRecursive(ArrayList<String> libs, int[] versions,
8494            ArrayList<PackageParser.Package> collected, Set<String> collectedNames) {
8495        final int libNameCount = libs.size();
8496        for (int i = 0; i < libNameCount; i++) {
8497            String libName = libs.get(i);
8498            int version = (versions != null && versions.length == libNameCount)
8499                    ? versions[i] : PackageManager.VERSION_CODE_HIGHEST;
8500            PackageParser.Package libPkg = findSharedNonSystemLibrary(libName, version);
8501            if (libPkg != null) {
8502                findSharedNonSystemLibrariesRecursive(libPkg, collected, collectedNames);
8503            }
8504        }
8505    }
8506
8507    private PackageParser.Package findSharedNonSystemLibrary(String name, int version) {
8508        synchronized (mPackages) {
8509            SharedLibraryEntry libEntry = getSharedLibraryEntryLPr(name, version);
8510            if (libEntry != null) {
8511                return mPackages.get(libEntry.apk);
8512            }
8513            return null;
8514        }
8515    }
8516
8517    private SharedLibraryEntry getSharedLibraryEntryLPr(String name, int version) {
8518        SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(name);
8519        if (versionedLib == null) {
8520            return null;
8521        }
8522        return versionedLib.get(version);
8523    }
8524
8525    private SharedLibraryEntry getLatestSharedLibraVersionLPr(PackageParser.Package pkg) {
8526        SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(
8527                pkg.staticSharedLibName);
8528        if (versionedLib == null) {
8529            return null;
8530        }
8531        int previousLibVersion = -1;
8532        final int versionCount = versionedLib.size();
8533        for (int i = 0; i < versionCount; i++) {
8534            final int libVersion = versionedLib.keyAt(i);
8535            if (libVersion < pkg.staticSharedLibVersion) {
8536                previousLibVersion = Math.max(previousLibVersion, libVersion);
8537            }
8538        }
8539        if (previousLibVersion >= 0) {
8540            return versionedLib.get(previousLibVersion);
8541        }
8542        return null;
8543    }
8544
8545    public void shutdown() {
8546        mPackageUsage.writeNow(mPackages);
8547        mCompilerStats.writeNow();
8548    }
8549
8550    @Override
8551    public void dumpProfiles(String packageName) {
8552        PackageParser.Package pkg;
8553        synchronized (mPackages) {
8554            pkg = mPackages.get(packageName);
8555            if (pkg == null) {
8556                throw new IllegalArgumentException("Unknown package: " + packageName);
8557            }
8558        }
8559        /* Only the shell, root, or the app user should be able to dump profiles. */
8560        int callingUid = Binder.getCallingUid();
8561        if (callingUid != Process.SHELL_UID &&
8562            callingUid != Process.ROOT_UID &&
8563            callingUid != pkg.applicationInfo.uid) {
8564            throw new SecurityException("dumpProfiles");
8565        }
8566
8567        synchronized (mInstallLock) {
8568            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dump profiles");
8569            final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid);
8570            try {
8571                List<String> allCodePaths = pkg.getAllCodePathsExcludingResourceOnly();
8572                String codePaths = TextUtils.join(";", allCodePaths);
8573                mInstaller.dumpProfiles(sharedGid, packageName, codePaths);
8574            } catch (InstallerException e) {
8575                Slog.w(TAG, "Failed to dump profiles", e);
8576            }
8577            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
8578        }
8579    }
8580
8581    @Override
8582    public void forceDexOpt(String packageName) {
8583        enforceSystemOrRoot("forceDexOpt");
8584
8585        PackageParser.Package pkg;
8586        synchronized (mPackages) {
8587            pkg = mPackages.get(packageName);
8588            if (pkg == null) {
8589                throw new IllegalArgumentException("Unknown package: " + packageName);
8590            }
8591        }
8592
8593        synchronized (mInstallLock) {
8594            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt");
8595
8596            // Whoever is calling forceDexOpt wants a fully compiled package.
8597            // Don't use profiles since that may cause compilation to be skipped.
8598            final int res = performDexOptInternalWithDependenciesLI(pkg,
8599                    false /* checkProfiles */, getCompilerFilterForReason(REASON_FORCED_DEXOPT),
8600                    true /* force */);
8601
8602            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
8603            if (res != PackageDexOptimizer.DEX_OPT_PERFORMED) {
8604                throw new IllegalStateException("Failed to dexopt: " + res);
8605            }
8606        }
8607    }
8608
8609    private boolean verifyPackageUpdateLPr(PackageSetting oldPkg, PackageParser.Package newPkg) {
8610        if ((oldPkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) {
8611            Slog.w(TAG, "Unable to update from " + oldPkg.name
8612                    + " to " + newPkg.packageName
8613                    + ": old package not in system partition");
8614            return false;
8615        } else if (mPackages.get(oldPkg.name) != null) {
8616            Slog.w(TAG, "Unable to update from " + oldPkg.name
8617                    + " to " + newPkg.packageName
8618                    + ": old package still exists");
8619            return false;
8620        }
8621        return true;
8622    }
8623
8624    void removeCodePathLI(File codePath) {
8625        if (codePath.isDirectory()) {
8626            try {
8627                mInstaller.rmPackageDir(codePath.getAbsolutePath());
8628            } catch (InstallerException e) {
8629                Slog.w(TAG, "Failed to remove code path", e);
8630            }
8631        } else {
8632            codePath.delete();
8633        }
8634    }
8635
8636    private int[] resolveUserIds(int userId) {
8637        return (userId == UserHandle.USER_ALL) ? sUserManager.getUserIds() : new int[] { userId };
8638    }
8639
8640    private void clearAppDataLIF(PackageParser.Package pkg, int userId, int flags) {
8641        if (pkg == null) {
8642            Slog.wtf(TAG, "Package was null!", new Throwable());
8643            return;
8644        }
8645        clearAppDataLeafLIF(pkg, userId, flags);
8646        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
8647        for (int i = 0; i < childCount; i++) {
8648            clearAppDataLeafLIF(pkg.childPackages.get(i), userId, flags);
8649        }
8650    }
8651
8652    private void clearAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) {
8653        final PackageSetting ps;
8654        synchronized (mPackages) {
8655            ps = mSettings.mPackages.get(pkg.packageName);
8656        }
8657        for (int realUserId : resolveUserIds(userId)) {
8658            final long ceDataInode = (ps != null) ? ps.getCeDataInode(realUserId) : 0;
8659            try {
8660                mInstaller.clearAppData(pkg.volumeUuid, pkg.packageName, realUserId, flags,
8661                        ceDataInode);
8662            } catch (InstallerException e) {
8663                Slog.w(TAG, String.valueOf(e));
8664            }
8665        }
8666    }
8667
8668    private void destroyAppDataLIF(PackageParser.Package pkg, int userId, int flags) {
8669        if (pkg == null) {
8670            Slog.wtf(TAG, "Package was null!", new Throwable());
8671            return;
8672        }
8673        destroyAppDataLeafLIF(pkg, userId, flags);
8674        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
8675        for (int i = 0; i < childCount; i++) {
8676            destroyAppDataLeafLIF(pkg.childPackages.get(i), userId, flags);
8677        }
8678    }
8679
8680    private void destroyAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) {
8681        final PackageSetting ps;
8682        synchronized (mPackages) {
8683            ps = mSettings.mPackages.get(pkg.packageName);
8684        }
8685        for (int realUserId : resolveUserIds(userId)) {
8686            final long ceDataInode = (ps != null) ? ps.getCeDataInode(realUserId) : 0;
8687            try {
8688                mInstaller.destroyAppData(pkg.volumeUuid, pkg.packageName, realUserId, flags,
8689                        ceDataInode);
8690            } catch (InstallerException e) {
8691                Slog.w(TAG, String.valueOf(e));
8692            }
8693        }
8694    }
8695
8696    private void destroyAppProfilesLIF(PackageParser.Package pkg, int userId) {
8697        if (pkg == null) {
8698            Slog.wtf(TAG, "Package was null!", new Throwable());
8699            return;
8700        }
8701        destroyAppProfilesLeafLIF(pkg);
8702        destroyAppReferenceProfileLeafLIF(pkg, userId, true /* removeBaseMarker */);
8703        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
8704        for (int i = 0; i < childCount; i++) {
8705            destroyAppProfilesLeafLIF(pkg.childPackages.get(i));
8706            destroyAppReferenceProfileLeafLIF(pkg.childPackages.get(i), userId,
8707                    true /* removeBaseMarker */);
8708        }
8709    }
8710
8711    private void destroyAppReferenceProfileLeafLIF(PackageParser.Package pkg, int userId,
8712            boolean removeBaseMarker) {
8713        if (pkg.isForwardLocked()) {
8714            return;
8715        }
8716
8717        for (String path : pkg.getAllCodePathsExcludingResourceOnly()) {
8718            try {
8719                path = PackageManagerServiceUtils.realpath(new File(path));
8720            } catch (IOException e) {
8721                // TODO: Should we return early here ?
8722                Slog.w(TAG, "Failed to get canonical path", e);
8723                continue;
8724            }
8725
8726            final String useMarker = path.replace('/', '@');
8727            for (int realUserId : resolveUserIds(userId)) {
8728                File profileDir = Environment.getDataProfilesDeForeignDexDirectory(realUserId);
8729                if (removeBaseMarker) {
8730                    File foreignUseMark = new File(profileDir, useMarker);
8731                    if (foreignUseMark.exists()) {
8732                        if (!foreignUseMark.delete()) {
8733                            Slog.w(TAG, "Unable to delete foreign user mark for package: "
8734                                    + pkg.packageName);
8735                        }
8736                    }
8737                }
8738
8739                File[] markers = profileDir.listFiles();
8740                if (markers != null) {
8741                    final String searchString = "@" + pkg.packageName + "@";
8742                    // We also delete all markers that contain the package name we're
8743                    // uninstalling. These are associated with secondary dex-files belonging
8744                    // to the package. Reconstructing the path of these dex files is messy
8745                    // in general.
8746                    for (File marker : markers) {
8747                        if (marker.getName().indexOf(searchString) > 0) {
8748                            if (!marker.delete()) {
8749                                Slog.w(TAG, "Unable to delete foreign user mark for package: "
8750                                    + pkg.packageName);
8751                            }
8752                        }
8753                    }
8754                }
8755            }
8756        }
8757    }
8758
8759    private void destroyAppProfilesLeafLIF(PackageParser.Package pkg) {
8760        try {
8761            mInstaller.destroyAppProfiles(pkg.packageName);
8762        } catch (InstallerException e) {
8763            Slog.w(TAG, String.valueOf(e));
8764        }
8765    }
8766
8767    private void clearAppProfilesLIF(PackageParser.Package pkg, int userId) {
8768        if (pkg == null) {
8769            Slog.wtf(TAG, "Package was null!", new Throwable());
8770            return;
8771        }
8772        clearAppProfilesLeafLIF(pkg);
8773        // We don't remove the base foreign use marker when clearing profiles because
8774        // we will rename it when the app is updated. Unlike the actual profile contents,
8775        // the foreign use marker is good across installs.
8776        destroyAppReferenceProfileLeafLIF(pkg, userId, false /* removeBaseMarker */);
8777        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
8778        for (int i = 0; i < childCount; i++) {
8779            clearAppProfilesLeafLIF(pkg.childPackages.get(i));
8780        }
8781    }
8782
8783    private void clearAppProfilesLeafLIF(PackageParser.Package pkg) {
8784        try {
8785            mInstaller.clearAppProfiles(pkg.packageName);
8786        } catch (InstallerException e) {
8787            Slog.w(TAG, String.valueOf(e));
8788        }
8789    }
8790
8791    private void setInstallAndUpdateTime(PackageParser.Package pkg, long firstInstallTime,
8792            long lastUpdateTime) {
8793        // Set parent install/update time
8794        PackageSetting ps = (PackageSetting) pkg.mExtras;
8795        if (ps != null) {
8796            ps.firstInstallTime = firstInstallTime;
8797            ps.lastUpdateTime = lastUpdateTime;
8798        }
8799        // Set children install/update time
8800        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
8801        for (int i = 0; i < childCount; i++) {
8802            PackageParser.Package childPkg = pkg.childPackages.get(i);
8803            ps = (PackageSetting) childPkg.mExtras;
8804            if (ps != null) {
8805                ps.firstInstallTime = firstInstallTime;
8806                ps.lastUpdateTime = lastUpdateTime;
8807            }
8808        }
8809    }
8810
8811    private void addSharedLibraryLPr(ArraySet<String> usesLibraryFiles, SharedLibraryEntry file,
8812            PackageParser.Package changingLib) {
8813        if (file.path != null) {
8814            usesLibraryFiles.add(file.path);
8815            return;
8816        }
8817        PackageParser.Package p = mPackages.get(file.apk);
8818        if (changingLib != null && changingLib.packageName.equals(file.apk)) {
8819            // If we are doing this while in the middle of updating a library apk,
8820            // then we need to make sure to use that new apk for determining the
8821            // dependencies here.  (We haven't yet finished committing the new apk
8822            // to the package manager state.)
8823            if (p == null || p.packageName.equals(changingLib.packageName)) {
8824                p = changingLib;
8825            }
8826        }
8827        if (p != null) {
8828            usesLibraryFiles.addAll(p.getAllCodePaths());
8829        }
8830    }
8831
8832    private void updateSharedLibrariesLPr(PackageParser.Package pkg,
8833            PackageParser.Package changingLib) throws PackageManagerException {
8834        if (pkg == null) {
8835            return;
8836        }
8837        ArraySet<String> usesLibraryFiles = null;
8838        if (pkg.usesLibraries != null) {
8839            usesLibraryFiles = addSharedLibrariesLPw(pkg.usesLibraries,
8840                    null, null, pkg.packageName, changingLib, true, null);
8841        }
8842        if (pkg.usesStaticLibraries != null) {
8843            usesLibraryFiles = addSharedLibrariesLPw(pkg.usesStaticLibraries,
8844                    pkg.usesStaticLibrariesVersions, pkg.usesStaticLibrariesCertDigests,
8845                    pkg.packageName, changingLib, true, usesLibraryFiles);
8846        }
8847        if (pkg.usesOptionalLibraries != null) {
8848            usesLibraryFiles = addSharedLibrariesLPw(pkg.usesOptionalLibraries,
8849                    null, null, pkg.packageName, changingLib, false, usesLibraryFiles);
8850        }
8851        if (!ArrayUtils.isEmpty(usesLibraryFiles)) {
8852            pkg.usesLibraryFiles = usesLibraryFiles.toArray(new String[usesLibraryFiles.size()]);
8853        } else {
8854            pkg.usesLibraryFiles = null;
8855        }
8856    }
8857
8858    private ArraySet<String> addSharedLibrariesLPw(@NonNull List<String> requestedLibraries,
8859            @Nullable int[] requiredVersions, @Nullable String[] requiredCertDigests,
8860            @NonNull String packageName, @Nullable PackageParser.Package changingLib,
8861            boolean required, @Nullable ArraySet<String> outUsedLibraries)
8862            throws PackageManagerException {
8863        final int libCount = requestedLibraries.size();
8864        for (int i = 0; i < libCount; i++) {
8865            final String libName = requestedLibraries.get(i);
8866            final int libVersion = requiredVersions != null ? requiredVersions[i]
8867                    : SharedLibraryInfo.VERSION_UNDEFINED;
8868            final SharedLibraryEntry libEntry = getSharedLibraryEntryLPr(libName, libVersion);
8869            if (libEntry == null) {
8870                if (required) {
8871                    throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY,
8872                            "Package " + packageName + " requires unavailable shared library "
8873                                    + libName + "; failing!");
8874                } else {
8875                    Slog.w(TAG, "Package " + packageName
8876                            + " desires unavailable shared library "
8877                            + libName + "; ignoring!");
8878                }
8879            } else {
8880                if (requiredVersions != null && requiredCertDigests != null) {
8881                    if (libEntry.info.getVersion() != requiredVersions[i]) {
8882                        throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY,
8883                            "Package " + packageName + " requires unavailable static shared"
8884                                    + " library " + libName + " version "
8885                                    + libEntry.info.getVersion() + "; failing!");
8886                    }
8887
8888                    PackageParser.Package libPkg = mPackages.get(libEntry.apk);
8889                    if (libPkg == null) {
8890                        throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY,
8891                                "Package " + packageName + " requires unavailable static shared"
8892                                        + " library; failing!");
8893                    }
8894
8895                    String expectedCertDigest = requiredCertDigests[i];
8896                    String libCertDigest = PackageUtils.computeCertSha256Digest(
8897                                libPkg.mSignatures[0]);
8898                    if (!libCertDigest.equalsIgnoreCase(expectedCertDigest)) {
8899                        throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY,
8900                                "Package " + packageName + " requires differently signed" +
8901                                        " static shared library; failing!");
8902                    }
8903                }
8904
8905                if (outUsedLibraries == null) {
8906                    outUsedLibraries = new ArraySet<>();
8907                }
8908                addSharedLibraryLPr(outUsedLibraries, libEntry, changingLib);
8909            }
8910        }
8911        return outUsedLibraries;
8912    }
8913
8914    private static boolean hasString(List<String> list, List<String> which) {
8915        if (list == null) {
8916            return false;
8917        }
8918        for (int i=list.size()-1; i>=0; i--) {
8919            for (int j=which.size()-1; j>=0; j--) {
8920                if (which.get(j).equals(list.get(i))) {
8921                    return true;
8922                }
8923            }
8924        }
8925        return false;
8926    }
8927
8928    private ArrayList<PackageParser.Package> updateAllSharedLibrariesLPw(
8929            PackageParser.Package changingPkg) {
8930        ArrayList<PackageParser.Package> res = null;
8931        for (PackageParser.Package pkg : mPackages.values()) {
8932            if (changingPkg != null
8933                    && !hasString(pkg.usesLibraries, changingPkg.libraryNames)
8934                    && !hasString(pkg.usesOptionalLibraries, changingPkg.libraryNames)
8935                    && !ArrayUtils.contains(pkg.usesStaticLibraries,
8936                            changingPkg.staticSharedLibName)) {
8937                return null;
8938            }
8939            if (res == null) {
8940                res = new ArrayList<>();
8941            }
8942            res.add(pkg);
8943            try {
8944                updateSharedLibrariesLPr(pkg, changingPkg);
8945            } catch (PackageManagerException e) {
8946                // If a system app update or an app and a required lib missing we
8947                // delete the package and for updated system apps keep the data as
8948                // it is better for the user to reinstall than to be in an limbo
8949                // state. Also libs disappearing under an app should never happen
8950                // - just in case.
8951                if (!pkg.isSystemApp() || pkg.isUpdatedSystemApp()) {
8952                    final int flags = pkg.isUpdatedSystemApp()
8953                            ? PackageManager.DELETE_KEEP_DATA : 0;
8954                    deletePackageLIF(pkg.packageName, null, true, sUserManager.getUserIds(),
8955                            flags , null, true, null);
8956                }
8957                Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
8958            }
8959        }
8960        return res;
8961    }
8962
8963    /**
8964     * Derive the value of the {@code cpuAbiOverride} based on the provided
8965     * value and an optional stored value from the package settings.
8966     */
8967    private static String deriveAbiOverride(String abiOverride, PackageSetting settings) {
8968        String cpuAbiOverride = null;
8969
8970        if (NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(abiOverride)) {
8971            cpuAbiOverride = null;
8972        } else if (abiOverride != null) {
8973            cpuAbiOverride = abiOverride;
8974        } else if (settings != null) {
8975            cpuAbiOverride = settings.cpuAbiOverrideString;
8976        }
8977
8978        return cpuAbiOverride;
8979    }
8980
8981    private PackageParser.Package scanPackageTracedLI(PackageParser.Package pkg,
8982            final int policyFlags, int scanFlags, long currentTime, @Nullable UserHandle user)
8983                    throws PackageManagerException {
8984        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage");
8985        // If the package has children and this is the first dive in the function
8986        // we recursively scan the package with the SCAN_CHECK_ONLY flag set to see
8987        // whether all packages (parent and children) would be successfully scanned
8988        // before the actual scan since scanning mutates internal state and we want
8989        // to atomically install the package and its children.
8990        if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
8991            if (pkg.childPackages != null && pkg.childPackages.size() > 0) {
8992                scanFlags |= SCAN_CHECK_ONLY;
8993            }
8994        } else {
8995            scanFlags &= ~SCAN_CHECK_ONLY;
8996        }
8997
8998        final PackageParser.Package scannedPkg;
8999        try {
9000            // Scan the parent
9001            scannedPkg = scanPackageLI(pkg, policyFlags, scanFlags, currentTime, user);
9002            // Scan the children
9003            final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
9004            for (int i = 0; i < childCount; i++) {
9005                PackageParser.Package childPkg = pkg.childPackages.get(i);
9006                scanPackageLI(childPkg, policyFlags,
9007                        scanFlags, currentTime, user);
9008            }
9009        } finally {
9010            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
9011        }
9012
9013        if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
9014            return scanPackageTracedLI(pkg, policyFlags, scanFlags, currentTime, user);
9015        }
9016
9017        return scannedPkg;
9018    }
9019
9020    private PackageParser.Package scanPackageLI(PackageParser.Package pkg, final int policyFlags,
9021            int scanFlags, long currentTime, @Nullable UserHandle user)
9022                    throws PackageManagerException {
9023        boolean success = false;
9024        try {
9025            final PackageParser.Package res = scanPackageDirtyLI(pkg, policyFlags, scanFlags,
9026                    currentTime, user);
9027            success = true;
9028            return res;
9029        } finally {
9030            if (!success && (scanFlags & SCAN_DELETE_DATA_ON_FAILURES) != 0) {
9031                // DELETE_DATA_ON_FAILURES is only used by frozen paths
9032                destroyAppDataLIF(pkg, UserHandle.USER_ALL,
9033                        StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
9034                destroyAppProfilesLIF(pkg, UserHandle.USER_ALL);
9035            }
9036        }
9037    }
9038
9039    /**
9040     * Returns {@code true} if the given file contains code. Otherwise {@code false}.
9041     */
9042    private static boolean apkHasCode(String fileName) {
9043        StrictJarFile jarFile = null;
9044        try {
9045            jarFile = new StrictJarFile(fileName,
9046                    false /*verify*/, false /*signatureSchemeRollbackProtectionsEnforced*/);
9047            return jarFile.findEntry("classes.dex") != null;
9048        } catch (IOException ignore) {
9049        } finally {
9050            try {
9051                if (jarFile != null) {
9052                    jarFile.close();
9053                }
9054            } catch (IOException ignore) {}
9055        }
9056        return false;
9057    }
9058
9059    /**
9060     * Enforces code policy for the package. This ensures that if an APK has
9061     * declared hasCode="true" in its manifest that the APK actually contains
9062     * code.
9063     *
9064     * @throws PackageManagerException If bytecode could not be found when it should exist
9065     */
9066    private static void assertCodePolicy(PackageParser.Package pkg)
9067            throws PackageManagerException {
9068        final boolean shouldHaveCode =
9069                (pkg.applicationInfo.flags & ApplicationInfo.FLAG_HAS_CODE) != 0;
9070        if (shouldHaveCode && !apkHasCode(pkg.baseCodePath)) {
9071            throw new PackageManagerException(INSTALL_FAILED_INVALID_APK,
9072                    "Package " + pkg.baseCodePath + " code is missing");
9073        }
9074
9075        if (!ArrayUtils.isEmpty(pkg.splitCodePaths)) {
9076            for (int i = 0; i < pkg.splitCodePaths.length; i++) {
9077                final boolean splitShouldHaveCode =
9078                        (pkg.splitFlags[i] & ApplicationInfo.FLAG_HAS_CODE) != 0;
9079                if (splitShouldHaveCode && !apkHasCode(pkg.splitCodePaths[i])) {
9080                    throw new PackageManagerException(INSTALL_FAILED_INVALID_APK,
9081                            "Package " + pkg.splitCodePaths[i] + " code is missing");
9082                }
9083            }
9084        }
9085    }
9086
9087    private PackageParser.Package scanPackageDirtyLI(PackageParser.Package pkg,
9088            final int policyFlags, final int scanFlags, long currentTime, @Nullable UserHandle user)
9089                    throws PackageManagerException {
9090        if (DEBUG_PACKAGE_SCANNING) {
9091            if ((policyFlags & PackageParser.PARSE_CHATTY) != 0)
9092                Log.d(TAG, "Scanning package " + pkg.packageName);
9093        }
9094
9095        applyPolicy(pkg, policyFlags);
9096
9097        assertPackageIsValid(pkg, policyFlags, scanFlags);
9098
9099        // Initialize package source and resource directories
9100        final File scanFile = new File(pkg.codePath);
9101        final File destCodeFile = new File(pkg.applicationInfo.getCodePath());
9102        final File destResourceFile = new File(pkg.applicationInfo.getResourcePath());
9103
9104        SharedUserSetting suid = null;
9105        PackageSetting pkgSetting = null;
9106
9107        // Getting the package setting may have a side-effect, so if we
9108        // are only checking if scan would succeed, stash a copy of the
9109        // old setting to restore at the end.
9110        PackageSetting nonMutatedPs = null;
9111
9112        // We keep references to the derived CPU Abis from settings in oder to reuse
9113        // them in the case where we're not upgrading or booting for the first time.
9114        String primaryCpuAbiFromSettings = null;
9115        String secondaryCpuAbiFromSettings = null;
9116
9117        // writer
9118        synchronized (mPackages) {
9119            if (pkg.mSharedUserId != null) {
9120                // SIDE EFFECTS; may potentially allocate a new shared user
9121                suid = mSettings.getSharedUserLPw(
9122                        pkg.mSharedUserId, 0 /*pkgFlags*/, 0 /*pkgPrivateFlags*/, true /*create*/);
9123                if (DEBUG_PACKAGE_SCANNING) {
9124                    if ((policyFlags & PackageParser.PARSE_CHATTY) != 0)
9125                        Log.d(TAG, "Shared UserID " + pkg.mSharedUserId + " (uid=" + suid.userId
9126                                + "): packages=" + suid.packages);
9127                }
9128            }
9129
9130            // Check if we are renaming from an original package name.
9131            PackageSetting origPackage = null;
9132            String realName = null;
9133            if (pkg.mOriginalPackages != null) {
9134                // This package may need to be renamed to a previously
9135                // installed name.  Let's check on that...
9136                final String renamed = mSettings.getRenamedPackageLPr(pkg.mRealPackage);
9137                if (pkg.mOriginalPackages.contains(renamed)) {
9138                    // This package had originally been installed as the
9139                    // original name, and we have already taken care of
9140                    // transitioning to the new one.  Just update the new
9141                    // one to continue using the old name.
9142                    realName = pkg.mRealPackage;
9143                    if (!pkg.packageName.equals(renamed)) {
9144                        // Callers into this function may have already taken
9145                        // care of renaming the package; only do it here if
9146                        // it is not already done.
9147                        pkg.setPackageName(renamed);
9148                    }
9149                } else {
9150                    for (int i=pkg.mOriginalPackages.size()-1; i>=0; i--) {
9151                        if ((origPackage = mSettings.getPackageLPr(
9152                                pkg.mOriginalPackages.get(i))) != null) {
9153                            // We do have the package already installed under its
9154                            // original name...  should we use it?
9155                            if (!verifyPackageUpdateLPr(origPackage, pkg)) {
9156                                // New package is not compatible with original.
9157                                origPackage = null;
9158                                continue;
9159                            } else if (origPackage.sharedUser != null) {
9160                                // Make sure uid is compatible between packages.
9161                                if (!origPackage.sharedUser.name.equals(pkg.mSharedUserId)) {
9162                                    Slog.w(TAG, "Unable to migrate data from " + origPackage.name
9163                                            + " to " + pkg.packageName + ": old uid "
9164                                            + origPackage.sharedUser.name
9165                                            + " differs from " + pkg.mSharedUserId);
9166                                    origPackage = null;
9167                                    continue;
9168                                }
9169                                // TODO: Add case when shared user id is added [b/28144775]
9170                            } else {
9171                                if (DEBUG_UPGRADE) Log.v(TAG, "Renaming new package "
9172                                        + pkg.packageName + " to old name " + origPackage.name);
9173                            }
9174                            break;
9175                        }
9176                    }
9177                }
9178            }
9179
9180            if (mTransferedPackages.contains(pkg.packageName)) {
9181                Slog.w(TAG, "Package " + pkg.packageName
9182                        + " was transferred to another, but its .apk remains");
9183            }
9184
9185            // See comments in nonMutatedPs declaration
9186            if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
9187                PackageSetting foundPs = mSettings.getPackageLPr(pkg.packageName);
9188                if (foundPs != null) {
9189                    nonMutatedPs = new PackageSetting(foundPs);
9190                }
9191            }
9192
9193            if ((scanFlags & SCAN_FIRST_BOOT_OR_UPGRADE) == 0) {
9194                PackageSetting foundPs = mSettings.getPackageLPr(pkg.packageName);
9195                if (foundPs != null) {
9196                    primaryCpuAbiFromSettings = foundPs.primaryCpuAbiString;
9197                    secondaryCpuAbiFromSettings = foundPs.secondaryCpuAbiString;
9198                }
9199            }
9200
9201            pkgSetting = mSettings.getPackageLPr(pkg.packageName);
9202            if (pkgSetting != null && pkgSetting.sharedUser != suid) {
9203                PackageManagerService.reportSettingsProblem(Log.WARN,
9204                        "Package " + pkg.packageName + " shared user changed from "
9205                                + (pkgSetting.sharedUser != null
9206                                        ? pkgSetting.sharedUser.name : "<nothing>")
9207                                + " to "
9208                                + (suid != null ? suid.name : "<nothing>")
9209                                + "; replacing with new");
9210                pkgSetting = null;
9211            }
9212            final PackageSetting oldPkgSetting =
9213                    pkgSetting == null ? null : new PackageSetting(pkgSetting);
9214            final PackageSetting disabledPkgSetting =
9215                    mSettings.getDisabledSystemPkgLPr(pkg.packageName);
9216
9217            String[] usesStaticLibraries = null;
9218            if (pkg.usesStaticLibraries != null) {
9219                usesStaticLibraries = new String[pkg.usesStaticLibraries.size()];
9220                pkg.usesStaticLibraries.toArray(usesStaticLibraries);
9221            }
9222
9223            if (pkgSetting == null) {
9224                final String parentPackageName = (pkg.parentPackage != null)
9225                        ? pkg.parentPackage.packageName : null;
9226                final boolean instantApp = (scanFlags & SCAN_AS_INSTANT_APP) != 0;
9227                // REMOVE SharedUserSetting from method; update in a separate call
9228                pkgSetting = Settings.createNewSetting(pkg.packageName, origPackage,
9229                        disabledPkgSetting, realName, suid, destCodeFile, destResourceFile,
9230                        pkg.applicationInfo.nativeLibraryRootDir, pkg.applicationInfo.primaryCpuAbi,
9231                        pkg.applicationInfo.secondaryCpuAbi, pkg.mVersionCode,
9232                        pkg.applicationInfo.flags, pkg.applicationInfo.privateFlags, user,
9233                        true /*allowInstall*/, instantApp, parentPackageName,
9234                        pkg.getChildPackageNames(), UserManagerService.getInstance(),
9235                        usesStaticLibraries, pkg.usesStaticLibrariesVersions);
9236                // SIDE EFFECTS; updates system state; move elsewhere
9237                if (origPackage != null) {
9238                    mSettings.addRenamedPackageLPw(pkg.packageName, origPackage.name);
9239                }
9240                mSettings.addUserToSettingLPw(pkgSetting);
9241            } else {
9242                // REMOVE SharedUserSetting from method; update in a separate call.
9243                //
9244                // TODO(narayan): This update is bogus. nativeLibraryDir & primaryCpuAbi,
9245                // secondaryCpuAbi are not known at this point so we always update them
9246                // to null here, only to reset them at a later point.
9247                Settings.updatePackageSetting(pkgSetting, disabledPkgSetting, suid, destCodeFile,
9248                        pkg.applicationInfo.nativeLibraryDir, pkg.applicationInfo.primaryCpuAbi,
9249                        pkg.applicationInfo.secondaryCpuAbi, pkg.applicationInfo.flags,
9250                        pkg.applicationInfo.privateFlags, pkg.getChildPackageNames(),
9251                        UserManagerService.getInstance(), usesStaticLibraries,
9252                        pkg.usesStaticLibrariesVersions);
9253            }
9254            // SIDE EFFECTS; persists system state to files on disk; move elsewhere
9255            mSettings.writeUserRestrictionsLPw(pkgSetting, oldPkgSetting);
9256
9257            // SIDE EFFECTS; modifies system state; move elsewhere
9258            if (pkgSetting.origPackage != null) {
9259                // If we are first transitioning from an original package,
9260                // fix up the new package's name now.  We need to do this after
9261                // looking up the package under its new name, so getPackageLP
9262                // can take care of fiddling things correctly.
9263                pkg.setPackageName(origPackage.name);
9264
9265                // File a report about this.
9266                String msg = "New package " + pkgSetting.realName
9267                        + " renamed to replace old package " + pkgSetting.name;
9268                reportSettingsProblem(Log.WARN, msg);
9269
9270                // Make a note of it.
9271                if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
9272                    mTransferedPackages.add(origPackage.name);
9273                }
9274
9275                // No longer need to retain this.
9276                pkgSetting.origPackage = null;
9277            }
9278
9279            // SIDE EFFECTS; modifies system state; move elsewhere
9280            if ((scanFlags & SCAN_CHECK_ONLY) == 0 && realName != null) {
9281                // Make a note of it.
9282                mTransferedPackages.add(pkg.packageName);
9283            }
9284
9285            if (mSettings.isDisabledSystemPackageLPr(pkg.packageName)) {
9286                pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
9287            }
9288
9289            if ((scanFlags & SCAN_BOOTING) == 0
9290                    && (policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
9291                // Check all shared libraries and map to their actual file path.
9292                // We only do this here for apps not on a system dir, because those
9293                // are the only ones that can fail an install due to this.  We
9294                // will take care of the system apps by updating all of their
9295                // library paths after the scan is done. Also during the initial
9296                // scan don't update any libs as we do this wholesale after all
9297                // apps are scanned to avoid dependency based scanning.
9298                updateSharedLibrariesLPr(pkg, null);
9299            }
9300
9301            if (mFoundPolicyFile) {
9302                SELinuxMMAC.assignSeInfoValue(pkg);
9303            }
9304            pkg.applicationInfo.uid = pkgSetting.appId;
9305            pkg.mExtras = pkgSetting;
9306
9307
9308            // Static shared libs have same package with different versions where
9309            // we internally use a synthetic package name to allow multiple versions
9310            // of the same package, therefore we need to compare signatures against
9311            // the package setting for the latest library version.
9312            PackageSetting signatureCheckPs = pkgSetting;
9313            if (pkg.applicationInfo.isStaticSharedLibrary()) {
9314                SharedLibraryEntry libraryEntry = getLatestSharedLibraVersionLPr(pkg);
9315                if (libraryEntry != null) {
9316                    signatureCheckPs = mSettings.getPackageLPr(libraryEntry.apk);
9317                }
9318            }
9319
9320            if (shouldCheckUpgradeKeySetLP(signatureCheckPs, scanFlags)) {
9321                if (checkUpgradeKeySetLP(signatureCheckPs, pkg)) {
9322                    // We just determined the app is signed correctly, so bring
9323                    // over the latest parsed certs.
9324                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
9325                } else {
9326                    if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
9327                        throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
9328                                "Package " + pkg.packageName + " upgrade keys do not match the "
9329                                + "previously installed version");
9330                    } else {
9331                        pkgSetting.signatures.mSignatures = pkg.mSignatures;
9332                        String msg = "System package " + pkg.packageName
9333                                + " signature changed; retaining data.";
9334                        reportSettingsProblem(Log.WARN, msg);
9335                    }
9336                }
9337            } else {
9338                try {
9339                    // SIDE EFFECTS; compareSignaturesCompat() changes KeysetManagerService
9340                    verifySignaturesLP(signatureCheckPs, pkg);
9341                    // We just determined the app is signed correctly, so bring
9342                    // over the latest parsed certs.
9343                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
9344                } catch (PackageManagerException e) {
9345                    if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
9346                        throw e;
9347                    }
9348                    // The signature has changed, but this package is in the system
9349                    // image...  let's recover!
9350                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
9351                    // However...  if this package is part of a shared user, but it
9352                    // doesn't match the signature of the shared user, let's fail.
9353                    // What this means is that you can't change the signatures
9354                    // associated with an overall shared user, which doesn't seem all
9355                    // that unreasonable.
9356                    if (signatureCheckPs.sharedUser != null) {
9357                        if (compareSignatures(signatureCheckPs.sharedUser.signatures.mSignatures,
9358                                pkg.mSignatures) != PackageManager.SIGNATURE_MATCH) {
9359                            throw new PackageManagerException(
9360                                    INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES,
9361                                    "Signature mismatch for shared user: "
9362                                            + pkgSetting.sharedUser);
9363                        }
9364                    }
9365                    // File a report about this.
9366                    String msg = "System package " + pkg.packageName
9367                            + " signature changed; retaining data.";
9368                    reportSettingsProblem(Log.WARN, msg);
9369                }
9370            }
9371
9372            if ((scanFlags & SCAN_CHECK_ONLY) == 0 && pkg.mAdoptPermissions != null) {
9373                // This package wants to adopt ownership of permissions from
9374                // another package.
9375                for (int i = pkg.mAdoptPermissions.size() - 1; i >= 0; i--) {
9376                    final String origName = pkg.mAdoptPermissions.get(i);
9377                    final PackageSetting orig = mSettings.getPackageLPr(origName);
9378                    if (orig != null) {
9379                        if (verifyPackageUpdateLPr(orig, pkg)) {
9380                            Slog.i(TAG, "Adopting permissions from " + origName + " to "
9381                                    + pkg.packageName);
9382                            // SIDE EFFECTS; updates permissions system state; move elsewhere
9383                            mSettings.transferPermissionsLPw(origName, pkg.packageName);
9384                        }
9385                    }
9386                }
9387            }
9388        }
9389
9390        pkg.applicationInfo.processName = fixProcessName(
9391                pkg.applicationInfo.packageName,
9392                pkg.applicationInfo.processName);
9393
9394        if (pkg != mPlatformPackage) {
9395            // Get all of our default paths setup
9396            pkg.applicationInfo.initForUser(UserHandle.USER_SYSTEM);
9397        }
9398
9399        final String cpuAbiOverride = deriveAbiOverride(pkg.cpuAbiOverride, pkgSetting);
9400
9401        if ((scanFlags & SCAN_NEW_INSTALL) == 0) {
9402            if ((scanFlags & SCAN_FIRST_BOOT_OR_UPGRADE) != 0) {
9403                Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "derivePackageAbi");
9404                derivePackageAbi(
9405                        pkg, scanFile, cpuAbiOverride, true /*extractLibs*/, mAppLib32InstallDir);
9406                Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
9407
9408                // Some system apps still use directory structure for native libraries
9409                // in which case we might end up not detecting abi solely based on apk
9410                // structure. Try to detect abi based on directory structure.
9411                if (isSystemApp(pkg) && !pkg.isUpdatedSystemApp() &&
9412                        pkg.applicationInfo.primaryCpuAbi == null) {
9413                    setBundledAppAbisAndRoots(pkg, pkgSetting);
9414                    setNativeLibraryPaths(pkg, mAppLib32InstallDir);
9415                }
9416            } else {
9417                // This is not a first boot or an upgrade, don't bother deriving the
9418                // ABI during the scan. Instead, trust the value that was stored in the
9419                // package setting.
9420                pkg.applicationInfo.primaryCpuAbi = primaryCpuAbiFromSettings;
9421                pkg.applicationInfo.secondaryCpuAbi = secondaryCpuAbiFromSettings;
9422
9423                setNativeLibraryPaths(pkg, mAppLib32InstallDir);
9424
9425                if (DEBUG_ABI_SELECTION) {
9426                    Slog.i(TAG, "Using ABIS and native lib paths from settings : " +
9427                        pkg.packageName + " " + pkg.applicationInfo.primaryCpuAbi + ", " +
9428                        pkg.applicationInfo.secondaryCpuAbi);
9429                }
9430            }
9431        } else {
9432            if ((scanFlags & SCAN_MOVE) != 0) {
9433                // We haven't run dex-opt for this move (since we've moved the compiled output too)
9434                // but we already have this packages package info in the PackageSetting. We just
9435                // use that and derive the native library path based on the new codepath.
9436                pkg.applicationInfo.primaryCpuAbi = pkgSetting.primaryCpuAbiString;
9437                pkg.applicationInfo.secondaryCpuAbi = pkgSetting.secondaryCpuAbiString;
9438            }
9439
9440            // Set native library paths again. For moves, the path will be updated based on the
9441            // ABIs we've determined above. For non-moves, the path will be updated based on the
9442            // ABIs we determined during compilation, but the path will depend on the final
9443            // package path (after the rename away from the stage path).
9444            setNativeLibraryPaths(pkg, mAppLib32InstallDir);
9445        }
9446
9447        // This is a special case for the "system" package, where the ABI is
9448        // dictated by the zygote configuration (and init.rc). We should keep track
9449        // of this ABI so that we can deal with "normal" applications that run under
9450        // the same UID correctly.
9451        if (mPlatformPackage == pkg) {
9452            pkg.applicationInfo.primaryCpuAbi = VMRuntime.getRuntime().is64Bit() ?
9453                    Build.SUPPORTED_64_BIT_ABIS[0] : Build.SUPPORTED_32_BIT_ABIS[0];
9454        }
9455
9456        // If there's a mismatch between the abi-override in the package setting
9457        // and the abiOverride specified for the install. Warn about this because we
9458        // would've already compiled the app without taking the package setting into
9459        // account.
9460        if ((scanFlags & SCAN_NO_DEX) == 0 && (scanFlags & SCAN_NEW_INSTALL) != 0) {
9461            if (cpuAbiOverride == null && pkgSetting.cpuAbiOverrideString != null) {
9462                Slog.w(TAG, "Ignoring persisted ABI override " + cpuAbiOverride +
9463                        " for package " + pkg.packageName);
9464            }
9465        }
9466
9467        pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi;
9468        pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi;
9469        pkgSetting.cpuAbiOverrideString = cpuAbiOverride;
9470
9471        // Copy the derived override back to the parsed package, so that we can
9472        // update the package settings accordingly.
9473        pkg.cpuAbiOverride = cpuAbiOverride;
9474
9475        if (DEBUG_ABI_SELECTION) {
9476            Slog.d(TAG, "Resolved nativeLibraryRoot for " + pkg.applicationInfo.packageName
9477                    + " to root=" + pkg.applicationInfo.nativeLibraryRootDir + ", isa="
9478                    + pkg.applicationInfo.nativeLibraryRootRequiresIsa);
9479        }
9480
9481        // Push the derived path down into PackageSettings so we know what to
9482        // clean up at uninstall time.
9483        pkgSetting.legacyNativeLibraryPathString = pkg.applicationInfo.nativeLibraryRootDir;
9484
9485        if (DEBUG_ABI_SELECTION) {
9486            Log.d(TAG, "Abis for package[" + pkg.packageName + "] are" +
9487                    " primary=" + pkg.applicationInfo.primaryCpuAbi +
9488                    " secondary=" + pkg.applicationInfo.secondaryCpuAbi);
9489        }
9490
9491        // SIDE EFFECTS; removes DEX files from disk; move elsewhere
9492        if ((scanFlags & SCAN_BOOTING) == 0 && pkgSetting.sharedUser != null) {
9493            // We don't do this here during boot because we can do it all
9494            // at once after scanning all existing packages.
9495            //
9496            // We also do this *before* we perform dexopt on this package, so that
9497            // we can avoid redundant dexopts, and also to make sure we've got the
9498            // code and package path correct.
9499            adjustCpuAbisForSharedUserLPw(pkgSetting.sharedUser.packages, pkg);
9500        }
9501
9502        if (mFactoryTest && pkg.requestedPermissions.contains(
9503                android.Manifest.permission.FACTORY_TEST)) {
9504            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_FACTORY_TEST;
9505        }
9506
9507        if (isSystemApp(pkg)) {
9508            pkgSetting.isOrphaned = true;
9509        }
9510
9511        // Take care of first install / last update times.
9512        final long scanFileTime = getLastModifiedTime(pkg, scanFile);
9513        if (currentTime != 0) {
9514            if (pkgSetting.firstInstallTime == 0) {
9515                pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = currentTime;
9516            } else if ((scanFlags & SCAN_UPDATE_TIME) != 0) {
9517                pkgSetting.lastUpdateTime = currentTime;
9518            }
9519        } else if (pkgSetting.firstInstallTime == 0) {
9520            // We need *something*.  Take time time stamp of the file.
9521            pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = scanFileTime;
9522        } else if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0) {
9523            if (scanFileTime != pkgSetting.timeStamp) {
9524                // A package on the system image has changed; consider this
9525                // to be an update.
9526                pkgSetting.lastUpdateTime = scanFileTime;
9527            }
9528        }
9529        pkgSetting.setTimeStamp(scanFileTime);
9530
9531        if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
9532            if (nonMutatedPs != null) {
9533                synchronized (mPackages) {
9534                    mSettings.mPackages.put(nonMutatedPs.name, nonMutatedPs);
9535                }
9536            }
9537        } else {
9538            final int userId = user == null ? 0 : user.getIdentifier();
9539            // Modify state for the given package setting
9540            commitPackageSettings(pkg, pkgSetting, user, scanFlags,
9541                    (policyFlags & PackageParser.PARSE_CHATTY) != 0 /*chatty*/);
9542            if (pkgSetting.getInstantApp(userId)) {
9543                mInstantAppRegistry.addInstantAppLPw(userId, pkgSetting.appId);
9544            }
9545        }
9546        return pkg;
9547    }
9548
9549    /**
9550     * Applies policy to the parsed package based upon the given policy flags.
9551     * Ensures the package is in a good state.
9552     * <p>
9553     * Implementation detail: This method must NOT have any side effect. It would
9554     * ideally be static, but, it requires locks to read system state.
9555     */
9556    private void applyPolicy(PackageParser.Package pkg, int policyFlags) {
9557        if ((policyFlags&PackageParser.PARSE_IS_SYSTEM) != 0) {
9558            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_SYSTEM;
9559            if (pkg.applicationInfo.isDirectBootAware()) {
9560                // we're direct boot aware; set for all components
9561                for (PackageParser.Service s : pkg.services) {
9562                    s.info.encryptionAware = s.info.directBootAware = true;
9563                }
9564                for (PackageParser.Provider p : pkg.providers) {
9565                    p.info.encryptionAware = p.info.directBootAware = true;
9566                }
9567                for (PackageParser.Activity a : pkg.activities) {
9568                    a.info.encryptionAware = a.info.directBootAware = true;
9569                }
9570                for (PackageParser.Activity r : pkg.receivers) {
9571                    r.info.encryptionAware = r.info.directBootAware = true;
9572                }
9573            }
9574        } else {
9575            // Only allow system apps to be flagged as core apps.
9576            pkg.coreApp = false;
9577            // clear flags not applicable to regular apps
9578            pkg.applicationInfo.privateFlags &=
9579                    ~ApplicationInfo.PRIVATE_FLAG_DEFAULT_TO_DEVICE_PROTECTED_STORAGE;
9580            pkg.applicationInfo.privateFlags &=
9581                    ~ApplicationInfo.PRIVATE_FLAG_DIRECT_BOOT_AWARE;
9582        }
9583        pkg.mTrustedOverlay = (policyFlags&PackageParser.PARSE_TRUSTED_OVERLAY) != 0;
9584
9585        if ((policyFlags&PackageParser.PARSE_IS_PRIVILEGED) != 0) {
9586            pkg.applicationInfo.privateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
9587        }
9588
9589        if (!isSystemApp(pkg)) {
9590            // Only system apps can use these features.
9591            pkg.mOriginalPackages = null;
9592            pkg.mRealPackage = null;
9593            pkg.mAdoptPermissions = null;
9594        }
9595    }
9596
9597    /**
9598     * Asserts the parsed package is valid according to the given policy. If the
9599     * package is invalid, for whatever reason, throws {@link PackgeManagerException}.
9600     * <p>
9601     * Implementation detail: This method must NOT have any side effects. It would
9602     * ideally be static, but, it requires locks to read system state.
9603     *
9604     * @throws PackageManagerException If the package fails any of the validation checks
9605     */
9606    private void assertPackageIsValid(PackageParser.Package pkg, int policyFlags, int scanFlags)
9607            throws PackageManagerException {
9608        if ((policyFlags & PackageParser.PARSE_ENFORCE_CODE) != 0) {
9609            assertCodePolicy(pkg);
9610        }
9611
9612        if (pkg.applicationInfo.getCodePath() == null ||
9613                pkg.applicationInfo.getResourcePath() == null) {
9614            // Bail out. The resource and code paths haven't been set.
9615            throw new PackageManagerException(INSTALL_FAILED_INVALID_APK,
9616                    "Code and resource paths haven't been set correctly");
9617        }
9618
9619        // Make sure we're not adding any bogus keyset info
9620        KeySetManagerService ksms = mSettings.mKeySetManagerService;
9621        ksms.assertScannedPackageValid(pkg);
9622
9623        synchronized (mPackages) {
9624            // The special "android" package can only be defined once
9625            if (pkg.packageName.equals("android")) {
9626                if (mAndroidApplication != null) {
9627                    Slog.w(TAG, "*************************************************");
9628                    Slog.w(TAG, "Core android package being redefined.  Skipping.");
9629                    Slog.w(TAG, " codePath=" + pkg.codePath);
9630                    Slog.w(TAG, "*************************************************");
9631                    throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE,
9632                            "Core android package being redefined.  Skipping.");
9633                }
9634            }
9635
9636            // A package name must be unique; don't allow duplicates
9637            if (mPackages.containsKey(pkg.packageName)) {
9638                throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE,
9639                        "Application package " + pkg.packageName
9640                        + " already installed.  Skipping duplicate.");
9641            }
9642
9643            if (pkg.applicationInfo.isStaticSharedLibrary()) {
9644                // Static libs have a synthetic package name containing the version
9645                // but we still want the base name to be unique.
9646                if (mPackages.containsKey(pkg.manifestPackageName)) {
9647                    throw new PackageManagerException(
9648                            "Duplicate static shared lib provider package");
9649                }
9650
9651                // Static shared libraries should have at least O target SDK
9652                if (pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.O) {
9653                    throw new PackageManagerException(
9654                            "Packages declaring static-shared libs must target O SDK or higher");
9655                }
9656
9657                // Package declaring static a shared lib cannot be instant apps
9658                if ((scanFlags & SCAN_AS_INSTANT_APP) != 0) {
9659                    throw new PackageManagerException(
9660                            "Packages declaring static-shared libs cannot be instant apps");
9661                }
9662
9663                // Package declaring static a shared lib cannot be renamed since the package
9664                // name is synthetic and apps can't code around package manager internals.
9665                if (!ArrayUtils.isEmpty(pkg.mOriginalPackages)) {
9666                    throw new PackageManagerException(
9667                            "Packages declaring static-shared libs cannot be renamed");
9668                }
9669
9670                // Package declaring static a shared lib cannot declare child packages
9671                if (!ArrayUtils.isEmpty(pkg.childPackages)) {
9672                    throw new PackageManagerException(
9673                            "Packages declaring static-shared libs cannot have child packages");
9674                }
9675
9676                // Package declaring static a shared lib cannot declare dynamic libs
9677                if (!ArrayUtils.isEmpty(pkg.libraryNames)) {
9678                    throw new PackageManagerException(
9679                            "Packages declaring static-shared libs cannot declare dynamic libs");
9680                }
9681
9682                // Package declaring static a shared lib cannot declare shared users
9683                if (pkg.mSharedUserId != null) {
9684                    throw new PackageManagerException(
9685                            "Packages declaring static-shared libs cannot declare shared users");
9686                }
9687
9688                // Static shared libs cannot declare activities
9689                if (!pkg.activities.isEmpty()) {
9690                    throw new PackageManagerException(
9691                            "Static shared libs cannot declare activities");
9692                }
9693
9694                // Static shared libs cannot declare services
9695                if (!pkg.services.isEmpty()) {
9696                    throw new PackageManagerException(
9697                            "Static shared libs cannot declare services");
9698                }
9699
9700                // Static shared libs cannot declare providers
9701                if (!pkg.providers.isEmpty()) {
9702                    throw new PackageManagerException(
9703                            "Static shared libs cannot declare content providers");
9704                }
9705
9706                // Static shared libs cannot declare receivers
9707                if (!pkg.receivers.isEmpty()) {
9708                    throw new PackageManagerException(
9709                            "Static shared libs cannot declare broadcast receivers");
9710                }
9711
9712                // Static shared libs cannot declare permission groups
9713                if (!pkg.permissionGroups.isEmpty()) {
9714                    throw new PackageManagerException(
9715                            "Static shared libs cannot declare permission groups");
9716                }
9717
9718                // Static shared libs cannot declare permissions
9719                if (!pkg.permissions.isEmpty()) {
9720                    throw new PackageManagerException(
9721                            "Static shared libs cannot declare permissions");
9722                }
9723
9724                // Static shared libs cannot declare protected broadcasts
9725                if (pkg.protectedBroadcasts != null) {
9726                    throw new PackageManagerException(
9727                            "Static shared libs cannot declare protected broadcasts");
9728                }
9729
9730                // Static shared libs cannot be overlay targets
9731                if (pkg.mOverlayTarget != null) {
9732                    throw new PackageManagerException(
9733                            "Static shared libs cannot be overlay targets");
9734                }
9735
9736                // The version codes must be ordered as lib versions
9737                int minVersionCode = Integer.MIN_VALUE;
9738                int maxVersionCode = Integer.MAX_VALUE;
9739
9740                SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(
9741                        pkg.staticSharedLibName);
9742                if (versionedLib != null) {
9743                    final int versionCount = versionedLib.size();
9744                    for (int i = 0; i < versionCount; i++) {
9745                        SharedLibraryInfo libInfo = versionedLib.valueAt(i).info;
9746                        // TODO: We will change version code to long, so in the new API it is long
9747                        final int libVersionCode = (int) libInfo.getDeclaringPackage()
9748                                .getVersionCode();
9749                        if (libInfo.getVersion() <  pkg.staticSharedLibVersion) {
9750                            minVersionCode = Math.max(minVersionCode, libVersionCode + 1);
9751                        } else if (libInfo.getVersion() >  pkg.staticSharedLibVersion) {
9752                            maxVersionCode = Math.min(maxVersionCode, libVersionCode - 1);
9753                        } else {
9754                            minVersionCode = maxVersionCode = libVersionCode;
9755                            break;
9756                        }
9757                    }
9758                }
9759                if (pkg.mVersionCode < minVersionCode || pkg.mVersionCode > maxVersionCode) {
9760                    throw new PackageManagerException("Static shared"
9761                            + " lib version codes must be ordered as lib versions");
9762                }
9763            }
9764
9765            // Only privileged apps and updated privileged apps can add child packages.
9766            if (pkg.childPackages != null && !pkg.childPackages.isEmpty()) {
9767                if ((policyFlags & PARSE_IS_PRIVILEGED) == 0) {
9768                    throw new PackageManagerException("Only privileged apps can add child "
9769                            + "packages. Ignoring package " + pkg.packageName);
9770                }
9771                final int childCount = pkg.childPackages.size();
9772                for (int i = 0; i < childCount; i++) {
9773                    PackageParser.Package childPkg = pkg.childPackages.get(i);
9774                    if (mSettings.hasOtherDisabledSystemPkgWithChildLPr(pkg.packageName,
9775                            childPkg.packageName)) {
9776                        throw new PackageManagerException("Can't override child of "
9777                                + "another disabled app. Ignoring package " + pkg.packageName);
9778                    }
9779                }
9780            }
9781
9782            // If we're only installing presumed-existing packages, require that the
9783            // scanned APK is both already known and at the path previously established
9784            // for it.  Previously unknown packages we pick up normally, but if we have an
9785            // a priori expectation about this package's install presence, enforce it.
9786            // With a singular exception for new system packages. When an OTA contains
9787            // a new system package, we allow the codepath to change from a system location
9788            // to the user-installed location. If we don't allow this change, any newer,
9789            // user-installed version of the application will be ignored.
9790            if ((scanFlags & SCAN_REQUIRE_KNOWN) != 0) {
9791                if (mExpectingBetter.containsKey(pkg.packageName)) {
9792                    logCriticalInfo(Log.WARN,
9793                            "Relax SCAN_REQUIRE_KNOWN requirement for package " + pkg.packageName);
9794                } else {
9795                    PackageSetting known = mSettings.getPackageLPr(pkg.packageName);
9796                    if (known != null) {
9797                        if (DEBUG_PACKAGE_SCANNING) {
9798                            Log.d(TAG, "Examining " + pkg.codePath
9799                                    + " and requiring known paths " + known.codePathString
9800                                    + " & " + known.resourcePathString);
9801                        }
9802                        if (!pkg.applicationInfo.getCodePath().equals(known.codePathString)
9803                                || !pkg.applicationInfo.getResourcePath().equals(
9804                                        known.resourcePathString)) {
9805                            throw new PackageManagerException(INSTALL_FAILED_PACKAGE_CHANGED,
9806                                    "Application package " + pkg.packageName
9807                                    + " found at " + pkg.applicationInfo.getCodePath()
9808                                    + " but expected at " + known.codePathString
9809                                    + "; ignoring.");
9810                        }
9811                    }
9812                }
9813            }
9814
9815            // Verify that this new package doesn't have any content providers
9816            // that conflict with existing packages.  Only do this if the
9817            // package isn't already installed, since we don't want to break
9818            // things that are installed.
9819            if ((scanFlags & SCAN_NEW_INSTALL) != 0) {
9820                final int N = pkg.providers.size();
9821                int i;
9822                for (i=0; i<N; i++) {
9823                    PackageParser.Provider p = pkg.providers.get(i);
9824                    if (p.info.authority != null) {
9825                        String names[] = p.info.authority.split(";");
9826                        for (int j = 0; j < names.length; j++) {
9827                            if (mProvidersByAuthority.containsKey(names[j])) {
9828                                PackageParser.Provider other = mProvidersByAuthority.get(names[j]);
9829                                final String otherPackageName =
9830                                        ((other != null && other.getComponentName() != null) ?
9831                                                other.getComponentName().getPackageName() : "?");
9832                                throw new PackageManagerException(
9833                                        INSTALL_FAILED_CONFLICTING_PROVIDER,
9834                                        "Can't install because provider name " + names[j]
9835                                                + " (in package " + pkg.applicationInfo.packageName
9836                                                + ") is already used by " + otherPackageName);
9837                            }
9838                        }
9839                    }
9840                }
9841            }
9842        }
9843    }
9844
9845    private boolean addSharedLibraryLPw(String path, String apk, String name, int version,
9846            int type, String declaringPackageName, int declaringVersionCode) {
9847        SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(name);
9848        if (versionedLib == null) {
9849            versionedLib = new SparseArray<>();
9850            mSharedLibraries.put(name, versionedLib);
9851            if (type == SharedLibraryInfo.TYPE_STATIC) {
9852                mStaticLibsByDeclaringPackage.put(declaringPackageName, versionedLib);
9853            }
9854        } else if (versionedLib.indexOfKey(version) >= 0) {
9855            return false;
9856        }
9857        SharedLibraryEntry libEntry = new SharedLibraryEntry(path, apk, name,
9858                version, type, declaringPackageName, declaringVersionCode);
9859        versionedLib.put(version, libEntry);
9860        return true;
9861    }
9862
9863    private boolean removeSharedLibraryLPw(String name, int version) {
9864        SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(name);
9865        if (versionedLib == null) {
9866            return false;
9867        }
9868        final int libIdx = versionedLib.indexOfKey(version);
9869        if (libIdx < 0) {
9870            return false;
9871        }
9872        SharedLibraryEntry libEntry = versionedLib.valueAt(libIdx);
9873        versionedLib.remove(version);
9874        if (versionedLib.size() <= 0) {
9875            mSharedLibraries.remove(name);
9876            if (libEntry.info.getType() == SharedLibraryInfo.TYPE_STATIC) {
9877                mStaticLibsByDeclaringPackage.remove(libEntry.info.getDeclaringPackage()
9878                        .getPackageName());
9879            }
9880        }
9881        return true;
9882    }
9883
9884    /**
9885     * Adds a scanned package to the system. When this method is finished, the package will
9886     * be available for query, resolution, etc...
9887     */
9888    private void commitPackageSettings(PackageParser.Package pkg, PackageSetting pkgSetting,
9889            UserHandle user, int scanFlags, boolean chatty) throws PackageManagerException {
9890        final String pkgName = pkg.packageName;
9891        if (mCustomResolverComponentName != null &&
9892                mCustomResolverComponentName.getPackageName().equals(pkg.packageName)) {
9893            setUpCustomResolverActivity(pkg);
9894        }
9895
9896        if (pkg.packageName.equals("android")) {
9897            synchronized (mPackages) {
9898                if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
9899                    // Set up information for our fall-back user intent resolution activity.
9900                    mPlatformPackage = pkg;
9901                    pkg.mVersionCode = mSdkVersion;
9902                    mAndroidApplication = pkg.applicationInfo;
9903                    if (!mResolverReplaced) {
9904                        mResolveActivity.applicationInfo = mAndroidApplication;
9905                        mResolveActivity.name = ResolverActivity.class.getName();
9906                        mResolveActivity.packageName = mAndroidApplication.packageName;
9907                        mResolveActivity.processName = "system:ui";
9908                        mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
9909                        mResolveActivity.documentLaunchMode = ActivityInfo.DOCUMENT_LAUNCH_NEVER;
9910                        mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS;
9911                        mResolveActivity.theme = R.style.Theme_Material_Dialog_Alert;
9912                        mResolveActivity.exported = true;
9913                        mResolveActivity.enabled = true;
9914                        mResolveActivity.resizeMode = ActivityInfo.RESIZE_MODE_RESIZEABLE;
9915                        mResolveActivity.configChanges = ActivityInfo.CONFIG_SCREEN_SIZE
9916                                | ActivityInfo.CONFIG_SMALLEST_SCREEN_SIZE
9917                                | ActivityInfo.CONFIG_SCREEN_LAYOUT
9918                                | ActivityInfo.CONFIG_ORIENTATION
9919                                | ActivityInfo.CONFIG_KEYBOARD
9920                                | ActivityInfo.CONFIG_KEYBOARD_HIDDEN;
9921                        mResolveInfo.activityInfo = mResolveActivity;
9922                        mResolveInfo.priority = 0;
9923                        mResolveInfo.preferredOrder = 0;
9924                        mResolveInfo.match = 0;
9925                        mResolveComponentName = new ComponentName(
9926                                mAndroidApplication.packageName, mResolveActivity.name);
9927                    }
9928                }
9929            }
9930        }
9931
9932        ArrayList<PackageParser.Package> clientLibPkgs = null;
9933        // writer
9934        synchronized (mPackages) {
9935            boolean hasStaticSharedLibs = false;
9936
9937            // Any app can add new static shared libraries
9938            if (pkg.staticSharedLibName != null) {
9939                // Static shared libs don't allow renaming as they have synthetic package
9940                // names to allow install of multiple versions, so use name from manifest.
9941                if (addSharedLibraryLPw(null, pkg.packageName, pkg.staticSharedLibName,
9942                        pkg.staticSharedLibVersion, SharedLibraryInfo.TYPE_STATIC,
9943                        pkg.manifestPackageName, pkg.mVersionCode)) {
9944                    hasStaticSharedLibs = true;
9945                } else {
9946                    Slog.w(TAG, "Package " + pkg.packageName + " library "
9947                                + pkg.staticSharedLibName + " already exists; skipping");
9948                }
9949                // Static shared libs cannot be updated once installed since they
9950                // use synthetic package name which includes the version code, so
9951                // not need to update other packages's shared lib dependencies.
9952            }
9953
9954            if (!hasStaticSharedLibs
9955                    && (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
9956                // Only system apps can add new dynamic shared libraries.
9957                if (pkg.libraryNames != null) {
9958                    for (int i = 0; i < pkg.libraryNames.size(); i++) {
9959                        String name = pkg.libraryNames.get(i);
9960                        boolean allowed = false;
9961                        if (pkg.isUpdatedSystemApp()) {
9962                            // New library entries can only be added through the
9963                            // system image.  This is important to get rid of a lot
9964                            // of nasty edge cases: for example if we allowed a non-
9965                            // system update of the app to add a library, then uninstalling
9966                            // the update would make the library go away, and assumptions
9967                            // we made such as through app install filtering would now
9968                            // have allowed apps on the device which aren't compatible
9969                            // with it.  Better to just have the restriction here, be
9970                            // conservative, and create many fewer cases that can negatively
9971                            // impact the user experience.
9972                            final PackageSetting sysPs = mSettings
9973                                    .getDisabledSystemPkgLPr(pkg.packageName);
9974                            if (sysPs.pkg != null && sysPs.pkg.libraryNames != null) {
9975                                for (int j = 0; j < sysPs.pkg.libraryNames.size(); j++) {
9976                                    if (name.equals(sysPs.pkg.libraryNames.get(j))) {
9977                                        allowed = true;
9978                                        break;
9979                                    }
9980                                }
9981                            }
9982                        } else {
9983                            allowed = true;
9984                        }
9985                        if (allowed) {
9986                            if (!addSharedLibraryLPw(null, pkg.packageName, name,
9987                                    SharedLibraryInfo.VERSION_UNDEFINED,
9988                                    SharedLibraryInfo.TYPE_DYNAMIC,
9989                                    pkg.packageName, pkg.mVersionCode)) {
9990                                Slog.w(TAG, "Package " + pkg.packageName + " library "
9991                                        + name + " already exists; skipping");
9992                            }
9993                        } else {
9994                            Slog.w(TAG, "Package " + pkg.packageName + " declares lib "
9995                                    + name + " that is not declared on system image; skipping");
9996                        }
9997                    }
9998
9999                    if ((scanFlags & SCAN_BOOTING) == 0) {
10000                        // If we are not booting, we need to update any applications
10001                        // that are clients of our shared library.  If we are booting,
10002                        // this will all be done once the scan is complete.
10003                        clientLibPkgs = updateAllSharedLibrariesLPw(pkg);
10004                    }
10005                }
10006            }
10007        }
10008
10009        if ((scanFlags & SCAN_BOOTING) != 0) {
10010            // No apps can run during boot scan, so they don't need to be frozen
10011        } else if ((scanFlags & SCAN_DONT_KILL_APP) != 0) {
10012            // Caller asked to not kill app, so it's probably not frozen
10013        } else if ((scanFlags & SCAN_IGNORE_FROZEN) != 0) {
10014            // Caller asked us to ignore frozen check for some reason; they
10015            // probably didn't know the package name
10016        } else {
10017            // We're doing major surgery on this package, so it better be frozen
10018            // right now to keep it from launching
10019            checkPackageFrozen(pkgName);
10020        }
10021
10022        // Also need to kill any apps that are dependent on the library.
10023        if (clientLibPkgs != null) {
10024            for (int i=0; i<clientLibPkgs.size(); i++) {
10025                PackageParser.Package clientPkg = clientLibPkgs.get(i);
10026                killApplication(clientPkg.applicationInfo.packageName,
10027                        clientPkg.applicationInfo.uid, "update lib");
10028            }
10029        }
10030
10031        // writer
10032        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings");
10033
10034        synchronized (mPackages) {
10035            // We don't expect installation to fail beyond this point
10036
10037            if (pkgSetting.pkg != null) {
10038                // Note that |user| might be null during the initial boot scan. If a codePath
10039                // for an app has changed during a boot scan, it's due to an app update that's
10040                // part of the system partition and marker changes must be applied to all users.
10041                final int userId = ((user != null) ? user : UserHandle.ALL).getIdentifier();
10042                final int[] userIds = resolveUserIds(userId);
10043                maybeRenameForeignDexMarkers(pkgSetting.pkg, pkg, userIds);
10044            }
10045
10046            // Add the new setting to mSettings
10047            mSettings.insertPackageSettingLPw(pkgSetting, pkg);
10048            // Add the new setting to mPackages
10049            mPackages.put(pkg.applicationInfo.packageName, pkg);
10050            // Make sure we don't accidentally delete its data.
10051            final Iterator<PackageCleanItem> iter = mSettings.mPackagesToBeCleaned.iterator();
10052            while (iter.hasNext()) {
10053                PackageCleanItem item = iter.next();
10054                if (pkgName.equals(item.packageName)) {
10055                    iter.remove();
10056                }
10057            }
10058
10059            // Add the package's KeySets to the global KeySetManagerService
10060            KeySetManagerService ksms = mSettings.mKeySetManagerService;
10061            ksms.addScannedPackageLPw(pkg);
10062
10063            int N = pkg.providers.size();
10064            StringBuilder r = null;
10065            int i;
10066            for (i=0; i<N; i++) {
10067                PackageParser.Provider p = pkg.providers.get(i);
10068                p.info.processName = fixProcessName(pkg.applicationInfo.processName,
10069                        p.info.processName);
10070                mProviders.addProvider(p);
10071                p.syncable = p.info.isSyncable;
10072                if (p.info.authority != null) {
10073                    String names[] = p.info.authority.split(";");
10074                    p.info.authority = null;
10075                    for (int j = 0; j < names.length; j++) {
10076                        if (j == 1 && p.syncable) {
10077                            // We only want the first authority for a provider to possibly be
10078                            // syncable, so if we already added this provider using a different
10079                            // authority clear the syncable flag. We copy the provider before
10080                            // changing it because the mProviders object contains a reference
10081                            // to a provider that we don't want to change.
10082                            // Only do this for the second authority since the resulting provider
10083                            // object can be the same for all future authorities for this provider.
10084                            p = new PackageParser.Provider(p);
10085                            p.syncable = false;
10086                        }
10087                        if (!mProvidersByAuthority.containsKey(names[j])) {
10088                            mProvidersByAuthority.put(names[j], p);
10089                            if (p.info.authority == null) {
10090                                p.info.authority = names[j];
10091                            } else {
10092                                p.info.authority = p.info.authority + ";" + names[j];
10093                            }
10094                            if (DEBUG_PACKAGE_SCANNING) {
10095                                if (chatty)
10096                                    Log.d(TAG, "Registered content provider: " + names[j]
10097                                            + ", className = " + p.info.name + ", isSyncable = "
10098                                            + p.info.isSyncable);
10099                            }
10100                        } else {
10101                            PackageParser.Provider other = mProvidersByAuthority.get(names[j]);
10102                            Slog.w(TAG, "Skipping provider name " + names[j] +
10103                                    " (in package " + pkg.applicationInfo.packageName +
10104                                    "): name already used by "
10105                                    + ((other != null && other.getComponentName() != null)
10106                                            ? other.getComponentName().getPackageName() : "?"));
10107                        }
10108                    }
10109                }
10110                if (chatty) {
10111                    if (r == null) {
10112                        r = new StringBuilder(256);
10113                    } else {
10114                        r.append(' ');
10115                    }
10116                    r.append(p.info.name);
10117                }
10118            }
10119            if (r != null) {
10120                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Providers: " + r);
10121            }
10122
10123            N = pkg.services.size();
10124            r = null;
10125            for (i=0; i<N; i++) {
10126                PackageParser.Service s = pkg.services.get(i);
10127                s.info.processName = fixProcessName(pkg.applicationInfo.processName,
10128                        s.info.processName);
10129                mServices.addService(s);
10130                if (chatty) {
10131                    if (r == null) {
10132                        r = new StringBuilder(256);
10133                    } else {
10134                        r.append(' ');
10135                    }
10136                    r.append(s.info.name);
10137                }
10138            }
10139            if (r != null) {
10140                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Services: " + r);
10141            }
10142
10143            N = pkg.receivers.size();
10144            r = null;
10145            for (i=0; i<N; i++) {
10146                PackageParser.Activity a = pkg.receivers.get(i);
10147                a.info.processName = fixProcessName(pkg.applicationInfo.processName,
10148                        a.info.processName);
10149                mReceivers.addActivity(a, "receiver");
10150                if (chatty) {
10151                    if (r == null) {
10152                        r = new StringBuilder(256);
10153                    } else {
10154                        r.append(' ');
10155                    }
10156                    r.append(a.info.name);
10157                }
10158            }
10159            if (r != null) {
10160                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Receivers: " + r);
10161            }
10162
10163            N = pkg.activities.size();
10164            r = null;
10165            for (i=0; i<N; i++) {
10166                PackageParser.Activity a = pkg.activities.get(i);
10167                a.info.processName = fixProcessName(pkg.applicationInfo.processName,
10168                        a.info.processName);
10169                mActivities.addActivity(a, "activity");
10170                if (chatty) {
10171                    if (r == null) {
10172                        r = new StringBuilder(256);
10173                    } else {
10174                        r.append(' ');
10175                    }
10176                    r.append(a.info.name);
10177                }
10178            }
10179            if (r != null) {
10180                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Activities: " + r);
10181            }
10182
10183            N = pkg.permissionGroups.size();
10184            r = null;
10185            for (i=0; i<N; i++) {
10186                PackageParser.PermissionGroup pg = pkg.permissionGroups.get(i);
10187                PackageParser.PermissionGroup cur = mPermissionGroups.get(pg.info.name);
10188                final String curPackageName = cur == null ? null : cur.info.packageName;
10189                // Dont allow ephemeral apps to define new permission groups.
10190                if ((scanFlags & SCAN_AS_INSTANT_APP) != 0) {
10191                    Slog.w(TAG, "Permission group " + pg.info.name + " from package "
10192                            + pg.info.packageName
10193                            + " ignored: instant apps cannot define new permission groups.");
10194                    continue;
10195                }
10196                final boolean isPackageUpdate = pg.info.packageName.equals(curPackageName);
10197                if (cur == null || isPackageUpdate) {
10198                    mPermissionGroups.put(pg.info.name, pg);
10199                    if (chatty) {
10200                        if (r == null) {
10201                            r = new StringBuilder(256);
10202                        } else {
10203                            r.append(' ');
10204                        }
10205                        if (isPackageUpdate) {
10206                            r.append("UPD:");
10207                        }
10208                        r.append(pg.info.name);
10209                    }
10210                } else {
10211                    Slog.w(TAG, "Permission group " + pg.info.name + " from package "
10212                            + pg.info.packageName + " ignored: original from "
10213                            + cur.info.packageName);
10214                    if (chatty) {
10215                        if (r == null) {
10216                            r = new StringBuilder(256);
10217                        } else {
10218                            r.append(' ');
10219                        }
10220                        r.append("DUP:");
10221                        r.append(pg.info.name);
10222                    }
10223                }
10224            }
10225            if (r != null) {
10226                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Permission Groups: " + r);
10227            }
10228
10229            N = pkg.permissions.size();
10230            r = null;
10231            for (i=0; i<N; i++) {
10232                PackageParser.Permission p = pkg.permissions.get(i);
10233
10234                // Dont allow ephemeral apps to define new permissions.
10235                if ((scanFlags & SCAN_AS_INSTANT_APP) != 0) {
10236                    Slog.w(TAG, "Permission " + p.info.name + " from package "
10237                            + p.info.packageName
10238                            + " ignored: instant apps cannot define new permissions.");
10239                    continue;
10240                }
10241
10242                // Assume by default that we did not install this permission into the system.
10243                p.info.flags &= ~PermissionInfo.FLAG_INSTALLED;
10244
10245                // Now that permission groups have a special meaning, we ignore permission
10246                // groups for legacy apps to prevent unexpected behavior. In particular,
10247                // permissions for one app being granted to someone just becase they happen
10248                // to be in a group defined by another app (before this had no implications).
10249                if (pkg.applicationInfo.targetSdkVersion > Build.VERSION_CODES.LOLLIPOP_MR1) {
10250                    p.group = mPermissionGroups.get(p.info.group);
10251                    // Warn for a permission in an unknown group.
10252                    if (p.info.group != null && p.group == null) {
10253                        Slog.w(TAG, "Permission " + p.info.name + " from package "
10254                                + p.info.packageName + " in an unknown group " + p.info.group);
10255                    }
10256                }
10257
10258                ArrayMap<String, BasePermission> permissionMap =
10259                        p.tree ? mSettings.mPermissionTrees
10260                                : mSettings.mPermissions;
10261                BasePermission bp = permissionMap.get(p.info.name);
10262
10263                // Allow system apps to redefine non-system permissions
10264                if (bp != null && !Objects.equals(bp.sourcePackage, p.info.packageName)) {
10265                    final boolean currentOwnerIsSystem = (bp.perm != null
10266                            && isSystemApp(bp.perm.owner));
10267                    if (isSystemApp(p.owner)) {
10268                        if (bp.type == BasePermission.TYPE_BUILTIN && bp.perm == null) {
10269                            // It's a built-in permission and no owner, take ownership now
10270                            bp.packageSetting = pkgSetting;
10271                            bp.perm = p;
10272                            bp.uid = pkg.applicationInfo.uid;
10273                            bp.sourcePackage = p.info.packageName;
10274                            p.info.flags |= PermissionInfo.FLAG_INSTALLED;
10275                        } else if (!currentOwnerIsSystem) {
10276                            String msg = "New decl " + p.owner + " of permission  "
10277                                    + p.info.name + " is system; overriding " + bp.sourcePackage;
10278                            reportSettingsProblem(Log.WARN, msg);
10279                            bp = null;
10280                        }
10281                    }
10282                }
10283
10284                if (bp == null) {
10285                    bp = new BasePermission(p.info.name, p.info.packageName,
10286                            BasePermission.TYPE_NORMAL);
10287                    permissionMap.put(p.info.name, bp);
10288                }
10289
10290                if (bp.perm == null) {
10291                    if (bp.sourcePackage == null
10292                            || bp.sourcePackage.equals(p.info.packageName)) {
10293                        BasePermission tree = findPermissionTreeLP(p.info.name);
10294                        if (tree == null
10295                                || tree.sourcePackage.equals(p.info.packageName)) {
10296                            bp.packageSetting = pkgSetting;
10297                            bp.perm = p;
10298                            bp.uid = pkg.applicationInfo.uid;
10299                            bp.sourcePackage = p.info.packageName;
10300                            p.info.flags |= PermissionInfo.FLAG_INSTALLED;
10301                            if (chatty) {
10302                                if (r == null) {
10303                                    r = new StringBuilder(256);
10304                                } else {
10305                                    r.append(' ');
10306                                }
10307                                r.append(p.info.name);
10308                            }
10309                        } else {
10310                            Slog.w(TAG, "Permission " + p.info.name + " from package "
10311                                    + p.info.packageName + " ignored: base tree "
10312                                    + tree.name + " is from package "
10313                                    + tree.sourcePackage);
10314                        }
10315                    } else {
10316                        Slog.w(TAG, "Permission " + p.info.name + " from package "
10317                                + p.info.packageName + " ignored: original from "
10318                                + bp.sourcePackage);
10319                    }
10320                } else if (chatty) {
10321                    if (r == null) {
10322                        r = new StringBuilder(256);
10323                    } else {
10324                        r.append(' ');
10325                    }
10326                    r.append("DUP:");
10327                    r.append(p.info.name);
10328                }
10329                if (bp.perm == p) {
10330                    bp.protectionLevel = p.info.protectionLevel;
10331                }
10332            }
10333
10334            if (r != null) {
10335                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Permissions: " + r);
10336            }
10337
10338            N = pkg.instrumentation.size();
10339            r = null;
10340            for (i=0; i<N; i++) {
10341                PackageParser.Instrumentation a = pkg.instrumentation.get(i);
10342                a.info.packageName = pkg.applicationInfo.packageName;
10343                a.info.sourceDir = pkg.applicationInfo.sourceDir;
10344                a.info.publicSourceDir = pkg.applicationInfo.publicSourceDir;
10345                a.info.splitNames = pkg.splitNames;
10346                a.info.splitSourceDirs = pkg.applicationInfo.splitSourceDirs;
10347                a.info.splitPublicSourceDirs = pkg.applicationInfo.splitPublicSourceDirs;
10348                a.info.splitDependencies = pkg.applicationInfo.splitDependencies;
10349                a.info.dataDir = pkg.applicationInfo.dataDir;
10350                a.info.deviceProtectedDataDir = pkg.applicationInfo.deviceProtectedDataDir;
10351                a.info.credentialProtectedDataDir = pkg.applicationInfo.credentialProtectedDataDir;
10352                a.info.nativeLibraryDir = pkg.applicationInfo.nativeLibraryDir;
10353                a.info.secondaryNativeLibraryDir = pkg.applicationInfo.secondaryNativeLibraryDir;
10354                mInstrumentation.put(a.getComponentName(), a);
10355                if (chatty) {
10356                    if (r == null) {
10357                        r = new StringBuilder(256);
10358                    } else {
10359                        r.append(' ');
10360                    }
10361                    r.append(a.info.name);
10362                }
10363            }
10364            if (r != null) {
10365                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Instrumentation: " + r);
10366            }
10367
10368            if (pkg.protectedBroadcasts != null) {
10369                N = pkg.protectedBroadcasts.size();
10370                for (i=0; i<N; i++) {
10371                    mProtectedBroadcasts.add(pkg.protectedBroadcasts.get(i));
10372                }
10373            }
10374        }
10375
10376        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
10377    }
10378
10379    private static void maybeRenameForeignDexMarkers(PackageParser.Package existing,
10380            PackageParser.Package update, int[] userIds) {
10381        if (existing.applicationInfo == null || update.applicationInfo == null) {
10382            // This isn't due to an app installation.
10383            return;
10384        }
10385
10386        final File oldCodePath = new File(existing.applicationInfo.getCodePath());
10387        final File newCodePath = new File(update.applicationInfo.getCodePath());
10388
10389        // The codePath hasn't changed, so there's nothing for us to do.
10390        if (Objects.equals(oldCodePath, newCodePath)) {
10391            return;
10392        }
10393
10394        File canonicalNewCodePath;
10395        try {
10396            canonicalNewCodePath = new File(PackageManagerServiceUtils.realpath(newCodePath));
10397        } catch (IOException e) {
10398            Slog.w(TAG, "Failed to get canonical path.", e);
10399            return;
10400        }
10401
10402        // This is a bit of a hack. The oldCodePath doesn't exist at this point (because
10403        // we've already renamed / deleted it) so we cannot call realpath on it. Here we assume
10404        // that the last component of the path (i.e, the name) doesn't need canonicalization
10405        // (i.e, that it isn't ".", ".." or a symbolic link). This is a valid assumption for now
10406        // but may change in the future. Hopefully this function won't exist at that point.
10407        final File canonicalOldCodePath = new File(canonicalNewCodePath.getParentFile(),
10408                oldCodePath.getName());
10409
10410        // Calculate the prefixes of the markers. These are just the paths with "/" replaced
10411        // with "@".
10412        String oldMarkerPrefix = canonicalOldCodePath.getAbsolutePath().replace('/', '@');
10413        if (!oldMarkerPrefix.endsWith("@")) {
10414            oldMarkerPrefix += "@";
10415        }
10416        String newMarkerPrefix = canonicalNewCodePath.getAbsolutePath().replace('/', '@');
10417        if (!newMarkerPrefix.endsWith("@")) {
10418            newMarkerPrefix += "@";
10419        }
10420
10421        List<String> updatedPaths = update.getAllCodePathsExcludingResourceOnly();
10422        List<String> markerSuffixes = new ArrayList<String>(updatedPaths.size());
10423        for (String updatedPath : updatedPaths) {
10424            String updatedPathName = new File(updatedPath).getName();
10425            markerSuffixes.add(updatedPathName.replace('/', '@'));
10426        }
10427
10428        for (int userId : userIds) {
10429            File profileDir = Environment.getDataProfilesDeForeignDexDirectory(userId);
10430
10431            for (String markerSuffix : markerSuffixes) {
10432                File oldForeignUseMark = new File(profileDir, oldMarkerPrefix + markerSuffix);
10433                File newForeignUseMark = new File(profileDir, newMarkerPrefix + markerSuffix);
10434                if (oldForeignUseMark.exists()) {
10435                    try {
10436                        Os.rename(oldForeignUseMark.getAbsolutePath(),
10437                                newForeignUseMark.getAbsolutePath());
10438                    } catch (ErrnoException e) {
10439                        Slog.w(TAG, "Failed to rename foreign use marker", e);
10440                        oldForeignUseMark.delete();
10441                    }
10442                }
10443            }
10444        }
10445    }
10446
10447    /**
10448     * Derive the ABI of a non-system package located at {@code scanFile}. This information
10449     * is derived purely on the basis of the contents of {@code scanFile} and
10450     * {@code cpuAbiOverride}.
10451     *
10452     * If {@code extractLibs} is true, native libraries are extracted from the app if required.
10453     */
10454    private static void derivePackageAbi(PackageParser.Package pkg, File scanFile,
10455                                 String cpuAbiOverride, boolean extractLibs,
10456                                 File appLib32InstallDir)
10457            throws PackageManagerException {
10458        // Give ourselves some initial paths; we'll come back for another
10459        // pass once we've determined ABI below.
10460        setNativeLibraryPaths(pkg, appLib32InstallDir);
10461
10462        // We would never need to extract libs for forward-locked and external packages,
10463        // since the container service will do it for us. We shouldn't attempt to
10464        // extract libs from system app when it was not updated.
10465        if (pkg.isForwardLocked() || pkg.applicationInfo.isExternalAsec() ||
10466                (isSystemApp(pkg) && !pkg.isUpdatedSystemApp())) {
10467            extractLibs = false;
10468        }
10469
10470        final String nativeLibraryRootStr = pkg.applicationInfo.nativeLibraryRootDir;
10471        final boolean useIsaSpecificSubdirs = pkg.applicationInfo.nativeLibraryRootRequiresIsa;
10472
10473        NativeLibraryHelper.Handle handle = null;
10474        try {
10475            handle = NativeLibraryHelper.Handle.create(pkg);
10476            // TODO(multiArch): This can be null for apps that didn't go through the
10477            // usual installation process. We can calculate it again, like we
10478            // do during install time.
10479            //
10480            // TODO(multiArch): Why do we need to rescan ASEC apps again ? It seems totally
10481            // unnecessary.
10482            final File nativeLibraryRoot = new File(nativeLibraryRootStr);
10483
10484            // Null out the abis so that they can be recalculated.
10485            pkg.applicationInfo.primaryCpuAbi = null;
10486            pkg.applicationInfo.secondaryCpuAbi = null;
10487            if (isMultiArch(pkg.applicationInfo)) {
10488                // Warn if we've set an abiOverride for multi-lib packages..
10489                // By definition, we need to copy both 32 and 64 bit libraries for
10490                // such packages.
10491                if (pkg.cpuAbiOverride != null
10492                        && !NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(pkg.cpuAbiOverride)) {
10493                    Slog.w(TAG, "Ignoring abiOverride for multi arch application.");
10494                }
10495
10496                int abi32 = PackageManager.NO_NATIVE_LIBRARIES;
10497                int abi64 = PackageManager.NO_NATIVE_LIBRARIES;
10498                if (Build.SUPPORTED_32_BIT_ABIS.length > 0) {
10499                    if (extractLibs) {
10500                        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyNativeBinaries");
10501                        abi32 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
10502                                nativeLibraryRoot, Build.SUPPORTED_32_BIT_ABIS,
10503                                useIsaSpecificSubdirs);
10504                    } else {
10505                        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "findSupportedAbi");
10506                        abi32 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_32_BIT_ABIS);
10507                    }
10508                    Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
10509                }
10510
10511                maybeThrowExceptionForMultiArchCopy(
10512                        "Error unpackaging 32 bit native libs for multiarch app.", abi32);
10513
10514                if (Build.SUPPORTED_64_BIT_ABIS.length > 0) {
10515                    if (extractLibs) {
10516                        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyNativeBinaries");
10517                        abi64 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
10518                                nativeLibraryRoot, Build.SUPPORTED_64_BIT_ABIS,
10519                                useIsaSpecificSubdirs);
10520                    } else {
10521                        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "findSupportedAbi");
10522                        abi64 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_64_BIT_ABIS);
10523                    }
10524                    Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
10525                }
10526
10527                maybeThrowExceptionForMultiArchCopy(
10528                        "Error unpackaging 64 bit native libs for multiarch app.", abi64);
10529
10530                if (abi64 >= 0) {
10531                    pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[abi64];
10532                }
10533
10534                if (abi32 >= 0) {
10535                    final String abi = Build.SUPPORTED_32_BIT_ABIS[abi32];
10536                    if (abi64 >= 0) {
10537                        if (pkg.use32bitAbi) {
10538                            pkg.applicationInfo.secondaryCpuAbi = pkg.applicationInfo.primaryCpuAbi;
10539                            pkg.applicationInfo.primaryCpuAbi = abi;
10540                        } else {
10541                            pkg.applicationInfo.secondaryCpuAbi = abi;
10542                        }
10543                    } else {
10544                        pkg.applicationInfo.primaryCpuAbi = abi;
10545                    }
10546                }
10547
10548            } else {
10549                String[] abiList = (cpuAbiOverride != null) ?
10550                        new String[] { cpuAbiOverride } : Build.SUPPORTED_ABIS;
10551
10552                // Enable gross and lame hacks for apps that are built with old
10553                // SDK tools. We must scan their APKs for renderscript bitcode and
10554                // not launch them if it's present. Don't bother checking on devices
10555                // that don't have 64 bit support.
10556                boolean needsRenderScriptOverride = false;
10557                if (Build.SUPPORTED_64_BIT_ABIS.length > 0 && cpuAbiOverride == null &&
10558                        NativeLibraryHelper.hasRenderscriptBitcode(handle)) {
10559                    abiList = Build.SUPPORTED_32_BIT_ABIS;
10560                    needsRenderScriptOverride = true;
10561                }
10562
10563                final int copyRet;
10564                if (extractLibs) {
10565                    Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyNativeBinaries");
10566                    copyRet = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
10567                            nativeLibraryRoot, abiList, useIsaSpecificSubdirs);
10568                } else {
10569                    Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "findSupportedAbi");
10570                    copyRet = NativeLibraryHelper.findSupportedAbi(handle, abiList);
10571                }
10572                Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
10573
10574                if (copyRet < 0 && copyRet != PackageManager.NO_NATIVE_LIBRARIES) {
10575                    throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR,
10576                            "Error unpackaging native libs for app, errorCode=" + copyRet);
10577                }
10578
10579                if (copyRet >= 0) {
10580                    pkg.applicationInfo.primaryCpuAbi = abiList[copyRet];
10581                } else if (copyRet == PackageManager.NO_NATIVE_LIBRARIES && cpuAbiOverride != null) {
10582                    pkg.applicationInfo.primaryCpuAbi = cpuAbiOverride;
10583                } else if (needsRenderScriptOverride) {
10584                    pkg.applicationInfo.primaryCpuAbi = abiList[0];
10585                }
10586            }
10587        } catch (IOException ioe) {
10588            Slog.e(TAG, "Unable to get canonical file " + ioe.toString());
10589        } finally {
10590            IoUtils.closeQuietly(handle);
10591        }
10592
10593        // Now that we've calculated the ABIs and determined if it's an internal app,
10594        // we will go ahead and populate the nativeLibraryPath.
10595        setNativeLibraryPaths(pkg, appLib32InstallDir);
10596    }
10597
10598    /**
10599     * Adjusts ABIs for a set of packages belonging to a shared user so that they all match.
10600     * i.e, so that all packages can be run inside a single process if required.
10601     *
10602     * Optionally, callers can pass in a parsed package via {@code newPackage} in which case
10603     * this function will either try and make the ABI for all packages in {@code packagesForUser}
10604     * match {@code scannedPackage} or will update the ABI of {@code scannedPackage} to match
10605     * the ABI selected for {@code packagesForUser}. This variant is used when installing or
10606     * updating a package that belongs to a shared user.
10607     *
10608     * NOTE: We currently only match for the primary CPU abi string. Matching the secondary
10609     * adds unnecessary complexity.
10610     */
10611    private void adjustCpuAbisForSharedUserLPw(Set<PackageSetting> packagesForUser,
10612            PackageParser.Package scannedPackage) {
10613        String requiredInstructionSet = null;
10614        if (scannedPackage != null && scannedPackage.applicationInfo.primaryCpuAbi != null) {
10615            requiredInstructionSet = VMRuntime.getInstructionSet(
10616                     scannedPackage.applicationInfo.primaryCpuAbi);
10617        }
10618
10619        PackageSetting requirer = null;
10620        for (PackageSetting ps : packagesForUser) {
10621            // If packagesForUser contains scannedPackage, we skip it. This will happen
10622            // when scannedPackage is an update of an existing package. Without this check,
10623            // we will never be able to change the ABI of any package belonging to a shared
10624            // user, even if it's compatible with other packages.
10625            if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) {
10626                if (ps.primaryCpuAbiString == null) {
10627                    continue;
10628                }
10629
10630                final String instructionSet = VMRuntime.getInstructionSet(ps.primaryCpuAbiString);
10631                if (requiredInstructionSet != null && !instructionSet.equals(requiredInstructionSet)) {
10632                    // We have a mismatch between instruction sets (say arm vs arm64) warn about
10633                    // this but there's not much we can do.
10634                    String errorMessage = "Instruction set mismatch, "
10635                            + ((requirer == null) ? "[caller]" : requirer)
10636                            + " requires " + requiredInstructionSet + " whereas " + ps
10637                            + " requires " + instructionSet;
10638                    Slog.w(TAG, errorMessage);
10639                }
10640
10641                if (requiredInstructionSet == null) {
10642                    requiredInstructionSet = instructionSet;
10643                    requirer = ps;
10644                }
10645            }
10646        }
10647
10648        if (requiredInstructionSet != null) {
10649            String adjustedAbi;
10650            if (requirer != null) {
10651                // requirer != null implies that either scannedPackage was null or that scannedPackage
10652                // did not require an ABI, in which case we have to adjust scannedPackage to match
10653                // the ABI of the set (which is the same as requirer's ABI)
10654                adjustedAbi = requirer.primaryCpuAbiString;
10655                if (scannedPackage != null) {
10656                    scannedPackage.applicationInfo.primaryCpuAbi = adjustedAbi;
10657                }
10658            } else {
10659                // requirer == null implies that we're updating all ABIs in the set to
10660                // match scannedPackage.
10661                adjustedAbi =  scannedPackage.applicationInfo.primaryCpuAbi;
10662            }
10663
10664            for (PackageSetting ps : packagesForUser) {
10665                if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) {
10666                    if (ps.primaryCpuAbiString != null) {
10667                        continue;
10668                    }
10669
10670                    ps.primaryCpuAbiString = adjustedAbi;
10671                    if (ps.pkg != null && ps.pkg.applicationInfo != null &&
10672                            !TextUtils.equals(adjustedAbi, ps.pkg.applicationInfo.primaryCpuAbi)) {
10673                        ps.pkg.applicationInfo.primaryCpuAbi = adjustedAbi;
10674                        Slog.i(TAG, "Adjusting ABI for " + ps.name + " to " + adjustedAbi
10675                                + " (requirer="
10676                                + (requirer == null ? "null" : requirer.pkg.packageName)
10677                                + ", scannedPackage="
10678                                + (scannedPackage != null ? scannedPackage.packageName : "null")
10679                                + ")");
10680                        try {
10681                            mInstaller.rmdex(ps.codePathString,
10682                                    getDexCodeInstructionSet(getPreferredInstructionSet()));
10683                        } catch (InstallerException ignored) {
10684                        }
10685                    }
10686                }
10687            }
10688        }
10689    }
10690
10691    private void setUpCustomResolverActivity(PackageParser.Package pkg) {
10692        synchronized (mPackages) {
10693            mResolverReplaced = true;
10694            // Set up information for custom user intent resolution activity.
10695            mResolveActivity.applicationInfo = pkg.applicationInfo;
10696            mResolveActivity.name = mCustomResolverComponentName.getClassName();
10697            mResolveActivity.packageName = pkg.applicationInfo.packageName;
10698            mResolveActivity.processName = pkg.applicationInfo.packageName;
10699            mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
10700            mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS |
10701                    ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS;
10702            mResolveActivity.theme = 0;
10703            mResolveActivity.exported = true;
10704            mResolveActivity.enabled = true;
10705            mResolveInfo.activityInfo = mResolveActivity;
10706            mResolveInfo.priority = 0;
10707            mResolveInfo.preferredOrder = 0;
10708            mResolveInfo.match = 0;
10709            mResolveComponentName = mCustomResolverComponentName;
10710            Slog.i(TAG, "Replacing default ResolverActivity with custom activity: " +
10711                    mResolveComponentName);
10712        }
10713    }
10714
10715    private void setUpInstantAppInstallerActivityLP(ComponentName installerComponent) {
10716        if (installerComponent == null) {
10717            if (DEBUG_EPHEMERAL) {
10718                Slog.d(TAG, "Clear ephemeral installer activity");
10719            }
10720            mInstantAppInstallerActivity.applicationInfo = null;
10721            return;
10722        }
10723
10724        if (DEBUG_EPHEMERAL) {
10725            Slog.d(TAG, "Set ephemeral installer activity: " + installerComponent);
10726        }
10727        final PackageParser.Package pkg = mPackages.get(installerComponent.getPackageName());
10728        // Set up information for ephemeral installer activity
10729        mInstantAppInstallerActivity.applicationInfo = pkg.applicationInfo;
10730        mInstantAppInstallerActivity.name = installerComponent.getClassName();
10731        mInstantAppInstallerActivity.packageName = pkg.applicationInfo.packageName;
10732        mInstantAppInstallerActivity.processName = pkg.applicationInfo.packageName;
10733        mInstantAppInstallerActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
10734        mInstantAppInstallerActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS
10735                | ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS;
10736        mInstantAppInstallerActivity.theme = 0;
10737        mInstantAppInstallerActivity.exported = true;
10738        mInstantAppInstallerActivity.enabled = true;
10739        mInstantAppInstallerInfo.activityInfo = mInstantAppInstallerActivity;
10740        mInstantAppInstallerInfo.priority = 0;
10741        mInstantAppInstallerInfo.preferredOrder = 1;
10742        mInstantAppInstallerInfo.isDefault = true;
10743        mInstantAppInstallerInfo.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART
10744                | IntentFilter.MATCH_ADJUSTMENT_NORMAL;
10745    }
10746
10747    private static String calculateBundledApkRoot(final String codePathString) {
10748        final File codePath = new File(codePathString);
10749        final File codeRoot;
10750        if (FileUtils.contains(Environment.getRootDirectory(), codePath)) {
10751            codeRoot = Environment.getRootDirectory();
10752        } else if (FileUtils.contains(Environment.getOemDirectory(), codePath)) {
10753            codeRoot = Environment.getOemDirectory();
10754        } else if (FileUtils.contains(Environment.getVendorDirectory(), codePath)) {
10755            codeRoot = Environment.getVendorDirectory();
10756        } else {
10757            // Unrecognized code path; take its top real segment as the apk root:
10758            // e.g. /something/app/blah.apk => /something
10759            try {
10760                File f = codePath.getCanonicalFile();
10761                File parent = f.getParentFile();    // non-null because codePath is a file
10762                File tmp;
10763                while ((tmp = parent.getParentFile()) != null) {
10764                    f = parent;
10765                    parent = tmp;
10766                }
10767                codeRoot = f;
10768                Slog.w(TAG, "Unrecognized code path "
10769                        + codePath + " - using " + codeRoot);
10770            } catch (IOException e) {
10771                // Can't canonicalize the code path -- shenanigans?
10772                Slog.w(TAG, "Can't canonicalize code path " + codePath);
10773                return Environment.getRootDirectory().getPath();
10774            }
10775        }
10776        return codeRoot.getPath();
10777    }
10778
10779    /**
10780     * Derive and set the location of native libraries for the given package,
10781     * which varies depending on where and how the package was installed.
10782     */
10783    private static void setNativeLibraryPaths(PackageParser.Package pkg, File appLib32InstallDir) {
10784        final ApplicationInfo info = pkg.applicationInfo;
10785        final String codePath = pkg.codePath;
10786        final File codeFile = new File(codePath);
10787        final boolean bundledApp = info.isSystemApp() && !info.isUpdatedSystemApp();
10788        final boolean asecApp = info.isForwardLocked() || info.isExternalAsec();
10789
10790        info.nativeLibraryRootDir = null;
10791        info.nativeLibraryRootRequiresIsa = false;
10792        info.nativeLibraryDir = null;
10793        info.secondaryNativeLibraryDir = null;
10794
10795        if (isApkFile(codeFile)) {
10796            // Monolithic install
10797            if (bundledApp) {
10798                // If "/system/lib64/apkname" exists, assume that is the per-package
10799                // native library directory to use; otherwise use "/system/lib/apkname".
10800                final String apkRoot = calculateBundledApkRoot(info.sourceDir);
10801                final boolean is64Bit = VMRuntime.is64BitInstructionSet(
10802                        getPrimaryInstructionSet(info));
10803
10804                // This is a bundled system app so choose the path based on the ABI.
10805                // if it's a 64 bit abi, use lib64 otherwise use lib32. Note that this
10806                // is just the default path.
10807                final String apkName = deriveCodePathName(codePath);
10808                final String libDir = is64Bit ? LIB64_DIR_NAME : LIB_DIR_NAME;
10809                info.nativeLibraryRootDir = Environment.buildPath(new File(apkRoot), libDir,
10810                        apkName).getAbsolutePath();
10811
10812                if (info.secondaryCpuAbi != null) {
10813                    final String secondaryLibDir = is64Bit ? LIB_DIR_NAME : LIB64_DIR_NAME;
10814                    info.secondaryNativeLibraryDir = Environment.buildPath(new File(apkRoot),
10815                            secondaryLibDir, apkName).getAbsolutePath();
10816                }
10817            } else if (asecApp) {
10818                info.nativeLibraryRootDir = new File(codeFile.getParentFile(), LIB_DIR_NAME)
10819                        .getAbsolutePath();
10820            } else {
10821                final String apkName = deriveCodePathName(codePath);
10822                info.nativeLibraryRootDir = new File(appLib32InstallDir, apkName)
10823                        .getAbsolutePath();
10824            }
10825
10826            info.nativeLibraryRootRequiresIsa = false;
10827            info.nativeLibraryDir = info.nativeLibraryRootDir;
10828        } else {
10829            // Cluster install
10830            info.nativeLibraryRootDir = new File(codeFile, LIB_DIR_NAME).getAbsolutePath();
10831            info.nativeLibraryRootRequiresIsa = true;
10832
10833            info.nativeLibraryDir = new File(info.nativeLibraryRootDir,
10834                    getPrimaryInstructionSet(info)).getAbsolutePath();
10835
10836            if (info.secondaryCpuAbi != null) {
10837                info.secondaryNativeLibraryDir = new File(info.nativeLibraryRootDir,
10838                        VMRuntime.getInstructionSet(info.secondaryCpuAbi)).getAbsolutePath();
10839            }
10840        }
10841    }
10842
10843    /**
10844     * Calculate the abis and roots for a bundled app. These can uniquely
10845     * be determined from the contents of the system partition, i.e whether
10846     * it contains 64 or 32 bit shared libraries etc. We do not validate any
10847     * of this information, and instead assume that the system was built
10848     * sensibly.
10849     */
10850    private static void setBundledAppAbisAndRoots(PackageParser.Package pkg,
10851                                           PackageSetting pkgSetting) {
10852        final String apkName = deriveCodePathName(pkg.applicationInfo.getCodePath());
10853
10854        // If "/system/lib64/apkname" exists, assume that is the per-package
10855        // native library directory to use; otherwise use "/system/lib/apkname".
10856        final String apkRoot = calculateBundledApkRoot(pkg.applicationInfo.sourceDir);
10857        setBundledAppAbi(pkg, apkRoot, apkName);
10858        // pkgSetting might be null during rescan following uninstall of updates
10859        // to a bundled app, so accommodate that possibility.  The settings in
10860        // that case will be established later from the parsed package.
10861        //
10862        // If the settings aren't null, sync them up with what we've just derived.
10863        // note that apkRoot isn't stored in the package settings.
10864        if (pkgSetting != null) {
10865            pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi;
10866            pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi;
10867        }
10868    }
10869
10870    /**
10871     * Deduces the ABI of a bundled app and sets the relevant fields on the
10872     * parsed pkg object.
10873     *
10874     * @param apkRoot the root of the installed apk, something like {@code /system} or {@code /oem}
10875     *        under which system libraries are installed.
10876     * @param apkName the name of the installed package.
10877     */
10878    private static void setBundledAppAbi(PackageParser.Package pkg, String apkRoot, String apkName) {
10879        final File codeFile = new File(pkg.codePath);
10880
10881        final boolean has64BitLibs;
10882        final boolean has32BitLibs;
10883        if (isApkFile(codeFile)) {
10884            // Monolithic install
10885            has64BitLibs = (new File(apkRoot, new File(LIB64_DIR_NAME, apkName).getPath())).exists();
10886            has32BitLibs = (new File(apkRoot, new File(LIB_DIR_NAME, apkName).getPath())).exists();
10887        } else {
10888            // Cluster install
10889            final File rootDir = new File(codeFile, LIB_DIR_NAME);
10890            if (!ArrayUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS)
10891                    && !TextUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS[0])) {
10892                final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_64_BIT_ABIS[0]);
10893                has64BitLibs = (new File(rootDir, isa)).exists();
10894            } else {
10895                has64BitLibs = false;
10896            }
10897            if (!ArrayUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS)
10898                    && !TextUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS[0])) {
10899                final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_32_BIT_ABIS[0]);
10900                has32BitLibs = (new File(rootDir, isa)).exists();
10901            } else {
10902                has32BitLibs = false;
10903            }
10904        }
10905
10906        if (has64BitLibs && !has32BitLibs) {
10907            // The package has 64 bit libs, but not 32 bit libs. Its primary
10908            // ABI should be 64 bit. We can safely assume here that the bundled
10909            // native libraries correspond to the most preferred ABI in the list.
10910
10911            pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
10912            pkg.applicationInfo.secondaryCpuAbi = null;
10913        } else if (has32BitLibs && !has64BitLibs) {
10914            // The package has 32 bit libs but not 64 bit libs. Its primary
10915            // ABI should be 32 bit.
10916
10917            pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
10918            pkg.applicationInfo.secondaryCpuAbi = null;
10919        } else if (has32BitLibs && has64BitLibs) {
10920            // The application has both 64 and 32 bit bundled libraries. We check
10921            // here that the app declares multiArch support, and warn if it doesn't.
10922            //
10923            // We will be lenient here and record both ABIs. The primary will be the
10924            // ABI that's higher on the list, i.e, a device that's configured to prefer
10925            // 64 bit apps will see a 64 bit primary ABI,
10926
10927            if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_MULTIARCH) == 0) {
10928                Slog.e(TAG, "Package " + pkg + " has multiple bundled libs, but is not multiarch.");
10929            }
10930
10931            if (VMRuntime.is64BitInstructionSet(getPreferredInstructionSet())) {
10932                pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
10933                pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
10934            } else {
10935                pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
10936                pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
10937            }
10938        } else {
10939            pkg.applicationInfo.primaryCpuAbi = null;
10940            pkg.applicationInfo.secondaryCpuAbi = null;
10941        }
10942    }
10943
10944    private void killApplication(String pkgName, int appId, String reason) {
10945        killApplication(pkgName, appId, UserHandle.USER_ALL, reason);
10946    }
10947
10948    private void killApplication(String pkgName, int appId, int userId, String reason) {
10949        // Request the ActivityManager to kill the process(only for existing packages)
10950        // so that we do not end up in a confused state while the user is still using the older
10951        // version of the application while the new one gets installed.
10952        final long token = Binder.clearCallingIdentity();
10953        try {
10954            IActivityManager am = ActivityManager.getService();
10955            if (am != null) {
10956                try {
10957                    am.killApplication(pkgName, appId, userId, reason);
10958                } catch (RemoteException e) {
10959                }
10960            }
10961        } finally {
10962            Binder.restoreCallingIdentity(token);
10963        }
10964    }
10965
10966    private void removePackageLI(PackageParser.Package pkg, boolean chatty) {
10967        // Remove the parent package setting
10968        PackageSetting ps = (PackageSetting) pkg.mExtras;
10969        if (ps != null) {
10970            removePackageLI(ps, chatty);
10971        }
10972        // Remove the child package setting
10973        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
10974        for (int i = 0; i < childCount; i++) {
10975            PackageParser.Package childPkg = pkg.childPackages.get(i);
10976            ps = (PackageSetting) childPkg.mExtras;
10977            if (ps != null) {
10978                removePackageLI(ps, chatty);
10979            }
10980        }
10981    }
10982
10983    void removePackageLI(PackageSetting ps, boolean chatty) {
10984        if (DEBUG_INSTALL) {
10985            if (chatty)
10986                Log.d(TAG, "Removing package " + ps.name);
10987        }
10988
10989        // writer
10990        synchronized (mPackages) {
10991            mPackages.remove(ps.name);
10992            final PackageParser.Package pkg = ps.pkg;
10993            if (pkg != null) {
10994                cleanPackageDataStructuresLILPw(pkg, chatty);
10995            }
10996        }
10997    }
10998
10999    void removeInstalledPackageLI(PackageParser.Package pkg, boolean chatty) {
11000        if (DEBUG_INSTALL) {
11001            if (chatty)
11002                Log.d(TAG, "Removing package " + pkg.applicationInfo.packageName);
11003        }
11004
11005        // writer
11006        synchronized (mPackages) {
11007            // Remove the parent package
11008            mPackages.remove(pkg.applicationInfo.packageName);
11009            cleanPackageDataStructuresLILPw(pkg, chatty);
11010
11011            // Remove the child packages
11012            final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
11013            for (int i = 0; i < childCount; i++) {
11014                PackageParser.Package childPkg = pkg.childPackages.get(i);
11015                mPackages.remove(childPkg.applicationInfo.packageName);
11016                cleanPackageDataStructuresLILPw(childPkg, chatty);
11017            }
11018        }
11019    }
11020
11021    void cleanPackageDataStructuresLILPw(PackageParser.Package pkg, boolean chatty) {
11022        int N = pkg.providers.size();
11023        StringBuilder r = null;
11024        int i;
11025        for (i=0; i<N; i++) {
11026            PackageParser.Provider p = pkg.providers.get(i);
11027            mProviders.removeProvider(p);
11028            if (p.info.authority == null) {
11029
11030                /* There was another ContentProvider with this authority when
11031                 * this app was installed so this authority is null,
11032                 * Ignore it as we don't have to unregister the provider.
11033                 */
11034                continue;
11035            }
11036            String names[] = p.info.authority.split(";");
11037            for (int j = 0; j < names.length; j++) {
11038                if (mProvidersByAuthority.get(names[j]) == p) {
11039                    mProvidersByAuthority.remove(names[j]);
11040                    if (DEBUG_REMOVE) {
11041                        if (chatty)
11042                            Log.d(TAG, "Unregistered content provider: " + names[j]
11043                                    + ", className = " + p.info.name + ", isSyncable = "
11044                                    + p.info.isSyncable);
11045                    }
11046                }
11047            }
11048            if (DEBUG_REMOVE && chatty) {
11049                if (r == null) {
11050                    r = new StringBuilder(256);
11051                } else {
11052                    r.append(' ');
11053                }
11054                r.append(p.info.name);
11055            }
11056        }
11057        if (r != null) {
11058            if (DEBUG_REMOVE) Log.d(TAG, "  Providers: " + r);
11059        }
11060
11061        N = pkg.services.size();
11062        r = null;
11063        for (i=0; i<N; i++) {
11064            PackageParser.Service s = pkg.services.get(i);
11065            mServices.removeService(s);
11066            if (chatty) {
11067                if (r == null) {
11068                    r = new StringBuilder(256);
11069                } else {
11070                    r.append(' ');
11071                }
11072                r.append(s.info.name);
11073            }
11074        }
11075        if (r != null) {
11076            if (DEBUG_REMOVE) Log.d(TAG, "  Services: " + r);
11077        }
11078
11079        N = pkg.receivers.size();
11080        r = null;
11081        for (i=0; i<N; i++) {
11082            PackageParser.Activity a = pkg.receivers.get(i);
11083            mReceivers.removeActivity(a, "receiver");
11084            if (DEBUG_REMOVE && chatty) {
11085                if (r == null) {
11086                    r = new StringBuilder(256);
11087                } else {
11088                    r.append(' ');
11089                }
11090                r.append(a.info.name);
11091            }
11092        }
11093        if (r != null) {
11094            if (DEBUG_REMOVE) Log.d(TAG, "  Receivers: " + r);
11095        }
11096
11097        N = pkg.activities.size();
11098        r = null;
11099        for (i=0; i<N; i++) {
11100            PackageParser.Activity a = pkg.activities.get(i);
11101            mActivities.removeActivity(a, "activity");
11102            if (DEBUG_REMOVE && chatty) {
11103                if (r == null) {
11104                    r = new StringBuilder(256);
11105                } else {
11106                    r.append(' ');
11107                }
11108                r.append(a.info.name);
11109            }
11110        }
11111        if (r != null) {
11112            if (DEBUG_REMOVE) Log.d(TAG, "  Activities: " + r);
11113        }
11114
11115        N = pkg.permissions.size();
11116        r = null;
11117        for (i=0; i<N; i++) {
11118            PackageParser.Permission p = pkg.permissions.get(i);
11119            BasePermission bp = mSettings.mPermissions.get(p.info.name);
11120            if (bp == null) {
11121                bp = mSettings.mPermissionTrees.get(p.info.name);
11122            }
11123            if (bp != null && bp.perm == p) {
11124                bp.perm = null;
11125                if (DEBUG_REMOVE && chatty) {
11126                    if (r == null) {
11127                        r = new StringBuilder(256);
11128                    } else {
11129                        r.append(' ');
11130                    }
11131                    r.append(p.info.name);
11132                }
11133            }
11134            if ((p.info.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
11135                ArraySet<String> appOpPkgs = mAppOpPermissionPackages.get(p.info.name);
11136                if (appOpPkgs != null) {
11137                    appOpPkgs.remove(pkg.packageName);
11138                }
11139            }
11140        }
11141        if (r != null) {
11142            if (DEBUG_REMOVE) Log.d(TAG, "  Permissions: " + r);
11143        }
11144
11145        N = pkg.requestedPermissions.size();
11146        r = null;
11147        for (i=0; i<N; i++) {
11148            String perm = pkg.requestedPermissions.get(i);
11149            BasePermission bp = mSettings.mPermissions.get(perm);
11150            if (bp != null && (bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
11151                ArraySet<String> appOpPkgs = mAppOpPermissionPackages.get(perm);
11152                if (appOpPkgs != null) {
11153                    appOpPkgs.remove(pkg.packageName);
11154                    if (appOpPkgs.isEmpty()) {
11155                        mAppOpPermissionPackages.remove(perm);
11156                    }
11157                }
11158            }
11159        }
11160        if (r != null) {
11161            if (DEBUG_REMOVE) Log.d(TAG, "  Permissions: " + r);
11162        }
11163
11164        N = pkg.instrumentation.size();
11165        r = null;
11166        for (i=0; i<N; i++) {
11167            PackageParser.Instrumentation a = pkg.instrumentation.get(i);
11168            mInstrumentation.remove(a.getComponentName());
11169            if (DEBUG_REMOVE && chatty) {
11170                if (r == null) {
11171                    r = new StringBuilder(256);
11172                } else {
11173                    r.append(' ');
11174                }
11175                r.append(a.info.name);
11176            }
11177        }
11178        if (r != null) {
11179            if (DEBUG_REMOVE) Log.d(TAG, "  Instrumentation: " + r);
11180        }
11181
11182        r = null;
11183        if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) {
11184            // Only system apps can hold shared libraries.
11185            if (pkg.libraryNames != null) {
11186                for (i = 0; i < pkg.libraryNames.size(); i++) {
11187                    String name = pkg.libraryNames.get(i);
11188                    if (removeSharedLibraryLPw(name, 0)) {
11189                        if (DEBUG_REMOVE && chatty) {
11190                            if (r == null) {
11191                                r = new StringBuilder(256);
11192                            } else {
11193                                r.append(' ');
11194                            }
11195                            r.append(name);
11196                        }
11197                    }
11198                }
11199            }
11200        }
11201
11202        r = null;
11203
11204        // Any package can hold static shared libraries.
11205        if (pkg.staticSharedLibName != null) {
11206            if (removeSharedLibraryLPw(pkg.staticSharedLibName, pkg.staticSharedLibVersion)) {
11207                if (DEBUG_REMOVE && chatty) {
11208                    if (r == null) {
11209                        r = new StringBuilder(256);
11210                    } else {
11211                        r.append(' ');
11212                    }
11213                    r.append(pkg.staticSharedLibName);
11214                }
11215            }
11216        }
11217
11218        if (r != null) {
11219            if (DEBUG_REMOVE) Log.d(TAG, "  Libraries: " + r);
11220        }
11221    }
11222
11223    private static boolean hasPermission(PackageParser.Package pkgInfo, String perm) {
11224        for (int i=pkgInfo.permissions.size()-1; i>=0; i--) {
11225            if (pkgInfo.permissions.get(i).info.name.equals(perm)) {
11226                return true;
11227            }
11228        }
11229        return false;
11230    }
11231
11232    static final int UPDATE_PERMISSIONS_ALL = 1<<0;
11233    static final int UPDATE_PERMISSIONS_REPLACE_PKG = 1<<1;
11234    static final int UPDATE_PERMISSIONS_REPLACE_ALL = 1<<2;
11235
11236    private void updatePermissionsLPw(PackageParser.Package pkg, int flags) {
11237        // Update the parent permissions
11238        updatePermissionsLPw(pkg.packageName, pkg, flags);
11239        // Update the child permissions
11240        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
11241        for (int i = 0; i < childCount; i++) {
11242            PackageParser.Package childPkg = pkg.childPackages.get(i);
11243            updatePermissionsLPw(childPkg.packageName, childPkg, flags);
11244        }
11245    }
11246
11247    private void updatePermissionsLPw(String changingPkg, PackageParser.Package pkgInfo,
11248            int flags) {
11249        final String volumeUuid = (pkgInfo != null) ? getVolumeUuidForPackage(pkgInfo) : null;
11250        updatePermissionsLPw(changingPkg, pkgInfo, volumeUuid, flags);
11251    }
11252
11253    private void updatePermissionsLPw(String changingPkg,
11254            PackageParser.Package pkgInfo, String replaceVolumeUuid, int flags) {
11255        // Make sure there are no dangling permission trees.
11256        Iterator<BasePermission> it = mSettings.mPermissionTrees.values().iterator();
11257        while (it.hasNext()) {
11258            final BasePermission bp = it.next();
11259            if (bp.packageSetting == null) {
11260                // We may not yet have parsed the package, so just see if
11261                // we still know about its settings.
11262                bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage);
11263            }
11264            if (bp.packageSetting == null) {
11265                Slog.w(TAG, "Removing dangling permission tree: " + bp.name
11266                        + " from package " + bp.sourcePackage);
11267                it.remove();
11268            } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) {
11269                if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) {
11270                    Slog.i(TAG, "Removing old permission tree: " + bp.name
11271                            + " from package " + bp.sourcePackage);
11272                    flags |= UPDATE_PERMISSIONS_ALL;
11273                    it.remove();
11274                }
11275            }
11276        }
11277
11278        // Make sure all dynamic permissions have been assigned to a package,
11279        // and make sure there are no dangling permissions.
11280        it = mSettings.mPermissions.values().iterator();
11281        while (it.hasNext()) {
11282            final BasePermission bp = it.next();
11283            if (bp.type == BasePermission.TYPE_DYNAMIC) {
11284                if (DEBUG_SETTINGS) Log.v(TAG, "Dynamic permission: name="
11285                        + bp.name + " pkg=" + bp.sourcePackage
11286                        + " info=" + bp.pendingInfo);
11287                if (bp.packageSetting == null && bp.pendingInfo != null) {
11288                    final BasePermission tree = findPermissionTreeLP(bp.name);
11289                    if (tree != null && tree.perm != null) {
11290                        bp.packageSetting = tree.packageSetting;
11291                        bp.perm = new PackageParser.Permission(tree.perm.owner,
11292                                new PermissionInfo(bp.pendingInfo));
11293                        bp.perm.info.packageName = tree.perm.info.packageName;
11294                        bp.perm.info.name = bp.name;
11295                        bp.uid = tree.uid;
11296                    }
11297                }
11298            }
11299            if (bp.packageSetting == null) {
11300                // We may not yet have parsed the package, so just see if
11301                // we still know about its settings.
11302                bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage);
11303            }
11304            if (bp.packageSetting == null) {
11305                Slog.w(TAG, "Removing dangling permission: " + bp.name
11306                        + " from package " + bp.sourcePackage);
11307                it.remove();
11308            } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) {
11309                if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) {
11310                    Slog.i(TAG, "Removing old permission: " + bp.name
11311                            + " from package " + bp.sourcePackage);
11312                    flags |= UPDATE_PERMISSIONS_ALL;
11313                    it.remove();
11314                }
11315            }
11316        }
11317
11318        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "grantPermissions");
11319        // Now update the permissions for all packages, in particular
11320        // replace the granted permissions of the system packages.
11321        if ((flags&UPDATE_PERMISSIONS_ALL) != 0) {
11322            for (PackageParser.Package pkg : mPackages.values()) {
11323                if (pkg != pkgInfo) {
11324                    // Only replace for packages on requested volume
11325                    final String volumeUuid = getVolumeUuidForPackage(pkg);
11326                    final boolean replace = ((flags & UPDATE_PERMISSIONS_REPLACE_ALL) != 0)
11327                            && Objects.equals(replaceVolumeUuid, volumeUuid);
11328                    grantPermissionsLPw(pkg, replace, changingPkg);
11329                }
11330            }
11331        }
11332
11333        if (pkgInfo != null) {
11334            // Only replace for packages on requested volume
11335            final String volumeUuid = getVolumeUuidForPackage(pkgInfo);
11336            final boolean replace = ((flags & UPDATE_PERMISSIONS_REPLACE_PKG) != 0)
11337                    && Objects.equals(replaceVolumeUuid, volumeUuid);
11338            grantPermissionsLPw(pkgInfo, replace, changingPkg);
11339        }
11340        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
11341    }
11342
11343    private void grantPermissionsLPw(PackageParser.Package pkg, boolean replace,
11344            String packageOfInterest) {
11345        // IMPORTANT: There are two types of permissions: install and runtime.
11346        // Install time permissions are granted when the app is installed to
11347        // all device users and users added in the future. Runtime permissions
11348        // are granted at runtime explicitly to specific users. Normal and signature
11349        // protected permissions are install time permissions. Dangerous permissions
11350        // are install permissions if the app's target SDK is Lollipop MR1 or older,
11351        // otherwise they are runtime permissions. This function does not manage
11352        // runtime permissions except for the case an app targeting Lollipop MR1
11353        // being upgraded to target a newer SDK, in which case dangerous permissions
11354        // are transformed from install time to runtime ones.
11355
11356        final PackageSetting ps = (PackageSetting) pkg.mExtras;
11357        if (ps == null) {
11358            return;
11359        }
11360
11361        PermissionsState permissionsState = ps.getPermissionsState();
11362        PermissionsState origPermissions = permissionsState;
11363
11364        final int[] currentUserIds = UserManagerService.getInstance().getUserIds();
11365
11366        boolean runtimePermissionsRevoked = false;
11367        int[] changedRuntimePermissionUserIds = EMPTY_INT_ARRAY;
11368
11369        boolean changedInstallPermission = false;
11370
11371        if (replace) {
11372            ps.installPermissionsFixed = false;
11373            if (!ps.isSharedUser()) {
11374                origPermissions = new PermissionsState(permissionsState);
11375                permissionsState.reset();
11376            } else {
11377                // We need to know only about runtime permission changes since the
11378                // calling code always writes the install permissions state but
11379                // the runtime ones are written only if changed. The only cases of
11380                // changed runtime permissions here are promotion of an install to
11381                // runtime and revocation of a runtime from a shared user.
11382                changedRuntimePermissionUserIds = revokeUnusedSharedUserPermissionsLPw(
11383                        ps.sharedUser, UserManagerService.getInstance().getUserIds());
11384                if (!ArrayUtils.isEmpty(changedRuntimePermissionUserIds)) {
11385                    runtimePermissionsRevoked = true;
11386                }
11387            }
11388        }
11389
11390        permissionsState.setGlobalGids(mGlobalGids);
11391
11392        final int N = pkg.requestedPermissions.size();
11393        for (int i=0; i<N; i++) {
11394            final String name = pkg.requestedPermissions.get(i);
11395            final BasePermission bp = mSettings.mPermissions.get(name);
11396
11397            if (DEBUG_INSTALL) {
11398                Log.i(TAG, "Package " + pkg.packageName + " checking " + name + ": " + bp);
11399            }
11400
11401            if (bp == null || bp.packageSetting == null) {
11402                if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) {
11403                    Slog.w(TAG, "Unknown permission " + name
11404                            + " in package " + pkg.packageName);
11405                }
11406                continue;
11407            }
11408
11409
11410            // Limit ephemeral apps to ephemeral allowed permissions.
11411            if (pkg.applicationInfo.isInstantApp() && !bp.isInstant()) {
11412                Log.i(TAG, "Denying non-ephemeral permission " + bp.name + " for package "
11413                        + pkg.packageName);
11414                continue;
11415            }
11416
11417            final String perm = bp.name;
11418            boolean allowedSig = false;
11419            int grant = GRANT_DENIED;
11420
11421            // Keep track of app op permissions.
11422            if ((bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
11423                ArraySet<String> pkgs = mAppOpPermissionPackages.get(bp.name);
11424                if (pkgs == null) {
11425                    pkgs = new ArraySet<>();
11426                    mAppOpPermissionPackages.put(bp.name, pkgs);
11427                }
11428                pkgs.add(pkg.packageName);
11429            }
11430
11431            final int level = bp.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE;
11432            final boolean appSupportsRuntimePermissions = pkg.applicationInfo.targetSdkVersion
11433                    >= Build.VERSION_CODES.M;
11434            switch (level) {
11435                case PermissionInfo.PROTECTION_NORMAL: {
11436                    // For all apps normal permissions are install time ones.
11437                    grant = GRANT_INSTALL;
11438                } break;
11439
11440                case PermissionInfo.PROTECTION_DANGEROUS: {
11441                    // If a permission review is required for legacy apps we represent
11442                    // their permissions as always granted runtime ones since we need
11443                    // to keep the review required permission flag per user while an
11444                    // install permission's state is shared across all users.
11445                    if (!appSupportsRuntimePermissions && !mPermissionReviewRequired) {
11446                        // For legacy apps dangerous permissions are install time ones.
11447                        grant = GRANT_INSTALL;
11448                    } else if (origPermissions.hasInstallPermission(bp.name)) {
11449                        // For legacy apps that became modern, install becomes runtime.
11450                        grant = GRANT_UPGRADE;
11451                    } else if (mPromoteSystemApps
11452                            && isSystemApp(ps)
11453                            && mExistingSystemPackages.contains(ps.name)) {
11454                        // For legacy system apps, install becomes runtime.
11455                        // We cannot check hasInstallPermission() for system apps since those
11456                        // permissions were granted implicitly and not persisted pre-M.
11457                        grant = GRANT_UPGRADE;
11458                    } else {
11459                        // For modern apps keep runtime permissions unchanged.
11460                        grant = GRANT_RUNTIME;
11461                    }
11462                } break;
11463
11464                case PermissionInfo.PROTECTION_SIGNATURE: {
11465                    // For all apps signature permissions are install time ones.
11466                    allowedSig = grantSignaturePermission(perm, pkg, bp, origPermissions);
11467                    if (allowedSig) {
11468                        grant = GRANT_INSTALL;
11469                    }
11470                } break;
11471            }
11472
11473            if (DEBUG_INSTALL) {
11474                Log.i(TAG, "Package " + pkg.packageName + " granting " + perm);
11475            }
11476
11477            if (grant != GRANT_DENIED) {
11478                if (!isSystemApp(ps) && ps.installPermissionsFixed) {
11479                    // If this is an existing, non-system package, then
11480                    // we can't add any new permissions to it.
11481                    if (!allowedSig && !origPermissions.hasInstallPermission(perm)) {
11482                        // Except...  if this is a permission that was added
11483                        // to the platform (note: need to only do this when
11484                        // updating the platform).
11485                        if (!isNewPlatformPermissionForPackage(perm, pkg)) {
11486                            grant = GRANT_DENIED;
11487                        }
11488                    }
11489                }
11490
11491                switch (grant) {
11492                    case GRANT_INSTALL: {
11493                        // Revoke this as runtime permission to handle the case of
11494                        // a runtime permission being downgraded to an install one.
11495                        // Also in permission review mode we keep dangerous permissions
11496                        // for legacy apps
11497                        for (int userId : UserManagerService.getInstance().getUserIds()) {
11498                            if (origPermissions.getRuntimePermissionState(
11499                                    bp.name, userId) != null) {
11500                                // Revoke the runtime permission and clear the flags.
11501                                origPermissions.revokeRuntimePermission(bp, userId);
11502                                origPermissions.updatePermissionFlags(bp, userId,
11503                                      PackageManager.MASK_PERMISSION_FLAGS, 0);
11504                                // If we revoked a permission permission, we have to write.
11505                                changedRuntimePermissionUserIds = ArrayUtils.appendInt(
11506                                        changedRuntimePermissionUserIds, userId);
11507                            }
11508                        }
11509                        // Grant an install permission.
11510                        if (permissionsState.grantInstallPermission(bp) !=
11511                                PermissionsState.PERMISSION_OPERATION_FAILURE) {
11512                            changedInstallPermission = true;
11513                        }
11514                    } break;
11515
11516                    case GRANT_RUNTIME: {
11517                        // Grant previously granted runtime permissions.
11518                        for (int userId : UserManagerService.getInstance().getUserIds()) {
11519                            PermissionState permissionState = origPermissions
11520                                    .getRuntimePermissionState(bp.name, userId);
11521                            int flags = permissionState != null
11522                                    ? permissionState.getFlags() : 0;
11523                            if (origPermissions.hasRuntimePermission(bp.name, userId)) {
11524                                // Don't propagate the permission in a permission review mode if
11525                                // the former was revoked, i.e. marked to not propagate on upgrade.
11526                                // Note that in a permission review mode install permissions are
11527                                // represented as constantly granted runtime ones since we need to
11528                                // keep a per user state associated with the permission. Also the
11529                                // revoke on upgrade flag is no longer applicable and is reset.
11530                                final boolean revokeOnUpgrade = (flags & PackageManager
11531                                        .FLAG_PERMISSION_REVOKE_ON_UPGRADE) != 0;
11532                                if (revokeOnUpgrade) {
11533                                    flags &= ~PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE;
11534                                    // Since we changed the flags, we have to write.
11535                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
11536                                            changedRuntimePermissionUserIds, userId);
11537                                }
11538                                if (!mPermissionReviewRequired || !revokeOnUpgrade) {
11539                                    if (permissionsState.grantRuntimePermission(bp, userId) ==
11540                                            PermissionsState.PERMISSION_OPERATION_FAILURE) {
11541                                        // If we cannot put the permission as it was,
11542                                        // we have to write.
11543                                        changedRuntimePermissionUserIds = ArrayUtils.appendInt(
11544                                                changedRuntimePermissionUserIds, userId);
11545                                    }
11546                                }
11547
11548                                // If the app supports runtime permissions no need for a review.
11549                                if (mPermissionReviewRequired
11550                                        && appSupportsRuntimePermissions
11551                                        && (flags & PackageManager
11552                                                .FLAG_PERMISSION_REVIEW_REQUIRED) != 0) {
11553                                    flags &= ~PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED;
11554                                    // Since we changed the flags, we have to write.
11555                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
11556                                            changedRuntimePermissionUserIds, userId);
11557                                }
11558                            } else if (mPermissionReviewRequired
11559                                    && !appSupportsRuntimePermissions) {
11560                                // For legacy apps that need a permission review, every new
11561                                // runtime permission is granted but it is pending a review.
11562                                // We also need to review only platform defined runtime
11563                                // permissions as these are the only ones the platform knows
11564                                // how to disable the API to simulate revocation as legacy
11565                                // apps don't expect to run with revoked permissions.
11566                                if (PLATFORM_PACKAGE_NAME.equals(bp.sourcePackage)) {
11567                                    if ((flags & FLAG_PERMISSION_REVIEW_REQUIRED) == 0) {
11568                                        flags |= FLAG_PERMISSION_REVIEW_REQUIRED;
11569                                        // We changed the flags, hence have to write.
11570                                        changedRuntimePermissionUserIds = ArrayUtils.appendInt(
11571                                                changedRuntimePermissionUserIds, userId);
11572                                    }
11573                                }
11574                                if (permissionsState.grantRuntimePermission(bp, userId)
11575                                        != PermissionsState.PERMISSION_OPERATION_FAILURE) {
11576                                    // We changed the permission, hence have to write.
11577                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
11578                                            changedRuntimePermissionUserIds, userId);
11579                                }
11580                            }
11581                            // Propagate the permission flags.
11582                            permissionsState.updatePermissionFlags(bp, userId, flags, flags);
11583                        }
11584                    } break;
11585
11586                    case GRANT_UPGRADE: {
11587                        // Grant runtime permissions for a previously held install permission.
11588                        PermissionState permissionState = origPermissions
11589                                .getInstallPermissionState(bp.name);
11590                        final int flags = permissionState != null ? permissionState.getFlags() : 0;
11591
11592                        if (origPermissions.revokeInstallPermission(bp)
11593                                != PermissionsState.PERMISSION_OPERATION_FAILURE) {
11594                            // We will be transferring the permission flags, so clear them.
11595                            origPermissions.updatePermissionFlags(bp, UserHandle.USER_ALL,
11596                                    PackageManager.MASK_PERMISSION_FLAGS, 0);
11597                            changedInstallPermission = true;
11598                        }
11599
11600                        // If the permission is not to be promoted to runtime we ignore it and
11601                        // also its other flags as they are not applicable to install permissions.
11602                        if ((flags & PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE) == 0) {
11603                            for (int userId : currentUserIds) {
11604                                if (permissionsState.grantRuntimePermission(bp, userId) !=
11605                                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
11606                                    // Transfer the permission flags.
11607                                    permissionsState.updatePermissionFlags(bp, userId,
11608                                            flags, flags);
11609                                    // If we granted the permission, we have to write.
11610                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
11611                                            changedRuntimePermissionUserIds, userId);
11612                                }
11613                            }
11614                        }
11615                    } break;
11616
11617                    default: {
11618                        if (packageOfInterest == null
11619                                || packageOfInterest.equals(pkg.packageName)) {
11620                            Slog.w(TAG, "Not granting permission " + perm
11621                                    + " to package " + pkg.packageName
11622                                    + " because it was previously installed without");
11623                        }
11624                    } break;
11625                }
11626            } else {
11627                if (permissionsState.revokeInstallPermission(bp) !=
11628                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
11629                    // Also drop the permission flags.
11630                    permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL,
11631                            PackageManager.MASK_PERMISSION_FLAGS, 0);
11632                    changedInstallPermission = true;
11633                    Slog.i(TAG, "Un-granting permission " + perm
11634                            + " from package " + pkg.packageName
11635                            + " (protectionLevel=" + bp.protectionLevel
11636                            + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
11637                            + ")");
11638                } else if ((bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) == 0) {
11639                    // Don't print warning for app op permissions, since it is fine for them
11640                    // not to be granted, there is a UI for the user to decide.
11641                    if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) {
11642                        Slog.w(TAG, "Not granting permission " + perm
11643                                + " to package " + pkg.packageName
11644                                + " (protectionLevel=" + bp.protectionLevel
11645                                + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
11646                                + ")");
11647                    }
11648                }
11649            }
11650        }
11651
11652        if ((changedInstallPermission || replace) && !ps.installPermissionsFixed &&
11653                !isSystemApp(ps) || isUpdatedSystemApp(ps)){
11654            // This is the first that we have heard about this package, so the
11655            // permissions we have now selected are fixed until explicitly
11656            // changed.
11657            ps.installPermissionsFixed = true;
11658        }
11659
11660        // Persist the runtime permissions state for users with changes. If permissions
11661        // were revoked because no app in the shared user declares them we have to
11662        // write synchronously to avoid losing runtime permissions state.
11663        for (int userId : changedRuntimePermissionUserIds) {
11664            mSettings.writeRuntimePermissionsForUserLPr(userId, runtimePermissionsRevoked);
11665        }
11666    }
11667
11668    private boolean isNewPlatformPermissionForPackage(String perm, PackageParser.Package pkg) {
11669        boolean allowed = false;
11670        final int NP = PackageParser.NEW_PERMISSIONS.length;
11671        for (int ip=0; ip<NP; ip++) {
11672            final PackageParser.NewPermissionInfo npi
11673                    = PackageParser.NEW_PERMISSIONS[ip];
11674            if (npi.name.equals(perm)
11675                    && pkg.applicationInfo.targetSdkVersion < npi.sdkVersion) {
11676                allowed = true;
11677                Log.i(TAG, "Auto-granting " + perm + " to old pkg "
11678                        + pkg.packageName);
11679                break;
11680            }
11681        }
11682        return allowed;
11683    }
11684
11685    private boolean grantSignaturePermission(String perm, PackageParser.Package pkg,
11686            BasePermission bp, PermissionsState origPermissions) {
11687        boolean privilegedPermission = (bp.protectionLevel
11688                & PermissionInfo.PROTECTION_FLAG_PRIVILEGED) != 0;
11689        boolean privappPermissionsDisable =
11690                RoSystemProperties.CONTROL_PRIVAPP_PERMISSIONS_DISABLE;
11691        boolean platformPermission = PLATFORM_PACKAGE_NAME.equals(bp.sourcePackage);
11692        boolean platformPackage = PLATFORM_PACKAGE_NAME.equals(pkg.packageName);
11693        if (!privappPermissionsDisable && privilegedPermission && pkg.isPrivilegedApp()
11694                && !platformPackage && platformPermission) {
11695            ArraySet<String> wlPermissions = SystemConfig.getInstance()
11696                    .getPrivAppPermissions(pkg.packageName);
11697            boolean whitelisted = wlPermissions != null && wlPermissions.contains(perm);
11698            if (!whitelisted) {
11699                Slog.w(TAG, "Privileged permission " + perm + " for package "
11700                        + pkg.packageName + " - not in privapp-permissions whitelist");
11701                if (!mSystemReady) {
11702                    if (mPrivappPermissionsViolations == null) {
11703                        mPrivappPermissionsViolations = new ArraySet<>();
11704                    }
11705                    mPrivappPermissionsViolations.add(pkg.packageName + ": " + perm);
11706                }
11707                if (RoSystemProperties.CONTROL_PRIVAPP_PERMISSIONS_ENFORCE) {
11708                    return false;
11709                }
11710            }
11711        }
11712        boolean allowed = (compareSignatures(
11713                bp.packageSetting.signatures.mSignatures, pkg.mSignatures)
11714                        == PackageManager.SIGNATURE_MATCH)
11715                || (compareSignatures(mPlatformPackage.mSignatures, pkg.mSignatures)
11716                        == PackageManager.SIGNATURE_MATCH);
11717        if (!allowed && privilegedPermission) {
11718            if (isSystemApp(pkg)) {
11719                // For updated system applications, a system permission
11720                // is granted only if it had been defined by the original application.
11721                if (pkg.isUpdatedSystemApp()) {
11722                    final PackageSetting sysPs = mSettings
11723                            .getDisabledSystemPkgLPr(pkg.packageName);
11724                    if (sysPs != null && sysPs.getPermissionsState().hasInstallPermission(perm)) {
11725                        // If the original was granted this permission, we take
11726                        // that grant decision as read and propagate it to the
11727                        // update.
11728                        if (sysPs.isPrivileged()) {
11729                            allowed = true;
11730                        }
11731                    } else {
11732                        // The system apk may have been updated with an older
11733                        // version of the one on the data partition, but which
11734                        // granted a new system permission that it didn't have
11735                        // before.  In this case we do want to allow the app to
11736                        // now get the new permission if the ancestral apk is
11737                        // privileged to get it.
11738                        if (sysPs != null && sysPs.pkg != null && sysPs.isPrivileged()) {
11739                            for (int j = 0; j < sysPs.pkg.requestedPermissions.size(); j++) {
11740                                if (perm.equals(sysPs.pkg.requestedPermissions.get(j))) {
11741                                    allowed = true;
11742                                    break;
11743                                }
11744                            }
11745                        }
11746                        // Also if a privileged parent package on the system image or any of
11747                        // its children requested a privileged permission, the updated child
11748                        // packages can also get the permission.
11749                        if (pkg.parentPackage != null) {
11750                            final PackageSetting disabledSysParentPs = mSettings
11751                                    .getDisabledSystemPkgLPr(pkg.parentPackage.packageName);
11752                            if (disabledSysParentPs != null && disabledSysParentPs.pkg != null
11753                                    && disabledSysParentPs.isPrivileged()) {
11754                                if (isPackageRequestingPermission(disabledSysParentPs.pkg, perm)) {
11755                                    allowed = true;
11756                                } else if (disabledSysParentPs.pkg.childPackages != null) {
11757                                    final int count = disabledSysParentPs.pkg.childPackages.size();
11758                                    for (int i = 0; i < count; i++) {
11759                                        PackageParser.Package disabledSysChildPkg =
11760                                                disabledSysParentPs.pkg.childPackages.get(i);
11761                                        if (isPackageRequestingPermission(disabledSysChildPkg,
11762                                                perm)) {
11763                                            allowed = true;
11764                                            break;
11765                                        }
11766                                    }
11767                                }
11768                            }
11769                        }
11770                    }
11771                } else {
11772                    allowed = isPrivilegedApp(pkg);
11773                }
11774            }
11775        }
11776        if (!allowed) {
11777            if (!allowed && (bp.protectionLevel
11778                    & PermissionInfo.PROTECTION_FLAG_PRE23) != 0
11779                    && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) {
11780                // If this was a previously normal/dangerous permission that got moved
11781                // to a system permission as part of the runtime permission redesign, then
11782                // we still want to blindly grant it to old apps.
11783                allowed = true;
11784            }
11785            if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_INSTALLER) != 0
11786                    && pkg.packageName.equals(mRequiredInstallerPackage)) {
11787                // If this permission is to be granted to the system installer and
11788                // this app is an installer, then it gets the permission.
11789                allowed = true;
11790            }
11791            if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_VERIFIER) != 0
11792                    && pkg.packageName.equals(mRequiredVerifierPackage)) {
11793                // If this permission is to be granted to the system verifier and
11794                // this app is a verifier, then it gets the permission.
11795                allowed = true;
11796            }
11797            if (!allowed && (bp.protectionLevel
11798                    & PermissionInfo.PROTECTION_FLAG_PREINSTALLED) != 0
11799                    && isSystemApp(pkg)) {
11800                // Any pre-installed system app is allowed to get this permission.
11801                allowed = true;
11802            }
11803            if (!allowed && (bp.protectionLevel
11804                    & PermissionInfo.PROTECTION_FLAG_DEVELOPMENT) != 0) {
11805                // For development permissions, a development permission
11806                // is granted only if it was already granted.
11807                allowed = origPermissions.hasInstallPermission(perm);
11808            }
11809            if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_SETUP) != 0
11810                    && pkg.packageName.equals(mSetupWizardPackage)) {
11811                // If this permission is to be granted to the system setup wizard and
11812                // this app is a setup wizard, then it gets the permission.
11813                allowed = true;
11814            }
11815        }
11816        return allowed;
11817    }
11818
11819    private boolean isPackageRequestingPermission(PackageParser.Package pkg, String permission) {
11820        final int permCount = pkg.requestedPermissions.size();
11821        for (int j = 0; j < permCount; j++) {
11822            String requestedPermission = pkg.requestedPermissions.get(j);
11823            if (permission.equals(requestedPermission)) {
11824                return true;
11825            }
11826        }
11827        return false;
11828    }
11829
11830    final class ActivityIntentResolver
11831            extends IntentResolver<PackageParser.ActivityIntentInfo, ResolveInfo> {
11832        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
11833                boolean defaultOnly, int userId) {
11834            if (!sUserManager.exists(userId)) return null;
11835            mFlags = (defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0);
11836            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
11837        }
11838
11839        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
11840                int userId) {
11841            if (!sUserManager.exists(userId)) return null;
11842            mFlags = flags;
11843            return super.queryIntent(intent, resolvedType,
11844                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0,
11845                    userId);
11846        }
11847
11848        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
11849                int flags, ArrayList<PackageParser.Activity> packageActivities, int userId) {
11850            if (!sUserManager.exists(userId)) return null;
11851            if (packageActivities == null) {
11852                return null;
11853            }
11854            mFlags = flags;
11855            final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0;
11856            final int N = packageActivities.size();
11857            ArrayList<PackageParser.ActivityIntentInfo[]> listCut =
11858                new ArrayList<PackageParser.ActivityIntentInfo[]>(N);
11859
11860            ArrayList<PackageParser.ActivityIntentInfo> intentFilters;
11861            for (int i = 0; i < N; ++i) {
11862                intentFilters = packageActivities.get(i).intents;
11863                if (intentFilters != null && intentFilters.size() > 0) {
11864                    PackageParser.ActivityIntentInfo[] array =
11865                            new PackageParser.ActivityIntentInfo[intentFilters.size()];
11866                    intentFilters.toArray(array);
11867                    listCut.add(array);
11868                }
11869            }
11870            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
11871        }
11872
11873        /**
11874         * Finds a privileged activity that matches the specified activity names.
11875         */
11876        private PackageParser.Activity findMatchingActivity(
11877                List<PackageParser.Activity> activityList, ActivityInfo activityInfo) {
11878            for (PackageParser.Activity sysActivity : activityList) {
11879                if (sysActivity.info.name.equals(activityInfo.name)) {
11880                    return sysActivity;
11881                }
11882                if (sysActivity.info.name.equals(activityInfo.targetActivity)) {
11883                    return sysActivity;
11884                }
11885                if (sysActivity.info.targetActivity != null) {
11886                    if (sysActivity.info.targetActivity.equals(activityInfo.name)) {
11887                        return sysActivity;
11888                    }
11889                    if (sysActivity.info.targetActivity.equals(activityInfo.targetActivity)) {
11890                        return sysActivity;
11891                    }
11892                }
11893            }
11894            return null;
11895        }
11896
11897        public class IterGenerator<E> {
11898            public Iterator<E> generate(ActivityIntentInfo info) {
11899                return null;
11900            }
11901        }
11902
11903        public class ActionIterGenerator extends IterGenerator<String> {
11904            @Override
11905            public Iterator<String> generate(ActivityIntentInfo info) {
11906                return info.actionsIterator();
11907            }
11908        }
11909
11910        public class CategoriesIterGenerator extends IterGenerator<String> {
11911            @Override
11912            public Iterator<String> generate(ActivityIntentInfo info) {
11913                return info.categoriesIterator();
11914            }
11915        }
11916
11917        public class SchemesIterGenerator extends IterGenerator<String> {
11918            @Override
11919            public Iterator<String> generate(ActivityIntentInfo info) {
11920                return info.schemesIterator();
11921            }
11922        }
11923
11924        public class AuthoritiesIterGenerator extends IterGenerator<IntentFilter.AuthorityEntry> {
11925            @Override
11926            public Iterator<IntentFilter.AuthorityEntry> generate(ActivityIntentInfo info) {
11927                return info.authoritiesIterator();
11928            }
11929        }
11930
11931        /**
11932         * <em>WARNING</em> for performance reasons, the passed in intentList WILL BE
11933         * MODIFIED. Do not pass in a list that should not be changed.
11934         */
11935        private <T> void getIntentListSubset(List<ActivityIntentInfo> intentList,
11936                IterGenerator<T> generator, Iterator<T> searchIterator) {
11937            // loop through the set of actions; every one must be found in the intent filter
11938            while (searchIterator.hasNext()) {
11939                // we must have at least one filter in the list to consider a match
11940                if (intentList.size() == 0) {
11941                    break;
11942                }
11943
11944                final T searchAction = searchIterator.next();
11945
11946                // loop through the set of intent filters
11947                final Iterator<ActivityIntentInfo> intentIter = intentList.iterator();
11948                while (intentIter.hasNext()) {
11949                    final ActivityIntentInfo intentInfo = intentIter.next();
11950                    boolean selectionFound = false;
11951
11952                    // loop through the intent filter's selection criteria; at least one
11953                    // of them must match the searched criteria
11954                    final Iterator<T> intentSelectionIter = generator.generate(intentInfo);
11955                    while (intentSelectionIter != null && intentSelectionIter.hasNext()) {
11956                        final T intentSelection = intentSelectionIter.next();
11957                        if (intentSelection != null && intentSelection.equals(searchAction)) {
11958                            selectionFound = true;
11959                            break;
11960                        }
11961                    }
11962
11963                    // the selection criteria wasn't found in this filter's set; this filter
11964                    // is not a potential match
11965                    if (!selectionFound) {
11966                        intentIter.remove();
11967                    }
11968                }
11969            }
11970        }
11971
11972        private boolean isProtectedAction(ActivityIntentInfo filter) {
11973            final Iterator<String> actionsIter = filter.actionsIterator();
11974            while (actionsIter != null && actionsIter.hasNext()) {
11975                final String filterAction = actionsIter.next();
11976                if (PROTECTED_ACTIONS.contains(filterAction)) {
11977                    return true;
11978                }
11979            }
11980            return false;
11981        }
11982
11983        /**
11984         * Adjusts the priority of the given intent filter according to policy.
11985         * <p>
11986         * <ul>
11987         * <li>The priority for non privileged applications is capped to '0'</li>
11988         * <li>The priority for protected actions on privileged applications is capped to '0'</li>
11989         * <li>The priority for unbundled updates to privileged applications is capped to the
11990         *      priority defined on the system partition</li>
11991         * </ul>
11992         * <p>
11993         * <em>NOTE:</em> There is one exception. For security reasons, the setup wizard is
11994         * allowed to obtain any priority on any action.
11995         */
11996        private void adjustPriority(
11997                List<PackageParser.Activity> systemActivities, ActivityIntentInfo intent) {
11998            // nothing to do; priority is fine as-is
11999            if (intent.getPriority() <= 0) {
12000                return;
12001            }
12002
12003            final ActivityInfo activityInfo = intent.activity.info;
12004            final ApplicationInfo applicationInfo = activityInfo.applicationInfo;
12005
12006            final boolean privilegedApp =
12007                    ((applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0);
12008            if (!privilegedApp) {
12009                // non-privileged applications can never define a priority >0
12010                Slog.w(TAG, "Non-privileged app; cap priority to 0;"
12011                        + " package: " + applicationInfo.packageName
12012                        + " activity: " + intent.activity.className
12013                        + " origPrio: " + intent.getPriority());
12014                intent.setPriority(0);
12015                return;
12016            }
12017
12018            if (systemActivities == null) {
12019                // the system package is not disabled; we're parsing the system partition
12020                if (isProtectedAction(intent)) {
12021                    if (mDeferProtectedFilters) {
12022                        // We can't deal with these just yet. No component should ever obtain a
12023                        // >0 priority for a protected actions, with ONE exception -- the setup
12024                        // wizard. The setup wizard, however, cannot be known until we're able to
12025                        // query it for the category CATEGORY_SETUP_WIZARD. Which we can't do
12026                        // until all intent filters have been processed. Chicken, meet egg.
12027                        // Let the filter temporarily have a high priority and rectify the
12028                        // priorities after all system packages have been scanned.
12029                        mProtectedFilters.add(intent);
12030                        if (DEBUG_FILTERS) {
12031                            Slog.i(TAG, "Protected action; save for later;"
12032                                    + " package: " + applicationInfo.packageName
12033                                    + " activity: " + intent.activity.className
12034                                    + " origPrio: " + intent.getPriority());
12035                        }
12036                        return;
12037                    } else {
12038                        if (DEBUG_FILTERS && mSetupWizardPackage == null) {
12039                            Slog.i(TAG, "No setup wizard;"
12040                                + " All protected intents capped to priority 0");
12041                        }
12042                        if (intent.activity.info.packageName.equals(mSetupWizardPackage)) {
12043                            if (DEBUG_FILTERS) {
12044                                Slog.i(TAG, "Found setup wizard;"
12045                                    + " allow priority " + intent.getPriority() + ";"
12046                                    + " package: " + intent.activity.info.packageName
12047                                    + " activity: " + intent.activity.className
12048                                    + " priority: " + intent.getPriority());
12049                            }
12050                            // setup wizard gets whatever it wants
12051                            return;
12052                        }
12053                        Slog.w(TAG, "Protected action; cap priority to 0;"
12054                                + " package: " + intent.activity.info.packageName
12055                                + " activity: " + intent.activity.className
12056                                + " origPrio: " + intent.getPriority());
12057                        intent.setPriority(0);
12058                        return;
12059                    }
12060                }
12061                // privileged apps on the system image get whatever priority they request
12062                return;
12063            }
12064
12065            // privileged app unbundled update ... try to find the same activity
12066            final PackageParser.Activity foundActivity =
12067                    findMatchingActivity(systemActivities, activityInfo);
12068            if (foundActivity == null) {
12069                // this is a new activity; it cannot obtain >0 priority
12070                if (DEBUG_FILTERS) {
12071                    Slog.i(TAG, "New activity; cap priority to 0;"
12072                            + " package: " + applicationInfo.packageName
12073                            + " activity: " + intent.activity.className
12074                            + " origPrio: " + intent.getPriority());
12075                }
12076                intent.setPriority(0);
12077                return;
12078            }
12079
12080            // found activity, now check for filter equivalence
12081
12082            // a shallow copy is enough; we modify the list, not its contents
12083            final List<ActivityIntentInfo> intentListCopy =
12084                    new ArrayList<>(foundActivity.intents);
12085            final List<ActivityIntentInfo> foundFilters = findFilters(intent);
12086
12087            // find matching action subsets
12088            final Iterator<String> actionsIterator = intent.actionsIterator();
12089            if (actionsIterator != null) {
12090                getIntentListSubset(
12091                        intentListCopy, new ActionIterGenerator(), actionsIterator);
12092                if (intentListCopy.size() == 0) {
12093                    // no more intents to match; we're not equivalent
12094                    if (DEBUG_FILTERS) {
12095                        Slog.i(TAG, "Mismatched action; cap priority to 0;"
12096                                + " package: " + applicationInfo.packageName
12097                                + " activity: " + intent.activity.className
12098                                + " origPrio: " + intent.getPriority());
12099                    }
12100                    intent.setPriority(0);
12101                    return;
12102                }
12103            }
12104
12105            // find matching category subsets
12106            final Iterator<String> categoriesIterator = intent.categoriesIterator();
12107            if (categoriesIterator != null) {
12108                getIntentListSubset(intentListCopy, new CategoriesIterGenerator(),
12109                        categoriesIterator);
12110                if (intentListCopy.size() == 0) {
12111                    // no more intents to match; we're not equivalent
12112                    if (DEBUG_FILTERS) {
12113                        Slog.i(TAG, "Mismatched category; cap priority to 0;"
12114                                + " package: " + applicationInfo.packageName
12115                                + " activity: " + intent.activity.className
12116                                + " origPrio: " + intent.getPriority());
12117                    }
12118                    intent.setPriority(0);
12119                    return;
12120                }
12121            }
12122
12123            // find matching schemes subsets
12124            final Iterator<String> schemesIterator = intent.schemesIterator();
12125            if (schemesIterator != null) {
12126                getIntentListSubset(intentListCopy, new SchemesIterGenerator(),
12127                        schemesIterator);
12128                if (intentListCopy.size() == 0) {
12129                    // no more intents to match; we're not equivalent
12130                    if (DEBUG_FILTERS) {
12131                        Slog.i(TAG, "Mismatched scheme; cap priority to 0;"
12132                                + " package: " + applicationInfo.packageName
12133                                + " activity: " + intent.activity.className
12134                                + " origPrio: " + intent.getPriority());
12135                    }
12136                    intent.setPriority(0);
12137                    return;
12138                }
12139            }
12140
12141            // find matching authorities subsets
12142            final Iterator<IntentFilter.AuthorityEntry>
12143                    authoritiesIterator = intent.authoritiesIterator();
12144            if (authoritiesIterator != null) {
12145                getIntentListSubset(intentListCopy,
12146                        new AuthoritiesIterGenerator(),
12147                        authoritiesIterator);
12148                if (intentListCopy.size() == 0) {
12149                    // no more intents to match; we're not equivalent
12150                    if (DEBUG_FILTERS) {
12151                        Slog.i(TAG, "Mismatched authority; cap priority to 0;"
12152                                + " package: " + applicationInfo.packageName
12153                                + " activity: " + intent.activity.className
12154                                + " origPrio: " + intent.getPriority());
12155                    }
12156                    intent.setPriority(0);
12157                    return;
12158                }
12159            }
12160
12161            // we found matching filter(s); app gets the max priority of all intents
12162            int cappedPriority = 0;
12163            for (int i = intentListCopy.size() - 1; i >= 0; --i) {
12164                cappedPriority = Math.max(cappedPriority, intentListCopy.get(i).getPriority());
12165            }
12166            if (intent.getPriority() > cappedPriority) {
12167                if (DEBUG_FILTERS) {
12168                    Slog.i(TAG, "Found matching filter(s);"
12169                            + " cap priority to " + cappedPriority + ";"
12170                            + " package: " + applicationInfo.packageName
12171                            + " activity: " + intent.activity.className
12172                            + " origPrio: " + intent.getPriority());
12173                }
12174                intent.setPriority(cappedPriority);
12175                return;
12176            }
12177            // all this for nothing; the requested priority was <= what was on the system
12178        }
12179
12180        public final void addActivity(PackageParser.Activity a, String type) {
12181            mActivities.put(a.getComponentName(), a);
12182            if (DEBUG_SHOW_INFO)
12183                Log.v(
12184                TAG, "  " + type + " " +
12185                (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":");
12186            if (DEBUG_SHOW_INFO)
12187                Log.v(TAG, "    Class=" + a.info.name);
12188            final int NI = a.intents.size();
12189            for (int j=0; j<NI; j++) {
12190                PackageParser.ActivityIntentInfo intent = a.intents.get(j);
12191                if ("activity".equals(type)) {
12192                    final PackageSetting ps =
12193                            mSettings.getDisabledSystemPkgLPr(intent.activity.info.packageName);
12194                    final List<PackageParser.Activity> systemActivities =
12195                            ps != null && ps.pkg != null ? ps.pkg.activities : null;
12196                    adjustPriority(systemActivities, intent);
12197                }
12198                if (DEBUG_SHOW_INFO) {
12199                    Log.v(TAG, "    IntentFilter:");
12200                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
12201                }
12202                if (!intent.debugCheck()) {
12203                    Log.w(TAG, "==> For Activity " + a.info.name);
12204                }
12205                addFilter(intent);
12206            }
12207        }
12208
12209        public final void removeActivity(PackageParser.Activity a, String type) {
12210            mActivities.remove(a.getComponentName());
12211            if (DEBUG_SHOW_INFO) {
12212                Log.v(TAG, "  " + type + " "
12213                        + (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel
12214                                : a.info.name) + ":");
12215                Log.v(TAG, "    Class=" + a.info.name);
12216            }
12217            final int NI = a.intents.size();
12218            for (int j=0; j<NI; j++) {
12219                PackageParser.ActivityIntentInfo intent = a.intents.get(j);
12220                if (DEBUG_SHOW_INFO) {
12221                    Log.v(TAG, "    IntentFilter:");
12222                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
12223                }
12224                removeFilter(intent);
12225            }
12226        }
12227
12228        @Override
12229        protected boolean allowFilterResult(
12230                PackageParser.ActivityIntentInfo filter, List<ResolveInfo> dest) {
12231            ActivityInfo filterAi = filter.activity.info;
12232            for (int i=dest.size()-1; i>=0; i--) {
12233                ActivityInfo destAi = dest.get(i).activityInfo;
12234                if (destAi.name == filterAi.name
12235                        && destAi.packageName == filterAi.packageName) {
12236                    return false;
12237                }
12238            }
12239            return true;
12240        }
12241
12242        @Override
12243        protected ActivityIntentInfo[] newArray(int size) {
12244            return new ActivityIntentInfo[size];
12245        }
12246
12247        @Override
12248        protected boolean isFilterStopped(PackageParser.ActivityIntentInfo filter, int userId) {
12249            if (!sUserManager.exists(userId)) return true;
12250            PackageParser.Package p = filter.activity.owner;
12251            if (p != null) {
12252                PackageSetting ps = (PackageSetting)p.mExtras;
12253                if (ps != null) {
12254                    // System apps are never considered stopped for purposes of
12255                    // filtering, because there may be no way for the user to
12256                    // actually re-launch them.
12257                    return (ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0
12258                            && ps.getStopped(userId);
12259                }
12260            }
12261            return false;
12262        }
12263
12264        @Override
12265        protected boolean isPackageForFilter(String packageName,
12266                PackageParser.ActivityIntentInfo info) {
12267            return packageName.equals(info.activity.owner.packageName);
12268        }
12269
12270        @Override
12271        protected ResolveInfo newResult(PackageParser.ActivityIntentInfo info,
12272                int match, int userId) {
12273            if (!sUserManager.exists(userId)) return null;
12274            if (!mSettings.isEnabledAndMatchLPr(info.activity.info, mFlags, userId)) {
12275                return null;
12276            }
12277            final PackageParser.Activity activity = info.activity;
12278            PackageSetting ps = (PackageSetting) activity.owner.mExtras;
12279            if (ps == null) {
12280                return null;
12281            }
12282            final PackageUserState userState = ps.readUserState(userId);
12283            ActivityInfo ai = PackageParser.generateActivityInfo(activity, mFlags,
12284                    userState, userId);
12285            if (ai == null) {
12286                return null;
12287            }
12288            final boolean matchVisibleToInstantApp =
12289                    (mFlags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
12290            final boolean isInstantApp = (mFlags & PackageManager.MATCH_INSTANT) != 0;
12291            // throw out filters that aren't visible to ephemeral apps
12292            if (matchVisibleToInstantApp
12293                    && !(info.isVisibleToInstantApp() || userState.instantApp)) {
12294                return null;
12295            }
12296            // throw out ephemeral filters if we're not explicitly requesting them
12297            if (!isInstantApp && userState.instantApp) {
12298                return null;
12299            }
12300            final ResolveInfo res = new ResolveInfo();
12301            res.activityInfo = ai;
12302            if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
12303                res.filter = info;
12304            }
12305            if (info != null) {
12306                res.handleAllWebDataURI = info.handleAllWebDataURI();
12307            }
12308            res.priority = info.getPriority();
12309            res.preferredOrder = activity.owner.mPreferredOrder;
12310            //System.out.println("Result: " + res.activityInfo.className +
12311            //                   " = " + res.priority);
12312            res.match = match;
12313            res.isDefault = info.hasDefault;
12314            res.labelRes = info.labelRes;
12315            res.nonLocalizedLabel = info.nonLocalizedLabel;
12316            if (userNeedsBadging(userId)) {
12317                res.noResourceId = true;
12318            } else {
12319                res.icon = info.icon;
12320            }
12321            res.iconResourceId = info.icon;
12322            res.system = res.activityInfo.applicationInfo.isSystemApp();
12323            return res;
12324        }
12325
12326        @Override
12327        protected void sortResults(List<ResolveInfo> results) {
12328            Collections.sort(results, mResolvePrioritySorter);
12329        }
12330
12331        @Override
12332        protected void dumpFilter(PrintWriter out, String prefix,
12333                PackageParser.ActivityIntentInfo filter) {
12334            out.print(prefix); out.print(
12335                    Integer.toHexString(System.identityHashCode(filter.activity)));
12336                    out.print(' ');
12337                    filter.activity.printComponentShortName(out);
12338                    out.print(" filter ");
12339                    out.println(Integer.toHexString(System.identityHashCode(filter)));
12340        }
12341
12342        @Override
12343        protected Object filterToLabel(PackageParser.ActivityIntentInfo filter) {
12344            return filter.activity;
12345        }
12346
12347        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
12348            PackageParser.Activity activity = (PackageParser.Activity)label;
12349            out.print(prefix); out.print(
12350                    Integer.toHexString(System.identityHashCode(activity)));
12351                    out.print(' ');
12352                    activity.printComponentShortName(out);
12353            if (count > 1) {
12354                out.print(" ("); out.print(count); out.print(" filters)");
12355            }
12356            out.println();
12357        }
12358
12359        // Keys are String (activity class name), values are Activity.
12360        private final ArrayMap<ComponentName, PackageParser.Activity> mActivities
12361                = new ArrayMap<ComponentName, PackageParser.Activity>();
12362        private int mFlags;
12363    }
12364
12365    private final class ServiceIntentResolver
12366            extends IntentResolver<PackageParser.ServiceIntentInfo, ResolveInfo> {
12367        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
12368                boolean defaultOnly, int userId) {
12369            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
12370            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
12371        }
12372
12373        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
12374                int userId) {
12375            if (!sUserManager.exists(userId)) return null;
12376            mFlags = flags;
12377            return super.queryIntent(intent, resolvedType,
12378                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0,
12379                    userId);
12380        }
12381
12382        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
12383                int flags, ArrayList<PackageParser.Service> packageServices, int userId) {
12384            if (!sUserManager.exists(userId)) return null;
12385            if (packageServices == null) {
12386                return null;
12387            }
12388            mFlags = flags;
12389            final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0;
12390            final int N = packageServices.size();
12391            ArrayList<PackageParser.ServiceIntentInfo[]> listCut =
12392                new ArrayList<PackageParser.ServiceIntentInfo[]>(N);
12393
12394            ArrayList<PackageParser.ServiceIntentInfo> intentFilters;
12395            for (int i = 0; i < N; ++i) {
12396                intentFilters = packageServices.get(i).intents;
12397                if (intentFilters != null && intentFilters.size() > 0) {
12398                    PackageParser.ServiceIntentInfo[] array =
12399                            new PackageParser.ServiceIntentInfo[intentFilters.size()];
12400                    intentFilters.toArray(array);
12401                    listCut.add(array);
12402                }
12403            }
12404            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
12405        }
12406
12407        public final void addService(PackageParser.Service s) {
12408            mServices.put(s.getComponentName(), s);
12409            if (DEBUG_SHOW_INFO) {
12410                Log.v(TAG, "  "
12411                        + (s.info.nonLocalizedLabel != null
12412                        ? s.info.nonLocalizedLabel : s.info.name) + ":");
12413                Log.v(TAG, "    Class=" + s.info.name);
12414            }
12415            final int NI = s.intents.size();
12416            int j;
12417            for (j=0; j<NI; j++) {
12418                PackageParser.ServiceIntentInfo intent = s.intents.get(j);
12419                if (DEBUG_SHOW_INFO) {
12420                    Log.v(TAG, "    IntentFilter:");
12421                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
12422                }
12423                if (!intent.debugCheck()) {
12424                    Log.w(TAG, "==> For Service " + s.info.name);
12425                }
12426                addFilter(intent);
12427            }
12428        }
12429
12430        public final void removeService(PackageParser.Service s) {
12431            mServices.remove(s.getComponentName());
12432            if (DEBUG_SHOW_INFO) {
12433                Log.v(TAG, "  " + (s.info.nonLocalizedLabel != null
12434                        ? s.info.nonLocalizedLabel : s.info.name) + ":");
12435                Log.v(TAG, "    Class=" + s.info.name);
12436            }
12437            final int NI = s.intents.size();
12438            int j;
12439            for (j=0; j<NI; j++) {
12440                PackageParser.ServiceIntentInfo intent = s.intents.get(j);
12441                if (DEBUG_SHOW_INFO) {
12442                    Log.v(TAG, "    IntentFilter:");
12443                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
12444                }
12445                removeFilter(intent);
12446            }
12447        }
12448
12449        @Override
12450        protected boolean allowFilterResult(
12451                PackageParser.ServiceIntentInfo filter, List<ResolveInfo> dest) {
12452            ServiceInfo filterSi = filter.service.info;
12453            for (int i=dest.size()-1; i>=0; i--) {
12454                ServiceInfo destAi = dest.get(i).serviceInfo;
12455                if (destAi.name == filterSi.name
12456                        && destAi.packageName == filterSi.packageName) {
12457                    return false;
12458                }
12459            }
12460            return true;
12461        }
12462
12463        @Override
12464        protected PackageParser.ServiceIntentInfo[] newArray(int size) {
12465            return new PackageParser.ServiceIntentInfo[size];
12466        }
12467
12468        @Override
12469        protected boolean isFilterStopped(PackageParser.ServiceIntentInfo filter, int userId) {
12470            if (!sUserManager.exists(userId)) return true;
12471            PackageParser.Package p = filter.service.owner;
12472            if (p != null) {
12473                PackageSetting ps = (PackageSetting)p.mExtras;
12474                if (ps != null) {
12475                    // System apps are never considered stopped for purposes of
12476                    // filtering, because there may be no way for the user to
12477                    // actually re-launch them.
12478                    return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0
12479                            && ps.getStopped(userId);
12480                }
12481            }
12482            return false;
12483        }
12484
12485        @Override
12486        protected boolean isPackageForFilter(String packageName,
12487                PackageParser.ServiceIntentInfo info) {
12488            return packageName.equals(info.service.owner.packageName);
12489        }
12490
12491        @Override
12492        protected ResolveInfo newResult(PackageParser.ServiceIntentInfo filter,
12493                int match, int userId) {
12494            if (!sUserManager.exists(userId)) return null;
12495            final PackageParser.ServiceIntentInfo info = (PackageParser.ServiceIntentInfo)filter;
12496            if (!mSettings.isEnabledAndMatchLPr(info.service.info, mFlags, userId)) {
12497                return null;
12498            }
12499            final PackageParser.Service service = info.service;
12500            PackageSetting ps = (PackageSetting) service.owner.mExtras;
12501            if (ps == null) {
12502                return null;
12503            }
12504            ServiceInfo si = PackageParser.generateServiceInfo(service, mFlags,
12505                    ps.readUserState(userId), userId);
12506            if (si == null) {
12507                return null;
12508            }
12509            final ResolveInfo res = new ResolveInfo();
12510            res.serviceInfo = si;
12511            if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
12512                res.filter = filter;
12513            }
12514            res.priority = info.getPriority();
12515            res.preferredOrder = service.owner.mPreferredOrder;
12516            res.match = match;
12517            res.isDefault = info.hasDefault;
12518            res.labelRes = info.labelRes;
12519            res.nonLocalizedLabel = info.nonLocalizedLabel;
12520            res.icon = info.icon;
12521            res.system = res.serviceInfo.applicationInfo.isSystemApp();
12522            return res;
12523        }
12524
12525        @Override
12526        protected void sortResults(List<ResolveInfo> results) {
12527            Collections.sort(results, mResolvePrioritySorter);
12528        }
12529
12530        @Override
12531        protected void dumpFilter(PrintWriter out, String prefix,
12532                PackageParser.ServiceIntentInfo filter) {
12533            out.print(prefix); out.print(
12534                    Integer.toHexString(System.identityHashCode(filter.service)));
12535                    out.print(' ');
12536                    filter.service.printComponentShortName(out);
12537                    out.print(" filter ");
12538                    out.println(Integer.toHexString(System.identityHashCode(filter)));
12539        }
12540
12541        @Override
12542        protected Object filterToLabel(PackageParser.ServiceIntentInfo filter) {
12543            return filter.service;
12544        }
12545
12546        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
12547            PackageParser.Service service = (PackageParser.Service)label;
12548            out.print(prefix); out.print(
12549                    Integer.toHexString(System.identityHashCode(service)));
12550                    out.print(' ');
12551                    service.printComponentShortName(out);
12552            if (count > 1) {
12553                out.print(" ("); out.print(count); out.print(" filters)");
12554            }
12555            out.println();
12556        }
12557
12558//        List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) {
12559//            final Iterator<ResolveInfo> i = resolveInfoList.iterator();
12560//            final List<ResolveInfo> retList = Lists.newArrayList();
12561//            while (i.hasNext()) {
12562//                final ResolveInfo resolveInfo = (ResolveInfo) i;
12563//                if (isEnabledLP(resolveInfo.serviceInfo)) {
12564//                    retList.add(resolveInfo);
12565//                }
12566//            }
12567//            return retList;
12568//        }
12569
12570        // Keys are String (activity class name), values are Activity.
12571        private final ArrayMap<ComponentName, PackageParser.Service> mServices
12572                = new ArrayMap<ComponentName, PackageParser.Service>();
12573        private int mFlags;
12574    }
12575
12576    private final class ProviderIntentResolver
12577            extends IntentResolver<PackageParser.ProviderIntentInfo, ResolveInfo> {
12578        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
12579                boolean defaultOnly, int userId) {
12580            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
12581            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
12582        }
12583
12584        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
12585                int userId) {
12586            if (!sUserManager.exists(userId))
12587                return null;
12588            mFlags = flags;
12589            return super.queryIntent(intent, resolvedType,
12590                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0,
12591                    userId);
12592        }
12593
12594        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
12595                int flags, ArrayList<PackageParser.Provider> packageProviders, int userId) {
12596            if (!sUserManager.exists(userId))
12597                return null;
12598            if (packageProviders == null) {
12599                return null;
12600            }
12601            mFlags = flags;
12602            final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0;
12603            final int N = packageProviders.size();
12604            ArrayList<PackageParser.ProviderIntentInfo[]> listCut =
12605                    new ArrayList<PackageParser.ProviderIntentInfo[]>(N);
12606
12607            ArrayList<PackageParser.ProviderIntentInfo> intentFilters;
12608            for (int i = 0; i < N; ++i) {
12609                intentFilters = packageProviders.get(i).intents;
12610                if (intentFilters != null && intentFilters.size() > 0) {
12611                    PackageParser.ProviderIntentInfo[] array =
12612                            new PackageParser.ProviderIntentInfo[intentFilters.size()];
12613                    intentFilters.toArray(array);
12614                    listCut.add(array);
12615                }
12616            }
12617            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
12618        }
12619
12620        public final void addProvider(PackageParser.Provider p) {
12621            if (mProviders.containsKey(p.getComponentName())) {
12622                Slog.w(TAG, "Provider " + p.getComponentName() + " already defined; ignoring");
12623                return;
12624            }
12625
12626            mProviders.put(p.getComponentName(), p);
12627            if (DEBUG_SHOW_INFO) {
12628                Log.v(TAG, "  "
12629                        + (p.info.nonLocalizedLabel != null
12630                                ? p.info.nonLocalizedLabel : p.info.name) + ":");
12631                Log.v(TAG, "    Class=" + p.info.name);
12632            }
12633            final int NI = p.intents.size();
12634            int j;
12635            for (j = 0; j < NI; j++) {
12636                PackageParser.ProviderIntentInfo intent = p.intents.get(j);
12637                if (DEBUG_SHOW_INFO) {
12638                    Log.v(TAG, "    IntentFilter:");
12639                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
12640                }
12641                if (!intent.debugCheck()) {
12642                    Log.w(TAG, "==> For Provider " + p.info.name);
12643                }
12644                addFilter(intent);
12645            }
12646        }
12647
12648        public final void removeProvider(PackageParser.Provider p) {
12649            mProviders.remove(p.getComponentName());
12650            if (DEBUG_SHOW_INFO) {
12651                Log.v(TAG, "  " + (p.info.nonLocalizedLabel != null
12652                        ? p.info.nonLocalizedLabel : p.info.name) + ":");
12653                Log.v(TAG, "    Class=" + p.info.name);
12654            }
12655            final int NI = p.intents.size();
12656            int j;
12657            for (j = 0; j < NI; j++) {
12658                PackageParser.ProviderIntentInfo intent = p.intents.get(j);
12659                if (DEBUG_SHOW_INFO) {
12660                    Log.v(TAG, "    IntentFilter:");
12661                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
12662                }
12663                removeFilter(intent);
12664            }
12665        }
12666
12667        @Override
12668        protected boolean allowFilterResult(
12669                PackageParser.ProviderIntentInfo filter, List<ResolveInfo> dest) {
12670            ProviderInfo filterPi = filter.provider.info;
12671            for (int i = dest.size() - 1; i >= 0; i--) {
12672                ProviderInfo destPi = dest.get(i).providerInfo;
12673                if (destPi.name == filterPi.name
12674                        && destPi.packageName == filterPi.packageName) {
12675                    return false;
12676                }
12677            }
12678            return true;
12679        }
12680
12681        @Override
12682        protected PackageParser.ProviderIntentInfo[] newArray(int size) {
12683            return new PackageParser.ProviderIntentInfo[size];
12684        }
12685
12686        @Override
12687        protected boolean isFilterStopped(PackageParser.ProviderIntentInfo filter, int userId) {
12688            if (!sUserManager.exists(userId))
12689                return true;
12690            PackageParser.Package p = filter.provider.owner;
12691            if (p != null) {
12692                PackageSetting ps = (PackageSetting) p.mExtras;
12693                if (ps != null) {
12694                    // System apps are never considered stopped for purposes of
12695                    // filtering, because there may be no way for the user to
12696                    // actually re-launch them.
12697                    return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0
12698                            && ps.getStopped(userId);
12699                }
12700            }
12701            return false;
12702        }
12703
12704        @Override
12705        protected boolean isPackageForFilter(String packageName,
12706                PackageParser.ProviderIntentInfo info) {
12707            return packageName.equals(info.provider.owner.packageName);
12708        }
12709
12710        @Override
12711        protected ResolveInfo newResult(PackageParser.ProviderIntentInfo filter,
12712                int match, int userId) {
12713            if (!sUserManager.exists(userId))
12714                return null;
12715            final PackageParser.ProviderIntentInfo info = filter;
12716            if (!mSettings.isEnabledAndMatchLPr(info.provider.info, mFlags, userId)) {
12717                return null;
12718            }
12719            final PackageParser.Provider provider = info.provider;
12720            PackageSetting ps = (PackageSetting) provider.owner.mExtras;
12721            if (ps == null) {
12722                return null;
12723            }
12724            ProviderInfo pi = PackageParser.generateProviderInfo(provider, mFlags,
12725                    ps.readUserState(userId), userId);
12726            if (pi == null) {
12727                return null;
12728            }
12729            final ResolveInfo res = new ResolveInfo();
12730            res.providerInfo = pi;
12731            if ((mFlags & PackageManager.GET_RESOLVED_FILTER) != 0) {
12732                res.filter = filter;
12733            }
12734            res.priority = info.getPriority();
12735            res.preferredOrder = provider.owner.mPreferredOrder;
12736            res.match = match;
12737            res.isDefault = info.hasDefault;
12738            res.labelRes = info.labelRes;
12739            res.nonLocalizedLabel = info.nonLocalizedLabel;
12740            res.icon = info.icon;
12741            res.system = res.providerInfo.applicationInfo.isSystemApp();
12742            return res;
12743        }
12744
12745        @Override
12746        protected void sortResults(List<ResolveInfo> results) {
12747            Collections.sort(results, mResolvePrioritySorter);
12748        }
12749
12750        @Override
12751        protected void dumpFilter(PrintWriter out, String prefix,
12752                PackageParser.ProviderIntentInfo filter) {
12753            out.print(prefix);
12754            out.print(
12755                    Integer.toHexString(System.identityHashCode(filter.provider)));
12756            out.print(' ');
12757            filter.provider.printComponentShortName(out);
12758            out.print(" filter ");
12759            out.println(Integer.toHexString(System.identityHashCode(filter)));
12760        }
12761
12762        @Override
12763        protected Object filterToLabel(PackageParser.ProviderIntentInfo filter) {
12764            return filter.provider;
12765        }
12766
12767        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
12768            PackageParser.Provider provider = (PackageParser.Provider)label;
12769            out.print(prefix); out.print(
12770                    Integer.toHexString(System.identityHashCode(provider)));
12771                    out.print(' ');
12772                    provider.printComponentShortName(out);
12773            if (count > 1) {
12774                out.print(" ("); out.print(count); out.print(" filters)");
12775            }
12776            out.println();
12777        }
12778
12779        private final ArrayMap<ComponentName, PackageParser.Provider> mProviders
12780                = new ArrayMap<ComponentName, PackageParser.Provider>();
12781        private int mFlags;
12782    }
12783
12784    static final class EphemeralIntentResolver
12785            extends IntentResolver<AuxiliaryResolveInfo, AuxiliaryResolveInfo> {
12786        /**
12787         * The result that has the highest defined order. Ordering applies on a
12788         * per-package basis. Mapping is from package name to Pair of order and
12789         * EphemeralResolveInfo.
12790         * <p>
12791         * NOTE: This is implemented as a field variable for convenience and efficiency.
12792         * By having a field variable, we're able to track filter ordering as soon as
12793         * a non-zero order is defined. Otherwise, multiple loops across the result set
12794         * would be needed to apply ordering. If the intent resolver becomes re-entrant,
12795         * this needs to be contained entirely within {@link #filterResults()}.
12796         */
12797        final ArrayMap<String, Pair<Integer, EphemeralResolveInfo>> mOrderResult = new ArrayMap<>();
12798
12799        @Override
12800        protected AuxiliaryResolveInfo[] newArray(int size) {
12801            return new AuxiliaryResolveInfo[size];
12802        }
12803
12804        @Override
12805        protected boolean isPackageForFilter(String packageName, AuxiliaryResolveInfo responseObj) {
12806            return true;
12807        }
12808
12809        @Override
12810        protected AuxiliaryResolveInfo newResult(AuxiliaryResolveInfo responseObj, int match,
12811                int userId) {
12812            if (!sUserManager.exists(userId)) {
12813                return null;
12814            }
12815            final String packageName = responseObj.resolveInfo.getPackageName();
12816            final Integer order = responseObj.getOrder();
12817            final Pair<Integer, EphemeralResolveInfo> lastOrderResult =
12818                    mOrderResult.get(packageName);
12819            // ordering is enabled and this item's order isn't high enough
12820            if (lastOrderResult != null && lastOrderResult.first >= order) {
12821                return null;
12822            }
12823            final EphemeralResolveInfo res = responseObj.resolveInfo;
12824            if (order > 0) {
12825                // non-zero order, enable ordering
12826                mOrderResult.put(packageName, new Pair<>(order, res));
12827            }
12828            return responseObj;
12829        }
12830
12831        @Override
12832        protected void filterResults(List<AuxiliaryResolveInfo> results) {
12833            // only do work if ordering is enabled [most of the time it won't be]
12834            if (mOrderResult.size() == 0) {
12835                return;
12836            }
12837            int resultSize = results.size();
12838            for (int i = 0; i < resultSize; i++) {
12839                final EphemeralResolveInfo info = results.get(i).resolveInfo;
12840                final String packageName = info.getPackageName();
12841                final Pair<Integer, EphemeralResolveInfo> savedInfo = mOrderResult.get(packageName);
12842                if (savedInfo == null) {
12843                    // package doesn't having ordering
12844                    continue;
12845                }
12846                if (savedInfo.second == info) {
12847                    // circled back to the highest ordered item; remove from order list
12848                    mOrderResult.remove(savedInfo);
12849                    if (mOrderResult.size() == 0) {
12850                        // no more ordered items
12851                        break;
12852                    }
12853                    continue;
12854                }
12855                // item has a worse order, remove it from the result list
12856                results.remove(i);
12857                resultSize--;
12858                i--;
12859            }
12860        }
12861    }
12862
12863    private static final Comparator<ResolveInfo> mResolvePrioritySorter =
12864            new Comparator<ResolveInfo>() {
12865        public int compare(ResolveInfo r1, ResolveInfo r2) {
12866            int v1 = r1.priority;
12867            int v2 = r2.priority;
12868            //System.out.println("Comparing: q1=" + q1 + " q2=" + q2);
12869            if (v1 != v2) {
12870                return (v1 > v2) ? -1 : 1;
12871            }
12872            v1 = r1.preferredOrder;
12873            v2 = r2.preferredOrder;
12874            if (v1 != v2) {
12875                return (v1 > v2) ? -1 : 1;
12876            }
12877            if (r1.isDefault != r2.isDefault) {
12878                return r1.isDefault ? -1 : 1;
12879            }
12880            v1 = r1.match;
12881            v2 = r2.match;
12882            //System.out.println("Comparing: m1=" + m1 + " m2=" + m2);
12883            if (v1 != v2) {
12884                return (v1 > v2) ? -1 : 1;
12885            }
12886            if (r1.system != r2.system) {
12887                return r1.system ? -1 : 1;
12888            }
12889            if (r1.activityInfo != null) {
12890                return r1.activityInfo.packageName.compareTo(r2.activityInfo.packageName);
12891            }
12892            if (r1.serviceInfo != null) {
12893                return r1.serviceInfo.packageName.compareTo(r2.serviceInfo.packageName);
12894            }
12895            if (r1.providerInfo != null) {
12896                return r1.providerInfo.packageName.compareTo(r2.providerInfo.packageName);
12897            }
12898            return 0;
12899        }
12900    };
12901
12902    private static final Comparator<ProviderInfo> mProviderInitOrderSorter =
12903            new Comparator<ProviderInfo>() {
12904        public int compare(ProviderInfo p1, ProviderInfo p2) {
12905            final int v1 = p1.initOrder;
12906            final int v2 = p2.initOrder;
12907            return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0);
12908        }
12909    };
12910
12911    final void sendPackageBroadcast(final String action, final String pkg, final Bundle extras,
12912            final int flags, final String targetPkg, final IIntentReceiver finishedReceiver,
12913            final int[] userIds) {
12914        mHandler.post(new Runnable() {
12915            @Override
12916            public void run() {
12917                try {
12918                    final IActivityManager am = ActivityManager.getService();
12919                    if (am == null) return;
12920                    final int[] resolvedUserIds;
12921                    if (userIds == null) {
12922                        resolvedUserIds = am.getRunningUserIds();
12923                    } else {
12924                        resolvedUserIds = userIds;
12925                    }
12926                    for (int id : resolvedUserIds) {
12927                        final Intent intent = new Intent(action,
12928                                pkg != null ? Uri.fromParts(PACKAGE_SCHEME, pkg, null) : null);
12929                        if (extras != null) {
12930                            intent.putExtras(extras);
12931                        }
12932                        if (targetPkg != null) {
12933                            intent.setPackage(targetPkg);
12934                        }
12935                        // Modify the UID when posting to other users
12936                        int uid = intent.getIntExtra(Intent.EXTRA_UID, -1);
12937                        if (uid > 0 && UserHandle.getUserId(uid) != id) {
12938                            uid = UserHandle.getUid(id, UserHandle.getAppId(uid));
12939                            intent.putExtra(Intent.EXTRA_UID, uid);
12940                        }
12941                        intent.putExtra(Intent.EXTRA_USER_HANDLE, id);
12942                        intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT | flags);
12943                        if (DEBUG_BROADCASTS) {
12944                            RuntimeException here = new RuntimeException("here");
12945                            here.fillInStackTrace();
12946                            Slog.d(TAG, "Sending to user " + id + ": "
12947                                    + intent.toShortString(false, true, false, false)
12948                                    + " " + intent.getExtras(), here);
12949                        }
12950                        am.broadcastIntent(null, intent, null, finishedReceiver,
12951                                0, null, null, null, android.app.AppOpsManager.OP_NONE,
12952                                null, finishedReceiver != null, false, id);
12953                    }
12954                } catch (RemoteException ex) {
12955                }
12956            }
12957        });
12958    }
12959
12960    /**
12961     * Check if the external storage media is available. This is true if there
12962     * is a mounted external storage medium or if the external storage is
12963     * emulated.
12964     */
12965    private boolean isExternalMediaAvailable() {
12966        return mMediaMounted || Environment.isExternalStorageEmulated();
12967    }
12968
12969    @Override
12970    public PackageCleanItem nextPackageToClean(PackageCleanItem lastPackage) {
12971        // writer
12972        synchronized (mPackages) {
12973            if (!isExternalMediaAvailable()) {
12974                // If the external storage is no longer mounted at this point,
12975                // the caller may not have been able to delete all of this
12976                // packages files and can not delete any more.  Bail.
12977                return null;
12978            }
12979            final ArrayList<PackageCleanItem> pkgs = mSettings.mPackagesToBeCleaned;
12980            if (lastPackage != null) {
12981                pkgs.remove(lastPackage);
12982            }
12983            if (pkgs.size() > 0) {
12984                return pkgs.get(0);
12985            }
12986        }
12987        return null;
12988    }
12989
12990    void schedulePackageCleaning(String packageName, int userId, boolean andCode) {
12991        final Message msg = mHandler.obtainMessage(START_CLEANING_PACKAGE,
12992                userId, andCode ? 1 : 0, packageName);
12993        if (mSystemReady) {
12994            msg.sendToTarget();
12995        } else {
12996            if (mPostSystemReadyMessages == null) {
12997                mPostSystemReadyMessages = new ArrayList<>();
12998            }
12999            mPostSystemReadyMessages.add(msg);
13000        }
13001    }
13002
13003    void startCleaningPackages() {
13004        // reader
13005        if (!isExternalMediaAvailable()) {
13006            return;
13007        }
13008        synchronized (mPackages) {
13009            if (mSettings.mPackagesToBeCleaned.isEmpty()) {
13010                return;
13011            }
13012        }
13013        Intent intent = new Intent(PackageManager.ACTION_CLEAN_EXTERNAL_STORAGE);
13014        intent.setComponent(DEFAULT_CONTAINER_COMPONENT);
13015        IActivityManager am = ActivityManager.getService();
13016        if (am != null) {
13017            try {
13018                am.startService(null, intent, null, -1, null, mContext.getOpPackageName(),
13019                        UserHandle.USER_SYSTEM);
13020            } catch (RemoteException e) {
13021            }
13022        }
13023    }
13024
13025    @Override
13026    public void installPackageAsUser(String originPath, IPackageInstallObserver2 observer,
13027            int installFlags, String installerPackageName, int userId) {
13028        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, null);
13029
13030        final int callingUid = Binder.getCallingUid();
13031        enforceCrossUserPermission(callingUid, userId,
13032                true /* requireFullPermission */, true /* checkShell */, "installPackageAsUser");
13033
13034        if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) {
13035            try {
13036                if (observer != null) {
13037                    observer.onPackageInstalled("", INSTALL_FAILED_USER_RESTRICTED, null, null);
13038                }
13039            } catch (RemoteException re) {
13040            }
13041            return;
13042        }
13043
13044        if ((callingUid == Process.SHELL_UID) || (callingUid == Process.ROOT_UID)) {
13045            installFlags |= PackageManager.INSTALL_FROM_ADB;
13046
13047        } else {
13048            // Caller holds INSTALL_PACKAGES permission, so we're less strict
13049            // about installerPackageName.
13050
13051            installFlags &= ~PackageManager.INSTALL_FROM_ADB;
13052            installFlags &= ~PackageManager.INSTALL_ALL_USERS;
13053        }
13054
13055        UserHandle user;
13056        if ((installFlags & PackageManager.INSTALL_ALL_USERS) != 0) {
13057            user = UserHandle.ALL;
13058        } else {
13059            user = new UserHandle(userId);
13060        }
13061
13062        // Only system components can circumvent runtime permissions when installing.
13063        if ((installFlags & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0
13064                && mContext.checkCallingOrSelfPermission(Manifest.permission
13065                .INSTALL_GRANT_RUNTIME_PERMISSIONS) == PackageManager.PERMISSION_DENIED) {
13066            throw new SecurityException("You need the "
13067                    + "android.permission.INSTALL_GRANT_RUNTIME_PERMISSIONS permission "
13068                    + "to use the PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS flag");
13069        }
13070
13071        if ((installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0
13072                || (installFlags & PackageManager.INSTALL_EXTERNAL) != 0) {
13073            throw new IllegalArgumentException(
13074                    "New installs into ASEC containers no longer supported");
13075        }
13076
13077        final File originFile = new File(originPath);
13078        final OriginInfo origin = OriginInfo.fromUntrustedFile(originFile);
13079
13080        final Message msg = mHandler.obtainMessage(INIT_COPY);
13081        final VerificationInfo verificationInfo = new VerificationInfo(
13082                null /*originatingUri*/, null /*referrer*/, -1 /*originatingUid*/, callingUid);
13083        final InstallParams params = new InstallParams(origin, null /*moveInfo*/, observer,
13084                installFlags, installerPackageName, null /*volumeUuid*/, verificationInfo, user,
13085                null /*packageAbiOverride*/, null /*grantedPermissions*/,
13086                null /*certificates*/, PackageManager.INSTALL_REASON_UNKNOWN);
13087        params.setTraceMethod("installAsUser").setTraceCookie(System.identityHashCode(params));
13088        msg.obj = params;
13089
13090        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "installAsUser",
13091                System.identityHashCode(msg.obj));
13092        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
13093                System.identityHashCode(msg.obj));
13094
13095        mHandler.sendMessage(msg);
13096    }
13097
13098
13099    /**
13100     * Ensure that the install reason matches what we know about the package installer (e.g. whether
13101     * it is acting on behalf on an enterprise or the user).
13102     *
13103     * Note that the ordering of the conditionals in this method is important. The checks we perform
13104     * are as follows, in this order:
13105     *
13106     * 1) If the install is being performed by a system app, we can trust the app to have set the
13107     *    install reason correctly. Thus, we pass through the install reason unchanged, no matter
13108     *    what it is.
13109     * 2) If the install is being performed by a device or profile owner app, the install reason
13110     *    should be enterprise policy. However, we cannot be sure that the device or profile owner
13111     *    set the install reason correctly. If the app targets an older SDK version where install
13112     *    reasons did not exist yet, or if the app author simply forgot, the install reason may be
13113     *    unset or wrong. Thus, we force the install reason to be enterprise policy.
13114     * 3) In all other cases, the install is being performed by a regular app that is neither part
13115     *    of the system nor a device or profile owner. We have no reason to believe that this app is
13116     *    acting on behalf of the enterprise admin. Thus, we check whether the install reason was
13117     *    set to enterprise policy and if so, change it to unknown instead.
13118     */
13119    private int fixUpInstallReason(String installerPackageName, int installerUid,
13120            int installReason) {
13121        if (checkUidPermission(android.Manifest.permission.INSTALL_PACKAGES, installerUid)
13122                == PERMISSION_GRANTED) {
13123            // If the install is being performed by a system app, we trust that app to have set the
13124            // install reason correctly.
13125            return installReason;
13126        }
13127
13128        final IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface(
13129            ServiceManager.getService(Context.DEVICE_POLICY_SERVICE));
13130        if (dpm != null) {
13131            ComponentName owner = null;
13132            try {
13133                owner = dpm.getDeviceOwnerComponent(true /* callingUserOnly */);
13134                if (owner == null) {
13135                    owner = dpm.getProfileOwner(UserHandle.getUserId(installerUid));
13136                }
13137            } catch (RemoteException e) {
13138            }
13139            if (owner != null && owner.getPackageName().equals(installerPackageName)) {
13140                // If the install is being performed by a device or profile owner, the install
13141                // reason should be enterprise policy.
13142                return PackageManager.INSTALL_REASON_POLICY;
13143            }
13144        }
13145
13146        if (installReason == PackageManager.INSTALL_REASON_POLICY) {
13147            // If the install is being performed by a regular app (i.e. neither system app nor
13148            // device or profile owner), we have no reason to believe that the app is acting on
13149            // behalf of an enterprise. If the app set the install reason to enterprise policy,
13150            // change it to unknown instead.
13151            return PackageManager.INSTALL_REASON_UNKNOWN;
13152        }
13153
13154        // If the install is being performed by a regular app and the install reason was set to any
13155        // value but enterprise policy, leave the install reason unchanged.
13156        return installReason;
13157    }
13158
13159    void installStage(String packageName, File stagedDir, String stagedCid,
13160            IPackageInstallObserver2 observer, PackageInstaller.SessionParams sessionParams,
13161            String installerPackageName, int installerUid, UserHandle user,
13162            Certificate[][] certificates) {
13163        if (DEBUG_EPHEMERAL) {
13164            if ((sessionParams.installFlags & PackageManager.INSTALL_INSTANT_APP) != 0) {
13165                Slog.d(TAG, "Ephemeral install of " + packageName);
13166            }
13167        }
13168        final VerificationInfo verificationInfo = new VerificationInfo(
13169                sessionParams.originatingUri, sessionParams.referrerUri,
13170                sessionParams.originatingUid, installerUid);
13171
13172        final OriginInfo origin;
13173        if (stagedDir != null) {
13174            origin = OriginInfo.fromStagedFile(stagedDir);
13175        } else {
13176            origin = OriginInfo.fromStagedContainer(stagedCid);
13177        }
13178
13179        final Message msg = mHandler.obtainMessage(INIT_COPY);
13180        final int installReason = fixUpInstallReason(installerPackageName, installerUid,
13181                sessionParams.installReason);
13182        final InstallParams params = new InstallParams(origin, null, observer,
13183                sessionParams.installFlags, installerPackageName, sessionParams.volumeUuid,
13184                verificationInfo, user, sessionParams.abiOverride,
13185                sessionParams.grantedRuntimePermissions, certificates, installReason);
13186        params.setTraceMethod("installStage").setTraceCookie(System.identityHashCode(params));
13187        msg.obj = params;
13188
13189        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "installStage",
13190                System.identityHashCode(msg.obj));
13191        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
13192                System.identityHashCode(msg.obj));
13193
13194        mHandler.sendMessage(msg);
13195    }
13196
13197    private void sendPackageAddedForUser(String packageName, PackageSetting pkgSetting,
13198            int userId) {
13199        final boolean isSystem = isSystemApp(pkgSetting) || isUpdatedSystemApp(pkgSetting);
13200        sendPackageAddedForNewUsers(packageName, isSystem, pkgSetting.appId, userId);
13201    }
13202
13203    private void sendPackageAddedForNewUsers(String packageName, boolean isSystem,
13204            int appId, int... userIds) {
13205        if (ArrayUtils.isEmpty(userIds)) {
13206            return;
13207        }
13208        Bundle extras = new Bundle(1);
13209        // Set to UID of the first user, EXTRA_UID is automatically updated in sendPackageBroadcast
13210        extras.putInt(Intent.EXTRA_UID, UserHandle.getUid(userIds[0], appId));
13211
13212        sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
13213                packageName, extras, 0, null, null, userIds);
13214        if (isSystem) {
13215            mHandler.post(() -> {
13216                        for (int userId : userIds) {
13217                            sendBootCompletedBroadcastToSystemApp(packageName, userId);
13218                        }
13219                    }
13220            );
13221        }
13222    }
13223
13224    /**
13225     * The just-installed/enabled app is bundled on the system, so presumed to be able to run
13226     * automatically without needing an explicit launch.
13227     * Send it a LOCKED_BOOT_COMPLETED/BOOT_COMPLETED if it would ordinarily have gotten ones.
13228     */
13229    private void sendBootCompletedBroadcastToSystemApp(String packageName, int userId) {
13230        // If user is not running, the app didn't miss any broadcast
13231        if (!mUserManagerInternal.isUserRunning(userId)) {
13232            return;
13233        }
13234        final IActivityManager am = ActivityManager.getService();
13235        try {
13236            // Deliver LOCKED_BOOT_COMPLETED first
13237            Intent lockedBcIntent = new Intent(Intent.ACTION_LOCKED_BOOT_COMPLETED)
13238                    .setPackage(packageName);
13239            final String[] requiredPermissions = {Manifest.permission.RECEIVE_BOOT_COMPLETED};
13240            am.broadcastIntent(null, lockedBcIntent, null, null, 0, null, null, requiredPermissions,
13241                    android.app.AppOpsManager.OP_NONE, null, false, false, userId);
13242
13243            // Deliver BOOT_COMPLETED only if user is unlocked
13244            if (mUserManagerInternal.isUserUnlockingOrUnlocked(userId)) {
13245                Intent bcIntent = new Intent(Intent.ACTION_BOOT_COMPLETED).setPackage(packageName);
13246                am.broadcastIntent(null, bcIntent, null, null, 0, null, null, requiredPermissions,
13247                        android.app.AppOpsManager.OP_NONE, null, false, false, userId);
13248            }
13249        } catch (RemoteException e) {
13250            throw e.rethrowFromSystemServer();
13251        }
13252    }
13253
13254    @Override
13255    public boolean setApplicationHiddenSettingAsUser(String packageName, boolean hidden,
13256            int userId) {
13257        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
13258        PackageSetting pkgSetting;
13259        final int uid = Binder.getCallingUid();
13260        enforceCrossUserPermission(uid, userId,
13261                true /* requireFullPermission */, true /* checkShell */,
13262                "setApplicationHiddenSetting for user " + userId);
13263
13264        if (hidden && isPackageDeviceAdmin(packageName, userId)) {
13265            Slog.w(TAG, "Not hiding package " + packageName + ": has active device admin");
13266            return false;
13267        }
13268
13269        long callingId = Binder.clearCallingIdentity();
13270        try {
13271            boolean sendAdded = false;
13272            boolean sendRemoved = false;
13273            // writer
13274            synchronized (mPackages) {
13275                pkgSetting = mSettings.mPackages.get(packageName);
13276                if (pkgSetting == null) {
13277                    return false;
13278                }
13279                // Do not allow "android" is being disabled
13280                if ("android".equals(packageName)) {
13281                    Slog.w(TAG, "Cannot hide package: android");
13282                    return false;
13283                }
13284                // Cannot hide static shared libs as they are considered
13285                // a part of the using app (emulating static linking). Also
13286                // static libs are installed always on internal storage.
13287                PackageParser.Package pkg = mPackages.get(packageName);
13288                if (pkg != null && pkg.staticSharedLibName != null) {
13289                    Slog.w(TAG, "Cannot hide package: " + packageName
13290                            + " providing static shared library: "
13291                            + pkg.staticSharedLibName);
13292                    return false;
13293                }
13294                // Only allow protected packages to hide themselves.
13295                if (hidden && !UserHandle.isSameApp(uid, pkgSetting.appId)
13296                        && mProtectedPackages.isPackageStateProtected(userId, packageName)) {
13297                    Slog.w(TAG, "Not hiding protected package: " + packageName);
13298                    return false;
13299                }
13300
13301                if (pkgSetting.getHidden(userId) != hidden) {
13302                    pkgSetting.setHidden(hidden, userId);
13303                    mSettings.writePackageRestrictionsLPr(userId);
13304                    if (hidden) {
13305                        sendRemoved = true;
13306                    } else {
13307                        sendAdded = true;
13308                    }
13309                }
13310            }
13311            if (sendAdded) {
13312                sendPackageAddedForUser(packageName, pkgSetting, userId);
13313                return true;
13314            }
13315            if (sendRemoved) {
13316                killApplication(packageName, UserHandle.getUid(userId, pkgSetting.appId),
13317                        "hiding pkg");
13318                sendApplicationHiddenForUser(packageName, pkgSetting, userId);
13319                return true;
13320            }
13321        } finally {
13322            Binder.restoreCallingIdentity(callingId);
13323        }
13324        return false;
13325    }
13326
13327    private void sendApplicationHiddenForUser(String packageName, PackageSetting pkgSetting,
13328            int userId) {
13329        final PackageRemovedInfo info = new PackageRemovedInfo();
13330        info.removedPackage = packageName;
13331        info.removedUsers = new int[] {userId};
13332        info.uid = UserHandle.getUid(userId, pkgSetting.appId);
13333        info.sendPackageRemovedBroadcasts(true /*killApp*/);
13334    }
13335
13336    private void sendPackagesSuspendedForUser(String[] pkgList, int userId, boolean suspended) {
13337        if (pkgList.length > 0) {
13338            Bundle extras = new Bundle(1);
13339            extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList);
13340
13341            sendPackageBroadcast(
13342                    suspended ? Intent.ACTION_PACKAGES_SUSPENDED
13343                            : Intent.ACTION_PACKAGES_UNSUSPENDED,
13344                    null, extras, Intent.FLAG_RECEIVER_REGISTERED_ONLY, null, null,
13345                    new int[] {userId});
13346        }
13347    }
13348
13349    /**
13350     * Returns true if application is not found or there was an error. Otherwise it returns
13351     * the hidden state of the package for the given user.
13352     */
13353    @Override
13354    public boolean getApplicationHiddenSettingAsUser(String packageName, int userId) {
13355        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
13356        enforceCrossUserPermission(Binder.getCallingUid(), userId,
13357                true /* requireFullPermission */, false /* checkShell */,
13358                "getApplicationHidden for user " + userId);
13359        PackageSetting pkgSetting;
13360        long callingId = Binder.clearCallingIdentity();
13361        try {
13362            // writer
13363            synchronized (mPackages) {
13364                pkgSetting = mSettings.mPackages.get(packageName);
13365                if (pkgSetting == null) {
13366                    return true;
13367                }
13368                return pkgSetting.getHidden(userId);
13369            }
13370        } finally {
13371            Binder.restoreCallingIdentity(callingId);
13372        }
13373    }
13374
13375    /**
13376     * @hide
13377     */
13378    @Override
13379    public int installExistingPackageAsUser(String packageName, int userId, int installFlags,
13380            int installReason) {
13381        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES,
13382                null);
13383        PackageSetting pkgSetting;
13384        final int uid = Binder.getCallingUid();
13385        enforceCrossUserPermission(uid, userId,
13386                true /* requireFullPermission */, true /* checkShell */,
13387                "installExistingPackage for user " + userId);
13388        if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) {
13389            return PackageManager.INSTALL_FAILED_USER_RESTRICTED;
13390        }
13391
13392        long callingId = Binder.clearCallingIdentity();
13393        try {
13394            boolean installed = false;
13395            final boolean instantApp =
13396                    (installFlags & PackageManager.INSTALL_INSTANT_APP) != 0;
13397            final boolean fullApp =
13398                    (installFlags & PackageManager.INSTALL_FULL_APP) != 0;
13399
13400            // writer
13401            synchronized (mPackages) {
13402                pkgSetting = mSettings.mPackages.get(packageName);
13403                if (pkgSetting == null) {
13404                    return PackageManager.INSTALL_FAILED_INVALID_URI;
13405                }
13406                if (!pkgSetting.getInstalled(userId)) {
13407                    pkgSetting.setInstalled(true, userId);
13408                    pkgSetting.setHidden(false, userId);
13409                    pkgSetting.setInstallReason(installReason, userId);
13410                    mSettings.writePackageRestrictionsLPr(userId);
13411                    mSettings.writeKernelMappingLPr(pkgSetting);
13412                    installed = true;
13413                } else if (fullApp && pkgSetting.getInstantApp(userId)) {
13414                    // upgrade app from instant to full; we don't allow app downgrade
13415                    installed = true;
13416                }
13417                setInstantAppForUser(pkgSetting, userId, instantApp, fullApp);
13418            }
13419
13420            if (installed) {
13421                if (pkgSetting.pkg != null) {
13422                    synchronized (mInstallLock) {
13423                        // We don't need to freeze for a brand new install
13424                        prepareAppDataAfterInstallLIF(pkgSetting.pkg);
13425                    }
13426                }
13427                sendPackageAddedForUser(packageName, pkgSetting, userId);
13428                synchronized (mPackages) {
13429                    updateSequenceNumberLP(packageName, new int[]{ userId });
13430                }
13431            }
13432        } finally {
13433            Binder.restoreCallingIdentity(callingId);
13434        }
13435
13436        return PackageManager.INSTALL_SUCCEEDED;
13437    }
13438
13439    void setInstantAppForUser(PackageSetting pkgSetting, int userId,
13440            boolean instantApp, boolean fullApp) {
13441        // no state specified; do nothing
13442        if (!instantApp && !fullApp) {
13443            return;
13444        }
13445        if (userId != UserHandle.USER_ALL) {
13446            if (instantApp && !pkgSetting.getInstantApp(userId)) {
13447                pkgSetting.setInstantApp(true /*instantApp*/, userId);
13448            } else if (fullApp && pkgSetting.getInstantApp(userId)) {
13449                pkgSetting.setInstantApp(false /*instantApp*/, userId);
13450            }
13451        } else {
13452            for (int currentUserId : sUserManager.getUserIds()) {
13453                if (instantApp && !pkgSetting.getInstantApp(currentUserId)) {
13454                    pkgSetting.setInstantApp(true /*instantApp*/, currentUserId);
13455                } else if (fullApp && pkgSetting.getInstantApp(currentUserId)) {
13456                    pkgSetting.setInstantApp(false /*instantApp*/, currentUserId);
13457                }
13458            }
13459        }
13460    }
13461
13462    boolean isUserRestricted(int userId, String restrictionKey) {
13463        Bundle restrictions = sUserManager.getUserRestrictions(userId);
13464        if (restrictions.getBoolean(restrictionKey, false)) {
13465            Log.w(TAG, "User is restricted: " + restrictionKey);
13466            return true;
13467        }
13468        return false;
13469    }
13470
13471    @Override
13472    public String[] setPackagesSuspendedAsUser(String[] packageNames, boolean suspended,
13473            int userId) {
13474        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
13475        enforceCrossUserPermission(Binder.getCallingUid(), userId,
13476                true /* requireFullPermission */, true /* checkShell */,
13477                "setPackagesSuspended for user " + userId);
13478
13479        if (ArrayUtils.isEmpty(packageNames)) {
13480            return packageNames;
13481        }
13482
13483        // List of package names for whom the suspended state has changed.
13484        List<String> changedPackages = new ArrayList<>(packageNames.length);
13485        // List of package names for whom the suspended state is not set as requested in this
13486        // method.
13487        List<String> unactionedPackages = new ArrayList<>(packageNames.length);
13488        long callingId = Binder.clearCallingIdentity();
13489        try {
13490            for (int i = 0; i < packageNames.length; i++) {
13491                String packageName = packageNames[i];
13492                boolean changed = false;
13493                final int appId;
13494                synchronized (mPackages) {
13495                    final PackageSetting pkgSetting = mSettings.mPackages.get(packageName);
13496                    if (pkgSetting == null) {
13497                        Slog.w(TAG, "Could not find package setting for package \"" + packageName
13498                                + "\". Skipping suspending/un-suspending.");
13499                        unactionedPackages.add(packageName);
13500                        continue;
13501                    }
13502                    appId = pkgSetting.appId;
13503                    if (pkgSetting.getSuspended(userId) != suspended) {
13504                        if (!canSuspendPackageForUserLocked(packageName, userId)) {
13505                            unactionedPackages.add(packageName);
13506                            continue;
13507                        }
13508                        pkgSetting.setSuspended(suspended, userId);
13509                        mSettings.writePackageRestrictionsLPr(userId);
13510                        changed = true;
13511                        changedPackages.add(packageName);
13512                    }
13513                }
13514
13515                if (changed && suspended) {
13516                    killApplication(packageName, UserHandle.getUid(userId, appId),
13517                            "suspending package");
13518                }
13519            }
13520        } finally {
13521            Binder.restoreCallingIdentity(callingId);
13522        }
13523
13524        if (!changedPackages.isEmpty()) {
13525            sendPackagesSuspendedForUser(changedPackages.toArray(
13526                    new String[changedPackages.size()]), userId, suspended);
13527        }
13528
13529        return unactionedPackages.toArray(new String[unactionedPackages.size()]);
13530    }
13531
13532    @Override
13533    public boolean isPackageSuspendedForUser(String packageName, int userId) {
13534        enforceCrossUserPermission(Binder.getCallingUid(), userId,
13535                true /* requireFullPermission */, false /* checkShell */,
13536                "isPackageSuspendedForUser for user " + userId);
13537        synchronized (mPackages) {
13538            final PackageSetting pkgSetting = mSettings.mPackages.get(packageName);
13539            if (pkgSetting == null) {
13540                throw new IllegalArgumentException("Unknown target package: " + packageName);
13541            }
13542            return pkgSetting.getSuspended(userId);
13543        }
13544    }
13545
13546    private boolean canSuspendPackageForUserLocked(String packageName, int userId) {
13547        if (isPackageDeviceAdmin(packageName, userId)) {
13548            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
13549                    + "\": has an active device admin");
13550            return false;
13551        }
13552
13553        String activeLauncherPackageName = getActiveLauncherPackageName(userId);
13554        if (packageName.equals(activeLauncherPackageName)) {
13555            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
13556                    + "\": contains the active launcher");
13557            return false;
13558        }
13559
13560        if (packageName.equals(mRequiredInstallerPackage)) {
13561            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
13562                    + "\": required for package installation");
13563            return false;
13564        }
13565
13566        if (packageName.equals(mRequiredUninstallerPackage)) {
13567            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
13568                    + "\": required for package uninstallation");
13569            return false;
13570        }
13571
13572        if (packageName.equals(mRequiredVerifierPackage)) {
13573            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
13574                    + "\": required for package verification");
13575            return false;
13576        }
13577
13578        if (packageName.equals(getDefaultDialerPackageName(userId))) {
13579            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
13580                    + "\": is the default dialer");
13581            return false;
13582        }
13583
13584        if (mProtectedPackages.isPackageStateProtected(userId, packageName)) {
13585            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
13586                    + "\": protected package");
13587            return false;
13588        }
13589
13590        // Cannot suspend static shared libs as they are considered
13591        // a part of the using app (emulating static linking). Also
13592        // static libs are installed always on internal storage.
13593        PackageParser.Package pkg = mPackages.get(packageName);
13594        if (pkg != null && pkg.applicationInfo.isStaticSharedLibrary()) {
13595            Slog.w(TAG, "Cannot suspend package: " + packageName
13596                    + " providing static shared library: "
13597                    + pkg.staticSharedLibName);
13598            return false;
13599        }
13600
13601        return true;
13602    }
13603
13604    private String getActiveLauncherPackageName(int userId) {
13605        Intent intent = new Intent(Intent.ACTION_MAIN);
13606        intent.addCategory(Intent.CATEGORY_HOME);
13607        ResolveInfo resolveInfo = resolveIntent(
13608                intent,
13609                intent.resolveTypeIfNeeded(mContext.getContentResolver()),
13610                PackageManager.MATCH_DEFAULT_ONLY,
13611                userId);
13612
13613        return resolveInfo == null ? null : resolveInfo.activityInfo.packageName;
13614    }
13615
13616    private String getDefaultDialerPackageName(int userId) {
13617        synchronized (mPackages) {
13618            return mSettings.getDefaultDialerPackageNameLPw(userId);
13619        }
13620    }
13621
13622    @Override
13623    public void verifyPendingInstall(int id, int verificationCode) throws RemoteException {
13624        mContext.enforceCallingOrSelfPermission(
13625                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
13626                "Only package verification agents can verify applications");
13627
13628        final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED);
13629        final PackageVerificationResponse response = new PackageVerificationResponse(
13630                verificationCode, Binder.getCallingUid());
13631        msg.arg1 = id;
13632        msg.obj = response;
13633        mHandler.sendMessage(msg);
13634    }
13635
13636    @Override
13637    public void extendVerificationTimeout(int id, int verificationCodeAtTimeout,
13638            long millisecondsToDelay) {
13639        mContext.enforceCallingOrSelfPermission(
13640                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
13641                "Only package verification agents can extend verification timeouts");
13642
13643        final PackageVerificationState state = mPendingVerification.get(id);
13644        final PackageVerificationResponse response = new PackageVerificationResponse(
13645                verificationCodeAtTimeout, Binder.getCallingUid());
13646
13647        if (millisecondsToDelay > PackageManager.MAXIMUM_VERIFICATION_TIMEOUT) {
13648            millisecondsToDelay = PackageManager.MAXIMUM_VERIFICATION_TIMEOUT;
13649        }
13650        if (millisecondsToDelay < 0) {
13651            millisecondsToDelay = 0;
13652        }
13653        if ((verificationCodeAtTimeout != PackageManager.VERIFICATION_ALLOW)
13654                && (verificationCodeAtTimeout != PackageManager.VERIFICATION_REJECT)) {
13655            verificationCodeAtTimeout = PackageManager.VERIFICATION_REJECT;
13656        }
13657
13658        if ((state != null) && !state.timeoutExtended()) {
13659            state.extendTimeout();
13660
13661            final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED);
13662            msg.arg1 = id;
13663            msg.obj = response;
13664            mHandler.sendMessageDelayed(msg, millisecondsToDelay);
13665        }
13666    }
13667
13668    private void broadcastPackageVerified(int verificationId, Uri packageUri,
13669            int verificationCode, UserHandle user) {
13670        final Intent intent = new Intent(Intent.ACTION_PACKAGE_VERIFIED);
13671        intent.setDataAndType(packageUri, PACKAGE_MIME_TYPE);
13672        intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
13673        intent.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId);
13674        intent.putExtra(PackageManager.EXTRA_VERIFICATION_RESULT, verificationCode);
13675
13676        mContext.sendBroadcastAsUser(intent, user,
13677                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT);
13678    }
13679
13680    private ComponentName matchComponentForVerifier(String packageName,
13681            List<ResolveInfo> receivers) {
13682        ActivityInfo targetReceiver = null;
13683
13684        final int NR = receivers.size();
13685        for (int i = 0; i < NR; i++) {
13686            final ResolveInfo info = receivers.get(i);
13687            if (info.activityInfo == null) {
13688                continue;
13689            }
13690
13691            if (packageName.equals(info.activityInfo.packageName)) {
13692                targetReceiver = info.activityInfo;
13693                break;
13694            }
13695        }
13696
13697        if (targetReceiver == null) {
13698            return null;
13699        }
13700
13701        return new ComponentName(targetReceiver.packageName, targetReceiver.name);
13702    }
13703
13704    private List<ComponentName> matchVerifiers(PackageInfoLite pkgInfo,
13705            List<ResolveInfo> receivers, final PackageVerificationState verificationState) {
13706        if (pkgInfo.verifiers.length == 0) {
13707            return null;
13708        }
13709
13710        final int N = pkgInfo.verifiers.length;
13711        final List<ComponentName> sufficientVerifiers = new ArrayList<ComponentName>(N + 1);
13712        for (int i = 0; i < N; i++) {
13713            final VerifierInfo verifierInfo = pkgInfo.verifiers[i];
13714
13715            final ComponentName comp = matchComponentForVerifier(verifierInfo.packageName,
13716                    receivers);
13717            if (comp == null) {
13718                continue;
13719            }
13720
13721            final int verifierUid = getUidForVerifier(verifierInfo);
13722            if (verifierUid == -1) {
13723                continue;
13724            }
13725
13726            if (DEBUG_VERIFY) {
13727                Slog.d(TAG, "Added sufficient verifier " + verifierInfo.packageName
13728                        + " with the correct signature");
13729            }
13730            sufficientVerifiers.add(comp);
13731            verificationState.addSufficientVerifier(verifierUid);
13732        }
13733
13734        return sufficientVerifiers;
13735    }
13736
13737    private int getUidForVerifier(VerifierInfo verifierInfo) {
13738        synchronized (mPackages) {
13739            final PackageParser.Package pkg = mPackages.get(verifierInfo.packageName);
13740            if (pkg == null) {
13741                return -1;
13742            } else if (pkg.mSignatures.length != 1) {
13743                Slog.i(TAG, "Verifier package " + verifierInfo.packageName
13744                        + " has more than one signature; ignoring");
13745                return -1;
13746            }
13747
13748            /*
13749             * If the public key of the package's signature does not match
13750             * our expected public key, then this is a different package and
13751             * we should skip.
13752             */
13753
13754            final byte[] expectedPublicKey;
13755            try {
13756                final Signature verifierSig = pkg.mSignatures[0];
13757                final PublicKey publicKey = verifierSig.getPublicKey();
13758                expectedPublicKey = publicKey.getEncoded();
13759            } catch (CertificateException e) {
13760                return -1;
13761            }
13762
13763            final byte[] actualPublicKey = verifierInfo.publicKey.getEncoded();
13764
13765            if (!Arrays.equals(actualPublicKey, expectedPublicKey)) {
13766                Slog.i(TAG, "Verifier package " + verifierInfo.packageName
13767                        + " does not have the expected public key; ignoring");
13768                return -1;
13769            }
13770
13771            return pkg.applicationInfo.uid;
13772        }
13773    }
13774
13775    @Override
13776    public void finishPackageInstall(int token, boolean didLaunch) {
13777        enforceSystemOrRoot("Only the system is allowed to finish installs");
13778
13779        if (DEBUG_INSTALL) {
13780            Slog.v(TAG, "BM finishing package install for " + token);
13781        }
13782        Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "restore", token);
13783
13784        final Message msg = mHandler.obtainMessage(POST_INSTALL, token, didLaunch ? 1 : 0);
13785        mHandler.sendMessage(msg);
13786    }
13787
13788    /**
13789     * Get the verification agent timeout.
13790     *
13791     * @return verification timeout in milliseconds
13792     */
13793    private long getVerificationTimeout() {
13794        return android.provider.Settings.Global.getLong(mContext.getContentResolver(),
13795                android.provider.Settings.Global.PACKAGE_VERIFIER_TIMEOUT,
13796                DEFAULT_VERIFICATION_TIMEOUT);
13797    }
13798
13799    /**
13800     * Get the default verification agent response code.
13801     *
13802     * @return default verification response code
13803     */
13804    private int getDefaultVerificationResponse() {
13805        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
13806                android.provider.Settings.Global.PACKAGE_VERIFIER_DEFAULT_RESPONSE,
13807                DEFAULT_VERIFICATION_RESPONSE);
13808    }
13809
13810    /**
13811     * Check whether or not package verification has been enabled.
13812     *
13813     * @return true if verification should be performed
13814     */
13815    private boolean isVerificationEnabled(int userId, int installFlags) {
13816        if (!DEFAULT_VERIFY_ENABLE) {
13817            return false;
13818        }
13819        // Ephemeral apps don't get the full verification treatment
13820        if ((installFlags & PackageManager.INSTALL_INSTANT_APP) != 0) {
13821            if (DEBUG_EPHEMERAL) {
13822                Slog.d(TAG, "INSTALL_EPHEMERAL so skipping verification");
13823            }
13824            return false;
13825        }
13826
13827        boolean ensureVerifyAppsEnabled = isUserRestricted(userId, UserManager.ENSURE_VERIFY_APPS);
13828
13829        // Check if installing from ADB
13830        if ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0) {
13831            // Do not run verification in a test harness environment
13832            if (ActivityManager.isRunningInTestHarness()) {
13833                return false;
13834            }
13835            if (ensureVerifyAppsEnabled) {
13836                return true;
13837            }
13838            // Check if the developer does not want package verification for ADB installs
13839            if (android.provider.Settings.Global.getInt(mContext.getContentResolver(),
13840                    android.provider.Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB, 1) == 0) {
13841                return false;
13842            }
13843        }
13844
13845        if (ensureVerifyAppsEnabled) {
13846            return true;
13847        }
13848
13849        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
13850                android.provider.Settings.Global.PACKAGE_VERIFIER_ENABLE, 1) == 1;
13851    }
13852
13853    @Override
13854    public void verifyIntentFilter(int id, int verificationCode, List<String> failedDomains)
13855            throws RemoteException {
13856        mContext.enforceCallingOrSelfPermission(
13857                Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT,
13858                "Only intentfilter verification agents can verify applications");
13859
13860        final Message msg = mHandler.obtainMessage(INTENT_FILTER_VERIFIED);
13861        final IntentFilterVerificationResponse response = new IntentFilterVerificationResponse(
13862                Binder.getCallingUid(), verificationCode, failedDomains);
13863        msg.arg1 = id;
13864        msg.obj = response;
13865        mHandler.sendMessage(msg);
13866    }
13867
13868    @Override
13869    public int getIntentVerificationStatus(String packageName, int userId) {
13870        synchronized (mPackages) {
13871            return mSettings.getIntentFilterVerificationStatusLPr(packageName, userId);
13872        }
13873    }
13874
13875    @Override
13876    public boolean updateIntentVerificationStatus(String packageName, int status, int userId) {
13877        mContext.enforceCallingOrSelfPermission(
13878                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
13879
13880        boolean result = false;
13881        synchronized (mPackages) {
13882            result = mSettings.updateIntentFilterVerificationStatusLPw(packageName, status, userId);
13883        }
13884        if (result) {
13885            scheduleWritePackageRestrictionsLocked(userId);
13886        }
13887        return result;
13888    }
13889
13890    @Override
13891    public @NonNull ParceledListSlice<IntentFilterVerificationInfo> getIntentFilterVerifications(
13892            String packageName) {
13893        synchronized (mPackages) {
13894            return new ParceledListSlice<>(mSettings.getIntentFilterVerificationsLPr(packageName));
13895        }
13896    }
13897
13898    @Override
13899    public @NonNull ParceledListSlice<IntentFilter> getAllIntentFilters(String packageName) {
13900        if (TextUtils.isEmpty(packageName)) {
13901            return ParceledListSlice.emptyList();
13902        }
13903        synchronized (mPackages) {
13904            PackageParser.Package pkg = mPackages.get(packageName);
13905            if (pkg == null || pkg.activities == null) {
13906                return ParceledListSlice.emptyList();
13907            }
13908            final int count = pkg.activities.size();
13909            ArrayList<IntentFilter> result = new ArrayList<>();
13910            for (int n=0; n<count; n++) {
13911                PackageParser.Activity activity = pkg.activities.get(n);
13912                if (activity.intents != null && activity.intents.size() > 0) {
13913                    result.addAll(activity.intents);
13914                }
13915            }
13916            return new ParceledListSlice<>(result);
13917        }
13918    }
13919
13920    @Override
13921    public boolean setDefaultBrowserPackageName(String packageName, int userId) {
13922        mContext.enforceCallingOrSelfPermission(
13923                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
13924
13925        synchronized (mPackages) {
13926            boolean result = mSettings.setDefaultBrowserPackageNameLPw(packageName, userId);
13927            if (packageName != null) {
13928                result |= updateIntentVerificationStatus(packageName,
13929                        PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS,
13930                        userId);
13931                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultBrowserLPr(
13932                        packageName, userId);
13933            }
13934            return result;
13935        }
13936    }
13937
13938    @Override
13939    public String getDefaultBrowserPackageName(int userId) {
13940        synchronized (mPackages) {
13941            return mSettings.getDefaultBrowserPackageNameLPw(userId);
13942        }
13943    }
13944
13945    /**
13946     * Get the "allow unknown sources" setting.
13947     *
13948     * @return the current "allow unknown sources" setting
13949     */
13950    private int getUnknownSourcesSettings() {
13951        return android.provider.Settings.Secure.getInt(mContext.getContentResolver(),
13952                android.provider.Settings.Secure.INSTALL_NON_MARKET_APPS,
13953                -1);
13954    }
13955
13956    @Override
13957    public void setInstallerPackageName(String targetPackage, String installerPackageName) {
13958        final int uid = Binder.getCallingUid();
13959        // writer
13960        synchronized (mPackages) {
13961            PackageSetting targetPackageSetting = mSettings.mPackages.get(targetPackage);
13962            if (targetPackageSetting == null) {
13963                throw new IllegalArgumentException("Unknown target package: " + targetPackage);
13964            }
13965
13966            PackageSetting installerPackageSetting;
13967            if (installerPackageName != null) {
13968                installerPackageSetting = mSettings.mPackages.get(installerPackageName);
13969                if (installerPackageSetting == null) {
13970                    throw new IllegalArgumentException("Unknown installer package: "
13971                            + installerPackageName);
13972                }
13973            } else {
13974                installerPackageSetting = null;
13975            }
13976
13977            Signature[] callerSignature;
13978            Object obj = mSettings.getUserIdLPr(uid);
13979            if (obj != null) {
13980                if (obj instanceof SharedUserSetting) {
13981                    callerSignature = ((SharedUserSetting)obj).signatures.mSignatures;
13982                } else if (obj instanceof PackageSetting) {
13983                    callerSignature = ((PackageSetting)obj).signatures.mSignatures;
13984                } else {
13985                    throw new SecurityException("Bad object " + obj + " for uid " + uid);
13986                }
13987            } else {
13988                throw new SecurityException("Unknown calling UID: " + uid);
13989            }
13990
13991            // Verify: can't set installerPackageName to a package that is
13992            // not signed with the same cert as the caller.
13993            if (installerPackageSetting != null) {
13994                if (compareSignatures(callerSignature,
13995                        installerPackageSetting.signatures.mSignatures)
13996                        != PackageManager.SIGNATURE_MATCH) {
13997                    throw new SecurityException(
13998                            "Caller does not have same cert as new installer package "
13999                            + installerPackageName);
14000                }
14001            }
14002
14003            // Verify: if target already has an installer package, it must
14004            // be signed with the same cert as the caller.
14005            if (targetPackageSetting.installerPackageName != null) {
14006                PackageSetting setting = mSettings.mPackages.get(
14007                        targetPackageSetting.installerPackageName);
14008                // If the currently set package isn't valid, then it's always
14009                // okay to change it.
14010                if (setting != null) {
14011                    if (compareSignatures(callerSignature,
14012                            setting.signatures.mSignatures)
14013                            != PackageManager.SIGNATURE_MATCH) {
14014                        throw new SecurityException(
14015                                "Caller does not have same cert as old installer package "
14016                                + targetPackageSetting.installerPackageName);
14017                    }
14018                }
14019            }
14020
14021            // Okay!
14022            targetPackageSetting.installerPackageName = installerPackageName;
14023            if (installerPackageName != null) {
14024                mSettings.mInstallerPackages.add(installerPackageName);
14025            }
14026            scheduleWriteSettingsLocked();
14027        }
14028    }
14029
14030    @Override
14031    public void setApplicationCategoryHint(String packageName, int categoryHint,
14032            String callerPackageName) {
14033        mContext.getSystemService(AppOpsManager.class).checkPackage(Binder.getCallingUid(),
14034                callerPackageName);
14035        synchronized (mPackages) {
14036            PackageSetting ps = mSettings.mPackages.get(packageName);
14037            if (ps == null) {
14038                throw new IllegalArgumentException("Unknown target package " + packageName);
14039            }
14040
14041            if (!Objects.equals(callerPackageName, ps.installerPackageName)) {
14042                throw new IllegalArgumentException("Calling package " + callerPackageName
14043                        + " is not installer for " + packageName);
14044            }
14045
14046            if (ps.categoryHint != categoryHint) {
14047                ps.categoryHint = categoryHint;
14048                scheduleWriteSettingsLocked();
14049            }
14050        }
14051    }
14052
14053    private void processPendingInstall(final InstallArgs args, final int currentStatus) {
14054        // Queue up an async operation since the package installation may take a little while.
14055        mHandler.post(new Runnable() {
14056            public void run() {
14057                mHandler.removeCallbacks(this);
14058                 // Result object to be returned
14059                PackageInstalledInfo res = new PackageInstalledInfo();
14060                res.setReturnCode(currentStatus);
14061                res.uid = -1;
14062                res.pkg = null;
14063                res.removedInfo = null;
14064                if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
14065                    args.doPreInstall(res.returnCode);
14066                    synchronized (mInstallLock) {
14067                        installPackageTracedLI(args, res);
14068                    }
14069                    args.doPostInstall(res.returnCode, res.uid);
14070                }
14071
14072                // A restore should be performed at this point if (a) the install
14073                // succeeded, (b) the operation is not an update, and (c) the new
14074                // package has not opted out of backup participation.
14075                final boolean update = res.removedInfo != null
14076                        && res.removedInfo.removedPackage != null;
14077                final int flags = (res.pkg == null) ? 0 : res.pkg.applicationInfo.flags;
14078                boolean doRestore = !update
14079                        && ((flags & ApplicationInfo.FLAG_ALLOW_BACKUP) != 0);
14080
14081                // Set up the post-install work request bookkeeping.  This will be used
14082                // and cleaned up by the post-install event handling regardless of whether
14083                // there's a restore pass performed.  Token values are >= 1.
14084                int token;
14085                if (mNextInstallToken < 0) mNextInstallToken = 1;
14086                token = mNextInstallToken++;
14087
14088                PostInstallData data = new PostInstallData(args, res);
14089                mRunningInstalls.put(token, data);
14090                if (DEBUG_INSTALL) Log.v(TAG, "+ starting restore round-trip " + token);
14091
14092                if (res.returnCode == PackageManager.INSTALL_SUCCEEDED && doRestore) {
14093                    // Pass responsibility to the Backup Manager.  It will perform a
14094                    // restore if appropriate, then pass responsibility back to the
14095                    // Package Manager to run the post-install observer callbacks
14096                    // and broadcasts.
14097                    IBackupManager bm = IBackupManager.Stub.asInterface(
14098                            ServiceManager.getService(Context.BACKUP_SERVICE));
14099                    if (bm != null) {
14100                        if (DEBUG_INSTALL) Log.v(TAG, "token " + token
14101                                + " to BM for possible restore");
14102                        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "restore", token);
14103                        try {
14104                            // TODO: http://b/22388012
14105                            if (bm.isBackupServiceActive(UserHandle.USER_SYSTEM)) {
14106                                bm.restoreAtInstall(res.pkg.applicationInfo.packageName, token);
14107                            } else {
14108                                doRestore = false;
14109                            }
14110                        } catch (RemoteException e) {
14111                            // can't happen; the backup manager is local
14112                        } catch (Exception e) {
14113                            Slog.e(TAG, "Exception trying to enqueue restore", e);
14114                            doRestore = false;
14115                        }
14116                    } else {
14117                        Slog.e(TAG, "Backup Manager not found!");
14118                        doRestore = false;
14119                    }
14120                }
14121
14122                if (!doRestore) {
14123                    // No restore possible, or the Backup Manager was mysteriously not
14124                    // available -- just fire the post-install work request directly.
14125                    if (DEBUG_INSTALL) Log.v(TAG, "No restore - queue post-install for " + token);
14126
14127                    Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "postInstall", token);
14128
14129                    Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0);
14130                    mHandler.sendMessage(msg);
14131                }
14132            }
14133        });
14134    }
14135
14136    /**
14137     * Callback from PackageSettings whenever an app is first transitioned out of the
14138     * 'stopped' state.  Normally we just issue the broadcast, but we can't do that if
14139     * the app was "launched" for a restoreAtInstall operation.  Therefore we check
14140     * here whether the app is the target of an ongoing install, and only send the
14141     * broadcast immediately if it is not in that state.  If it *is* undergoing a restore,
14142     * the first-launch broadcast will be sent implicitly on that basis in POST_INSTALL
14143     * handling.
14144     */
14145    void notifyFirstLaunch(final String pkgName, final String installerPackage, final int userId) {
14146        // Serialize this with the rest of the install-process message chain.  In the
14147        // restore-at-install case, this Runnable will necessarily run before the
14148        // POST_INSTALL message is processed, so the contents of mRunningInstalls
14149        // are coherent.  In the non-restore case, the app has already completed install
14150        // and been launched through some other means, so it is not in a problematic
14151        // state for observers to see the FIRST_LAUNCH signal.
14152        mHandler.post(new Runnable() {
14153            @Override
14154            public void run() {
14155                for (int i = 0; i < mRunningInstalls.size(); i++) {
14156                    final PostInstallData data = mRunningInstalls.valueAt(i);
14157                    if (data.res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
14158                        continue;
14159                    }
14160                    if (pkgName.equals(data.res.pkg.applicationInfo.packageName)) {
14161                        // right package; but is it for the right user?
14162                        for (int uIndex = 0; uIndex < data.res.newUsers.length; uIndex++) {
14163                            if (userId == data.res.newUsers[uIndex]) {
14164                                if (DEBUG_BACKUP) {
14165                                    Slog.i(TAG, "Package " + pkgName
14166                                            + " being restored so deferring FIRST_LAUNCH");
14167                                }
14168                                return;
14169                            }
14170                        }
14171                    }
14172                }
14173                // didn't find it, so not being restored
14174                if (DEBUG_BACKUP) {
14175                    Slog.i(TAG, "Package " + pkgName + " sending normal FIRST_LAUNCH");
14176                }
14177                sendFirstLaunchBroadcast(pkgName, installerPackage, new int[] {userId});
14178            }
14179        });
14180    }
14181
14182    private void sendFirstLaunchBroadcast(String pkgName, String installerPkg, int[] userIds) {
14183        sendPackageBroadcast(Intent.ACTION_PACKAGE_FIRST_LAUNCH, pkgName, null, 0,
14184                installerPkg, null, userIds);
14185    }
14186
14187    private abstract class HandlerParams {
14188        private static final int MAX_RETRIES = 4;
14189
14190        /**
14191         * Number of times startCopy() has been attempted and had a non-fatal
14192         * error.
14193         */
14194        private int mRetries = 0;
14195
14196        /** User handle for the user requesting the information or installation. */
14197        private final UserHandle mUser;
14198        String traceMethod;
14199        int traceCookie;
14200
14201        HandlerParams(UserHandle user) {
14202            mUser = user;
14203        }
14204
14205        UserHandle getUser() {
14206            return mUser;
14207        }
14208
14209        HandlerParams setTraceMethod(String traceMethod) {
14210            this.traceMethod = traceMethod;
14211            return this;
14212        }
14213
14214        HandlerParams setTraceCookie(int traceCookie) {
14215            this.traceCookie = traceCookie;
14216            return this;
14217        }
14218
14219        final boolean startCopy() {
14220            boolean res;
14221            try {
14222                if (DEBUG_INSTALL) Slog.i(TAG, "startCopy " + mUser + ": " + this);
14223
14224                if (++mRetries > MAX_RETRIES) {
14225                    Slog.w(TAG, "Failed to invoke remote methods on default container service. Giving up");
14226                    mHandler.sendEmptyMessage(MCS_GIVE_UP);
14227                    handleServiceError();
14228                    return false;
14229                } else {
14230                    handleStartCopy();
14231                    res = true;
14232                }
14233            } catch (RemoteException e) {
14234                if (DEBUG_INSTALL) Slog.i(TAG, "Posting install MCS_RECONNECT");
14235                mHandler.sendEmptyMessage(MCS_RECONNECT);
14236                res = false;
14237            }
14238            handleReturnCode();
14239            return res;
14240        }
14241
14242        final void serviceError() {
14243            if (DEBUG_INSTALL) Slog.i(TAG, "serviceError");
14244            handleServiceError();
14245            handleReturnCode();
14246        }
14247
14248        abstract void handleStartCopy() throws RemoteException;
14249        abstract void handleServiceError();
14250        abstract void handleReturnCode();
14251    }
14252
14253    private static void clearDirectory(IMediaContainerService mcs, File[] paths) {
14254        for (File path : paths) {
14255            try {
14256                mcs.clearDirectory(path.getAbsolutePath());
14257            } catch (RemoteException e) {
14258            }
14259        }
14260    }
14261
14262    static class OriginInfo {
14263        /**
14264         * Location where install is coming from, before it has been
14265         * copied/renamed into place. This could be a single monolithic APK
14266         * file, or a cluster directory. This location may be untrusted.
14267         */
14268        final File file;
14269        final String cid;
14270
14271        /**
14272         * Flag indicating that {@link #file} or {@link #cid} has already been
14273         * staged, meaning downstream users don't need to defensively copy the
14274         * contents.
14275         */
14276        final boolean staged;
14277
14278        /**
14279         * Flag indicating that {@link #file} or {@link #cid} is an already
14280         * installed app that is being moved.
14281         */
14282        final boolean existing;
14283
14284        final String resolvedPath;
14285        final File resolvedFile;
14286
14287        static OriginInfo fromNothing() {
14288            return new OriginInfo(null, null, false, false);
14289        }
14290
14291        static OriginInfo fromUntrustedFile(File file) {
14292            return new OriginInfo(file, null, false, false);
14293        }
14294
14295        static OriginInfo fromExistingFile(File file) {
14296            return new OriginInfo(file, null, false, true);
14297        }
14298
14299        static OriginInfo fromStagedFile(File file) {
14300            return new OriginInfo(file, null, true, false);
14301        }
14302
14303        static OriginInfo fromStagedContainer(String cid) {
14304            return new OriginInfo(null, cid, true, false);
14305        }
14306
14307        private OriginInfo(File file, String cid, boolean staged, boolean existing) {
14308            this.file = file;
14309            this.cid = cid;
14310            this.staged = staged;
14311            this.existing = existing;
14312
14313            if (cid != null) {
14314                resolvedPath = PackageHelper.getSdDir(cid);
14315                resolvedFile = new File(resolvedPath);
14316            } else if (file != null) {
14317                resolvedPath = file.getAbsolutePath();
14318                resolvedFile = file;
14319            } else {
14320                resolvedPath = null;
14321                resolvedFile = null;
14322            }
14323        }
14324    }
14325
14326    static class MoveInfo {
14327        final int moveId;
14328        final String fromUuid;
14329        final String toUuid;
14330        final String packageName;
14331        final String dataAppName;
14332        final int appId;
14333        final String seinfo;
14334        final int targetSdkVersion;
14335
14336        public MoveInfo(int moveId, String fromUuid, String toUuid, String packageName,
14337                String dataAppName, int appId, String seinfo, int targetSdkVersion) {
14338            this.moveId = moveId;
14339            this.fromUuid = fromUuid;
14340            this.toUuid = toUuid;
14341            this.packageName = packageName;
14342            this.dataAppName = dataAppName;
14343            this.appId = appId;
14344            this.seinfo = seinfo;
14345            this.targetSdkVersion = targetSdkVersion;
14346        }
14347    }
14348
14349    static class VerificationInfo {
14350        /** A constant used to indicate that a uid value is not present. */
14351        public static final int NO_UID = -1;
14352
14353        /** URI referencing where the package was downloaded from. */
14354        final Uri originatingUri;
14355
14356        /** HTTP referrer URI associated with the originatingURI. */
14357        final Uri referrer;
14358
14359        /** UID of the application that the install request originated from. */
14360        final int originatingUid;
14361
14362        /** UID of application requesting the install */
14363        final int installerUid;
14364
14365        VerificationInfo(Uri originatingUri, Uri referrer, int originatingUid, int installerUid) {
14366            this.originatingUri = originatingUri;
14367            this.referrer = referrer;
14368            this.originatingUid = originatingUid;
14369            this.installerUid = installerUid;
14370        }
14371    }
14372
14373    class InstallParams extends HandlerParams {
14374        final OriginInfo origin;
14375        final MoveInfo move;
14376        final IPackageInstallObserver2 observer;
14377        int installFlags;
14378        final String installerPackageName;
14379        final String volumeUuid;
14380        private InstallArgs mArgs;
14381        private int mRet;
14382        final String packageAbiOverride;
14383        final String[] grantedRuntimePermissions;
14384        final VerificationInfo verificationInfo;
14385        final Certificate[][] certificates;
14386        final int installReason;
14387
14388        InstallParams(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer,
14389                int installFlags, String installerPackageName, String volumeUuid,
14390                VerificationInfo verificationInfo, UserHandle user, String packageAbiOverride,
14391                String[] grantedPermissions, Certificate[][] certificates, int installReason) {
14392            super(user);
14393            this.origin = origin;
14394            this.move = move;
14395            this.observer = observer;
14396            this.installFlags = installFlags;
14397            this.installerPackageName = installerPackageName;
14398            this.volumeUuid = volumeUuid;
14399            this.verificationInfo = verificationInfo;
14400            this.packageAbiOverride = packageAbiOverride;
14401            this.grantedRuntimePermissions = grantedPermissions;
14402            this.certificates = certificates;
14403            this.installReason = installReason;
14404        }
14405
14406        @Override
14407        public String toString() {
14408            return "InstallParams{" + Integer.toHexString(System.identityHashCode(this))
14409                    + " file=" + origin.file + " cid=" + origin.cid + "}";
14410        }
14411
14412        private int installLocationPolicy(PackageInfoLite pkgLite) {
14413            String packageName = pkgLite.packageName;
14414            int installLocation = pkgLite.installLocation;
14415            boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
14416            // reader
14417            synchronized (mPackages) {
14418                // Currently installed package which the new package is attempting to replace or
14419                // null if no such package is installed.
14420                PackageParser.Package installedPkg = mPackages.get(packageName);
14421                // Package which currently owns the data which the new package will own if installed.
14422                // If an app is unstalled while keeping data (e.g., adb uninstall -k), installedPkg
14423                // will be null whereas dataOwnerPkg will contain information about the package
14424                // which was uninstalled while keeping its data.
14425                PackageParser.Package dataOwnerPkg = installedPkg;
14426                if (dataOwnerPkg  == null) {
14427                    PackageSetting ps = mSettings.mPackages.get(packageName);
14428                    if (ps != null) {
14429                        dataOwnerPkg = ps.pkg;
14430                    }
14431                }
14432
14433                if (dataOwnerPkg != null) {
14434                    // If installed, the package will get access to data left on the device by its
14435                    // predecessor. As a security measure, this is permited only if this is not a
14436                    // version downgrade or if the predecessor package is marked as debuggable and
14437                    // a downgrade is explicitly requested.
14438                    //
14439                    // On debuggable platform builds, downgrades are permitted even for
14440                    // non-debuggable packages to make testing easier. Debuggable platform builds do
14441                    // not offer security guarantees and thus it's OK to disable some security
14442                    // mechanisms to make debugging/testing easier on those builds. However, even on
14443                    // debuggable builds downgrades of packages are permitted only if requested via
14444                    // installFlags. This is because we aim to keep the behavior of debuggable
14445                    // platform builds as close as possible to the behavior of non-debuggable
14446                    // platform builds.
14447                    final boolean downgradeRequested =
14448                            (installFlags & PackageManager.INSTALL_ALLOW_DOWNGRADE) != 0;
14449                    final boolean packageDebuggable =
14450                                (dataOwnerPkg.applicationInfo.flags
14451                                        & ApplicationInfo.FLAG_DEBUGGABLE) != 0;
14452                    final boolean downgradePermitted =
14453                            (downgradeRequested) && ((Build.IS_DEBUGGABLE) || (packageDebuggable));
14454                    if (!downgradePermitted) {
14455                        try {
14456                            checkDowngrade(dataOwnerPkg, pkgLite);
14457                        } catch (PackageManagerException e) {
14458                            Slog.w(TAG, "Downgrade detected: " + e.getMessage());
14459                            return PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE;
14460                        }
14461                    }
14462                }
14463
14464                if (installedPkg != null) {
14465                    if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
14466                        // Check for updated system application.
14467                        if ((installedPkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
14468                            if (onSd) {
14469                                Slog.w(TAG, "Cannot install update to system app on sdcard");
14470                                return PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION;
14471                            }
14472                            return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
14473                        } else {
14474                            if (onSd) {
14475                                // Install flag overrides everything.
14476                                return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
14477                            }
14478                            // If current upgrade specifies particular preference
14479                            if (installLocation == PackageInfo.INSTALL_LOCATION_INTERNAL_ONLY) {
14480                                // Application explicitly specified internal.
14481                                return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
14482                            } else if (installLocation == PackageInfo.INSTALL_LOCATION_PREFER_EXTERNAL) {
14483                                // App explictly prefers external. Let policy decide
14484                            } else {
14485                                // Prefer previous location
14486                                if (isExternal(installedPkg)) {
14487                                    return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
14488                                }
14489                                return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
14490                            }
14491                        }
14492                    } else {
14493                        // Invalid install. Return error code
14494                        return PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS;
14495                    }
14496                }
14497            }
14498            // All the special cases have been taken care of.
14499            // Return result based on recommended install location.
14500            if (onSd) {
14501                return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
14502            }
14503            return pkgLite.recommendedInstallLocation;
14504        }
14505
14506        /*
14507         * Invoke remote method to get package information and install
14508         * location values. Override install location based on default
14509         * policy if needed and then create install arguments based
14510         * on the install location.
14511         */
14512        public void handleStartCopy() throws RemoteException {
14513            int ret = PackageManager.INSTALL_SUCCEEDED;
14514
14515            // If we're already staged, we've firmly committed to an install location
14516            if (origin.staged) {
14517                if (origin.file != null) {
14518                    installFlags |= PackageManager.INSTALL_INTERNAL;
14519                    installFlags &= ~PackageManager.INSTALL_EXTERNAL;
14520                } else if (origin.cid != null) {
14521                    installFlags |= PackageManager.INSTALL_EXTERNAL;
14522                    installFlags &= ~PackageManager.INSTALL_INTERNAL;
14523                } else {
14524                    throw new IllegalStateException("Invalid stage location");
14525                }
14526            }
14527
14528            final boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
14529            final boolean onInt = (installFlags & PackageManager.INSTALL_INTERNAL) != 0;
14530            final boolean ephemeral = (installFlags & PackageManager.INSTALL_INSTANT_APP) != 0;
14531            PackageInfoLite pkgLite = null;
14532
14533            if (onInt && onSd) {
14534                // Check if both bits are set.
14535                Slog.w(TAG, "Conflicting flags specified for installing on both internal and external");
14536                ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
14537            } else if (onSd && ephemeral) {
14538                Slog.w(TAG,  "Conflicting flags specified for installing ephemeral on external");
14539                ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
14540            } else {
14541                pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, installFlags,
14542                        packageAbiOverride);
14543
14544                if (DEBUG_EPHEMERAL && ephemeral) {
14545                    Slog.v(TAG, "pkgLite for install: " + pkgLite);
14546                }
14547
14548                /*
14549                 * If we have too little free space, try to free cache
14550                 * before giving up.
14551                 */
14552                if (!origin.staged && pkgLite.recommendedInstallLocation
14553                        == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) {
14554                    // TODO: focus freeing disk space on the target device
14555                    final StorageManager storage = StorageManager.from(mContext);
14556                    final long lowThreshold = storage.getStorageLowBytes(
14557                            Environment.getDataDirectory());
14558
14559                    final long sizeBytes = mContainerService.calculateInstalledSize(
14560                            origin.resolvedPath, isForwardLocked(), packageAbiOverride);
14561
14562                    try {
14563                        mInstaller.freeCache(null, sizeBytes + lowThreshold, 0);
14564                        pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath,
14565                                installFlags, packageAbiOverride);
14566                    } catch (InstallerException e) {
14567                        Slog.w(TAG, "Failed to free cache", e);
14568                    }
14569
14570                    /*
14571                     * The cache free must have deleted the file we
14572                     * downloaded to install.
14573                     *
14574                     * TODO: fix the "freeCache" call to not delete
14575                     *       the file we care about.
14576                     */
14577                    if (pkgLite.recommendedInstallLocation
14578                            == PackageHelper.RECOMMEND_FAILED_INVALID_URI) {
14579                        pkgLite.recommendedInstallLocation
14580                            = PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE;
14581                    }
14582                }
14583            }
14584
14585            if (ret == PackageManager.INSTALL_SUCCEEDED) {
14586                int loc = pkgLite.recommendedInstallLocation;
14587                if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION) {
14588                    ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
14589                } else if (loc == PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS) {
14590                    ret = PackageManager.INSTALL_FAILED_ALREADY_EXISTS;
14591                } else if (loc == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) {
14592                    ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
14593                } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_APK) {
14594                    ret = PackageManager.INSTALL_FAILED_INVALID_APK;
14595                } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_URI) {
14596                    ret = PackageManager.INSTALL_FAILED_INVALID_URI;
14597                } else if (loc == PackageHelper.RECOMMEND_MEDIA_UNAVAILABLE) {
14598                    ret = PackageManager.INSTALL_FAILED_MEDIA_UNAVAILABLE;
14599                } else {
14600                    // Override with defaults if needed.
14601                    loc = installLocationPolicy(pkgLite);
14602                    if (loc == PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE) {
14603                        ret = PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE;
14604                    } else if (!onSd && !onInt) {
14605                        // Override install location with flags
14606                        if (loc == PackageHelper.RECOMMEND_INSTALL_EXTERNAL) {
14607                            // Set the flag to install on external media.
14608                            installFlags |= PackageManager.INSTALL_EXTERNAL;
14609                            installFlags &= ~PackageManager.INSTALL_INTERNAL;
14610                        } else if (loc == PackageHelper.RECOMMEND_INSTALL_EPHEMERAL) {
14611                            if (DEBUG_EPHEMERAL) {
14612                                Slog.v(TAG, "...setting INSTALL_EPHEMERAL install flag");
14613                            }
14614                            installFlags |= PackageManager.INSTALL_INSTANT_APP;
14615                            installFlags &= ~(PackageManager.INSTALL_EXTERNAL
14616                                    |PackageManager.INSTALL_INTERNAL);
14617                        } else {
14618                            // Make sure the flag for installing on external
14619                            // media is unset
14620                            installFlags |= PackageManager.INSTALL_INTERNAL;
14621                            installFlags &= ~PackageManager.INSTALL_EXTERNAL;
14622                        }
14623                    }
14624                }
14625            }
14626
14627            final InstallArgs args = createInstallArgs(this);
14628            mArgs = args;
14629
14630            if (ret == PackageManager.INSTALL_SUCCEEDED) {
14631                // TODO: http://b/22976637
14632                // Apps installed for "all" users use the device owner to verify the app
14633                UserHandle verifierUser = getUser();
14634                if (verifierUser == UserHandle.ALL) {
14635                    verifierUser = UserHandle.SYSTEM;
14636                }
14637
14638                /*
14639                 * Determine if we have any installed package verifiers. If we
14640                 * do, then we'll defer to them to verify the packages.
14641                 */
14642                final int requiredUid = mRequiredVerifierPackage == null ? -1
14643                        : getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING,
14644                                verifierUser.getIdentifier());
14645                if (!origin.existing && requiredUid != -1
14646                        && isVerificationEnabled(verifierUser.getIdentifier(), installFlags)) {
14647                    final Intent verification = new Intent(
14648                            Intent.ACTION_PACKAGE_NEEDS_VERIFICATION);
14649                    verification.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
14650                    verification.setDataAndType(Uri.fromFile(new File(origin.resolvedPath)),
14651                            PACKAGE_MIME_TYPE);
14652                    verification.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
14653
14654                    // Query all live verifiers based on current user state
14655                    final List<ResolveInfo> receivers = queryIntentReceiversInternal(verification,
14656                            PACKAGE_MIME_TYPE, 0, verifierUser.getIdentifier());
14657
14658                    if (DEBUG_VERIFY) {
14659                        Slog.d(TAG, "Found " + receivers.size() + " verifiers for intent "
14660                                + verification.toString() + " with " + pkgLite.verifiers.length
14661                                + " optional verifiers");
14662                    }
14663
14664                    final int verificationId = mPendingVerificationToken++;
14665
14666                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId);
14667
14668                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_PACKAGE,
14669                            installerPackageName);
14670
14671                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALL_FLAGS,
14672                            installFlags);
14673
14674                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_PACKAGE_NAME,
14675                            pkgLite.packageName);
14676
14677                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_VERSION_CODE,
14678                            pkgLite.versionCode);
14679
14680                    if (verificationInfo != null) {
14681                        if (verificationInfo.originatingUri != null) {
14682                            verification.putExtra(Intent.EXTRA_ORIGINATING_URI,
14683                                    verificationInfo.originatingUri);
14684                        }
14685                        if (verificationInfo.referrer != null) {
14686                            verification.putExtra(Intent.EXTRA_REFERRER,
14687                                    verificationInfo.referrer);
14688                        }
14689                        if (verificationInfo.originatingUid >= 0) {
14690                            verification.putExtra(Intent.EXTRA_ORIGINATING_UID,
14691                                    verificationInfo.originatingUid);
14692                        }
14693                        if (verificationInfo.installerUid >= 0) {
14694                            verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_UID,
14695                                    verificationInfo.installerUid);
14696                        }
14697                    }
14698
14699                    final PackageVerificationState verificationState = new PackageVerificationState(
14700                            requiredUid, args);
14701
14702                    mPendingVerification.append(verificationId, verificationState);
14703
14704                    final List<ComponentName> sufficientVerifiers = matchVerifiers(pkgLite,
14705                            receivers, verificationState);
14706
14707                    DeviceIdleController.LocalService idleController = getDeviceIdleController();
14708                    final long idleDuration = getVerificationTimeout();
14709
14710                    /*
14711                     * If any sufficient verifiers were listed in the package
14712                     * manifest, attempt to ask them.
14713                     */
14714                    if (sufficientVerifiers != null) {
14715                        final int N = sufficientVerifiers.size();
14716                        if (N == 0) {
14717                            Slog.i(TAG, "Additional verifiers required, but none installed.");
14718                            ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
14719                        } else {
14720                            for (int i = 0; i < N; i++) {
14721                                final ComponentName verifierComponent = sufficientVerifiers.get(i);
14722                                idleController.addPowerSaveTempWhitelistApp(Process.myUid(),
14723                                        verifierComponent.getPackageName(), idleDuration,
14724                                        verifierUser.getIdentifier(), false, "package verifier");
14725
14726                                final Intent sufficientIntent = new Intent(verification);
14727                                sufficientIntent.setComponent(verifierComponent);
14728                                mContext.sendBroadcastAsUser(sufficientIntent, verifierUser);
14729                            }
14730                        }
14731                    }
14732
14733                    final ComponentName requiredVerifierComponent = matchComponentForVerifier(
14734                            mRequiredVerifierPackage, receivers);
14735                    if (ret == PackageManager.INSTALL_SUCCEEDED
14736                            && mRequiredVerifierPackage != null) {
14737                        Trace.asyncTraceBegin(
14738                                TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId);
14739                        /*
14740                         * Send the intent to the required verification agent,
14741                         * but only start the verification timeout after the
14742                         * target BroadcastReceivers have run.
14743                         */
14744                        verification.setComponent(requiredVerifierComponent);
14745                        idleController.addPowerSaveTempWhitelistApp(Process.myUid(),
14746                                requiredVerifierComponent.getPackageName(), idleDuration,
14747                                verifierUser.getIdentifier(), false, "package verifier");
14748                        mContext.sendOrderedBroadcastAsUser(verification, verifierUser,
14749                                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
14750                                new BroadcastReceiver() {
14751                                    @Override
14752                                    public void onReceive(Context context, Intent intent) {
14753                                        final Message msg = mHandler
14754                                                .obtainMessage(CHECK_PENDING_VERIFICATION);
14755                                        msg.arg1 = verificationId;
14756                                        mHandler.sendMessageDelayed(msg, getVerificationTimeout());
14757                                    }
14758                                }, null, 0, null, null);
14759
14760                        /*
14761                         * We don't want the copy to proceed until verification
14762                         * succeeds, so null out this field.
14763                         */
14764                        mArgs = null;
14765                    }
14766                } else {
14767                    /*
14768                     * No package verification is enabled, so immediately start
14769                     * the remote call to initiate copy using temporary file.
14770                     */
14771                    ret = args.copyApk(mContainerService, true);
14772                }
14773            }
14774
14775            mRet = ret;
14776        }
14777
14778        @Override
14779        void handleReturnCode() {
14780            // If mArgs is null, then MCS couldn't be reached. When it
14781            // reconnects, it will try again to install. At that point, this
14782            // will succeed.
14783            if (mArgs != null) {
14784                processPendingInstall(mArgs, mRet);
14785            }
14786        }
14787
14788        @Override
14789        void handleServiceError() {
14790            mArgs = createInstallArgs(this);
14791            mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
14792        }
14793
14794        public boolean isForwardLocked() {
14795            return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
14796        }
14797    }
14798
14799    /**
14800     * Used during creation of InstallArgs
14801     *
14802     * @param installFlags package installation flags
14803     * @return true if should be installed on external storage
14804     */
14805    private static boolean installOnExternalAsec(int installFlags) {
14806        if ((installFlags & PackageManager.INSTALL_INTERNAL) != 0) {
14807            return false;
14808        }
14809        if ((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) {
14810            return true;
14811        }
14812        return false;
14813    }
14814
14815    /**
14816     * Used during creation of InstallArgs
14817     *
14818     * @param installFlags package installation flags
14819     * @return true if should be installed as forward locked
14820     */
14821    private static boolean installForwardLocked(int installFlags) {
14822        return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
14823    }
14824
14825    private InstallArgs createInstallArgs(InstallParams params) {
14826        if (params.move != null) {
14827            return new MoveInstallArgs(params);
14828        } else if (installOnExternalAsec(params.installFlags) || params.isForwardLocked()) {
14829            return new AsecInstallArgs(params);
14830        } else {
14831            return new FileInstallArgs(params);
14832        }
14833    }
14834
14835    /**
14836     * Create args that describe an existing installed package. Typically used
14837     * when cleaning up old installs, or used as a move source.
14838     */
14839    private InstallArgs createInstallArgsForExisting(int installFlags, String codePath,
14840            String resourcePath, String[] instructionSets) {
14841        final boolean isInAsec;
14842        if (installOnExternalAsec(installFlags)) {
14843            /* Apps on SD card are always in ASEC containers. */
14844            isInAsec = true;
14845        } else if (installForwardLocked(installFlags)
14846                && !codePath.startsWith(mDrmAppPrivateInstallDir.getAbsolutePath())) {
14847            /*
14848             * Forward-locked apps are only in ASEC containers if they're the
14849             * new style
14850             */
14851            isInAsec = true;
14852        } else {
14853            isInAsec = false;
14854        }
14855
14856        if (isInAsec) {
14857            return new AsecInstallArgs(codePath, instructionSets,
14858                    installOnExternalAsec(installFlags), installForwardLocked(installFlags));
14859        } else {
14860            return new FileInstallArgs(codePath, resourcePath, instructionSets);
14861        }
14862    }
14863
14864    static abstract class InstallArgs {
14865        /** @see InstallParams#origin */
14866        final OriginInfo origin;
14867        /** @see InstallParams#move */
14868        final MoveInfo move;
14869
14870        final IPackageInstallObserver2 observer;
14871        // Always refers to PackageManager flags only
14872        final int installFlags;
14873        final String installerPackageName;
14874        final String volumeUuid;
14875        final UserHandle user;
14876        final String abiOverride;
14877        final String[] installGrantPermissions;
14878        /** If non-null, drop an async trace when the install completes */
14879        final String traceMethod;
14880        final int traceCookie;
14881        final Certificate[][] certificates;
14882        final int installReason;
14883
14884        // The list of instruction sets supported by this app. This is currently
14885        // only used during the rmdex() phase to clean up resources. We can get rid of this
14886        // if we move dex files under the common app path.
14887        /* nullable */ String[] instructionSets;
14888
14889        InstallArgs(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer,
14890                int installFlags, String installerPackageName, String volumeUuid,
14891                UserHandle user, String[] instructionSets,
14892                String abiOverride, String[] installGrantPermissions,
14893                String traceMethod, int traceCookie, Certificate[][] certificates,
14894                int installReason) {
14895            this.origin = origin;
14896            this.move = move;
14897            this.installFlags = installFlags;
14898            this.observer = observer;
14899            this.installerPackageName = installerPackageName;
14900            this.volumeUuid = volumeUuid;
14901            this.user = user;
14902            this.instructionSets = instructionSets;
14903            this.abiOverride = abiOverride;
14904            this.installGrantPermissions = installGrantPermissions;
14905            this.traceMethod = traceMethod;
14906            this.traceCookie = traceCookie;
14907            this.certificates = certificates;
14908            this.installReason = installReason;
14909        }
14910
14911        abstract int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException;
14912        abstract int doPreInstall(int status);
14913
14914        /**
14915         * Rename package into final resting place. All paths on the given
14916         * scanned package should be updated to reflect the rename.
14917         */
14918        abstract boolean doRename(int status, PackageParser.Package pkg, String oldCodePath);
14919        abstract int doPostInstall(int status, int uid);
14920
14921        /** @see PackageSettingBase#codePathString */
14922        abstract String getCodePath();
14923        /** @see PackageSettingBase#resourcePathString */
14924        abstract String getResourcePath();
14925
14926        // Need installer lock especially for dex file removal.
14927        abstract void cleanUpResourcesLI();
14928        abstract boolean doPostDeleteLI(boolean delete);
14929
14930        /**
14931         * Called before the source arguments are copied. This is used mostly
14932         * for MoveParams when it needs to read the source file to put it in the
14933         * destination.
14934         */
14935        int doPreCopy() {
14936            return PackageManager.INSTALL_SUCCEEDED;
14937        }
14938
14939        /**
14940         * Called after the source arguments are copied. This is used mostly for
14941         * MoveParams when it needs to read the source file to put it in the
14942         * destination.
14943         */
14944        int doPostCopy(int uid) {
14945            return PackageManager.INSTALL_SUCCEEDED;
14946        }
14947
14948        protected boolean isFwdLocked() {
14949            return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
14950        }
14951
14952        protected boolean isExternalAsec() {
14953            return (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
14954        }
14955
14956        protected boolean isEphemeral() {
14957            return (installFlags & PackageManager.INSTALL_INSTANT_APP) != 0;
14958        }
14959
14960        UserHandle getUser() {
14961            return user;
14962        }
14963    }
14964
14965    private void removeDexFiles(List<String> allCodePaths, String[] instructionSets) {
14966        if (!allCodePaths.isEmpty()) {
14967            if (instructionSets == null) {
14968                throw new IllegalStateException("instructionSet == null");
14969            }
14970            String[] dexCodeInstructionSets = getDexCodeInstructionSets(instructionSets);
14971            for (String codePath : allCodePaths) {
14972                for (String dexCodeInstructionSet : dexCodeInstructionSets) {
14973                    try {
14974                        mInstaller.rmdex(codePath, dexCodeInstructionSet);
14975                    } catch (InstallerException ignored) {
14976                    }
14977                }
14978            }
14979        }
14980    }
14981
14982    /**
14983     * Logic to handle installation of non-ASEC applications, including copying
14984     * and renaming logic.
14985     */
14986    class FileInstallArgs extends InstallArgs {
14987        private File codeFile;
14988        private File resourceFile;
14989
14990        // Example topology:
14991        // /data/app/com.example/base.apk
14992        // /data/app/com.example/split_foo.apk
14993        // /data/app/com.example/lib/arm/libfoo.so
14994        // /data/app/com.example/lib/arm64/libfoo.so
14995        // /data/app/com.example/dalvik/arm/base.apk@classes.dex
14996
14997        /** New install */
14998        FileInstallArgs(InstallParams params) {
14999            super(params.origin, params.move, params.observer, params.installFlags,
15000                    params.installerPackageName, params.volumeUuid,
15001                    params.getUser(), null /*instructionSets*/, params.packageAbiOverride,
15002                    params.grantedRuntimePermissions,
15003                    params.traceMethod, params.traceCookie, params.certificates,
15004                    params.installReason);
15005            if (isFwdLocked()) {
15006                throw new IllegalArgumentException("Forward locking only supported in ASEC");
15007            }
15008        }
15009
15010        /** Existing install */
15011        FileInstallArgs(String codePath, String resourcePath, String[] instructionSets) {
15012            super(OriginInfo.fromNothing(), null, null, 0, null, null, null, instructionSets,
15013                    null, null, null, 0, null /*certificates*/,
15014                    PackageManager.INSTALL_REASON_UNKNOWN);
15015            this.codeFile = (codePath != null) ? new File(codePath) : null;
15016            this.resourceFile = (resourcePath != null) ? new File(resourcePath) : null;
15017        }
15018
15019        int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
15020            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyApk");
15021            try {
15022                return doCopyApk(imcs, temp);
15023            } finally {
15024                Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
15025            }
15026        }
15027
15028        private int doCopyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
15029            if (origin.staged) {
15030                if (DEBUG_INSTALL) Slog.d(TAG, origin.file + " already staged; skipping copy");
15031                codeFile = origin.file;
15032                resourceFile = origin.file;
15033                return PackageManager.INSTALL_SUCCEEDED;
15034            }
15035
15036            try {
15037                final boolean isEphemeral = (installFlags & PackageManager.INSTALL_INSTANT_APP) != 0;
15038                final File tempDir =
15039                        mInstallerService.allocateStageDirLegacy(volumeUuid, isEphemeral);
15040                codeFile = tempDir;
15041                resourceFile = tempDir;
15042            } catch (IOException e) {
15043                Slog.w(TAG, "Failed to create copy file: " + e);
15044                return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
15045            }
15046
15047            final IParcelFileDescriptorFactory target = new IParcelFileDescriptorFactory.Stub() {
15048                @Override
15049                public ParcelFileDescriptor open(String name, int mode) throws RemoteException {
15050                    if (!FileUtils.isValidExtFilename(name)) {
15051                        throw new IllegalArgumentException("Invalid filename: " + name);
15052                    }
15053                    try {
15054                        final File file = new File(codeFile, name);
15055                        final FileDescriptor fd = Os.open(file.getAbsolutePath(),
15056                                O_RDWR | O_CREAT, 0644);
15057                        Os.chmod(file.getAbsolutePath(), 0644);
15058                        return new ParcelFileDescriptor(fd);
15059                    } catch (ErrnoException e) {
15060                        throw new RemoteException("Failed to open: " + e.getMessage());
15061                    }
15062                }
15063            };
15064
15065            int ret = PackageManager.INSTALL_SUCCEEDED;
15066            ret = imcs.copyPackage(origin.file.getAbsolutePath(), target);
15067            if (ret != PackageManager.INSTALL_SUCCEEDED) {
15068                Slog.e(TAG, "Failed to copy package");
15069                return ret;
15070            }
15071
15072            final File libraryRoot = new File(codeFile, LIB_DIR_NAME);
15073            NativeLibraryHelper.Handle handle = null;
15074            try {
15075                handle = NativeLibraryHelper.Handle.create(codeFile);
15076                ret = NativeLibraryHelper.copyNativeBinariesWithOverride(handle, libraryRoot,
15077                        abiOverride);
15078            } catch (IOException e) {
15079                Slog.e(TAG, "Copying native libraries failed", e);
15080                ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
15081            } finally {
15082                IoUtils.closeQuietly(handle);
15083            }
15084
15085            return ret;
15086        }
15087
15088        int doPreInstall(int status) {
15089            if (status != PackageManager.INSTALL_SUCCEEDED) {
15090                cleanUp();
15091            }
15092            return status;
15093        }
15094
15095        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
15096            if (status != PackageManager.INSTALL_SUCCEEDED) {
15097                cleanUp();
15098                return false;
15099            }
15100
15101            final File targetDir = codeFile.getParentFile();
15102            final File beforeCodeFile = codeFile;
15103            final File afterCodeFile = getNextCodePath(targetDir, pkg.packageName);
15104
15105            if (DEBUG_INSTALL) Slog.d(TAG, "Renaming " + beforeCodeFile + " to " + afterCodeFile);
15106            try {
15107                Os.rename(beforeCodeFile.getAbsolutePath(), afterCodeFile.getAbsolutePath());
15108            } catch (ErrnoException e) {
15109                Slog.w(TAG, "Failed to rename", e);
15110                return false;
15111            }
15112
15113            if (!SELinux.restoreconRecursive(afterCodeFile)) {
15114                Slog.w(TAG, "Failed to restorecon");
15115                return false;
15116            }
15117
15118            // Reflect the rename internally
15119            codeFile = afterCodeFile;
15120            resourceFile = afterCodeFile;
15121
15122            // Reflect the rename in scanned details
15123            pkg.setCodePath(afterCodeFile.getAbsolutePath());
15124            pkg.setBaseCodePath(FileUtils.rewriteAfterRename(beforeCodeFile,
15125                    afterCodeFile, pkg.baseCodePath));
15126            pkg.setSplitCodePaths(FileUtils.rewriteAfterRename(beforeCodeFile,
15127                    afterCodeFile, pkg.splitCodePaths));
15128
15129            // Reflect the rename in app info
15130            pkg.setApplicationVolumeUuid(pkg.volumeUuid);
15131            pkg.setApplicationInfoCodePath(pkg.codePath);
15132            pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
15133            pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
15134            pkg.setApplicationInfoResourcePath(pkg.codePath);
15135            pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath);
15136            pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
15137
15138            return true;
15139        }
15140
15141        int doPostInstall(int status, int uid) {
15142            if (status != PackageManager.INSTALL_SUCCEEDED) {
15143                cleanUp();
15144            }
15145            return status;
15146        }
15147
15148        @Override
15149        String getCodePath() {
15150            return (codeFile != null) ? codeFile.getAbsolutePath() : null;
15151        }
15152
15153        @Override
15154        String getResourcePath() {
15155            return (resourceFile != null) ? resourceFile.getAbsolutePath() : null;
15156        }
15157
15158        private boolean cleanUp() {
15159            if (codeFile == null || !codeFile.exists()) {
15160                return false;
15161            }
15162
15163            removeCodePathLI(codeFile);
15164
15165            if (resourceFile != null && !FileUtils.contains(codeFile, resourceFile)) {
15166                resourceFile.delete();
15167            }
15168
15169            return true;
15170        }
15171
15172        void cleanUpResourcesLI() {
15173            // Try enumerating all code paths before deleting
15174            List<String> allCodePaths = Collections.EMPTY_LIST;
15175            if (codeFile != null && codeFile.exists()) {
15176                try {
15177                    final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0);
15178                    allCodePaths = pkg.getAllCodePaths();
15179                } catch (PackageParserException e) {
15180                    // Ignored; we tried our best
15181                }
15182            }
15183
15184            cleanUp();
15185            removeDexFiles(allCodePaths, instructionSets);
15186        }
15187
15188        boolean doPostDeleteLI(boolean delete) {
15189            // XXX err, shouldn't we respect the delete flag?
15190            cleanUpResourcesLI();
15191            return true;
15192        }
15193    }
15194
15195    private boolean isAsecExternal(String cid) {
15196        final String asecPath = PackageHelper.getSdFilesystem(cid);
15197        return !asecPath.startsWith(mAsecInternalPath);
15198    }
15199
15200    private static void maybeThrowExceptionForMultiArchCopy(String message, int copyRet) throws
15201            PackageManagerException {
15202        if (copyRet < 0) {
15203            if (copyRet != PackageManager.NO_NATIVE_LIBRARIES &&
15204                    copyRet != PackageManager.INSTALL_FAILED_NO_MATCHING_ABIS) {
15205                throw new PackageManagerException(copyRet, message);
15206            }
15207        }
15208    }
15209
15210    /**
15211     * Extract the StorageManagerService "container ID" from the full code path of an
15212     * .apk.
15213     */
15214    static String cidFromCodePath(String fullCodePath) {
15215        int eidx = fullCodePath.lastIndexOf("/");
15216        String subStr1 = fullCodePath.substring(0, eidx);
15217        int sidx = subStr1.lastIndexOf("/");
15218        return subStr1.substring(sidx+1, eidx);
15219    }
15220
15221    /**
15222     * Logic to handle installation of ASEC applications, including copying and
15223     * renaming logic.
15224     */
15225    class AsecInstallArgs extends InstallArgs {
15226        static final String RES_FILE_NAME = "pkg.apk";
15227        static final String PUBLIC_RES_FILE_NAME = "res.zip";
15228
15229        String cid;
15230        String packagePath;
15231        String resourcePath;
15232
15233        /** New install */
15234        AsecInstallArgs(InstallParams params) {
15235            super(params.origin, params.move, params.observer, params.installFlags,
15236                    params.installerPackageName, params.volumeUuid,
15237                    params.getUser(), null /* instruction sets */, params.packageAbiOverride,
15238                    params.grantedRuntimePermissions,
15239                    params.traceMethod, params.traceCookie, params.certificates,
15240                    params.installReason);
15241        }
15242
15243        /** Existing install */
15244        AsecInstallArgs(String fullCodePath, String[] instructionSets,
15245                        boolean isExternal, boolean isForwardLocked) {
15246            super(OriginInfo.fromNothing(), null, null, (isExternal ? INSTALL_EXTERNAL : 0)
15247                    | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null,
15248                    instructionSets, null, null, null, 0, null /*certificates*/,
15249                    PackageManager.INSTALL_REASON_UNKNOWN);
15250            // Hackily pretend we're still looking at a full code path
15251            if (!fullCodePath.endsWith(RES_FILE_NAME)) {
15252                fullCodePath = new File(fullCodePath, RES_FILE_NAME).getAbsolutePath();
15253            }
15254
15255            // Extract cid from fullCodePath
15256            int eidx = fullCodePath.lastIndexOf("/");
15257            String subStr1 = fullCodePath.substring(0, eidx);
15258            int sidx = subStr1.lastIndexOf("/");
15259            cid = subStr1.substring(sidx+1, eidx);
15260            setMountPath(subStr1);
15261        }
15262
15263        AsecInstallArgs(String cid, String[] instructionSets, boolean isForwardLocked) {
15264            super(OriginInfo.fromNothing(), null, null, (isAsecExternal(cid) ? INSTALL_EXTERNAL : 0)
15265                    | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null,
15266                    instructionSets, null, null, null, 0, null /*certificates*/,
15267                    PackageManager.INSTALL_REASON_UNKNOWN);
15268            this.cid = cid;
15269            setMountPath(PackageHelper.getSdDir(cid));
15270        }
15271
15272        void createCopyFile() {
15273            cid = mInstallerService.allocateExternalStageCidLegacy();
15274        }
15275
15276        int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
15277            if (origin.staged && origin.cid != null) {
15278                if (DEBUG_INSTALL) Slog.d(TAG, origin.cid + " already staged; skipping copy");
15279                cid = origin.cid;
15280                setMountPath(PackageHelper.getSdDir(cid));
15281                return PackageManager.INSTALL_SUCCEEDED;
15282            }
15283
15284            if (temp) {
15285                createCopyFile();
15286            } else {
15287                /*
15288                 * Pre-emptively destroy the container since it's destroyed if
15289                 * copying fails due to it existing anyway.
15290                 */
15291                PackageHelper.destroySdDir(cid);
15292            }
15293
15294            final String newMountPath = imcs.copyPackageToContainer(
15295                    origin.file.getAbsolutePath(), cid, getEncryptKey(), isExternalAsec(),
15296                    isFwdLocked(), deriveAbiOverride(abiOverride, null /* settings */));
15297
15298            if (newMountPath != null) {
15299                setMountPath(newMountPath);
15300                return PackageManager.INSTALL_SUCCEEDED;
15301            } else {
15302                return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
15303            }
15304        }
15305
15306        @Override
15307        String getCodePath() {
15308            return packagePath;
15309        }
15310
15311        @Override
15312        String getResourcePath() {
15313            return resourcePath;
15314        }
15315
15316        int doPreInstall(int status) {
15317            if (status != PackageManager.INSTALL_SUCCEEDED) {
15318                // Destroy container
15319                PackageHelper.destroySdDir(cid);
15320            } else {
15321                boolean mounted = PackageHelper.isContainerMounted(cid);
15322                if (!mounted) {
15323                    String newMountPath = PackageHelper.mountSdDir(cid, getEncryptKey(),
15324                            Process.SYSTEM_UID);
15325                    if (newMountPath != null) {
15326                        setMountPath(newMountPath);
15327                    } else {
15328                        return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
15329                    }
15330                }
15331            }
15332            return status;
15333        }
15334
15335        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
15336            String newCacheId = getNextCodePath(oldCodePath, pkg.packageName, "/" + RES_FILE_NAME);
15337            String newMountPath = null;
15338            if (PackageHelper.isContainerMounted(cid)) {
15339                // Unmount the container
15340                if (!PackageHelper.unMountSdDir(cid)) {
15341                    Slog.i(TAG, "Failed to unmount " + cid + " before renaming");
15342                    return false;
15343                }
15344            }
15345            if (!PackageHelper.renameSdDir(cid, newCacheId)) {
15346                Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId +
15347                        " which might be stale. Will try to clean up.");
15348                // Clean up the stale container and proceed to recreate.
15349                if (!PackageHelper.destroySdDir(newCacheId)) {
15350                    Slog.e(TAG, "Very strange. Cannot clean up stale container " + newCacheId);
15351                    return false;
15352                }
15353                // Successfully cleaned up stale container. Try to rename again.
15354                if (!PackageHelper.renameSdDir(cid, newCacheId)) {
15355                    Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId
15356                            + " inspite of cleaning it up.");
15357                    return false;
15358                }
15359            }
15360            if (!PackageHelper.isContainerMounted(newCacheId)) {
15361                Slog.w(TAG, "Mounting container " + newCacheId);
15362                newMountPath = PackageHelper.mountSdDir(newCacheId,
15363                        getEncryptKey(), Process.SYSTEM_UID);
15364            } else {
15365                newMountPath = PackageHelper.getSdDir(newCacheId);
15366            }
15367            if (newMountPath == null) {
15368                Slog.w(TAG, "Failed to get cache path for  " + newCacheId);
15369                return false;
15370            }
15371            Log.i(TAG, "Succesfully renamed " + cid +
15372                    " to " + newCacheId +
15373                    " at new path: " + newMountPath);
15374            cid = newCacheId;
15375
15376            final File beforeCodeFile = new File(packagePath);
15377            setMountPath(newMountPath);
15378            final File afterCodeFile = new File(packagePath);
15379
15380            // Reflect the rename in scanned details
15381            pkg.setCodePath(afterCodeFile.getAbsolutePath());
15382            pkg.setBaseCodePath(FileUtils.rewriteAfterRename(beforeCodeFile,
15383                    afterCodeFile, pkg.baseCodePath));
15384            pkg.setSplitCodePaths(FileUtils.rewriteAfterRename(beforeCodeFile,
15385                    afterCodeFile, pkg.splitCodePaths));
15386
15387            // Reflect the rename in app info
15388            pkg.setApplicationVolumeUuid(pkg.volumeUuid);
15389            pkg.setApplicationInfoCodePath(pkg.codePath);
15390            pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
15391            pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
15392            pkg.setApplicationInfoResourcePath(pkg.codePath);
15393            pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath);
15394            pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
15395
15396            return true;
15397        }
15398
15399        private void setMountPath(String mountPath) {
15400            final File mountFile = new File(mountPath);
15401
15402            final File monolithicFile = new File(mountFile, RES_FILE_NAME);
15403            if (monolithicFile.exists()) {
15404                packagePath = monolithicFile.getAbsolutePath();
15405                if (isFwdLocked()) {
15406                    resourcePath = new File(mountFile, PUBLIC_RES_FILE_NAME).getAbsolutePath();
15407                } else {
15408                    resourcePath = packagePath;
15409                }
15410            } else {
15411                packagePath = mountFile.getAbsolutePath();
15412                resourcePath = packagePath;
15413            }
15414        }
15415
15416        int doPostInstall(int status, int uid) {
15417            if (status != PackageManager.INSTALL_SUCCEEDED) {
15418                cleanUp();
15419            } else {
15420                final int groupOwner;
15421                final String protectedFile;
15422                if (isFwdLocked()) {
15423                    groupOwner = UserHandle.getSharedAppGid(uid);
15424                    protectedFile = RES_FILE_NAME;
15425                } else {
15426                    groupOwner = -1;
15427                    protectedFile = null;
15428                }
15429
15430                if (uid < Process.FIRST_APPLICATION_UID
15431                        || !PackageHelper.fixSdPermissions(cid, groupOwner, protectedFile)) {
15432                    Slog.e(TAG, "Failed to finalize " + cid);
15433                    PackageHelper.destroySdDir(cid);
15434                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
15435                }
15436
15437                boolean mounted = PackageHelper.isContainerMounted(cid);
15438                if (!mounted) {
15439                    PackageHelper.mountSdDir(cid, getEncryptKey(), Process.myUid());
15440                }
15441            }
15442            return status;
15443        }
15444
15445        private void cleanUp() {
15446            if (DEBUG_SD_INSTALL) Slog.i(TAG, "cleanUp");
15447
15448            // Destroy secure container
15449            PackageHelper.destroySdDir(cid);
15450        }
15451
15452        private List<String> getAllCodePaths() {
15453            final File codeFile = new File(getCodePath());
15454            if (codeFile != null && codeFile.exists()) {
15455                try {
15456                    final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0);
15457                    return pkg.getAllCodePaths();
15458                } catch (PackageParserException e) {
15459                    // Ignored; we tried our best
15460                }
15461            }
15462            return Collections.EMPTY_LIST;
15463        }
15464
15465        void cleanUpResourcesLI() {
15466            // Enumerate all code paths before deleting
15467            cleanUpResourcesLI(getAllCodePaths());
15468        }
15469
15470        private void cleanUpResourcesLI(List<String> allCodePaths) {
15471            cleanUp();
15472            removeDexFiles(allCodePaths, instructionSets);
15473        }
15474
15475        String getPackageName() {
15476            return getAsecPackageName(cid);
15477        }
15478
15479        boolean doPostDeleteLI(boolean delete) {
15480            if (DEBUG_SD_INSTALL) Slog.i(TAG, "doPostDeleteLI() del=" + delete);
15481            final List<String> allCodePaths = getAllCodePaths();
15482            boolean mounted = PackageHelper.isContainerMounted(cid);
15483            if (mounted) {
15484                // Unmount first
15485                if (PackageHelper.unMountSdDir(cid)) {
15486                    mounted = false;
15487                }
15488            }
15489            if (!mounted && delete) {
15490                cleanUpResourcesLI(allCodePaths);
15491            }
15492            return !mounted;
15493        }
15494
15495        @Override
15496        int doPreCopy() {
15497            if (isFwdLocked()) {
15498                if (!PackageHelper.fixSdPermissions(cid, getPackageUid(DEFAULT_CONTAINER_PACKAGE,
15499                        MATCH_SYSTEM_ONLY, UserHandle.USER_SYSTEM), RES_FILE_NAME)) {
15500                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
15501                }
15502            }
15503
15504            return PackageManager.INSTALL_SUCCEEDED;
15505        }
15506
15507        @Override
15508        int doPostCopy(int uid) {
15509            if (isFwdLocked()) {
15510                if (uid < Process.FIRST_APPLICATION_UID
15511                        || !PackageHelper.fixSdPermissions(cid, UserHandle.getSharedAppGid(uid),
15512                                RES_FILE_NAME)) {
15513                    Slog.e(TAG, "Failed to finalize " + cid);
15514                    PackageHelper.destroySdDir(cid);
15515                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
15516                }
15517            }
15518
15519            return PackageManager.INSTALL_SUCCEEDED;
15520        }
15521    }
15522
15523    /**
15524     * Logic to handle movement of existing installed applications.
15525     */
15526    class MoveInstallArgs extends InstallArgs {
15527        private File codeFile;
15528        private File resourceFile;
15529
15530        /** New install */
15531        MoveInstallArgs(InstallParams params) {
15532            super(params.origin, params.move, params.observer, params.installFlags,
15533                    params.installerPackageName, params.volumeUuid,
15534                    params.getUser(), null /* instruction sets */, params.packageAbiOverride,
15535                    params.grantedRuntimePermissions,
15536                    params.traceMethod, params.traceCookie, params.certificates,
15537                    params.installReason);
15538        }
15539
15540        int copyApk(IMediaContainerService imcs, boolean temp) {
15541            if (DEBUG_INSTALL) Slog.d(TAG, "Moving " + move.packageName + " from "
15542                    + move.fromUuid + " to " + move.toUuid);
15543            synchronized (mInstaller) {
15544                try {
15545                    mInstaller.moveCompleteApp(move.fromUuid, move.toUuid, move.packageName,
15546                            move.dataAppName, move.appId, move.seinfo, move.targetSdkVersion);
15547                } catch (InstallerException e) {
15548                    Slog.w(TAG, "Failed to move app", e);
15549                    return PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
15550                }
15551            }
15552
15553            codeFile = new File(Environment.getDataAppDirectory(move.toUuid), move.dataAppName);
15554            resourceFile = codeFile;
15555            if (DEBUG_INSTALL) Slog.d(TAG, "codeFile after move is " + codeFile);
15556
15557            return PackageManager.INSTALL_SUCCEEDED;
15558        }
15559
15560        int doPreInstall(int status) {
15561            if (status != PackageManager.INSTALL_SUCCEEDED) {
15562                cleanUp(move.toUuid);
15563            }
15564            return status;
15565        }
15566
15567        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
15568            if (status != PackageManager.INSTALL_SUCCEEDED) {
15569                cleanUp(move.toUuid);
15570                return false;
15571            }
15572
15573            // Reflect the move in app info
15574            pkg.setApplicationVolumeUuid(pkg.volumeUuid);
15575            pkg.setApplicationInfoCodePath(pkg.codePath);
15576            pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
15577            pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
15578            pkg.setApplicationInfoResourcePath(pkg.codePath);
15579            pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath);
15580            pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
15581
15582            return true;
15583        }
15584
15585        int doPostInstall(int status, int uid) {
15586            if (status == PackageManager.INSTALL_SUCCEEDED) {
15587                cleanUp(move.fromUuid);
15588            } else {
15589                cleanUp(move.toUuid);
15590            }
15591            return status;
15592        }
15593
15594        @Override
15595        String getCodePath() {
15596            return (codeFile != null) ? codeFile.getAbsolutePath() : null;
15597        }
15598
15599        @Override
15600        String getResourcePath() {
15601            return (resourceFile != null) ? resourceFile.getAbsolutePath() : null;
15602        }
15603
15604        private boolean cleanUp(String volumeUuid) {
15605            final File codeFile = new File(Environment.getDataAppDirectory(volumeUuid),
15606                    move.dataAppName);
15607            Slog.d(TAG, "Cleaning up " + move.packageName + " on " + volumeUuid);
15608            final int[] userIds = sUserManager.getUserIds();
15609            synchronized (mInstallLock) {
15610                // Clean up both app data and code
15611                // All package moves are frozen until finished
15612                for (int userId : userIds) {
15613                    try {
15614                        mInstaller.destroyAppData(volumeUuid, move.packageName, userId,
15615                                StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE, 0);
15616                    } catch (InstallerException e) {
15617                        Slog.w(TAG, String.valueOf(e));
15618                    }
15619                }
15620                removeCodePathLI(codeFile);
15621            }
15622            return true;
15623        }
15624
15625        void cleanUpResourcesLI() {
15626            throw new UnsupportedOperationException();
15627        }
15628
15629        boolean doPostDeleteLI(boolean delete) {
15630            throw new UnsupportedOperationException();
15631        }
15632    }
15633
15634    static String getAsecPackageName(String packageCid) {
15635        int idx = packageCid.lastIndexOf("-");
15636        if (idx == -1) {
15637            return packageCid;
15638        }
15639        return packageCid.substring(0, idx);
15640    }
15641
15642    // Utility method used to create code paths based on package name and available index.
15643    private static String getNextCodePath(String oldCodePath, String prefix, String suffix) {
15644        String idxStr = "";
15645        int idx = 1;
15646        // Fall back to default value of idx=1 if prefix is not
15647        // part of oldCodePath
15648        if (oldCodePath != null) {
15649            String subStr = oldCodePath;
15650            // Drop the suffix right away
15651            if (suffix != null && subStr.endsWith(suffix)) {
15652                subStr = subStr.substring(0, subStr.length() - suffix.length());
15653            }
15654            // If oldCodePath already contains prefix find out the
15655            // ending index to either increment or decrement.
15656            int sidx = subStr.lastIndexOf(prefix);
15657            if (sidx != -1) {
15658                subStr = subStr.substring(sidx + prefix.length());
15659                if (subStr != null) {
15660                    if (subStr.startsWith(INSTALL_PACKAGE_SUFFIX)) {
15661                        subStr = subStr.substring(INSTALL_PACKAGE_SUFFIX.length());
15662                    }
15663                    try {
15664                        idx = Integer.parseInt(subStr);
15665                        if (idx <= 1) {
15666                            idx++;
15667                        } else {
15668                            idx--;
15669                        }
15670                    } catch(NumberFormatException e) {
15671                    }
15672                }
15673            }
15674        }
15675        idxStr = INSTALL_PACKAGE_SUFFIX + Integer.toString(idx);
15676        return prefix + idxStr;
15677    }
15678
15679    private File getNextCodePath(File targetDir, String packageName) {
15680        File result;
15681        SecureRandom random = new SecureRandom();
15682        byte[] bytes = new byte[16];
15683        do {
15684            random.nextBytes(bytes);
15685            String suffix = Base64.encodeToString(bytes, Base64.URL_SAFE | Base64.NO_WRAP);
15686            result = new File(targetDir, packageName + "-" + suffix);
15687        } while (result.exists());
15688        return result;
15689    }
15690
15691    // Utility method that returns the relative package path with respect
15692    // to the installation directory. Like say for /data/data/com.test-1.apk
15693    // string com.test-1 is returned.
15694    static String deriveCodePathName(String codePath) {
15695        if (codePath == null) {
15696            return null;
15697        }
15698        final File codeFile = new File(codePath);
15699        final String name = codeFile.getName();
15700        if (codeFile.isDirectory()) {
15701            return name;
15702        } else if (name.endsWith(".apk") || name.endsWith(".tmp")) {
15703            final int lastDot = name.lastIndexOf('.');
15704            return name.substring(0, lastDot);
15705        } else {
15706            Slog.w(TAG, "Odd, " + codePath + " doesn't look like an APK");
15707            return null;
15708        }
15709    }
15710
15711    static class PackageInstalledInfo {
15712        String name;
15713        int uid;
15714        // The set of users that originally had this package installed.
15715        int[] origUsers;
15716        // The set of users that now have this package installed.
15717        int[] newUsers;
15718        PackageParser.Package pkg;
15719        int returnCode;
15720        String returnMsg;
15721        PackageRemovedInfo removedInfo;
15722        ArrayMap<String, PackageInstalledInfo> addedChildPackages;
15723
15724        public void setError(int code, String msg) {
15725            setReturnCode(code);
15726            setReturnMessage(msg);
15727            Slog.w(TAG, msg);
15728        }
15729
15730        public void setError(String msg, PackageParserException e) {
15731            setReturnCode(e.error);
15732            setReturnMessage(ExceptionUtils.getCompleteMessage(msg, e));
15733            Slog.w(TAG, msg, e);
15734        }
15735
15736        public void setError(String msg, PackageManagerException e) {
15737            returnCode = e.error;
15738            setReturnMessage(ExceptionUtils.getCompleteMessage(msg, e));
15739            Slog.w(TAG, msg, e);
15740        }
15741
15742        public void setReturnCode(int returnCode) {
15743            this.returnCode = returnCode;
15744            final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0;
15745            for (int i = 0; i < childCount; i++) {
15746                addedChildPackages.valueAt(i).returnCode = returnCode;
15747            }
15748        }
15749
15750        private void setReturnMessage(String returnMsg) {
15751            this.returnMsg = returnMsg;
15752            final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0;
15753            for (int i = 0; i < childCount; i++) {
15754                addedChildPackages.valueAt(i).returnMsg = returnMsg;
15755            }
15756        }
15757
15758        // In some error cases we want to convey more info back to the observer
15759        String origPackage;
15760        String origPermission;
15761    }
15762
15763    /*
15764     * Install a non-existing package.
15765     */
15766    private void installNewPackageLIF(PackageParser.Package pkg, final int policyFlags,
15767            int scanFlags, UserHandle user, String installerPackageName, String volumeUuid,
15768            PackageInstalledInfo res, int installReason) {
15769        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installNewPackage");
15770
15771        // Remember this for later, in case we need to rollback this install
15772        String pkgName = pkg.packageName;
15773
15774        if (DEBUG_INSTALL) Slog.d(TAG, "installNewPackageLI: " + pkg);
15775
15776        synchronized(mPackages) {
15777            final String renamedPackage = mSettings.getRenamedPackageLPr(pkgName);
15778            if (renamedPackage != null) {
15779                // A package with the same name is already installed, though
15780                // it has been renamed to an older name.  The package we
15781                // are trying to install should be installed as an update to
15782                // the existing one, but that has not been requested, so bail.
15783                res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName
15784                        + " without first uninstalling package running as "
15785                        + renamedPackage);
15786                return;
15787            }
15788            if (mPackages.containsKey(pkgName)) {
15789                // Don't allow installation over an existing package with the same name.
15790                res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName
15791                        + " without first uninstalling.");
15792                return;
15793            }
15794        }
15795
15796        try {
15797            PackageParser.Package newPackage = scanPackageTracedLI(pkg, policyFlags, scanFlags,
15798                    System.currentTimeMillis(), user);
15799
15800            updateSettingsLI(newPackage, installerPackageName, null, res, user, installReason);
15801
15802            if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
15803                prepareAppDataAfterInstallLIF(newPackage);
15804
15805            } else {
15806                // Remove package from internal structures, but keep around any
15807                // data that might have already existed
15808                deletePackageLIF(pkgName, UserHandle.ALL, false, null,
15809                        PackageManager.DELETE_KEEP_DATA, res.removedInfo, true, null);
15810            }
15811        } catch (PackageManagerException e) {
15812            res.setError("Package couldn't be installed in " + pkg.codePath, e);
15813        }
15814
15815        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
15816    }
15817
15818    private boolean shouldCheckUpgradeKeySetLP(PackageSetting oldPs, int scanFlags) {
15819        // Can't rotate keys during boot or if sharedUser.
15820        if (oldPs == null || (scanFlags&SCAN_INITIAL) != 0 || oldPs.sharedUser != null
15821                || !oldPs.keySetData.isUsingUpgradeKeySets()) {
15822            return false;
15823        }
15824        // app is using upgradeKeySets; make sure all are valid
15825        KeySetManagerService ksms = mSettings.mKeySetManagerService;
15826        long[] upgradeKeySets = oldPs.keySetData.getUpgradeKeySets();
15827        for (int i = 0; i < upgradeKeySets.length; i++) {
15828            if (!ksms.isIdValidKeySetId(upgradeKeySets[i])) {
15829                Slog.wtf(TAG, "Package "
15830                         + (oldPs.name != null ? oldPs.name : "<null>")
15831                         + " contains upgrade-key-set reference to unknown key-set: "
15832                         + upgradeKeySets[i]
15833                         + " reverting to signatures check.");
15834                return false;
15835            }
15836        }
15837        return true;
15838    }
15839
15840    private boolean checkUpgradeKeySetLP(PackageSetting oldPS, PackageParser.Package newPkg) {
15841        // Upgrade keysets are being used.  Determine if new package has a superset of the
15842        // required keys.
15843        long[] upgradeKeySets = oldPS.keySetData.getUpgradeKeySets();
15844        KeySetManagerService ksms = mSettings.mKeySetManagerService;
15845        for (int i = 0; i < upgradeKeySets.length; i++) {
15846            Set<PublicKey> upgradeSet = ksms.getPublicKeysFromKeySetLPr(upgradeKeySets[i]);
15847            if (upgradeSet != null && newPkg.mSigningKeys.containsAll(upgradeSet)) {
15848                return true;
15849            }
15850        }
15851        return false;
15852    }
15853
15854    private static void updateDigest(MessageDigest digest, File file) throws IOException {
15855        try (DigestInputStream digestStream =
15856                new DigestInputStream(new FileInputStream(file), digest)) {
15857            while (digestStream.read() != -1) {} // nothing to do; just plow through the file
15858        }
15859    }
15860
15861    private void replacePackageLIF(PackageParser.Package pkg, final int policyFlags, int scanFlags,
15862            UserHandle user, String installerPackageName, PackageInstalledInfo res,
15863            int installReason) {
15864        final boolean isInstantApp = (scanFlags & SCAN_AS_INSTANT_APP) != 0;
15865
15866        final PackageParser.Package oldPackage;
15867        final String pkgName = pkg.packageName;
15868        final int[] allUsers;
15869        final int[] installedUsers;
15870
15871        synchronized(mPackages) {
15872            oldPackage = mPackages.get(pkgName);
15873            if (DEBUG_INSTALL) Slog.d(TAG, "replacePackageLI: new=" + pkg + ", old=" + oldPackage);
15874
15875            // don't allow upgrade to target a release SDK from a pre-release SDK
15876            final boolean oldTargetsPreRelease = oldPackage.applicationInfo.targetSdkVersion
15877                    == android.os.Build.VERSION_CODES.CUR_DEVELOPMENT;
15878            final boolean newTargetsPreRelease = pkg.applicationInfo.targetSdkVersion
15879                    == android.os.Build.VERSION_CODES.CUR_DEVELOPMENT;
15880            if (oldTargetsPreRelease
15881                    && !newTargetsPreRelease
15882                    && ((policyFlags & PackageParser.PARSE_FORCE_SDK) == 0)) {
15883                Slog.w(TAG, "Can't install package targeting released sdk");
15884                res.setReturnCode(PackageManager.INSTALL_FAILED_UPDATE_INCOMPATIBLE);
15885                return;
15886            }
15887
15888            final PackageSetting ps = mSettings.mPackages.get(pkgName);
15889
15890            // don't allow an upgrade from full to ephemeral
15891            if (isInstantApp && !ps.getInstantApp(user.getIdentifier())) {
15892                // can't downgrade from full to instant
15893                Slog.w(TAG, "Can't replace app with instant app: " + pkgName);
15894                res.setReturnCode(PackageManager.INSTALL_FAILED_INSTANT_APP_INVALID);
15895                return;
15896            }
15897
15898            // verify signatures are valid
15899            if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) {
15900                if (!checkUpgradeKeySetLP(ps, pkg)) {
15901                    res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
15902                            "New package not signed by keys specified by upgrade-keysets: "
15903                                    + pkgName);
15904                    return;
15905                }
15906            } else {
15907                // default to original signature matching
15908                if (compareSignatures(oldPackage.mSignatures, pkg.mSignatures)
15909                        != PackageManager.SIGNATURE_MATCH) {
15910                    res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
15911                            "New package has a different signature: " + pkgName);
15912                    return;
15913                }
15914            }
15915
15916            // don't allow a system upgrade unless the upgrade hash matches
15917            if (oldPackage.restrictUpdateHash != null && oldPackage.isSystemApp()) {
15918                byte[] digestBytes = null;
15919                try {
15920                    final MessageDigest digest = MessageDigest.getInstance("SHA-512");
15921                    updateDigest(digest, new File(pkg.baseCodePath));
15922                    if (!ArrayUtils.isEmpty(pkg.splitCodePaths)) {
15923                        for (String path : pkg.splitCodePaths) {
15924                            updateDigest(digest, new File(path));
15925                        }
15926                    }
15927                    digestBytes = digest.digest();
15928                } catch (NoSuchAlgorithmException | IOException e) {
15929                    res.setError(INSTALL_FAILED_INVALID_APK,
15930                            "Could not compute hash: " + pkgName);
15931                    return;
15932                }
15933                if (!Arrays.equals(oldPackage.restrictUpdateHash, digestBytes)) {
15934                    res.setError(INSTALL_FAILED_INVALID_APK,
15935                            "New package fails restrict-update check: " + pkgName);
15936                    return;
15937                }
15938                // retain upgrade restriction
15939                pkg.restrictUpdateHash = oldPackage.restrictUpdateHash;
15940            }
15941
15942            // Check for shared user id changes
15943            String invalidPackageName =
15944                    getParentOrChildPackageChangedSharedUser(oldPackage, pkg);
15945            if (invalidPackageName != null) {
15946                res.setError(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE,
15947                        "Package " + invalidPackageName + " tried to change user "
15948                                + oldPackage.mSharedUserId);
15949                return;
15950            }
15951
15952            // In case of rollback, remember per-user/profile install state
15953            allUsers = sUserManager.getUserIds();
15954            installedUsers = ps.queryInstalledUsers(allUsers, true);
15955        }
15956
15957        // Update what is removed
15958        res.removedInfo = new PackageRemovedInfo();
15959        res.removedInfo.uid = oldPackage.applicationInfo.uid;
15960        res.removedInfo.removedPackage = oldPackage.packageName;
15961        res.removedInfo.isStaticSharedLib = pkg.staticSharedLibName != null;
15962        res.removedInfo.isUpdate = true;
15963        res.removedInfo.origUsers = installedUsers;
15964        final PackageSetting ps = mSettings.getPackageLPr(pkgName);
15965        res.removedInfo.installReasons = new SparseArray<>(installedUsers.length);
15966        for (int i = 0; i < installedUsers.length; i++) {
15967            final int userId = installedUsers[i];
15968            res.removedInfo.installReasons.put(userId, ps.getInstallReason(userId));
15969        }
15970
15971        final int childCount = (oldPackage.childPackages != null)
15972                ? oldPackage.childPackages.size() : 0;
15973        for (int i = 0; i < childCount; i++) {
15974            boolean childPackageUpdated = false;
15975            PackageParser.Package childPkg = oldPackage.childPackages.get(i);
15976            final PackageSetting childPs = mSettings.getPackageLPr(childPkg.packageName);
15977            if (res.addedChildPackages != null) {
15978                PackageInstalledInfo childRes = res.addedChildPackages.get(childPkg.packageName);
15979                if (childRes != null) {
15980                    childRes.removedInfo.uid = childPkg.applicationInfo.uid;
15981                    childRes.removedInfo.removedPackage = childPkg.packageName;
15982                    childRes.removedInfo.isUpdate = true;
15983                    childRes.removedInfo.installReasons = res.removedInfo.installReasons;
15984                    childPackageUpdated = true;
15985                }
15986            }
15987            if (!childPackageUpdated) {
15988                PackageRemovedInfo childRemovedRes = new PackageRemovedInfo();
15989                childRemovedRes.removedPackage = childPkg.packageName;
15990                childRemovedRes.isUpdate = false;
15991                childRemovedRes.dataRemoved = true;
15992                synchronized (mPackages) {
15993                    if (childPs != null) {
15994                        childRemovedRes.origUsers = childPs.queryInstalledUsers(allUsers, true);
15995                    }
15996                }
15997                if (res.removedInfo.removedChildPackages == null) {
15998                    res.removedInfo.removedChildPackages = new ArrayMap<>();
15999                }
16000                res.removedInfo.removedChildPackages.put(childPkg.packageName, childRemovedRes);
16001            }
16002        }
16003
16004        boolean sysPkg = (isSystemApp(oldPackage));
16005        if (sysPkg) {
16006            // Set the system/privileged flags as needed
16007            final boolean privileged =
16008                    (oldPackage.applicationInfo.privateFlags
16009                            & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0;
16010            final int systemPolicyFlags = policyFlags
16011                    | PackageParser.PARSE_IS_SYSTEM
16012                    | (privileged ? PackageParser.PARSE_IS_PRIVILEGED : 0);
16013
16014            replaceSystemPackageLIF(oldPackage, pkg, systemPolicyFlags, scanFlags,
16015                    user, allUsers, installerPackageName, res, installReason);
16016        } else {
16017            replaceNonSystemPackageLIF(oldPackage, pkg, policyFlags, scanFlags,
16018                    user, allUsers, installerPackageName, res, installReason);
16019        }
16020    }
16021
16022    public List<String> getPreviousCodePaths(String packageName) {
16023        final PackageSetting ps = mSettings.mPackages.get(packageName);
16024        final List<String> result = new ArrayList<String>();
16025        if (ps != null && ps.oldCodePaths != null) {
16026            result.addAll(ps.oldCodePaths);
16027        }
16028        return result;
16029    }
16030
16031    private void replaceNonSystemPackageLIF(PackageParser.Package deletedPackage,
16032            PackageParser.Package pkg, final int policyFlags, int scanFlags, UserHandle user,
16033            int[] allUsers, String installerPackageName, PackageInstalledInfo res,
16034            int installReason) {
16035        if (DEBUG_INSTALL) Slog.d(TAG, "replaceNonSystemPackageLI: new=" + pkg + ", old="
16036                + deletedPackage);
16037
16038        String pkgName = deletedPackage.packageName;
16039        boolean deletedPkg = true;
16040        boolean addedPkg = false;
16041        boolean updatedSettings = false;
16042        final boolean killApp = (scanFlags & SCAN_DONT_KILL_APP) == 0;
16043        final int deleteFlags = PackageManager.DELETE_KEEP_DATA
16044                | (killApp ? 0 : PackageManager.DELETE_DONT_KILL_APP);
16045
16046        final long origUpdateTime = (pkg.mExtras != null)
16047                ? ((PackageSetting)pkg.mExtras).lastUpdateTime : 0;
16048
16049        // First delete the existing package while retaining the data directory
16050        if (!deletePackageLIF(pkgName, null, true, allUsers, deleteFlags,
16051                res.removedInfo, true, pkg)) {
16052            // If the existing package wasn't successfully deleted
16053            res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, "replaceNonSystemPackageLI");
16054            deletedPkg = false;
16055        } else {
16056            // Successfully deleted the old package; proceed with replace.
16057
16058            // If deleted package lived in a container, give users a chance to
16059            // relinquish resources before killing.
16060            if (deletedPackage.isForwardLocked() || isExternal(deletedPackage)) {
16061                if (DEBUG_INSTALL) {
16062                    Slog.i(TAG, "upgrading pkg " + deletedPackage + " is ASEC-hosted -> UNAVAILABLE");
16063                }
16064                final int[] uidArray = new int[] { deletedPackage.applicationInfo.uid };
16065                final ArrayList<String> pkgList = new ArrayList<String>(1);
16066                pkgList.add(deletedPackage.applicationInfo.packageName);
16067                sendResourcesChangedBroadcast(false, true, pkgList, uidArray, null);
16068            }
16069
16070            clearAppDataLIF(pkg, UserHandle.USER_ALL, StorageManager.FLAG_STORAGE_DE
16071                    | StorageManager.FLAG_STORAGE_CE | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
16072            clearAppProfilesLIF(deletedPackage, UserHandle.USER_ALL);
16073
16074            try {
16075                final PackageParser.Package newPackage = scanPackageTracedLI(pkg, policyFlags,
16076                        scanFlags | SCAN_UPDATE_TIME, System.currentTimeMillis(), user);
16077                updateSettingsLI(newPackage, installerPackageName, allUsers, res, user,
16078                        installReason);
16079
16080                // Update the in-memory copy of the previous code paths.
16081                PackageSetting ps = mSettings.mPackages.get(pkgName);
16082                if (!killApp) {
16083                    if (ps.oldCodePaths == null) {
16084                        ps.oldCodePaths = new ArraySet<>();
16085                    }
16086                    Collections.addAll(ps.oldCodePaths, deletedPackage.baseCodePath);
16087                    if (deletedPackage.splitCodePaths != null) {
16088                        Collections.addAll(ps.oldCodePaths, deletedPackage.splitCodePaths);
16089                    }
16090                } else {
16091                    ps.oldCodePaths = null;
16092                }
16093                if (ps.childPackageNames != null) {
16094                    for (int i = ps.childPackageNames.size() - 1; i >= 0; --i) {
16095                        final String childPkgName = ps.childPackageNames.get(i);
16096                        final PackageSetting childPs = mSettings.mPackages.get(childPkgName);
16097                        childPs.oldCodePaths = ps.oldCodePaths;
16098                    }
16099                }
16100                // set instant app status, but, only if it's explicitly specified
16101                final boolean instantApp = (scanFlags & SCAN_AS_INSTANT_APP) != 0;
16102                final boolean fullApp = (scanFlags & SCAN_AS_FULL_APP) != 0;
16103                setInstantAppForUser(ps, user.getIdentifier(), instantApp, fullApp);
16104                prepareAppDataAfterInstallLIF(newPackage);
16105                addedPkg = true;
16106            } catch (PackageManagerException e) {
16107                res.setError("Package couldn't be installed in " + pkg.codePath, e);
16108            }
16109        }
16110
16111        if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
16112            if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, rolling pack: " + pkgName);
16113
16114            // Revert all internal state mutations and added folders for the failed install
16115            if (addedPkg) {
16116                deletePackageLIF(pkgName, null, true, allUsers, deleteFlags,
16117                        res.removedInfo, true, null);
16118            }
16119
16120            // Restore the old package
16121            if (deletedPkg) {
16122                if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, reinstalling: " + deletedPackage);
16123                File restoreFile = new File(deletedPackage.codePath);
16124                // Parse old package
16125                boolean oldExternal = isExternal(deletedPackage);
16126                int oldParseFlags  = mDefParseFlags | PackageParser.PARSE_CHATTY |
16127                        (deletedPackage.isForwardLocked() ? PackageParser.PARSE_FORWARD_LOCK : 0) |
16128                        (oldExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0);
16129                int oldScanFlags = SCAN_UPDATE_SIGNATURE | SCAN_UPDATE_TIME;
16130                try {
16131                    scanPackageTracedLI(restoreFile, oldParseFlags, oldScanFlags, origUpdateTime,
16132                            null);
16133                } catch (PackageManagerException e) {
16134                    Slog.e(TAG, "Failed to restore package : " + pkgName + " after failed upgrade: "
16135                            + e.getMessage());
16136                    return;
16137                }
16138
16139                synchronized (mPackages) {
16140                    // Ensure the installer package name up to date
16141                    setInstallerPackageNameLPw(deletedPackage, installerPackageName);
16142
16143                    // Update permissions for restored package
16144                    updatePermissionsLPw(deletedPackage, UPDATE_PERMISSIONS_ALL);
16145
16146                    mSettings.writeLPr();
16147                }
16148
16149                Slog.i(TAG, "Successfully restored package : " + pkgName + " after failed upgrade");
16150            }
16151        } else {
16152            synchronized (mPackages) {
16153                PackageSetting ps = mSettings.getPackageLPr(pkg.packageName);
16154                if (ps != null) {
16155                    res.removedInfo.removedForAllUsers = mPackages.get(ps.name) == null;
16156                    if (res.removedInfo.removedChildPackages != null) {
16157                        final int childCount = res.removedInfo.removedChildPackages.size();
16158                        // Iterate in reverse as we may modify the collection
16159                        for (int i = childCount - 1; i >= 0; i--) {
16160                            String childPackageName = res.removedInfo.removedChildPackages.keyAt(i);
16161                            if (res.addedChildPackages.containsKey(childPackageName)) {
16162                                res.removedInfo.removedChildPackages.removeAt(i);
16163                            } else {
16164                                PackageRemovedInfo childInfo = res.removedInfo
16165                                        .removedChildPackages.valueAt(i);
16166                                childInfo.removedForAllUsers = mPackages.get(
16167                                        childInfo.removedPackage) == null;
16168                            }
16169                        }
16170                    }
16171                }
16172            }
16173        }
16174    }
16175
16176    private void replaceSystemPackageLIF(PackageParser.Package deletedPackage,
16177            PackageParser.Package pkg, final int policyFlags, int scanFlags, UserHandle user,
16178            int[] allUsers, String installerPackageName, PackageInstalledInfo res,
16179            int installReason) {
16180        if (DEBUG_INSTALL) Slog.d(TAG, "replaceSystemPackageLI: new=" + pkg
16181                + ", old=" + deletedPackage);
16182
16183        final boolean disabledSystem;
16184
16185        // Remove existing system package
16186        removePackageLI(deletedPackage, true);
16187
16188        synchronized (mPackages) {
16189            disabledSystem = disableSystemPackageLPw(deletedPackage, pkg);
16190        }
16191        if (!disabledSystem) {
16192            // We didn't need to disable the .apk as a current system package,
16193            // which means we are replacing another update that is already
16194            // installed.  We need to make sure to delete the older one's .apk.
16195            res.removedInfo.args = createInstallArgsForExisting(0,
16196                    deletedPackage.applicationInfo.getCodePath(),
16197                    deletedPackage.applicationInfo.getResourcePath(),
16198                    getAppDexInstructionSets(deletedPackage.applicationInfo));
16199        } else {
16200            res.removedInfo.args = null;
16201        }
16202
16203        // Successfully disabled the old package. Now proceed with re-installation
16204        clearAppDataLIF(pkg, UserHandle.USER_ALL, StorageManager.FLAG_STORAGE_DE
16205                | StorageManager.FLAG_STORAGE_CE | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
16206        clearAppProfilesLIF(deletedPackage, UserHandle.USER_ALL);
16207
16208        res.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
16209        pkg.setApplicationInfoFlags(ApplicationInfo.FLAG_UPDATED_SYSTEM_APP,
16210                ApplicationInfo.FLAG_UPDATED_SYSTEM_APP);
16211
16212        PackageParser.Package newPackage = null;
16213        try {
16214            // Add the package to the internal data structures
16215            newPackage = scanPackageTracedLI(pkg, policyFlags, scanFlags, 0, user);
16216
16217            // Set the update and install times
16218            PackageSetting deletedPkgSetting = (PackageSetting) deletedPackage.mExtras;
16219            setInstallAndUpdateTime(newPackage, deletedPkgSetting.firstInstallTime,
16220                    System.currentTimeMillis());
16221
16222            // Update the package dynamic state if succeeded
16223            if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
16224                // Now that the install succeeded make sure we remove data
16225                // directories for any child package the update removed.
16226                final int deletedChildCount = (deletedPackage.childPackages != null)
16227                        ? deletedPackage.childPackages.size() : 0;
16228                final int newChildCount = (newPackage.childPackages != null)
16229                        ? newPackage.childPackages.size() : 0;
16230                for (int i = 0; i < deletedChildCount; i++) {
16231                    PackageParser.Package deletedChildPkg = deletedPackage.childPackages.get(i);
16232                    boolean childPackageDeleted = true;
16233                    for (int j = 0; j < newChildCount; j++) {
16234                        PackageParser.Package newChildPkg = newPackage.childPackages.get(j);
16235                        if (deletedChildPkg.packageName.equals(newChildPkg.packageName)) {
16236                            childPackageDeleted = false;
16237                            break;
16238                        }
16239                    }
16240                    if (childPackageDeleted) {
16241                        PackageSetting ps = mSettings.getDisabledSystemPkgLPr(
16242                                deletedChildPkg.packageName);
16243                        if (ps != null && res.removedInfo.removedChildPackages != null) {
16244                            PackageRemovedInfo removedChildRes = res.removedInfo
16245                                    .removedChildPackages.get(deletedChildPkg.packageName);
16246                            removePackageDataLIF(ps, allUsers, removedChildRes, 0, false);
16247                            removedChildRes.removedForAllUsers = mPackages.get(ps.name) == null;
16248                        }
16249                    }
16250                }
16251
16252                updateSettingsLI(newPackage, installerPackageName, allUsers, res, user,
16253                        installReason);
16254                prepareAppDataAfterInstallLIF(newPackage);
16255            }
16256        } catch (PackageManagerException e) {
16257            res.setReturnCode(INSTALL_FAILED_INTERNAL_ERROR);
16258            res.setError("Package couldn't be installed in " + pkg.codePath, e);
16259        }
16260
16261        if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
16262            // Re installation failed. Restore old information
16263            // Remove new pkg information
16264            if (newPackage != null) {
16265                removeInstalledPackageLI(newPackage, true);
16266            }
16267            // Add back the old system package
16268            try {
16269                scanPackageTracedLI(deletedPackage, policyFlags, SCAN_UPDATE_SIGNATURE, 0, user);
16270            } catch (PackageManagerException e) {
16271                Slog.e(TAG, "Failed to restore original package: " + e.getMessage());
16272            }
16273
16274            synchronized (mPackages) {
16275                if (disabledSystem) {
16276                    enableSystemPackageLPw(deletedPackage);
16277                }
16278
16279                // Ensure the installer package name up to date
16280                setInstallerPackageNameLPw(deletedPackage, installerPackageName);
16281
16282                // Update permissions for restored package
16283                updatePermissionsLPw(deletedPackage, UPDATE_PERMISSIONS_ALL);
16284
16285                mSettings.writeLPr();
16286            }
16287
16288            Slog.i(TAG, "Successfully restored package : " + deletedPackage.packageName
16289                    + " after failed upgrade");
16290        }
16291    }
16292
16293    /**
16294     * Checks whether the parent or any of the child packages have a change shared
16295     * user. For a package to be a valid update the shred users of the parent and
16296     * the children should match. We may later support changing child shared users.
16297     * @param oldPkg The updated package.
16298     * @param newPkg The update package.
16299     * @return The shared user that change between the versions.
16300     */
16301    private String getParentOrChildPackageChangedSharedUser(PackageParser.Package oldPkg,
16302            PackageParser.Package newPkg) {
16303        // Check parent shared user
16304        if (!Objects.equals(oldPkg.mSharedUserId, newPkg.mSharedUserId)) {
16305            return newPkg.packageName;
16306        }
16307        // Check child shared users
16308        final int oldChildCount = (oldPkg.childPackages != null) ? oldPkg.childPackages.size() : 0;
16309        final int newChildCount = (newPkg.childPackages != null) ? newPkg.childPackages.size() : 0;
16310        for (int i = 0; i < newChildCount; i++) {
16311            PackageParser.Package newChildPkg = newPkg.childPackages.get(i);
16312            // If this child was present, did it have the same shared user?
16313            for (int j = 0; j < oldChildCount; j++) {
16314                PackageParser.Package oldChildPkg = oldPkg.childPackages.get(j);
16315                if (newChildPkg.packageName.equals(oldChildPkg.packageName)
16316                        && !Objects.equals(newChildPkg.mSharedUserId, oldChildPkg.mSharedUserId)) {
16317                    return newChildPkg.packageName;
16318                }
16319            }
16320        }
16321        return null;
16322    }
16323
16324    private void removeNativeBinariesLI(PackageSetting ps) {
16325        // Remove the lib path for the parent package
16326        if (ps != null) {
16327            NativeLibraryHelper.removeNativeBinariesLI(ps.legacyNativeLibraryPathString);
16328            // Remove the lib path for the child packages
16329            final int childCount = (ps.childPackageNames != null) ? ps.childPackageNames.size() : 0;
16330            for (int i = 0; i < childCount; i++) {
16331                PackageSetting childPs = null;
16332                synchronized (mPackages) {
16333                    childPs = mSettings.getPackageLPr(ps.childPackageNames.get(i));
16334                }
16335                if (childPs != null) {
16336                    NativeLibraryHelper.removeNativeBinariesLI(childPs
16337                            .legacyNativeLibraryPathString);
16338                }
16339            }
16340        }
16341    }
16342
16343    private void enableSystemPackageLPw(PackageParser.Package pkg) {
16344        // Enable the parent package
16345        mSettings.enableSystemPackageLPw(pkg.packageName);
16346        // Enable the child packages
16347        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
16348        for (int i = 0; i < childCount; i++) {
16349            PackageParser.Package childPkg = pkg.childPackages.get(i);
16350            mSettings.enableSystemPackageLPw(childPkg.packageName);
16351        }
16352    }
16353
16354    private boolean disableSystemPackageLPw(PackageParser.Package oldPkg,
16355            PackageParser.Package newPkg) {
16356        // Disable the parent package (parent always replaced)
16357        boolean disabled = mSettings.disableSystemPackageLPw(oldPkg.packageName, true);
16358        // Disable the child packages
16359        final int childCount = (oldPkg.childPackages != null) ? oldPkg.childPackages.size() : 0;
16360        for (int i = 0; i < childCount; i++) {
16361            PackageParser.Package childPkg = oldPkg.childPackages.get(i);
16362            final boolean replace = newPkg.hasChildPackage(childPkg.packageName);
16363            disabled |= mSettings.disableSystemPackageLPw(childPkg.packageName, replace);
16364        }
16365        return disabled;
16366    }
16367
16368    private void setInstallerPackageNameLPw(PackageParser.Package pkg,
16369            String installerPackageName) {
16370        // Enable the parent package
16371        mSettings.setInstallerPackageName(pkg.packageName, installerPackageName);
16372        // Enable the child packages
16373        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
16374        for (int i = 0; i < childCount; i++) {
16375            PackageParser.Package childPkg = pkg.childPackages.get(i);
16376            mSettings.setInstallerPackageName(childPkg.packageName, installerPackageName);
16377        }
16378    }
16379
16380    private int[] revokeUnusedSharedUserPermissionsLPw(SharedUserSetting su, int[] allUserIds) {
16381        // Collect all used permissions in the UID
16382        ArraySet<String> usedPermissions = new ArraySet<>();
16383        final int packageCount = su.packages.size();
16384        for (int i = 0; i < packageCount; i++) {
16385            PackageSetting ps = su.packages.valueAt(i);
16386            if (ps.pkg == null) {
16387                continue;
16388            }
16389            final int requestedPermCount = ps.pkg.requestedPermissions.size();
16390            for (int j = 0; j < requestedPermCount; j++) {
16391                String permission = ps.pkg.requestedPermissions.get(j);
16392                BasePermission bp = mSettings.mPermissions.get(permission);
16393                if (bp != null) {
16394                    usedPermissions.add(permission);
16395                }
16396            }
16397        }
16398
16399        PermissionsState permissionsState = su.getPermissionsState();
16400        // Prune install permissions
16401        List<PermissionState> installPermStates = permissionsState.getInstallPermissionStates();
16402        final int installPermCount = installPermStates.size();
16403        for (int i = installPermCount - 1; i >= 0;  i--) {
16404            PermissionState permissionState = installPermStates.get(i);
16405            if (!usedPermissions.contains(permissionState.getName())) {
16406                BasePermission bp = mSettings.mPermissions.get(permissionState.getName());
16407                if (bp != null) {
16408                    permissionsState.revokeInstallPermission(bp);
16409                    permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL,
16410                            PackageManager.MASK_PERMISSION_FLAGS, 0);
16411                }
16412            }
16413        }
16414
16415        int[] runtimePermissionChangedUserIds = EmptyArray.INT;
16416
16417        // Prune runtime permissions
16418        for (int userId : allUserIds) {
16419            List<PermissionState> runtimePermStates = permissionsState
16420                    .getRuntimePermissionStates(userId);
16421            final int runtimePermCount = runtimePermStates.size();
16422            for (int i = runtimePermCount - 1; i >= 0; i--) {
16423                PermissionState permissionState = runtimePermStates.get(i);
16424                if (!usedPermissions.contains(permissionState.getName())) {
16425                    BasePermission bp = mSettings.mPermissions.get(permissionState.getName());
16426                    if (bp != null) {
16427                        permissionsState.revokeRuntimePermission(bp, userId);
16428                        permissionsState.updatePermissionFlags(bp, userId,
16429                                PackageManager.MASK_PERMISSION_FLAGS, 0);
16430                        runtimePermissionChangedUserIds = ArrayUtils.appendInt(
16431                                runtimePermissionChangedUserIds, userId);
16432                    }
16433                }
16434            }
16435        }
16436
16437        return runtimePermissionChangedUserIds;
16438    }
16439
16440    private void updateSettingsLI(PackageParser.Package newPackage, String installerPackageName,
16441            int[] allUsers, PackageInstalledInfo res, UserHandle user, int installReason) {
16442        // Update the parent package setting
16443        updateSettingsInternalLI(newPackage, installerPackageName, allUsers, res.origUsers,
16444                res, user, installReason);
16445        // Update the child packages setting
16446        final int childCount = (newPackage.childPackages != null)
16447                ? newPackage.childPackages.size() : 0;
16448        for (int i = 0; i < childCount; i++) {
16449            PackageParser.Package childPackage = newPackage.childPackages.get(i);
16450            PackageInstalledInfo childRes = res.addedChildPackages.get(childPackage.packageName);
16451            updateSettingsInternalLI(childPackage, installerPackageName, allUsers,
16452                    childRes.origUsers, childRes, user, installReason);
16453        }
16454    }
16455
16456    private void updateSettingsInternalLI(PackageParser.Package newPackage,
16457            String installerPackageName, int[] allUsers, int[] installedForUsers,
16458            PackageInstalledInfo res, UserHandle user, int installReason) {
16459        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings");
16460
16461        String pkgName = newPackage.packageName;
16462        synchronized (mPackages) {
16463            //write settings. the installStatus will be incomplete at this stage.
16464            //note that the new package setting would have already been
16465            //added to mPackages. It hasn't been persisted yet.
16466            mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_INCOMPLETE);
16467            // TODO: Remove this write? It's also written at the end of this method
16468            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings");
16469            mSettings.writeLPr();
16470            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
16471        }
16472
16473        if (DEBUG_INSTALL) Slog.d(TAG, "New package installed in " + newPackage.codePath);
16474        synchronized (mPackages) {
16475            updatePermissionsLPw(newPackage.packageName, newPackage,
16476                    UPDATE_PERMISSIONS_REPLACE_PKG | (newPackage.permissions.size() > 0
16477                            ? UPDATE_PERMISSIONS_ALL : 0));
16478            // For system-bundled packages, we assume that installing an upgraded version
16479            // of the package implies that the user actually wants to run that new code,
16480            // so we enable the package.
16481            PackageSetting ps = mSettings.mPackages.get(pkgName);
16482            final int userId = user.getIdentifier();
16483            if (ps != null) {
16484                if (isSystemApp(newPackage)) {
16485                    if (DEBUG_INSTALL) {
16486                        Slog.d(TAG, "Implicitly enabling system package on upgrade: " + pkgName);
16487                    }
16488                    // Enable system package for requested users
16489                    if (res.origUsers != null) {
16490                        for (int origUserId : res.origUsers) {
16491                            if (userId == UserHandle.USER_ALL || userId == origUserId) {
16492                                ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT,
16493                                        origUserId, installerPackageName);
16494                            }
16495                        }
16496                    }
16497                    // Also convey the prior install/uninstall state
16498                    if (allUsers != null && installedForUsers != null) {
16499                        for (int currentUserId : allUsers) {
16500                            final boolean installed = ArrayUtils.contains(
16501                                    installedForUsers, currentUserId);
16502                            if (DEBUG_INSTALL) {
16503                                Slog.d(TAG, "    user " + currentUserId + " => " + installed);
16504                            }
16505                            ps.setInstalled(installed, currentUserId);
16506                        }
16507                        // these install state changes will be persisted in the
16508                        // upcoming call to mSettings.writeLPr().
16509                    }
16510                }
16511                // It's implied that when a user requests installation, they want the app to be
16512                // installed and enabled.
16513                if (userId != UserHandle.USER_ALL) {
16514                    ps.setInstalled(true, userId);
16515                    ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, userId, installerPackageName);
16516                }
16517
16518                // When replacing an existing package, preserve the original install reason for all
16519                // users that had the package installed before.
16520                final Set<Integer> previousUserIds = new ArraySet<>();
16521                if (res.removedInfo != null && res.removedInfo.installReasons != null) {
16522                    final int installReasonCount = res.removedInfo.installReasons.size();
16523                    for (int i = 0; i < installReasonCount; i++) {
16524                        final int previousUserId = res.removedInfo.installReasons.keyAt(i);
16525                        final int previousInstallReason = res.removedInfo.installReasons.valueAt(i);
16526                        ps.setInstallReason(previousInstallReason, previousUserId);
16527                        previousUserIds.add(previousUserId);
16528                    }
16529                }
16530
16531                // Set install reason for users that are having the package newly installed.
16532                if (userId == UserHandle.USER_ALL) {
16533                    for (int currentUserId : sUserManager.getUserIds()) {
16534                        if (!previousUserIds.contains(currentUserId)) {
16535                            ps.setInstallReason(installReason, currentUserId);
16536                        }
16537                    }
16538                } else if (!previousUserIds.contains(userId)) {
16539                    ps.setInstallReason(installReason, userId);
16540                }
16541                mSettings.writeKernelMappingLPr(ps);
16542            }
16543            res.name = pkgName;
16544            res.uid = newPackage.applicationInfo.uid;
16545            res.pkg = newPackage;
16546            mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_COMPLETE);
16547            mSettings.setInstallerPackageName(pkgName, installerPackageName);
16548            res.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
16549            //to update install status
16550            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings");
16551            mSettings.writeLPr();
16552            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
16553        }
16554
16555        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
16556    }
16557
16558    private void installPackageTracedLI(InstallArgs args, PackageInstalledInfo res) {
16559        try {
16560            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installPackage");
16561            installPackageLI(args, res);
16562        } finally {
16563            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
16564        }
16565    }
16566
16567    private void installPackageLI(InstallArgs args, PackageInstalledInfo res) {
16568        final int installFlags = args.installFlags;
16569        final String installerPackageName = args.installerPackageName;
16570        final String volumeUuid = args.volumeUuid;
16571        final File tmpPackageFile = new File(args.getCodePath());
16572        final boolean forwardLocked = ((installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0);
16573        final boolean onExternal = (((installFlags & PackageManager.INSTALL_EXTERNAL) != 0)
16574                || (args.volumeUuid != null));
16575        final boolean instantApp = ((installFlags & PackageManager.INSTALL_INSTANT_APP) != 0);
16576        final boolean fullApp = ((installFlags & PackageManager.INSTALL_FULL_APP) != 0);
16577        final boolean forceSdk = ((installFlags & PackageManager.INSTALL_FORCE_SDK) != 0);
16578        boolean replace = false;
16579        int scanFlags = SCAN_NEW_INSTALL | SCAN_UPDATE_SIGNATURE;
16580        if (args.move != null) {
16581            // moving a complete application; perform an initial scan on the new install location
16582            scanFlags |= SCAN_INITIAL;
16583        }
16584        if ((installFlags & PackageManager.INSTALL_DONT_KILL_APP) != 0) {
16585            scanFlags |= SCAN_DONT_KILL_APP;
16586        }
16587        if (instantApp) {
16588            scanFlags |= SCAN_AS_INSTANT_APP;
16589        }
16590        if (fullApp) {
16591            scanFlags |= SCAN_AS_FULL_APP;
16592        }
16593
16594        // Result object to be returned
16595        res.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
16596
16597        if (DEBUG_INSTALL) Slog.d(TAG, "installPackageLI: path=" + tmpPackageFile);
16598
16599        // Sanity check
16600        if (instantApp && (forwardLocked || onExternal)) {
16601            Slog.i(TAG, "Incompatible ephemeral install; fwdLocked=" + forwardLocked
16602                    + " external=" + onExternal);
16603            res.setReturnCode(PackageManager.INSTALL_FAILED_INSTANT_APP_INVALID);
16604            return;
16605        }
16606
16607        // Retrieve PackageSettings and parse package
16608        final int parseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY
16609                | PackageParser.PARSE_ENFORCE_CODE
16610                | (forwardLocked ? PackageParser.PARSE_FORWARD_LOCK : 0)
16611                | (onExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0)
16612                | (instantApp ? PackageParser.PARSE_IS_EPHEMERAL : 0)
16613                | (forceSdk ? PackageParser.PARSE_FORCE_SDK : 0);
16614        PackageParser pp = new PackageParser();
16615        pp.setSeparateProcesses(mSeparateProcesses);
16616        pp.setDisplayMetrics(mMetrics);
16617
16618        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "parsePackage");
16619        final PackageParser.Package pkg;
16620        try {
16621            pkg = pp.parsePackage(tmpPackageFile, parseFlags);
16622        } catch (PackageParserException e) {
16623            res.setError("Failed parse during installPackageLI", e);
16624            return;
16625        } finally {
16626            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
16627        }
16628
16629//        // Ephemeral apps must have target SDK >= O.
16630//        // TODO: Update conditional and error message when O gets locked down
16631//        if (instantApp && pkg.applicationInfo.targetSdkVersion <= Build.VERSION_CODES.N_MR1) {
16632//            res.setError(PackageManager.INSTALL_FAILED_EPHEMERAL_INVALID,
16633//                    "Ephemeral apps must have target SDK version of at least O");
16634//            return;
16635//        }
16636
16637        if (pkg.applicationInfo.isStaticSharedLibrary()) {
16638            // Static shared libraries have synthetic package names
16639            renameStaticSharedLibraryPackage(pkg);
16640
16641            // No static shared libs on external storage
16642            if (onExternal) {
16643                Slog.i(TAG, "Static shared libs can only be installed on internal storage.");
16644                res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION,
16645                        "Packages declaring static-shared libs cannot be updated");
16646                return;
16647            }
16648        }
16649
16650        // If we are installing a clustered package add results for the children
16651        if (pkg.childPackages != null) {
16652            synchronized (mPackages) {
16653                final int childCount = pkg.childPackages.size();
16654                for (int i = 0; i < childCount; i++) {
16655                    PackageParser.Package childPkg = pkg.childPackages.get(i);
16656                    PackageInstalledInfo childRes = new PackageInstalledInfo();
16657                    childRes.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
16658                    childRes.pkg = childPkg;
16659                    childRes.name = childPkg.packageName;
16660                    PackageSetting childPs = mSettings.getPackageLPr(childPkg.packageName);
16661                    if (childPs != null) {
16662                        childRes.origUsers = childPs.queryInstalledUsers(
16663                                sUserManager.getUserIds(), true);
16664                    }
16665                    if ((mPackages.containsKey(childPkg.packageName))) {
16666                        childRes.removedInfo = new PackageRemovedInfo();
16667                        childRes.removedInfo.removedPackage = childPkg.packageName;
16668                    }
16669                    if (res.addedChildPackages == null) {
16670                        res.addedChildPackages = new ArrayMap<>();
16671                    }
16672                    res.addedChildPackages.put(childPkg.packageName, childRes);
16673                }
16674            }
16675        }
16676
16677        // If package doesn't declare API override, mark that we have an install
16678        // time CPU ABI override.
16679        if (TextUtils.isEmpty(pkg.cpuAbiOverride)) {
16680            pkg.cpuAbiOverride = args.abiOverride;
16681        }
16682
16683        String pkgName = res.name = pkg.packageName;
16684        if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_TEST_ONLY) != 0) {
16685            if ((installFlags & PackageManager.INSTALL_ALLOW_TEST) == 0) {
16686                res.setError(INSTALL_FAILED_TEST_ONLY, "installPackageLI");
16687                return;
16688            }
16689        }
16690
16691        try {
16692            // either use what we've been given or parse directly from the APK
16693            if (args.certificates != null) {
16694                try {
16695                    PackageParser.populateCertificates(pkg, args.certificates);
16696                } catch (PackageParserException e) {
16697                    // there was something wrong with the certificates we were given;
16698                    // try to pull them from the APK
16699                    PackageParser.collectCertificates(pkg, parseFlags);
16700                }
16701            } else {
16702                PackageParser.collectCertificates(pkg, parseFlags);
16703            }
16704        } catch (PackageParserException e) {
16705            res.setError("Failed collect during installPackageLI", e);
16706            return;
16707        }
16708
16709        // Get rid of all references to package scan path via parser.
16710        pp = null;
16711        String oldCodePath = null;
16712        boolean systemApp = false;
16713        synchronized (mPackages) {
16714            // Check if installing already existing package
16715            if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
16716                String oldName = mSettings.getRenamedPackageLPr(pkgName);
16717                if (pkg.mOriginalPackages != null
16718                        && pkg.mOriginalPackages.contains(oldName)
16719                        && mPackages.containsKey(oldName)) {
16720                    // This package is derived from an original package,
16721                    // and this device has been updating from that original
16722                    // name.  We must continue using the original name, so
16723                    // rename the new package here.
16724                    pkg.setPackageName(oldName);
16725                    pkgName = pkg.packageName;
16726                    replace = true;
16727                    if (DEBUG_INSTALL) Slog.d(TAG, "Replacing existing renamed package: oldName="
16728                            + oldName + " pkgName=" + pkgName);
16729                } else if (mPackages.containsKey(pkgName)) {
16730                    // This package, under its official name, already exists
16731                    // on the device; we should replace it.
16732                    replace = true;
16733                    if (DEBUG_INSTALL) Slog.d(TAG, "Replace existing pacakge: " + pkgName);
16734                }
16735
16736                // Child packages are installed through the parent package
16737                if (pkg.parentPackage != null) {
16738                    res.setError(PackageManager.INSTALL_PARSE_FAILED_BAD_PACKAGE_NAME,
16739                            "Package " + pkg.packageName + " is child of package "
16740                                    + pkg.parentPackage.parentPackage + ". Child packages "
16741                                    + "can be updated only through the parent package.");
16742                    return;
16743                }
16744
16745                if (replace) {
16746                    // Prevent apps opting out from runtime permissions
16747                    PackageParser.Package oldPackage = mPackages.get(pkgName);
16748                    final int oldTargetSdk = oldPackage.applicationInfo.targetSdkVersion;
16749                    final int newTargetSdk = pkg.applicationInfo.targetSdkVersion;
16750                    if (oldTargetSdk > Build.VERSION_CODES.LOLLIPOP_MR1
16751                            && newTargetSdk <= Build.VERSION_CODES.LOLLIPOP_MR1) {
16752                        res.setError(PackageManager.INSTALL_FAILED_PERMISSION_MODEL_DOWNGRADE,
16753                                "Package " + pkg.packageName + " new target SDK " + newTargetSdk
16754                                        + " doesn't support runtime permissions but the old"
16755                                        + " target SDK " + oldTargetSdk + " does.");
16756                        return;
16757                    }
16758
16759                    // Prevent installing of child packages
16760                    if (oldPackage.parentPackage != null) {
16761                        res.setError(PackageManager.INSTALL_PARSE_FAILED_BAD_PACKAGE_NAME,
16762                                "Package " + pkg.packageName + " is child of package "
16763                                        + oldPackage.parentPackage + ". Child packages "
16764                                        + "can be updated only through the parent package.");
16765                        return;
16766                    }
16767                }
16768            }
16769
16770            PackageSetting ps = mSettings.mPackages.get(pkgName);
16771            if (ps != null) {
16772                if (DEBUG_INSTALL) Slog.d(TAG, "Existing package: " + ps);
16773
16774                // Static shared libs have same package with different versions where
16775                // we internally use a synthetic package name to allow multiple versions
16776                // of the same package, therefore we need to compare signatures against
16777                // the package setting for the latest library version.
16778                PackageSetting signatureCheckPs = ps;
16779                if (pkg.applicationInfo.isStaticSharedLibrary()) {
16780                    SharedLibraryEntry libraryEntry = getLatestSharedLibraVersionLPr(pkg);
16781                    if (libraryEntry != null) {
16782                        signatureCheckPs = mSettings.getPackageLPr(libraryEntry.apk);
16783                    }
16784                }
16785
16786                // Quick sanity check that we're signed correctly if updating;
16787                // we'll check this again later when scanning, but we want to
16788                // bail early here before tripping over redefined permissions.
16789                if (shouldCheckUpgradeKeySetLP(signatureCheckPs, scanFlags)) {
16790                    if (!checkUpgradeKeySetLP(signatureCheckPs, pkg)) {
16791                        res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package "
16792                                + pkg.packageName + " upgrade keys do not match the "
16793                                + "previously installed version");
16794                        return;
16795                    }
16796                } else {
16797                    try {
16798                        verifySignaturesLP(signatureCheckPs, pkg);
16799                    } catch (PackageManagerException e) {
16800                        res.setError(e.error, e.getMessage());
16801                        return;
16802                    }
16803                }
16804
16805                oldCodePath = mSettings.mPackages.get(pkgName).codePathString;
16806                if (ps.pkg != null && ps.pkg.applicationInfo != null) {
16807                    systemApp = (ps.pkg.applicationInfo.flags &
16808                            ApplicationInfo.FLAG_SYSTEM) != 0;
16809                }
16810                res.origUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
16811            }
16812
16813            // Check whether the newly-scanned package wants to define an already-defined perm
16814            int N = pkg.permissions.size();
16815            for (int i = N-1; i >= 0; i--) {
16816                PackageParser.Permission perm = pkg.permissions.get(i);
16817                BasePermission bp = mSettings.mPermissions.get(perm.info.name);
16818                if (bp != null) {
16819                    // If the defining package is signed with our cert, it's okay.  This
16820                    // also includes the "updating the same package" case, of course.
16821                    // "updating same package" could also involve key-rotation.
16822                    final boolean sigsOk;
16823                    if (bp.sourcePackage.equals(pkg.packageName)
16824                            && (bp.packageSetting instanceof PackageSetting)
16825                            && (shouldCheckUpgradeKeySetLP((PackageSetting) bp.packageSetting,
16826                                    scanFlags))) {
16827                        sigsOk = checkUpgradeKeySetLP((PackageSetting) bp.packageSetting, pkg);
16828                    } else {
16829                        sigsOk = compareSignatures(bp.packageSetting.signatures.mSignatures,
16830                                pkg.mSignatures) == PackageManager.SIGNATURE_MATCH;
16831                    }
16832                    if (!sigsOk) {
16833                        // If the owning package is the system itself, we log but allow
16834                        // install to proceed; we fail the install on all other permission
16835                        // redefinitions.
16836                        if (!bp.sourcePackage.equals("android")) {
16837                            res.setError(INSTALL_FAILED_DUPLICATE_PERMISSION, "Package "
16838                                    + pkg.packageName + " attempting to redeclare permission "
16839                                    + perm.info.name + " already owned by " + bp.sourcePackage);
16840                            res.origPermission = perm.info.name;
16841                            res.origPackage = bp.sourcePackage;
16842                            return;
16843                        } else {
16844                            Slog.w(TAG, "Package " + pkg.packageName
16845                                    + " attempting to redeclare system permission "
16846                                    + perm.info.name + "; ignoring new declaration");
16847                            pkg.permissions.remove(i);
16848                        }
16849                    } else if (!PLATFORM_PACKAGE_NAME.equals(pkg.packageName)) {
16850                        // Prevent apps to change protection level to dangerous from any other
16851                        // type as this would allow a privilege escalation where an app adds a
16852                        // normal/signature permission in other app's group and later redefines
16853                        // it as dangerous leading to the group auto-grant.
16854                        if ((perm.info.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE)
16855                                == PermissionInfo.PROTECTION_DANGEROUS) {
16856                            if (bp != null && !bp.isRuntime()) {
16857                                Slog.w(TAG, "Package " + pkg.packageName + " trying to change a "
16858                                        + "non-runtime permission " + perm.info.name
16859                                        + " to runtime; keeping old protection level");
16860                                perm.info.protectionLevel = bp.protectionLevel;
16861                            }
16862                        }
16863                    }
16864                }
16865            }
16866        }
16867
16868        if (systemApp) {
16869            if (onExternal) {
16870                // Abort update; system app can't be replaced with app on sdcard
16871                res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION,
16872                        "Cannot install updates to system apps on sdcard");
16873                return;
16874            } else if (instantApp) {
16875                // Abort update; system app can't be replaced with an instant app
16876                res.setError(INSTALL_FAILED_INSTANT_APP_INVALID,
16877                        "Cannot update a system app with an instant app");
16878                return;
16879            }
16880        }
16881
16882        if (args.move != null) {
16883            // We did an in-place move, so dex is ready to roll
16884            scanFlags |= SCAN_NO_DEX;
16885            scanFlags |= SCAN_MOVE;
16886
16887            synchronized (mPackages) {
16888                final PackageSetting ps = mSettings.mPackages.get(pkgName);
16889                if (ps == null) {
16890                    res.setError(INSTALL_FAILED_INTERNAL_ERROR,
16891                            "Missing settings for moved package " + pkgName);
16892                }
16893
16894                // We moved the entire application as-is, so bring over the
16895                // previously derived ABI information.
16896                pkg.applicationInfo.primaryCpuAbi = ps.primaryCpuAbiString;
16897                pkg.applicationInfo.secondaryCpuAbi = ps.secondaryCpuAbiString;
16898            }
16899
16900        } else if (!forwardLocked && !pkg.applicationInfo.isExternalAsec()) {
16901            // Enable SCAN_NO_DEX flag to skip dexopt at a later stage
16902            scanFlags |= SCAN_NO_DEX;
16903
16904            try {
16905                String abiOverride = (TextUtils.isEmpty(pkg.cpuAbiOverride) ?
16906                    args.abiOverride : pkg.cpuAbiOverride);
16907                derivePackageAbi(pkg, new File(pkg.codePath), abiOverride,
16908                        true /*extractLibs*/, mAppLib32InstallDir);
16909            } catch (PackageManagerException pme) {
16910                Slog.e(TAG, "Error deriving application ABI", pme);
16911                res.setError(INSTALL_FAILED_INTERNAL_ERROR, "Error deriving application ABI");
16912                return;
16913            }
16914
16915            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt");
16916            // Do not run PackageDexOptimizer through the local performDexOpt
16917            // method because `pkg` may not be in `mPackages` yet.
16918            //
16919            // Also, don't fail application installs if the dexopt step fails.
16920            mPackageDexOptimizer.performDexOpt(pkg, pkg.usesLibraryFiles,
16921                    null /* instructionSets */, false /* checkProfiles */,
16922                    getCompilerFilterForReason(REASON_INSTALL),
16923                    getOrCreateCompilerPackageStats(pkg));
16924            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
16925
16926            // Notify BackgroundDexOptJobService that the package has been changed.
16927            // If this is an update of a package which used to fail to compile,
16928            // BDOS will remove it from its blacklist.
16929            // TODO: Layering violation
16930            BackgroundDexOptJobService.notifyPackageChanged(pkg.packageName);
16931        }
16932
16933        if (!args.doRename(res.returnCode, pkg, oldCodePath)) {
16934            res.setError(INSTALL_FAILED_INSUFFICIENT_STORAGE, "Failed rename");
16935            return;
16936        }
16937
16938        startIntentFilterVerifications(args.user.getIdentifier(), replace, pkg);
16939
16940        try (PackageFreezer freezer = freezePackageForInstall(pkgName, installFlags,
16941                "installPackageLI")) {
16942            if (replace) {
16943                if (pkg.applicationInfo.isStaticSharedLibrary()) {
16944                    // Static libs have a synthetic package name containing the version
16945                    // and cannot be updated as an update would get a new package name,
16946                    // unless this is the exact same version code which is useful for
16947                    // development.
16948                    PackageParser.Package existingPkg = mPackages.get(pkg.packageName);
16949                    if (existingPkg != null && existingPkg.mVersionCode != pkg.mVersionCode) {
16950                        res.setError(INSTALL_FAILED_DUPLICATE_PACKAGE, "Packages declaring "
16951                                + "static-shared libs cannot be updated");
16952                        return;
16953                    }
16954                }
16955                replacePackageLIF(pkg, parseFlags, scanFlags | SCAN_REPLACING, args.user,
16956                        installerPackageName, res, args.installReason);
16957            } else {
16958                installNewPackageLIF(pkg, parseFlags, scanFlags | SCAN_DELETE_DATA_ON_FAILURES,
16959                        args.user, installerPackageName, volumeUuid, res, args.installReason);
16960            }
16961        }
16962        synchronized (mPackages) {
16963            final PackageSetting ps = mSettings.mPackages.get(pkgName);
16964            if (ps != null) {
16965                res.newUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
16966            }
16967
16968            final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
16969            for (int i = 0; i < childCount; i++) {
16970                PackageParser.Package childPkg = pkg.childPackages.get(i);
16971                PackageInstalledInfo childRes = res.addedChildPackages.get(childPkg.packageName);
16972                PackageSetting childPs = mSettings.getPackageLPr(childPkg.packageName);
16973                if (childPs != null) {
16974                    childRes.newUsers = childPs.queryInstalledUsers(
16975                            sUserManager.getUserIds(), true);
16976                }
16977            }
16978
16979            if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
16980                updateSequenceNumberLP(pkgName, res.newUsers);
16981            }
16982        }
16983    }
16984
16985    private void startIntentFilterVerifications(int userId, boolean replacing,
16986            PackageParser.Package pkg) {
16987        if (mIntentFilterVerifierComponent == null) {
16988            Slog.w(TAG, "No IntentFilter verification will not be done as "
16989                    + "there is no IntentFilterVerifier available!");
16990            return;
16991        }
16992
16993        final int verifierUid = getPackageUid(
16994                mIntentFilterVerifierComponent.getPackageName(),
16995                MATCH_DEBUG_TRIAGED_MISSING,
16996                (userId == UserHandle.USER_ALL) ? UserHandle.USER_SYSTEM : userId);
16997
16998        Message msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS);
16999        msg.obj = new IFVerificationParams(pkg, replacing, userId, verifierUid);
17000        mHandler.sendMessage(msg);
17001
17002        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
17003        for (int i = 0; i < childCount; i++) {
17004            PackageParser.Package childPkg = pkg.childPackages.get(i);
17005            msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS);
17006            msg.obj = new IFVerificationParams(childPkg, replacing, userId, verifierUid);
17007            mHandler.sendMessage(msg);
17008        }
17009    }
17010
17011    private void verifyIntentFiltersIfNeeded(int userId, int verifierUid, boolean replacing,
17012            PackageParser.Package pkg) {
17013        int size = pkg.activities.size();
17014        if (size == 0) {
17015            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
17016                    "No activity, so no need to verify any IntentFilter!");
17017            return;
17018        }
17019
17020        final boolean hasDomainURLs = hasDomainURLs(pkg);
17021        if (!hasDomainURLs) {
17022            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
17023                    "No domain URLs, so no need to verify any IntentFilter!");
17024            return;
17025        }
17026
17027        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Checking for userId:" + userId
17028                + " if any IntentFilter from the " + size
17029                + " Activities needs verification ...");
17030
17031        int count = 0;
17032        final String packageName = pkg.packageName;
17033
17034        synchronized (mPackages) {
17035            // If this is a new install and we see that we've already run verification for this
17036            // package, we have nothing to do: it means the state was restored from backup.
17037            if (!replacing) {
17038                IntentFilterVerificationInfo ivi =
17039                        mSettings.getIntentFilterVerificationLPr(packageName);
17040                if (ivi != null) {
17041                    if (DEBUG_DOMAIN_VERIFICATION) {
17042                        Slog.i(TAG, "Package " + packageName+ " already verified: status="
17043                                + ivi.getStatusString());
17044                    }
17045                    return;
17046                }
17047            }
17048
17049            // If any filters need to be verified, then all need to be.
17050            boolean needToVerify = false;
17051            for (PackageParser.Activity a : pkg.activities) {
17052                for (ActivityIntentInfo filter : a.intents) {
17053                    if (filter.needsVerification() && needsNetworkVerificationLPr(filter)) {
17054                        if (DEBUG_DOMAIN_VERIFICATION) {
17055                            Slog.d(TAG, "Intent filter needs verification, so processing all filters");
17056                        }
17057                        needToVerify = true;
17058                        break;
17059                    }
17060                }
17061            }
17062
17063            if (needToVerify) {
17064                final int verificationId = mIntentFilterVerificationToken++;
17065                for (PackageParser.Activity a : pkg.activities) {
17066                    for (ActivityIntentInfo filter : a.intents) {
17067                        if (filter.handlesWebUris(true) && needsNetworkVerificationLPr(filter)) {
17068                            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
17069                                    "Verification needed for IntentFilter:" + filter.toString());
17070                            mIntentFilterVerifier.addOneIntentFilterVerification(
17071                                    verifierUid, userId, verificationId, filter, packageName);
17072                            count++;
17073                        }
17074                    }
17075                }
17076            }
17077        }
17078
17079        if (count > 0) {
17080            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Starting " + count
17081                    + " IntentFilter verification" + (count > 1 ? "s" : "")
17082                    +  " for userId:" + userId);
17083            mIntentFilterVerifier.startVerifications(userId);
17084        } else {
17085            if (DEBUG_DOMAIN_VERIFICATION) {
17086                Slog.d(TAG, "No filters or not all autoVerify for " + packageName);
17087            }
17088        }
17089    }
17090
17091    private boolean needsNetworkVerificationLPr(ActivityIntentInfo filter) {
17092        final ComponentName cn  = filter.activity.getComponentName();
17093        final String packageName = cn.getPackageName();
17094
17095        IntentFilterVerificationInfo ivi = mSettings.getIntentFilterVerificationLPr(
17096                packageName);
17097        if (ivi == null) {
17098            return true;
17099        }
17100        int status = ivi.getStatus();
17101        switch (status) {
17102            case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED:
17103            case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK:
17104                return true;
17105
17106            default:
17107                // Nothing to do
17108                return false;
17109        }
17110    }
17111
17112    private static boolean isMultiArch(ApplicationInfo info) {
17113        return (info.flags & ApplicationInfo.FLAG_MULTIARCH) != 0;
17114    }
17115
17116    private static boolean isExternal(PackageParser.Package pkg) {
17117        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
17118    }
17119
17120    private static boolean isExternal(PackageSetting ps) {
17121        return (ps.pkgFlags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
17122    }
17123
17124    private static boolean isSystemApp(PackageParser.Package pkg) {
17125        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0;
17126    }
17127
17128    private static boolean isPrivilegedApp(PackageParser.Package pkg) {
17129        return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0;
17130    }
17131
17132    private static boolean hasDomainURLs(PackageParser.Package pkg) {
17133        return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_HAS_DOMAIN_URLS) != 0;
17134    }
17135
17136    private static boolean isSystemApp(PackageSetting ps) {
17137        return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0;
17138    }
17139
17140    private static boolean isUpdatedSystemApp(PackageSetting ps) {
17141        return (ps.pkgFlags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0;
17142    }
17143
17144    private int packageFlagsToInstallFlags(PackageSetting ps) {
17145        int installFlags = 0;
17146        if (isExternal(ps) && TextUtils.isEmpty(ps.volumeUuid)) {
17147            // This existing package was an external ASEC install when we have
17148            // the external flag without a UUID
17149            installFlags |= PackageManager.INSTALL_EXTERNAL;
17150        }
17151        if (ps.isForwardLocked()) {
17152            installFlags |= PackageManager.INSTALL_FORWARD_LOCK;
17153        }
17154        return installFlags;
17155    }
17156
17157    private String getVolumeUuidForPackage(PackageParser.Package pkg) {
17158        if (isExternal(pkg)) {
17159            if (TextUtils.isEmpty(pkg.volumeUuid)) {
17160                return StorageManager.UUID_PRIMARY_PHYSICAL;
17161            } else {
17162                return pkg.volumeUuid;
17163            }
17164        } else {
17165            return StorageManager.UUID_PRIVATE_INTERNAL;
17166        }
17167    }
17168
17169    private VersionInfo getSettingsVersionForPackage(PackageParser.Package pkg) {
17170        if (isExternal(pkg)) {
17171            if (TextUtils.isEmpty(pkg.volumeUuid)) {
17172                return mSettings.getExternalVersion();
17173            } else {
17174                return mSettings.findOrCreateVersion(pkg.volumeUuid);
17175            }
17176        } else {
17177            return mSettings.getInternalVersion();
17178        }
17179    }
17180
17181    private void deleteTempPackageFiles() {
17182        final FilenameFilter filter = new FilenameFilter() {
17183            public boolean accept(File dir, String name) {
17184                return name.startsWith("vmdl") && name.endsWith(".tmp");
17185            }
17186        };
17187        for (File file : mDrmAppPrivateInstallDir.listFiles(filter)) {
17188            file.delete();
17189        }
17190    }
17191
17192    @Override
17193    public void deletePackageAsUser(String packageName, int versionCode,
17194            IPackageDeleteObserver observer, int userId, int flags) {
17195        deletePackageVersioned(new VersionedPackage(packageName, versionCode),
17196                new LegacyPackageDeleteObserver(observer).getBinder(), userId, flags);
17197    }
17198
17199    @Override
17200    public void deletePackageVersioned(VersionedPackage versionedPackage,
17201            final IPackageDeleteObserver2 observer, final int userId, final int deleteFlags) {
17202        mContext.enforceCallingOrSelfPermission(
17203                android.Manifest.permission.DELETE_PACKAGES, null);
17204        Preconditions.checkNotNull(versionedPackage);
17205        Preconditions.checkNotNull(observer);
17206        Preconditions.checkArgumentInRange(versionedPackage.getVersionCode(),
17207                PackageManager.VERSION_CODE_HIGHEST,
17208                Integer.MAX_VALUE, "versionCode must be >= -1");
17209
17210        final String packageName = versionedPackage.getPackageName();
17211        // TODO: We will change version code to long, so in the new API it is long
17212        final int versionCode = (int) versionedPackage.getVersionCode();
17213        final String internalPackageName;
17214        synchronized (mPackages) {
17215            // Normalize package name to handle renamed packages and static libs
17216            internalPackageName = resolveInternalPackageNameLPr(versionedPackage.getPackageName(),
17217                    // TODO: We will change version code to long, so in the new API it is long
17218                    (int) versionedPackage.getVersionCode());
17219        }
17220
17221        final int uid = Binder.getCallingUid();
17222        if (!isOrphaned(internalPackageName)
17223                && !isCallerAllowedToSilentlyUninstall(uid, internalPackageName)) {
17224            try {
17225                final Intent intent = new Intent(Intent.ACTION_UNINSTALL_PACKAGE);
17226                intent.setData(Uri.fromParts(PACKAGE_SCHEME, packageName, null));
17227                intent.putExtra(PackageInstaller.EXTRA_CALLBACK, observer.asBinder());
17228                observer.onUserActionRequired(intent);
17229            } catch (RemoteException re) {
17230            }
17231            return;
17232        }
17233        final boolean deleteAllUsers = (deleteFlags & PackageManager.DELETE_ALL_USERS) != 0;
17234        final int[] users = deleteAllUsers ? sUserManager.getUserIds() : new int[]{ userId };
17235        if (UserHandle.getUserId(uid) != userId || (deleteAllUsers && users.length > 1)) {
17236            mContext.enforceCallingOrSelfPermission(
17237                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
17238                    "deletePackage for user " + userId);
17239        }
17240
17241        if (isUserRestricted(userId, UserManager.DISALLOW_UNINSTALL_APPS)) {
17242            try {
17243                observer.onPackageDeleted(packageName,
17244                        PackageManager.DELETE_FAILED_USER_RESTRICTED, null);
17245            } catch (RemoteException re) {
17246            }
17247            return;
17248        }
17249
17250        if (!deleteAllUsers && getBlockUninstallForUser(internalPackageName, userId)) {
17251            try {
17252                observer.onPackageDeleted(packageName,
17253                        PackageManager.DELETE_FAILED_OWNER_BLOCKED, null);
17254            } catch (RemoteException re) {
17255            }
17256            return;
17257        }
17258
17259        if (DEBUG_REMOVE) {
17260            Slog.d(TAG, "deletePackageAsUser: pkg=" + internalPackageName + " user=" + userId
17261                    + " deleteAllUsers: " + deleteAllUsers + " version="
17262                    + (versionCode == PackageManager.VERSION_CODE_HIGHEST
17263                    ? "VERSION_CODE_HIGHEST" : versionCode));
17264        }
17265        // Queue up an async operation since the package deletion may take a little while.
17266        mHandler.post(new Runnable() {
17267            public void run() {
17268                mHandler.removeCallbacks(this);
17269                int returnCode;
17270                if (!deleteAllUsers) {
17271                    returnCode = deletePackageX(internalPackageName, versionCode,
17272                            userId, deleteFlags);
17273                } else {
17274                    int[] blockUninstallUserIds = getBlockUninstallForUsers(
17275                            internalPackageName, users);
17276                    // If nobody is blocking uninstall, proceed with delete for all users
17277                    if (ArrayUtils.isEmpty(blockUninstallUserIds)) {
17278                        returnCode = deletePackageX(internalPackageName, versionCode,
17279                                userId, deleteFlags);
17280                    } else {
17281                        // Otherwise uninstall individually for users with blockUninstalls=false
17282                        final int userFlags = deleteFlags & ~PackageManager.DELETE_ALL_USERS;
17283                        for (int userId : users) {
17284                            if (!ArrayUtils.contains(blockUninstallUserIds, userId)) {
17285                                returnCode = deletePackageX(internalPackageName, versionCode,
17286                                        userId, userFlags);
17287                                if (returnCode != PackageManager.DELETE_SUCCEEDED) {
17288                                    Slog.w(TAG, "Package delete failed for user " + userId
17289                                            + ", returnCode " + returnCode);
17290                                }
17291                            }
17292                        }
17293                        // The app has only been marked uninstalled for certain users.
17294                        // We still need to report that delete was blocked
17295                        returnCode = PackageManager.DELETE_FAILED_OWNER_BLOCKED;
17296                    }
17297                }
17298                try {
17299                    observer.onPackageDeleted(packageName, returnCode, null);
17300                } catch (RemoteException e) {
17301                    Log.i(TAG, "Observer no longer exists.");
17302                } //end catch
17303            } //end run
17304        });
17305    }
17306
17307    private String resolveExternalPackageNameLPr(PackageParser.Package pkg) {
17308        if (pkg.staticSharedLibName != null) {
17309            return pkg.manifestPackageName;
17310        }
17311        return pkg.packageName;
17312    }
17313
17314    private String resolveInternalPackageNameLPr(String packageName, int versionCode) {
17315        // Handle renamed packages
17316        String normalizedPackageName = mSettings.getRenamedPackageLPr(packageName);
17317        packageName = normalizedPackageName != null ? normalizedPackageName : packageName;
17318
17319        // Is this a static library?
17320        SparseArray<SharedLibraryEntry> versionedLib =
17321                mStaticLibsByDeclaringPackage.get(packageName);
17322        if (versionedLib == null || versionedLib.size() <= 0) {
17323            return packageName;
17324        }
17325
17326        // Figure out which lib versions the caller can see
17327        SparseIntArray versionsCallerCanSee = null;
17328        final int callingAppId = UserHandle.getAppId(Binder.getCallingUid());
17329        if (callingAppId != Process.SYSTEM_UID && callingAppId != Process.SHELL_UID
17330                && callingAppId != Process.ROOT_UID) {
17331            versionsCallerCanSee = new SparseIntArray();
17332            String libName = versionedLib.valueAt(0).info.getName();
17333            String[] uidPackages = getPackagesForUid(Binder.getCallingUid());
17334            if (uidPackages != null) {
17335                for (String uidPackage : uidPackages) {
17336                    PackageSetting ps = mSettings.getPackageLPr(uidPackage);
17337                    final int libIdx = ArrayUtils.indexOf(ps.usesStaticLibraries, libName);
17338                    if (libIdx >= 0) {
17339                        final int libVersion = ps.usesStaticLibrariesVersions[libIdx];
17340                        versionsCallerCanSee.append(libVersion, libVersion);
17341                    }
17342                }
17343            }
17344        }
17345
17346        // Caller can see nothing - done
17347        if (versionsCallerCanSee != null && versionsCallerCanSee.size() <= 0) {
17348            return packageName;
17349        }
17350
17351        // Find the version the caller can see and the app version code
17352        SharedLibraryEntry highestVersion = null;
17353        final int versionCount = versionedLib.size();
17354        for (int i = 0; i < versionCount; i++) {
17355            SharedLibraryEntry libEntry = versionedLib.valueAt(i);
17356            if (versionsCallerCanSee != null && versionsCallerCanSee.indexOfKey(
17357                    libEntry.info.getVersion()) < 0) {
17358                continue;
17359            }
17360            // TODO: We will change version code to long, so in the new API it is long
17361            final int libVersionCode = (int) libEntry.info.getDeclaringPackage().getVersionCode();
17362            if (versionCode != PackageManager.VERSION_CODE_HIGHEST) {
17363                if (libVersionCode == versionCode) {
17364                    return libEntry.apk;
17365                }
17366            } else if (highestVersion == null) {
17367                highestVersion = libEntry;
17368            } else if (libVersionCode  > highestVersion.info
17369                    .getDeclaringPackage().getVersionCode()) {
17370                highestVersion = libEntry;
17371            }
17372        }
17373
17374        if (highestVersion != null) {
17375            return highestVersion.apk;
17376        }
17377
17378        return packageName;
17379    }
17380
17381    private boolean isCallerAllowedToSilentlyUninstall(int callingUid, String pkgName) {
17382        if (callingUid == Process.SHELL_UID || callingUid == Process.ROOT_UID
17383              || callingUid == Process.SYSTEM_UID) {
17384            return true;
17385        }
17386        final int callingUserId = UserHandle.getUserId(callingUid);
17387        // If the caller installed the pkgName, then allow it to silently uninstall.
17388        if (callingUid == getPackageUid(getInstallerPackageName(pkgName), 0, callingUserId)) {
17389            return true;
17390        }
17391
17392        // Allow package verifier to silently uninstall.
17393        if (mRequiredVerifierPackage != null &&
17394                callingUid == getPackageUid(mRequiredVerifierPackage, 0, callingUserId)) {
17395            return true;
17396        }
17397
17398        // Allow package uninstaller to silently uninstall.
17399        if (mRequiredUninstallerPackage != null &&
17400                callingUid == getPackageUid(mRequiredUninstallerPackage, 0, callingUserId)) {
17401            return true;
17402        }
17403
17404        // Allow storage manager to silently uninstall.
17405        if (mStorageManagerPackage != null &&
17406                callingUid == getPackageUid(mStorageManagerPackage, 0, callingUserId)) {
17407            return true;
17408        }
17409        return false;
17410    }
17411
17412    private int[] getBlockUninstallForUsers(String packageName, int[] userIds) {
17413        int[] result = EMPTY_INT_ARRAY;
17414        for (int userId : userIds) {
17415            if (getBlockUninstallForUser(packageName, userId)) {
17416                result = ArrayUtils.appendInt(result, userId);
17417            }
17418        }
17419        return result;
17420    }
17421
17422    @Override
17423    public boolean isPackageDeviceAdminOnAnyUser(String packageName) {
17424        return isPackageDeviceAdmin(packageName, UserHandle.USER_ALL);
17425    }
17426
17427    private boolean isPackageDeviceAdmin(String packageName, int userId) {
17428        IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface(
17429                ServiceManager.getService(Context.DEVICE_POLICY_SERVICE));
17430        try {
17431            if (dpm != null) {
17432                final ComponentName deviceOwnerComponentName = dpm.getDeviceOwnerComponent(
17433                        /* callingUserOnly =*/ false);
17434                final String deviceOwnerPackageName = deviceOwnerComponentName == null ? null
17435                        : deviceOwnerComponentName.getPackageName();
17436                // Does the package contains the device owner?
17437                // TODO Do we have to do it even if userId != UserHandle.USER_ALL?  Otherwise,
17438                // this check is probably not needed, since DO should be registered as a device
17439                // admin on some user too. (Original bug for this: b/17657954)
17440                if (packageName.equals(deviceOwnerPackageName)) {
17441                    return true;
17442                }
17443                // Does it contain a device admin for any user?
17444                int[] users;
17445                if (userId == UserHandle.USER_ALL) {
17446                    users = sUserManager.getUserIds();
17447                } else {
17448                    users = new int[]{userId};
17449                }
17450                for (int i = 0; i < users.length; ++i) {
17451                    if (dpm.packageHasActiveAdmins(packageName, users[i])) {
17452                        return true;
17453                    }
17454                }
17455            }
17456        } catch (RemoteException e) {
17457        }
17458        return false;
17459    }
17460
17461    private boolean shouldKeepUninstalledPackageLPr(String packageName) {
17462        return mKeepUninstalledPackages != null && mKeepUninstalledPackages.contains(packageName);
17463    }
17464
17465    /**
17466     *  This method is an internal method that could be get invoked either
17467     *  to delete an installed package or to clean up a failed installation.
17468     *  After deleting an installed package, a broadcast is sent to notify any
17469     *  listeners that the package has been removed. For cleaning up a failed
17470     *  installation, the broadcast is not necessary since the package's
17471     *  installation wouldn't have sent the initial broadcast either
17472     *  The key steps in deleting a package are
17473     *  deleting the package information in internal structures like mPackages,
17474     *  deleting the packages base directories through installd
17475     *  updating mSettings to reflect current status
17476     *  persisting settings for later use
17477     *  sending a broadcast if necessary
17478     */
17479    private int deletePackageX(String packageName, int versionCode, int userId, int deleteFlags) {
17480        final PackageRemovedInfo info = new PackageRemovedInfo();
17481        final boolean res;
17482
17483        final int removeUser = (deleteFlags & PackageManager.DELETE_ALL_USERS) != 0
17484                ? UserHandle.USER_ALL : userId;
17485
17486        if (isPackageDeviceAdmin(packageName, removeUser)) {
17487            Slog.w(TAG, "Not removing package " + packageName + ": has active device admin");
17488            return PackageManager.DELETE_FAILED_DEVICE_POLICY_MANAGER;
17489        }
17490
17491        PackageSetting uninstalledPs = null;
17492
17493        // for the uninstall-updates case and restricted profiles, remember the per-
17494        // user handle installed state
17495        int[] allUsers;
17496        synchronized (mPackages) {
17497            uninstalledPs = mSettings.mPackages.get(packageName);
17498            if (uninstalledPs == null) {
17499                Slog.w(TAG, "Not removing non-existent package " + packageName);
17500                return PackageManager.DELETE_FAILED_INTERNAL_ERROR;
17501            }
17502
17503            if (versionCode != PackageManager.VERSION_CODE_HIGHEST
17504                    && uninstalledPs.versionCode != versionCode) {
17505                Slog.w(TAG, "Not removing package " + packageName + " with versionCode "
17506                        + uninstalledPs.versionCode + " != " + versionCode);
17507                return PackageManager.DELETE_FAILED_INTERNAL_ERROR;
17508            }
17509
17510            // Static shared libs can be declared by any package, so let us not
17511            // allow removing a package if it provides a lib others depend on.
17512            PackageParser.Package pkg = mPackages.get(packageName);
17513            if (pkg != null && pkg.staticSharedLibName != null) {
17514                SharedLibraryEntry libEntry = getSharedLibraryEntryLPr(pkg.staticSharedLibName,
17515                        pkg.staticSharedLibVersion);
17516                if (libEntry != null) {
17517                    List<VersionedPackage> libClientPackages = getPackagesUsingSharedLibraryLPr(
17518                            libEntry.info, 0, userId);
17519                    if (!ArrayUtils.isEmpty(libClientPackages)) {
17520                        Slog.w(TAG, "Not removing package " + pkg.manifestPackageName
17521                                + " hosting lib " + libEntry.info.getName() + " version "
17522                                + libEntry.info.getVersion()  + " used by " + libClientPackages);
17523                        return PackageManager.DELETE_FAILED_USED_SHARED_LIBRARY;
17524                    }
17525                }
17526            }
17527
17528            allUsers = sUserManager.getUserIds();
17529            info.origUsers = uninstalledPs.queryInstalledUsers(allUsers, true);
17530        }
17531
17532        final int freezeUser;
17533        if (isUpdatedSystemApp(uninstalledPs)
17534                && ((deleteFlags & PackageManager.DELETE_SYSTEM_APP) == 0)) {
17535            // We're downgrading a system app, which will apply to all users, so
17536            // freeze them all during the downgrade
17537            freezeUser = UserHandle.USER_ALL;
17538        } else {
17539            freezeUser = removeUser;
17540        }
17541
17542        synchronized (mInstallLock) {
17543            if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageX: pkg=" + packageName + " user=" + userId);
17544            try (PackageFreezer freezer = freezePackageForDelete(packageName, freezeUser,
17545                    deleteFlags, "deletePackageX")) {
17546                res = deletePackageLIF(packageName, UserHandle.of(removeUser), true, allUsers,
17547                        deleteFlags | FLAGS_REMOVE_CHATTY, info, true, null);
17548            }
17549            synchronized (mPackages) {
17550                if (res) {
17551                    mInstantAppRegistry.onPackageUninstalledLPw(uninstalledPs.pkg,
17552                            info.removedUsers);
17553                    updateSequenceNumberLP(packageName, info.removedUsers);
17554                }
17555            }
17556        }
17557
17558        if (res) {
17559            final boolean killApp = (deleteFlags & PackageManager.DELETE_DONT_KILL_APP) == 0;
17560            info.sendPackageRemovedBroadcasts(killApp);
17561            info.sendSystemPackageUpdatedBroadcasts();
17562            info.sendSystemPackageAppearedBroadcasts();
17563        }
17564        // Force a gc here.
17565        Runtime.getRuntime().gc();
17566        // Delete the resources here after sending the broadcast to let
17567        // other processes clean up before deleting resources.
17568        if (info.args != null) {
17569            synchronized (mInstallLock) {
17570                info.args.doPostDeleteLI(true);
17571            }
17572        }
17573
17574        return res ? PackageManager.DELETE_SUCCEEDED : PackageManager.DELETE_FAILED_INTERNAL_ERROR;
17575    }
17576
17577    class PackageRemovedInfo {
17578        String removedPackage;
17579        int uid = -1;
17580        int removedAppId = -1;
17581        int[] origUsers;
17582        int[] removedUsers = null;
17583        SparseArray<Integer> installReasons;
17584        boolean isRemovedPackageSystemUpdate = false;
17585        boolean isUpdate;
17586        boolean dataRemoved;
17587        boolean removedForAllUsers;
17588        boolean isStaticSharedLib;
17589        // Clean up resources deleted packages.
17590        InstallArgs args = null;
17591        ArrayMap<String, PackageRemovedInfo> removedChildPackages;
17592        ArrayMap<String, PackageInstalledInfo> appearedChildPackages;
17593
17594        void sendPackageRemovedBroadcasts(boolean killApp) {
17595            sendPackageRemovedBroadcastInternal(killApp);
17596            final int childCount = removedChildPackages != null ? removedChildPackages.size() : 0;
17597            for (int i = 0; i < childCount; i++) {
17598                PackageRemovedInfo childInfo = removedChildPackages.valueAt(i);
17599                childInfo.sendPackageRemovedBroadcastInternal(killApp);
17600            }
17601        }
17602
17603        void sendSystemPackageUpdatedBroadcasts() {
17604            if (isRemovedPackageSystemUpdate) {
17605                sendSystemPackageUpdatedBroadcastsInternal();
17606                final int childCount = (removedChildPackages != null)
17607                        ? removedChildPackages.size() : 0;
17608                for (int i = 0; i < childCount; i++) {
17609                    PackageRemovedInfo childInfo = removedChildPackages.valueAt(i);
17610                    if (childInfo.isRemovedPackageSystemUpdate) {
17611                        childInfo.sendSystemPackageUpdatedBroadcastsInternal();
17612                    }
17613                }
17614            }
17615        }
17616
17617        void sendSystemPackageAppearedBroadcasts() {
17618            final int packageCount = (appearedChildPackages != null)
17619                    ? appearedChildPackages.size() : 0;
17620            for (int i = 0; i < packageCount; i++) {
17621                PackageInstalledInfo installedInfo = appearedChildPackages.valueAt(i);
17622                sendPackageAddedForNewUsers(installedInfo.name, true,
17623                        UserHandle.getAppId(installedInfo.uid), installedInfo.newUsers);
17624            }
17625        }
17626
17627        private void sendSystemPackageUpdatedBroadcastsInternal() {
17628            Bundle extras = new Bundle(2);
17629            extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid);
17630            extras.putBoolean(Intent.EXTRA_REPLACING, true);
17631            sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, removedPackage,
17632                    extras, 0, null, null, null);
17633            sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, removedPackage,
17634                    extras, 0, null, null, null);
17635            sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, null,
17636                    null, 0, removedPackage, null, null);
17637        }
17638
17639        private void sendPackageRemovedBroadcastInternal(boolean killApp) {
17640            // Don't send static shared library removal broadcasts as these
17641            // libs are visible only the the apps that depend on them an one
17642            // cannot remove the library if it has a dependency.
17643            if (isStaticSharedLib) {
17644                return;
17645            }
17646            Bundle extras = new Bundle(2);
17647            extras.putInt(Intent.EXTRA_UID, removedAppId >= 0  ? removedAppId : uid);
17648            extras.putBoolean(Intent.EXTRA_DATA_REMOVED, dataRemoved);
17649            extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, !killApp);
17650            if (isUpdate || isRemovedPackageSystemUpdate) {
17651                extras.putBoolean(Intent.EXTRA_REPLACING, true);
17652            }
17653            extras.putBoolean(Intent.EXTRA_REMOVED_FOR_ALL_USERS, removedForAllUsers);
17654            if (removedPackage != null) {
17655                sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, removedPackage,
17656                        extras, 0, null, null, removedUsers);
17657                if (dataRemoved && !isRemovedPackageSystemUpdate) {
17658                    sendPackageBroadcast(Intent.ACTION_PACKAGE_FULLY_REMOVED,
17659                            removedPackage, extras, Intent.FLAG_RECEIVER_INCLUDE_BACKGROUND,
17660                            null, null, removedUsers);
17661                }
17662            }
17663            if (removedAppId >= 0) {
17664                sendPackageBroadcast(Intent.ACTION_UID_REMOVED, null, extras, 0, null, null,
17665                        removedUsers);
17666            }
17667        }
17668    }
17669
17670    /*
17671     * This method deletes the package from internal data structures. If the DONT_DELETE_DATA
17672     * flag is not set, the data directory is removed as well.
17673     * make sure this flag is set for partially installed apps. If not its meaningless to
17674     * delete a partially installed application.
17675     */
17676    private void removePackageDataLIF(PackageSetting ps, int[] allUserHandles,
17677            PackageRemovedInfo outInfo, int flags, boolean writeSettings) {
17678        String packageName = ps.name;
17679        if (DEBUG_REMOVE) Slog.d(TAG, "removePackageDataLI: " + ps);
17680        // Retrieve object to delete permissions for shared user later on
17681        final PackageParser.Package deletedPkg;
17682        final PackageSetting deletedPs;
17683        // reader
17684        synchronized (mPackages) {
17685            deletedPkg = mPackages.get(packageName);
17686            deletedPs = mSettings.mPackages.get(packageName);
17687            if (outInfo != null) {
17688                outInfo.removedPackage = packageName;
17689                outInfo.isStaticSharedLib = deletedPkg != null
17690                        && deletedPkg.staticSharedLibName != null;
17691                outInfo.removedUsers = deletedPs != null
17692                        ? deletedPs.queryInstalledUsers(sUserManager.getUserIds(), true)
17693                        : null;
17694            }
17695        }
17696
17697        removePackageLI(ps, (flags & FLAGS_REMOVE_CHATTY) != 0);
17698
17699        if ((flags & PackageManager.DELETE_KEEP_DATA) == 0) {
17700            final PackageParser.Package resolvedPkg;
17701            if (deletedPkg != null) {
17702                resolvedPkg = deletedPkg;
17703            } else {
17704                // We don't have a parsed package when it lives on an ejected
17705                // adopted storage device, so fake something together
17706                resolvedPkg = new PackageParser.Package(ps.name);
17707                resolvedPkg.setVolumeUuid(ps.volumeUuid);
17708            }
17709            destroyAppDataLIF(resolvedPkg, UserHandle.USER_ALL,
17710                    StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
17711            destroyAppProfilesLIF(resolvedPkg, UserHandle.USER_ALL);
17712            if (outInfo != null) {
17713                outInfo.dataRemoved = true;
17714            }
17715            schedulePackageCleaning(packageName, UserHandle.USER_ALL, true);
17716        }
17717
17718        int removedAppId = -1;
17719
17720        // writer
17721        synchronized (mPackages) {
17722            boolean installedStateChanged = false;
17723            if (deletedPs != null) {
17724                if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) {
17725                    clearIntentFilterVerificationsLPw(deletedPs.name, UserHandle.USER_ALL);
17726                    clearDefaultBrowserIfNeeded(packageName);
17727                    mSettings.mKeySetManagerService.removeAppKeySetDataLPw(packageName);
17728                    removedAppId = mSettings.removePackageLPw(packageName);
17729                    if (outInfo != null) {
17730                        outInfo.removedAppId = removedAppId;
17731                    }
17732                    updatePermissionsLPw(deletedPs.name, null, 0);
17733                    if (deletedPs.sharedUser != null) {
17734                        // Remove permissions associated with package. Since runtime
17735                        // permissions are per user we have to kill the removed package
17736                        // or packages running under the shared user of the removed
17737                        // package if revoking the permissions requested only by the removed
17738                        // package is successful and this causes a change in gids.
17739                        for (int userId : UserManagerService.getInstance().getUserIds()) {
17740                            final int userIdToKill = mSettings.updateSharedUserPermsLPw(deletedPs,
17741                                    userId);
17742                            if (userIdToKill == UserHandle.USER_ALL
17743                                    || userIdToKill >= UserHandle.USER_SYSTEM) {
17744                                // If gids changed for this user, kill all affected packages.
17745                                mHandler.post(new Runnable() {
17746                                    @Override
17747                                    public void run() {
17748                                        // This has to happen with no lock held.
17749                                        killApplication(deletedPs.name, deletedPs.appId,
17750                                                KILL_APP_REASON_GIDS_CHANGED);
17751                                    }
17752                                });
17753                                break;
17754                            }
17755                        }
17756                    }
17757                    clearPackagePreferredActivitiesLPw(deletedPs.name, UserHandle.USER_ALL);
17758                }
17759                // make sure to preserve per-user disabled state if this removal was just
17760                // a downgrade of a system app to the factory package
17761                if (allUserHandles != null && outInfo != null && outInfo.origUsers != null) {
17762                    if (DEBUG_REMOVE) {
17763                        Slog.d(TAG, "Propagating install state across downgrade");
17764                    }
17765                    for (int userId : allUserHandles) {
17766                        final boolean installed = ArrayUtils.contains(outInfo.origUsers, userId);
17767                        if (DEBUG_REMOVE) {
17768                            Slog.d(TAG, "    user " + userId + " => " + installed);
17769                        }
17770                        if (installed != ps.getInstalled(userId)) {
17771                            installedStateChanged = true;
17772                        }
17773                        ps.setInstalled(installed, userId);
17774                    }
17775                }
17776            }
17777            // can downgrade to reader
17778            if (writeSettings) {
17779                // Save settings now
17780                mSettings.writeLPr();
17781            }
17782            if (installedStateChanged) {
17783                mSettings.writeKernelMappingLPr(ps);
17784            }
17785        }
17786        if (removedAppId != -1) {
17787            // A user ID was deleted here. Go through all users and remove it
17788            // from KeyStore.
17789            removeKeystoreDataIfNeeded(UserHandle.USER_ALL, removedAppId);
17790        }
17791    }
17792
17793    static boolean locationIsPrivileged(File path) {
17794        try {
17795            final String privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app")
17796                    .getCanonicalPath();
17797            return path.getCanonicalPath().startsWith(privilegedAppDir);
17798        } catch (IOException e) {
17799            Slog.e(TAG, "Unable to access code path " + path);
17800        }
17801        return false;
17802    }
17803
17804    /*
17805     * Tries to delete system package.
17806     */
17807    private boolean deleteSystemPackageLIF(PackageParser.Package deletedPkg,
17808            PackageSetting deletedPs, int[] allUserHandles, int flags, PackageRemovedInfo outInfo,
17809            boolean writeSettings) {
17810        if (deletedPs.parentPackageName != null) {
17811            Slog.w(TAG, "Attempt to delete child system package " + deletedPkg.packageName);
17812            return false;
17813        }
17814
17815        final boolean applyUserRestrictions
17816                = (allUserHandles != null) && (outInfo.origUsers != null);
17817        final PackageSetting disabledPs;
17818        // Confirm if the system package has been updated
17819        // An updated system app can be deleted. This will also have to restore
17820        // the system pkg from system partition
17821        // reader
17822        synchronized (mPackages) {
17823            disabledPs = mSettings.getDisabledSystemPkgLPr(deletedPs.name);
17824        }
17825
17826        if (DEBUG_REMOVE) Slog.d(TAG, "deleteSystemPackageLI: newPs=" + deletedPkg.packageName
17827                + " disabledPs=" + disabledPs);
17828
17829        if (disabledPs == null) {
17830            Slog.w(TAG, "Attempt to delete unknown system package "+ deletedPkg.packageName);
17831            return false;
17832        } else if (DEBUG_REMOVE) {
17833            Slog.d(TAG, "Deleting system pkg from data partition");
17834        }
17835
17836        if (DEBUG_REMOVE) {
17837            if (applyUserRestrictions) {
17838                Slog.d(TAG, "Remembering install states:");
17839                for (int userId : allUserHandles) {
17840                    final boolean finstalled = ArrayUtils.contains(outInfo.origUsers, userId);
17841                    Slog.d(TAG, "   u=" + userId + " inst=" + finstalled);
17842                }
17843            }
17844        }
17845
17846        // Delete the updated package
17847        outInfo.isRemovedPackageSystemUpdate = true;
17848        if (outInfo.removedChildPackages != null) {
17849            final int childCount = (deletedPs.childPackageNames != null)
17850                    ? deletedPs.childPackageNames.size() : 0;
17851            for (int i = 0; i < childCount; i++) {
17852                String childPackageName = deletedPs.childPackageNames.get(i);
17853                if (disabledPs.childPackageNames != null && disabledPs.childPackageNames
17854                        .contains(childPackageName)) {
17855                    PackageRemovedInfo childInfo = outInfo.removedChildPackages.get(
17856                            childPackageName);
17857                    if (childInfo != null) {
17858                        childInfo.isRemovedPackageSystemUpdate = true;
17859                    }
17860                }
17861            }
17862        }
17863
17864        if (disabledPs.versionCode < deletedPs.versionCode) {
17865            // Delete data for downgrades
17866            flags &= ~PackageManager.DELETE_KEEP_DATA;
17867        } else {
17868            // Preserve data by setting flag
17869            flags |= PackageManager.DELETE_KEEP_DATA;
17870        }
17871
17872        boolean ret = deleteInstalledPackageLIF(deletedPs, true, flags, allUserHandles,
17873                outInfo, writeSettings, disabledPs.pkg);
17874        if (!ret) {
17875            return false;
17876        }
17877
17878        // writer
17879        synchronized (mPackages) {
17880            // Reinstate the old system package
17881            enableSystemPackageLPw(disabledPs.pkg);
17882            // Remove any native libraries from the upgraded package.
17883            removeNativeBinariesLI(deletedPs);
17884        }
17885
17886        // Install the system package
17887        if (DEBUG_REMOVE) Slog.d(TAG, "Re-installing system package: " + disabledPs);
17888        int parseFlags = mDefParseFlags
17889                | PackageParser.PARSE_MUST_BE_APK
17890                | PackageParser.PARSE_IS_SYSTEM
17891                | PackageParser.PARSE_IS_SYSTEM_DIR;
17892        if (locationIsPrivileged(disabledPs.codePath)) {
17893            parseFlags |= PackageParser.PARSE_IS_PRIVILEGED;
17894        }
17895
17896        final PackageParser.Package newPkg;
17897        try {
17898            newPkg = scanPackageTracedLI(disabledPs.codePath, parseFlags, 0 /* scanFlags */,
17899                0 /* currentTime */, null);
17900        } catch (PackageManagerException e) {
17901            Slog.w(TAG, "Failed to restore system package:" + deletedPkg.packageName + ": "
17902                    + e.getMessage());
17903            return false;
17904        }
17905
17906        try {
17907            // update shared libraries for the newly re-installed system package
17908            updateSharedLibrariesLPr(newPkg, null);
17909        } catch (PackageManagerException e) {
17910            Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
17911        }
17912
17913        prepareAppDataAfterInstallLIF(newPkg);
17914
17915        // writer
17916        synchronized (mPackages) {
17917            PackageSetting ps = mSettings.mPackages.get(newPkg.packageName);
17918
17919            // Propagate the permissions state as we do not want to drop on the floor
17920            // runtime permissions. The update permissions method below will take
17921            // care of removing obsolete permissions and grant install permissions.
17922            ps.getPermissionsState().copyFrom(deletedPs.getPermissionsState());
17923            updatePermissionsLPw(newPkg.packageName, newPkg,
17924                    UPDATE_PERMISSIONS_ALL | UPDATE_PERMISSIONS_REPLACE_PKG);
17925
17926            if (applyUserRestrictions) {
17927                boolean installedStateChanged = false;
17928                if (DEBUG_REMOVE) {
17929                    Slog.d(TAG, "Propagating install state across reinstall");
17930                }
17931                for (int userId : allUserHandles) {
17932                    final boolean installed = ArrayUtils.contains(outInfo.origUsers, userId);
17933                    if (DEBUG_REMOVE) {
17934                        Slog.d(TAG, "    user " + userId + " => " + installed);
17935                    }
17936                    if (installed != ps.getInstalled(userId)) {
17937                        installedStateChanged = true;
17938                    }
17939                    ps.setInstalled(installed, userId);
17940
17941                    mSettings.writeRuntimePermissionsForUserLPr(userId, false);
17942                }
17943                // Regardless of writeSettings we need to ensure that this restriction
17944                // state propagation is persisted
17945                mSettings.writeAllUsersPackageRestrictionsLPr();
17946                if (installedStateChanged) {
17947                    mSettings.writeKernelMappingLPr(ps);
17948                }
17949            }
17950            // can downgrade to reader here
17951            if (writeSettings) {
17952                mSettings.writeLPr();
17953            }
17954        }
17955        return true;
17956    }
17957
17958    private boolean deleteInstalledPackageLIF(PackageSetting ps,
17959            boolean deleteCodeAndResources, int flags, int[] allUserHandles,
17960            PackageRemovedInfo outInfo, boolean writeSettings,
17961            PackageParser.Package replacingPackage) {
17962        synchronized (mPackages) {
17963            if (outInfo != null) {
17964                outInfo.uid = ps.appId;
17965            }
17966
17967            if (outInfo != null && outInfo.removedChildPackages != null) {
17968                final int childCount = (ps.childPackageNames != null)
17969                        ? ps.childPackageNames.size() : 0;
17970                for (int i = 0; i < childCount; i++) {
17971                    String childPackageName = ps.childPackageNames.get(i);
17972                    PackageSetting childPs = mSettings.mPackages.get(childPackageName);
17973                    if (childPs == null) {
17974                        return false;
17975                    }
17976                    PackageRemovedInfo childInfo = outInfo.removedChildPackages.get(
17977                            childPackageName);
17978                    if (childInfo != null) {
17979                        childInfo.uid = childPs.appId;
17980                    }
17981                }
17982            }
17983        }
17984
17985        // Delete package data from internal structures and also remove data if flag is set
17986        removePackageDataLIF(ps, allUserHandles, outInfo, flags, writeSettings);
17987
17988        // Delete the child packages data
17989        final int childCount = (ps.childPackageNames != null) ? ps.childPackageNames.size() : 0;
17990        for (int i = 0; i < childCount; i++) {
17991            PackageSetting childPs;
17992            synchronized (mPackages) {
17993                childPs = mSettings.getPackageLPr(ps.childPackageNames.get(i));
17994            }
17995            if (childPs != null) {
17996                PackageRemovedInfo childOutInfo = (outInfo != null
17997                        && outInfo.removedChildPackages != null)
17998                        ? outInfo.removedChildPackages.get(childPs.name) : null;
17999                final int deleteFlags = (flags & DELETE_KEEP_DATA) != 0
18000                        && (replacingPackage != null
18001                        && !replacingPackage.hasChildPackage(childPs.name))
18002                        ? flags & ~DELETE_KEEP_DATA : flags;
18003                removePackageDataLIF(childPs, allUserHandles, childOutInfo,
18004                        deleteFlags, writeSettings);
18005            }
18006        }
18007
18008        // Delete application code and resources only for parent packages
18009        if (ps.parentPackageName == null) {
18010            if (deleteCodeAndResources && (outInfo != null)) {
18011                outInfo.args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
18012                        ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
18013                if (DEBUG_SD_INSTALL) Slog.i(TAG, "args=" + outInfo.args);
18014            }
18015        }
18016
18017        return true;
18018    }
18019
18020    @Override
18021    public boolean setBlockUninstallForUser(String packageName, boolean blockUninstall,
18022            int userId) {
18023        mContext.enforceCallingOrSelfPermission(
18024                android.Manifest.permission.DELETE_PACKAGES, null);
18025        synchronized (mPackages) {
18026            PackageSetting ps = mSettings.mPackages.get(packageName);
18027            if (ps == null) {
18028                Log.i(TAG, "Package doesn't exist in set block uninstall " + packageName);
18029                return false;
18030            }
18031            // Cannot block uninstall of static shared libs as they are
18032            // considered a part of the using app (emulating static linking).
18033            // Also static libs are installed always on internal storage.
18034            PackageParser.Package pkg = mPackages.get(packageName);
18035            if (pkg != null && pkg.staticSharedLibName != null) {
18036                Slog.w(TAG, "Cannot block uninstall of package: " + packageName
18037                        + " providing static shared library: " + pkg.staticSharedLibName);
18038                return false;
18039            }
18040            if (!ps.getInstalled(userId)) {
18041                // Can't block uninstall for an app that is not installed or enabled.
18042                Log.i(TAG, "Package not installed in set block uninstall " + packageName);
18043                return false;
18044            }
18045            ps.setBlockUninstall(blockUninstall, userId);
18046            mSettings.writePackageRestrictionsLPr(userId);
18047        }
18048        return true;
18049    }
18050
18051    @Override
18052    public boolean getBlockUninstallForUser(String packageName, int userId) {
18053        synchronized (mPackages) {
18054            PackageSetting ps = mSettings.mPackages.get(packageName);
18055            if (ps == null) {
18056                Log.i(TAG, "Package doesn't exist in get block uninstall " + packageName);
18057                return false;
18058            }
18059            return ps.getBlockUninstall(userId);
18060        }
18061    }
18062
18063    @Override
18064    public boolean setRequiredForSystemUser(String packageName, boolean systemUserApp) {
18065        int callingUid = Binder.getCallingUid();
18066        if (callingUid != Process.SYSTEM_UID && callingUid != Process.ROOT_UID) {
18067            throw new SecurityException(
18068                    "setRequiredForSystemUser can only be run by the system or root");
18069        }
18070        synchronized (mPackages) {
18071            PackageSetting ps = mSettings.mPackages.get(packageName);
18072            if (ps == null) {
18073                Log.w(TAG, "Package doesn't exist: " + packageName);
18074                return false;
18075            }
18076            if (systemUserApp) {
18077                ps.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_REQUIRED_FOR_SYSTEM_USER;
18078            } else {
18079                ps.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_REQUIRED_FOR_SYSTEM_USER;
18080            }
18081            mSettings.writeLPr();
18082        }
18083        return true;
18084    }
18085
18086    /*
18087     * This method handles package deletion in general
18088     */
18089    private boolean deletePackageLIF(String packageName, UserHandle user,
18090            boolean deleteCodeAndResources, int[] allUserHandles, int flags,
18091            PackageRemovedInfo outInfo, boolean writeSettings,
18092            PackageParser.Package replacingPackage) {
18093        if (packageName == null) {
18094            Slog.w(TAG, "Attempt to delete null packageName.");
18095            return false;
18096        }
18097
18098        if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageLI: " + packageName + " user " + user);
18099
18100        PackageSetting ps;
18101        synchronized (mPackages) {
18102            ps = mSettings.mPackages.get(packageName);
18103            if (ps == null) {
18104                Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
18105                return false;
18106            }
18107
18108            if (ps.parentPackageName != null && (!isSystemApp(ps)
18109                    || (flags & PackageManager.DELETE_SYSTEM_APP) != 0)) {
18110                if (DEBUG_REMOVE) {
18111                    Slog.d(TAG, "Uninstalled child package:" + packageName + " for user:"
18112                            + ((user == null) ? UserHandle.USER_ALL : user));
18113                }
18114                final int removedUserId = (user != null) ? user.getIdentifier()
18115                        : UserHandle.USER_ALL;
18116                if (!clearPackageStateForUserLIF(ps, removedUserId, outInfo)) {
18117                    return false;
18118                }
18119                markPackageUninstalledForUserLPw(ps, user);
18120                scheduleWritePackageRestrictionsLocked(user);
18121                return true;
18122            }
18123        }
18124
18125        if (((!isSystemApp(ps) || (flags&PackageManager.DELETE_SYSTEM_APP) != 0) && user != null
18126                && user.getIdentifier() != UserHandle.USER_ALL)) {
18127            // The caller is asking that the package only be deleted for a single
18128            // user.  To do this, we just mark its uninstalled state and delete
18129            // its data. If this is a system app, we only allow this to happen if
18130            // they have set the special DELETE_SYSTEM_APP which requests different
18131            // semantics than normal for uninstalling system apps.
18132            markPackageUninstalledForUserLPw(ps, user);
18133
18134            if (!isSystemApp(ps)) {
18135                // Do not uninstall the APK if an app should be cached
18136                boolean keepUninstalledPackage = shouldKeepUninstalledPackageLPr(packageName);
18137                if (ps.isAnyInstalled(sUserManager.getUserIds()) || keepUninstalledPackage) {
18138                    // Other user still have this package installed, so all
18139                    // we need to do is clear this user's data and save that
18140                    // it is uninstalled.
18141                    if (DEBUG_REMOVE) Slog.d(TAG, "Still installed by other users");
18142                    if (!clearPackageStateForUserLIF(ps, user.getIdentifier(), outInfo)) {
18143                        return false;
18144                    }
18145                    scheduleWritePackageRestrictionsLocked(user);
18146                    return true;
18147                } else {
18148                    // We need to set it back to 'installed' so the uninstall
18149                    // broadcasts will be sent correctly.
18150                    if (DEBUG_REMOVE) Slog.d(TAG, "Not installed by other users, full delete");
18151                    ps.setInstalled(true, user.getIdentifier());
18152                    mSettings.writeKernelMappingLPr(ps);
18153                }
18154            } else {
18155                // This is a system app, so we assume that the
18156                // other users still have this package installed, so all
18157                // we need to do is clear this user's data and save that
18158                // it is uninstalled.
18159                if (DEBUG_REMOVE) Slog.d(TAG, "Deleting system app");
18160                if (!clearPackageStateForUserLIF(ps, user.getIdentifier(), outInfo)) {
18161                    return false;
18162                }
18163                scheduleWritePackageRestrictionsLocked(user);
18164                return true;
18165            }
18166        }
18167
18168        // If we are deleting a composite package for all users, keep track
18169        // of result for each child.
18170        if (ps.childPackageNames != null && outInfo != null) {
18171            synchronized (mPackages) {
18172                final int childCount = ps.childPackageNames.size();
18173                outInfo.removedChildPackages = new ArrayMap<>(childCount);
18174                for (int i = 0; i < childCount; i++) {
18175                    String childPackageName = ps.childPackageNames.get(i);
18176                    PackageRemovedInfo childInfo = new PackageRemovedInfo();
18177                    childInfo.removedPackage = childPackageName;
18178                    outInfo.removedChildPackages.put(childPackageName, childInfo);
18179                    PackageSetting childPs = mSettings.getPackageLPr(childPackageName);
18180                    if (childPs != null) {
18181                        childInfo.origUsers = childPs.queryInstalledUsers(allUserHandles, true);
18182                    }
18183                }
18184            }
18185        }
18186
18187        boolean ret = false;
18188        if (isSystemApp(ps)) {
18189            if (DEBUG_REMOVE) Slog.d(TAG, "Removing system package: " + ps.name);
18190            // When an updated system application is deleted we delete the existing resources
18191            // as well and fall back to existing code in system partition
18192            ret = deleteSystemPackageLIF(ps.pkg, ps, allUserHandles, flags, outInfo, writeSettings);
18193        } else {
18194            if (DEBUG_REMOVE) Slog.d(TAG, "Removing non-system package: " + ps.name);
18195            ret = deleteInstalledPackageLIF(ps, deleteCodeAndResources, flags, allUserHandles,
18196                    outInfo, writeSettings, replacingPackage);
18197        }
18198
18199        // Take a note whether we deleted the package for all users
18200        if (outInfo != null) {
18201            outInfo.removedForAllUsers = mPackages.get(ps.name) == null;
18202            if (outInfo.removedChildPackages != null) {
18203                synchronized (mPackages) {
18204                    final int childCount = outInfo.removedChildPackages.size();
18205                    for (int i = 0; i < childCount; i++) {
18206                        PackageRemovedInfo childInfo = outInfo.removedChildPackages.valueAt(i);
18207                        if (childInfo != null) {
18208                            childInfo.removedForAllUsers = mPackages.get(
18209                                    childInfo.removedPackage) == null;
18210                        }
18211                    }
18212                }
18213            }
18214            // If we uninstalled an update to a system app there may be some
18215            // child packages that appeared as they are declared in the system
18216            // app but were not declared in the update.
18217            if (isSystemApp(ps)) {
18218                synchronized (mPackages) {
18219                    PackageSetting updatedPs = mSettings.getPackageLPr(ps.name);
18220                    final int childCount = (updatedPs.childPackageNames != null)
18221                            ? updatedPs.childPackageNames.size() : 0;
18222                    for (int i = 0; i < childCount; i++) {
18223                        String childPackageName = updatedPs.childPackageNames.get(i);
18224                        if (outInfo.removedChildPackages == null
18225                                || outInfo.removedChildPackages.indexOfKey(childPackageName) < 0) {
18226                            PackageSetting childPs = mSettings.getPackageLPr(childPackageName);
18227                            if (childPs == null) {
18228                                continue;
18229                            }
18230                            PackageInstalledInfo installRes = new PackageInstalledInfo();
18231                            installRes.name = childPackageName;
18232                            installRes.newUsers = childPs.queryInstalledUsers(allUserHandles, true);
18233                            installRes.pkg = mPackages.get(childPackageName);
18234                            installRes.uid = childPs.pkg.applicationInfo.uid;
18235                            if (outInfo.appearedChildPackages == null) {
18236                                outInfo.appearedChildPackages = new ArrayMap<>();
18237                            }
18238                            outInfo.appearedChildPackages.put(childPackageName, installRes);
18239                        }
18240                    }
18241                }
18242            }
18243        }
18244
18245        return ret;
18246    }
18247
18248    private void markPackageUninstalledForUserLPw(PackageSetting ps, UserHandle user) {
18249        final int[] userIds = (user == null || user.getIdentifier() == UserHandle.USER_ALL)
18250                ? sUserManager.getUserIds() : new int[] {user.getIdentifier()};
18251        for (int nextUserId : userIds) {
18252            if (DEBUG_REMOVE) {
18253                Slog.d(TAG, "Marking package:" + ps.name + " uninstalled for user:" + nextUserId);
18254            }
18255            ps.setUserState(nextUserId, 0, COMPONENT_ENABLED_STATE_DEFAULT,
18256                    false /*installed*/,
18257                    true /*stopped*/,
18258                    true /*notLaunched*/,
18259                    false /*hidden*/,
18260                    false /*suspended*/,
18261                    false /*instantApp*/,
18262                    null /*lastDisableAppCaller*/,
18263                    null /*enabledComponents*/,
18264                    null /*disabledComponents*/,
18265                    false /*blockUninstall*/,
18266                    ps.readUserState(nextUserId).domainVerificationStatus,
18267                    0, PackageManager.INSTALL_REASON_UNKNOWN);
18268        }
18269        mSettings.writeKernelMappingLPr(ps);
18270    }
18271
18272    private boolean clearPackageStateForUserLIF(PackageSetting ps, int userId,
18273            PackageRemovedInfo outInfo) {
18274        final PackageParser.Package pkg;
18275        synchronized (mPackages) {
18276            pkg = mPackages.get(ps.name);
18277        }
18278
18279        final int[] userIds = (userId == UserHandle.USER_ALL) ? sUserManager.getUserIds()
18280                : new int[] {userId};
18281        for (int nextUserId : userIds) {
18282            if (DEBUG_REMOVE) {
18283                Slog.d(TAG, "Updating package:" + ps.name + " install state for user:"
18284                        + nextUserId);
18285            }
18286
18287            destroyAppDataLIF(pkg, userId,
18288                    StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
18289            destroyAppProfilesLIF(pkg, userId);
18290            removeKeystoreDataIfNeeded(nextUserId, ps.appId);
18291            schedulePackageCleaning(ps.name, nextUserId, false);
18292            synchronized (mPackages) {
18293                if (clearPackagePreferredActivitiesLPw(ps.name, nextUserId)) {
18294                    scheduleWritePackageRestrictionsLocked(nextUserId);
18295                }
18296                resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, nextUserId);
18297            }
18298        }
18299
18300        if (outInfo != null) {
18301            outInfo.removedPackage = ps.name;
18302            outInfo.isStaticSharedLib = pkg != null && pkg.staticSharedLibName != null;
18303            outInfo.removedAppId = ps.appId;
18304            outInfo.removedUsers = userIds;
18305        }
18306
18307        return true;
18308    }
18309
18310    private final class ClearStorageConnection implements ServiceConnection {
18311        IMediaContainerService mContainerService;
18312
18313        @Override
18314        public void onServiceConnected(ComponentName name, IBinder service) {
18315            synchronized (this) {
18316                mContainerService = IMediaContainerService.Stub
18317                        .asInterface(Binder.allowBlocking(service));
18318                notifyAll();
18319            }
18320        }
18321
18322        @Override
18323        public void onServiceDisconnected(ComponentName name) {
18324        }
18325    }
18326
18327    private void clearExternalStorageDataSync(String packageName, int userId, boolean allData) {
18328        if (DEFAULT_CONTAINER_PACKAGE.equals(packageName)) return;
18329
18330        final boolean mounted;
18331        if (Environment.isExternalStorageEmulated()) {
18332            mounted = true;
18333        } else {
18334            final String status = Environment.getExternalStorageState();
18335
18336            mounted = status.equals(Environment.MEDIA_MOUNTED)
18337                    || status.equals(Environment.MEDIA_MOUNTED_READ_ONLY);
18338        }
18339
18340        if (!mounted) {
18341            return;
18342        }
18343
18344        final Intent containerIntent = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
18345        int[] users;
18346        if (userId == UserHandle.USER_ALL) {
18347            users = sUserManager.getUserIds();
18348        } else {
18349            users = new int[] { userId };
18350        }
18351        final ClearStorageConnection conn = new ClearStorageConnection();
18352        if (mContext.bindServiceAsUser(
18353                containerIntent, conn, Context.BIND_AUTO_CREATE, UserHandle.SYSTEM)) {
18354            try {
18355                for (int curUser : users) {
18356                    long timeout = SystemClock.uptimeMillis() + 5000;
18357                    synchronized (conn) {
18358                        long now;
18359                        while (conn.mContainerService == null &&
18360                                (now = SystemClock.uptimeMillis()) < timeout) {
18361                            try {
18362                                conn.wait(timeout - now);
18363                            } catch (InterruptedException e) {
18364                            }
18365                        }
18366                    }
18367                    if (conn.mContainerService == null) {
18368                        return;
18369                    }
18370
18371                    final UserEnvironment userEnv = new UserEnvironment(curUser);
18372                    clearDirectory(conn.mContainerService,
18373                            userEnv.buildExternalStorageAppCacheDirs(packageName));
18374                    if (allData) {
18375                        clearDirectory(conn.mContainerService,
18376                                userEnv.buildExternalStorageAppDataDirs(packageName));
18377                        clearDirectory(conn.mContainerService,
18378                                userEnv.buildExternalStorageAppMediaDirs(packageName));
18379                    }
18380                }
18381            } finally {
18382                mContext.unbindService(conn);
18383            }
18384        }
18385    }
18386
18387    @Override
18388    public void clearApplicationProfileData(String packageName) {
18389        enforceSystemOrRoot("Only the system can clear all profile data");
18390
18391        final PackageParser.Package pkg;
18392        synchronized (mPackages) {
18393            pkg = mPackages.get(packageName);
18394        }
18395
18396        try (PackageFreezer freezer = freezePackage(packageName, "clearApplicationProfileData")) {
18397            synchronized (mInstallLock) {
18398                clearAppProfilesLIF(pkg, UserHandle.USER_ALL);
18399                destroyAppReferenceProfileLeafLIF(pkg, UserHandle.USER_ALL,
18400                        true /* removeBaseMarker */);
18401            }
18402        }
18403    }
18404
18405    @Override
18406    public void clearApplicationUserData(final String packageName,
18407            final IPackageDataObserver observer, final int userId) {
18408        mContext.enforceCallingOrSelfPermission(
18409                android.Manifest.permission.CLEAR_APP_USER_DATA, null);
18410
18411        enforceCrossUserPermission(Binder.getCallingUid(), userId,
18412                true /* requireFullPermission */, false /* checkShell */, "clear application data");
18413
18414        if (mProtectedPackages.isPackageDataProtected(userId, packageName)) {
18415            throw new SecurityException("Cannot clear data for a protected package: "
18416                    + packageName);
18417        }
18418        // Queue up an async operation since the package deletion may take a little while.
18419        mHandler.post(new Runnable() {
18420            public void run() {
18421                mHandler.removeCallbacks(this);
18422                final boolean succeeded;
18423                try (PackageFreezer freezer = freezePackage(packageName,
18424                        "clearApplicationUserData")) {
18425                    synchronized (mInstallLock) {
18426                        succeeded = clearApplicationUserDataLIF(packageName, userId);
18427                    }
18428                    clearExternalStorageDataSync(packageName, userId, true);
18429                    synchronized (mPackages) {
18430                        mInstantAppRegistry.deleteInstantApplicationMetadataLPw(
18431                                packageName, userId);
18432                    }
18433                }
18434                if (succeeded) {
18435                    // invoke DeviceStorageMonitor's update method to clear any notifications
18436                    DeviceStorageMonitorInternal dsm = LocalServices
18437                            .getService(DeviceStorageMonitorInternal.class);
18438                    if (dsm != null) {
18439                        dsm.checkMemory();
18440                    }
18441                }
18442                if(observer != null) {
18443                    try {
18444                        observer.onRemoveCompleted(packageName, succeeded);
18445                    } catch (RemoteException e) {
18446                        Log.i(TAG, "Observer no longer exists.");
18447                    }
18448                } //end if observer
18449            } //end run
18450        });
18451    }
18452
18453    private boolean clearApplicationUserDataLIF(String packageName, int userId) {
18454        if (packageName == null) {
18455            Slog.w(TAG, "Attempt to delete null packageName.");
18456            return false;
18457        }
18458
18459        // Try finding details about the requested package
18460        PackageParser.Package pkg;
18461        synchronized (mPackages) {
18462            pkg = mPackages.get(packageName);
18463            if (pkg == null) {
18464                final PackageSetting ps = mSettings.mPackages.get(packageName);
18465                if (ps != null) {
18466                    pkg = ps.pkg;
18467                }
18468            }
18469
18470            if (pkg == null) {
18471                Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
18472                return false;
18473            }
18474
18475            PackageSetting ps = (PackageSetting) pkg.mExtras;
18476            resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
18477        }
18478
18479        clearAppDataLIF(pkg, userId,
18480                StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
18481
18482        final int appId = UserHandle.getAppId(pkg.applicationInfo.uid);
18483        removeKeystoreDataIfNeeded(userId, appId);
18484
18485        UserManagerInternal umInternal = getUserManagerInternal();
18486        final int flags;
18487        if (umInternal.isUserUnlockingOrUnlocked(userId)) {
18488            flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
18489        } else if (umInternal.isUserRunning(userId)) {
18490            flags = StorageManager.FLAG_STORAGE_DE;
18491        } else {
18492            flags = 0;
18493        }
18494        prepareAppDataContentsLIF(pkg, userId, flags);
18495
18496        return true;
18497    }
18498
18499    /**
18500     * Reverts user permission state changes (permissions and flags) in
18501     * all packages for a given user.
18502     *
18503     * @param userId The device user for which to do a reset.
18504     */
18505    private void resetUserChangesToRuntimePermissionsAndFlagsLPw(int userId) {
18506        final int packageCount = mPackages.size();
18507        for (int i = 0; i < packageCount; i++) {
18508            PackageParser.Package pkg = mPackages.valueAt(i);
18509            PackageSetting ps = (PackageSetting) pkg.mExtras;
18510            resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
18511        }
18512    }
18513
18514    private void resetNetworkPolicies(int userId) {
18515        LocalServices.getService(NetworkPolicyManagerInternal.class).resetUserState(userId);
18516    }
18517
18518    /**
18519     * Reverts user permission state changes (permissions and flags).
18520     *
18521     * @param ps The package for which to reset.
18522     * @param userId The device user for which to do a reset.
18523     */
18524    private void resetUserChangesToRuntimePermissionsAndFlagsLPw(
18525            final PackageSetting ps, final int userId) {
18526        if (ps.pkg == null) {
18527            return;
18528        }
18529
18530        // These are flags that can change base on user actions.
18531        final int userSettableMask = FLAG_PERMISSION_USER_SET
18532                | FLAG_PERMISSION_USER_FIXED
18533                | FLAG_PERMISSION_REVOKE_ON_UPGRADE
18534                | FLAG_PERMISSION_REVIEW_REQUIRED;
18535
18536        final int policyOrSystemFlags = FLAG_PERMISSION_SYSTEM_FIXED
18537                | FLAG_PERMISSION_POLICY_FIXED;
18538
18539        boolean writeInstallPermissions = false;
18540        boolean writeRuntimePermissions = false;
18541
18542        final int permissionCount = ps.pkg.requestedPermissions.size();
18543        for (int i = 0; i < permissionCount; i++) {
18544            String permission = ps.pkg.requestedPermissions.get(i);
18545
18546            BasePermission bp = mSettings.mPermissions.get(permission);
18547            if (bp == null) {
18548                continue;
18549            }
18550
18551            // If shared user we just reset the state to which only this app contributed.
18552            if (ps.sharedUser != null) {
18553                boolean used = false;
18554                final int packageCount = ps.sharedUser.packages.size();
18555                for (int j = 0; j < packageCount; j++) {
18556                    PackageSetting pkg = ps.sharedUser.packages.valueAt(j);
18557                    if (pkg.pkg != null && !pkg.pkg.packageName.equals(ps.pkg.packageName)
18558                            && pkg.pkg.requestedPermissions.contains(permission)) {
18559                        used = true;
18560                        break;
18561                    }
18562                }
18563                if (used) {
18564                    continue;
18565                }
18566            }
18567
18568            PermissionsState permissionsState = ps.getPermissionsState();
18569
18570            final int oldFlags = permissionsState.getPermissionFlags(bp.name, userId);
18571
18572            // Always clear the user settable flags.
18573            final boolean hasInstallState = permissionsState.getInstallPermissionState(
18574                    bp.name) != null;
18575            // If permission review is enabled and this is a legacy app, mark the
18576            // permission as requiring a review as this is the initial state.
18577            int flags = 0;
18578            if (mPermissionReviewRequired
18579                    && ps.pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) {
18580                flags |= FLAG_PERMISSION_REVIEW_REQUIRED;
18581            }
18582            if (permissionsState.updatePermissionFlags(bp, userId, userSettableMask, flags)) {
18583                if (hasInstallState) {
18584                    writeInstallPermissions = true;
18585                } else {
18586                    writeRuntimePermissions = true;
18587                }
18588            }
18589
18590            // Below is only runtime permission handling.
18591            if (!bp.isRuntime()) {
18592                continue;
18593            }
18594
18595            // Never clobber system or policy.
18596            if ((oldFlags & policyOrSystemFlags) != 0) {
18597                continue;
18598            }
18599
18600            // If this permission was granted by default, make sure it is.
18601            if ((oldFlags & FLAG_PERMISSION_GRANTED_BY_DEFAULT) != 0) {
18602                if (permissionsState.grantRuntimePermission(bp, userId)
18603                        != PERMISSION_OPERATION_FAILURE) {
18604                    writeRuntimePermissions = true;
18605                }
18606            // If permission review is enabled the permissions for a legacy apps
18607            // are represented as constantly granted runtime ones, so don't revoke.
18608            } else if ((flags & FLAG_PERMISSION_REVIEW_REQUIRED) == 0) {
18609                // Otherwise, reset the permission.
18610                final int revokeResult = permissionsState.revokeRuntimePermission(bp, userId);
18611                switch (revokeResult) {
18612                    case PERMISSION_OPERATION_SUCCESS:
18613                    case PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: {
18614                        writeRuntimePermissions = true;
18615                        final int appId = ps.appId;
18616                        mHandler.post(new Runnable() {
18617                            @Override
18618                            public void run() {
18619                                killUid(appId, userId, KILL_APP_REASON_PERMISSIONS_REVOKED);
18620                            }
18621                        });
18622                    } break;
18623                }
18624            }
18625        }
18626
18627        // Synchronously write as we are taking permissions away.
18628        if (writeRuntimePermissions) {
18629            mSettings.writeRuntimePermissionsForUserLPr(userId, true);
18630        }
18631
18632        // Synchronously write as we are taking permissions away.
18633        if (writeInstallPermissions) {
18634            mSettings.writeLPr();
18635        }
18636    }
18637
18638    /**
18639     * Remove entries from the keystore daemon. Will only remove it if the
18640     * {@code appId} is valid.
18641     */
18642    private static void removeKeystoreDataIfNeeded(int userId, int appId) {
18643        if (appId < 0) {
18644            return;
18645        }
18646
18647        final KeyStore keyStore = KeyStore.getInstance();
18648        if (keyStore != null) {
18649            if (userId == UserHandle.USER_ALL) {
18650                for (final int individual : sUserManager.getUserIds()) {
18651                    keyStore.clearUid(UserHandle.getUid(individual, appId));
18652                }
18653            } else {
18654                keyStore.clearUid(UserHandle.getUid(userId, appId));
18655            }
18656        } else {
18657            Slog.w(TAG, "Could not contact keystore to clear entries for app id " + appId);
18658        }
18659    }
18660
18661    @Override
18662    public void deleteApplicationCacheFiles(final String packageName,
18663            final IPackageDataObserver observer) {
18664        final int userId = UserHandle.getCallingUserId();
18665        deleteApplicationCacheFilesAsUser(packageName, userId, observer);
18666    }
18667
18668    @Override
18669    public void deleteApplicationCacheFilesAsUser(final String packageName, final int userId,
18670            final IPackageDataObserver observer) {
18671        mContext.enforceCallingOrSelfPermission(
18672                android.Manifest.permission.DELETE_CACHE_FILES, null);
18673        enforceCrossUserPermission(Binder.getCallingUid(), userId,
18674                /* requireFullPermission= */ true, /* checkShell= */ false,
18675                "delete application cache files");
18676
18677        final PackageParser.Package pkg;
18678        synchronized (mPackages) {
18679            pkg = mPackages.get(packageName);
18680        }
18681
18682        // Queue up an async operation since the package deletion may take a little while.
18683        mHandler.post(new Runnable() {
18684            public void run() {
18685                synchronized (mInstallLock) {
18686                    final int flags = StorageManager.FLAG_STORAGE_DE
18687                            | StorageManager.FLAG_STORAGE_CE;
18688                    // We're only clearing cache files, so we don't care if the
18689                    // app is unfrozen and still able to run
18690                    clearAppDataLIF(pkg, userId, flags | Installer.FLAG_CLEAR_CACHE_ONLY);
18691                    clearAppDataLIF(pkg, userId, flags | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
18692                }
18693                clearExternalStorageDataSync(packageName, userId, false);
18694                if (observer != null) {
18695                    try {
18696                        observer.onRemoveCompleted(packageName, true);
18697                    } catch (RemoteException e) {
18698                        Log.i(TAG, "Observer no longer exists.");
18699                    }
18700                }
18701            }
18702        });
18703    }
18704
18705    @Override
18706    public void getPackageSizeInfo(final String packageName, int userHandle,
18707            final IPackageStatsObserver observer) {
18708        Slog.w(TAG, "Shame on you for calling a hidden API. Shame!");
18709        try {
18710            observer.onGetStatsCompleted(null, false);
18711        } catch (RemoteException ignored) {
18712        }
18713    }
18714
18715    private boolean getPackageSizeInfoLI(String packageName, int userId, PackageStats stats) {
18716        final PackageSetting ps;
18717        synchronized (mPackages) {
18718            ps = mSettings.mPackages.get(packageName);
18719            if (ps == null) {
18720                Slog.w(TAG, "Failed to find settings for " + packageName);
18721                return false;
18722            }
18723        }
18724
18725        final String[] packageNames = { packageName };
18726        final long[] ceDataInodes = { ps.getCeDataInode(userId) };
18727        final String[] codePaths = { ps.codePathString };
18728
18729        try {
18730            mInstaller.getAppSize(ps.volumeUuid, packageNames, userId, 0,
18731                    ps.appId, ceDataInodes, codePaths, stats);
18732
18733            // For now, ignore code size of packages on system partition
18734            if (isSystemApp(ps) && !isUpdatedSystemApp(ps)) {
18735                stats.codeSize = 0;
18736            }
18737
18738            // External clients expect these to be tracked separately
18739            stats.dataSize -= stats.cacheSize;
18740
18741        } catch (InstallerException e) {
18742            Slog.w(TAG, String.valueOf(e));
18743            return false;
18744        }
18745
18746        return true;
18747    }
18748
18749    private int getUidTargetSdkVersionLockedLPr(int uid) {
18750        Object obj = mSettings.getUserIdLPr(uid);
18751        if (obj instanceof SharedUserSetting) {
18752            final SharedUserSetting sus = (SharedUserSetting) obj;
18753            int vers = Build.VERSION_CODES.CUR_DEVELOPMENT;
18754            final Iterator<PackageSetting> it = sus.packages.iterator();
18755            while (it.hasNext()) {
18756                final PackageSetting ps = it.next();
18757                if (ps.pkg != null) {
18758                    int v = ps.pkg.applicationInfo.targetSdkVersion;
18759                    if (v < vers) vers = v;
18760                }
18761            }
18762            return vers;
18763        } else if (obj instanceof PackageSetting) {
18764            final PackageSetting ps = (PackageSetting) obj;
18765            if (ps.pkg != null) {
18766                return ps.pkg.applicationInfo.targetSdkVersion;
18767            }
18768        }
18769        return Build.VERSION_CODES.CUR_DEVELOPMENT;
18770    }
18771
18772    @Override
18773    public void addPreferredActivity(IntentFilter filter, int match,
18774            ComponentName[] set, ComponentName activity, int userId) {
18775        addPreferredActivityInternal(filter, match, set, activity, true, userId,
18776                "Adding preferred");
18777    }
18778
18779    private void addPreferredActivityInternal(IntentFilter filter, int match,
18780            ComponentName[] set, ComponentName activity, boolean always, int userId,
18781            String opname) {
18782        // writer
18783        int callingUid = Binder.getCallingUid();
18784        enforceCrossUserPermission(callingUid, userId,
18785                true /* requireFullPermission */, false /* checkShell */, "add preferred activity");
18786        if (filter.countActions() == 0) {
18787            Slog.w(TAG, "Cannot set a preferred activity with no filter actions");
18788            return;
18789        }
18790        synchronized (mPackages) {
18791            if (mContext.checkCallingOrSelfPermission(
18792                    android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
18793                    != PackageManager.PERMISSION_GRANTED) {
18794                if (getUidTargetSdkVersionLockedLPr(callingUid)
18795                        < Build.VERSION_CODES.FROYO) {
18796                    Slog.w(TAG, "Ignoring addPreferredActivity() from uid "
18797                            + callingUid);
18798                    return;
18799                }
18800                mContext.enforceCallingOrSelfPermission(
18801                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
18802            }
18803
18804            PreferredIntentResolver pir = mSettings.editPreferredActivitiesLPw(userId);
18805            Slog.i(TAG, opname + " activity " + activity.flattenToShortString() + " for user "
18806                    + userId + ":");
18807            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
18808            pir.addFilter(new PreferredActivity(filter, match, set, activity, always));
18809            scheduleWritePackageRestrictionsLocked(userId);
18810            postPreferredActivityChangedBroadcast(userId);
18811        }
18812    }
18813
18814    private void postPreferredActivityChangedBroadcast(int userId) {
18815        mHandler.post(() -> {
18816            final IActivityManager am = ActivityManager.getService();
18817            if (am == null) {
18818                return;
18819            }
18820
18821            final Intent intent = new Intent(Intent.ACTION_PREFERRED_ACTIVITY_CHANGED);
18822            intent.putExtra(Intent.EXTRA_USER_HANDLE, userId);
18823            try {
18824                am.broadcastIntent(null, intent, null, null,
18825                        0, null, null, null, android.app.AppOpsManager.OP_NONE,
18826                        null, false, false, userId);
18827            } catch (RemoteException e) {
18828            }
18829        });
18830    }
18831
18832    @Override
18833    public void replacePreferredActivity(IntentFilter filter, int match,
18834            ComponentName[] set, ComponentName activity, int userId) {
18835        if (filter.countActions() != 1) {
18836            throw new IllegalArgumentException(
18837                    "replacePreferredActivity expects filter to have only 1 action.");
18838        }
18839        if (filter.countDataAuthorities() != 0
18840                || filter.countDataPaths() != 0
18841                || filter.countDataSchemes() > 1
18842                || filter.countDataTypes() != 0) {
18843            throw new IllegalArgumentException(
18844                    "replacePreferredActivity expects filter to have no data authorities, " +
18845                    "paths, or types; and at most one scheme.");
18846        }
18847
18848        final int callingUid = Binder.getCallingUid();
18849        enforceCrossUserPermission(callingUid, userId,
18850                true /* requireFullPermission */, false /* checkShell */,
18851                "replace preferred activity");
18852        synchronized (mPackages) {
18853            if (mContext.checkCallingOrSelfPermission(
18854                    android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
18855                    != PackageManager.PERMISSION_GRANTED) {
18856                if (getUidTargetSdkVersionLockedLPr(callingUid)
18857                        < Build.VERSION_CODES.FROYO) {
18858                    Slog.w(TAG, "Ignoring replacePreferredActivity() from uid "
18859                            + Binder.getCallingUid());
18860                    return;
18861                }
18862                mContext.enforceCallingOrSelfPermission(
18863                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
18864            }
18865
18866            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
18867            if (pir != null) {
18868                // Get all of the existing entries that exactly match this filter.
18869                ArrayList<PreferredActivity> existing = pir.findFilters(filter);
18870                if (existing != null && existing.size() == 1) {
18871                    PreferredActivity cur = existing.get(0);
18872                    if (DEBUG_PREFERRED) {
18873                        Slog.i(TAG, "Checking replace of preferred:");
18874                        filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
18875                        if (!cur.mPref.mAlways) {
18876                            Slog.i(TAG, "  -- CUR; not mAlways!");
18877                        } else {
18878                            Slog.i(TAG, "  -- CUR: mMatch=" + cur.mPref.mMatch);
18879                            Slog.i(TAG, "  -- CUR: mSet="
18880                                    + Arrays.toString(cur.mPref.mSetComponents));
18881                            Slog.i(TAG, "  -- CUR: mComponent=" + cur.mPref.mShortComponent);
18882                            Slog.i(TAG, "  -- NEW: mMatch="
18883                                    + (match&IntentFilter.MATCH_CATEGORY_MASK));
18884                            Slog.i(TAG, "  -- CUR: mSet=" + Arrays.toString(set));
18885                            Slog.i(TAG, "  -- CUR: mComponent=" + activity.flattenToShortString());
18886                        }
18887                    }
18888                    if (cur.mPref.mAlways && cur.mPref.mComponent.equals(activity)
18889                            && cur.mPref.mMatch == (match&IntentFilter.MATCH_CATEGORY_MASK)
18890                            && cur.mPref.sameSet(set)) {
18891                        // Setting the preferred activity to what it happens to be already
18892                        if (DEBUG_PREFERRED) {
18893                            Slog.i(TAG, "Replacing with same preferred activity "
18894                                    + cur.mPref.mShortComponent + " for user "
18895                                    + userId + ":");
18896                            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
18897                        }
18898                        return;
18899                    }
18900                }
18901
18902                if (existing != null) {
18903                    if (DEBUG_PREFERRED) {
18904                        Slog.i(TAG, existing.size() + " existing preferred matches for:");
18905                        filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
18906                    }
18907                    for (int i = 0; i < existing.size(); i++) {
18908                        PreferredActivity pa = existing.get(i);
18909                        if (DEBUG_PREFERRED) {
18910                            Slog.i(TAG, "Removing existing preferred activity "
18911                                    + pa.mPref.mComponent + ":");
18912                            pa.dump(new LogPrinter(Log.INFO, TAG), "  ");
18913                        }
18914                        pir.removeFilter(pa);
18915                    }
18916                }
18917            }
18918            addPreferredActivityInternal(filter, match, set, activity, true, userId,
18919                    "Replacing preferred");
18920        }
18921    }
18922
18923    @Override
18924    public void clearPackagePreferredActivities(String packageName) {
18925        final int uid = Binder.getCallingUid();
18926        // writer
18927        synchronized (mPackages) {
18928            PackageParser.Package pkg = mPackages.get(packageName);
18929            if (pkg == null || pkg.applicationInfo.uid != uid) {
18930                if (mContext.checkCallingOrSelfPermission(
18931                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
18932                        != PackageManager.PERMISSION_GRANTED) {
18933                    if (getUidTargetSdkVersionLockedLPr(Binder.getCallingUid())
18934                            < Build.VERSION_CODES.FROYO) {
18935                        Slog.w(TAG, "Ignoring clearPackagePreferredActivities() from uid "
18936                                + Binder.getCallingUid());
18937                        return;
18938                    }
18939                    mContext.enforceCallingOrSelfPermission(
18940                            android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
18941                }
18942            }
18943
18944            int user = UserHandle.getCallingUserId();
18945            if (clearPackagePreferredActivitiesLPw(packageName, user)) {
18946                scheduleWritePackageRestrictionsLocked(user);
18947            }
18948        }
18949    }
18950
18951    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
18952    boolean clearPackagePreferredActivitiesLPw(String packageName, int userId) {
18953        ArrayList<PreferredActivity> removed = null;
18954        boolean changed = false;
18955        for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
18956            final int thisUserId = mSettings.mPreferredActivities.keyAt(i);
18957            PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
18958            if (userId != UserHandle.USER_ALL && userId != thisUserId) {
18959                continue;
18960            }
18961            Iterator<PreferredActivity> it = pir.filterIterator();
18962            while (it.hasNext()) {
18963                PreferredActivity pa = it.next();
18964                // Mark entry for removal only if it matches the package name
18965                // and the entry is of type "always".
18966                if (packageName == null ||
18967                        (pa.mPref.mComponent.getPackageName().equals(packageName)
18968                                && pa.mPref.mAlways)) {
18969                    if (removed == null) {
18970                        removed = new ArrayList<PreferredActivity>();
18971                    }
18972                    removed.add(pa);
18973                }
18974            }
18975            if (removed != null) {
18976                for (int j=0; j<removed.size(); j++) {
18977                    PreferredActivity pa = removed.get(j);
18978                    pir.removeFilter(pa);
18979                }
18980                changed = true;
18981            }
18982        }
18983        if (changed) {
18984            postPreferredActivityChangedBroadcast(userId);
18985        }
18986        return changed;
18987    }
18988
18989    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
18990    private void clearIntentFilterVerificationsLPw(int userId) {
18991        final int packageCount = mPackages.size();
18992        for (int i = 0; i < packageCount; i++) {
18993            PackageParser.Package pkg = mPackages.valueAt(i);
18994            clearIntentFilterVerificationsLPw(pkg.packageName, userId);
18995        }
18996    }
18997
18998    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
18999    void clearIntentFilterVerificationsLPw(String packageName, int userId) {
19000        if (userId == UserHandle.USER_ALL) {
19001            if (mSettings.removeIntentFilterVerificationLPw(packageName,
19002                    sUserManager.getUserIds())) {
19003                for (int oneUserId : sUserManager.getUserIds()) {
19004                    scheduleWritePackageRestrictionsLocked(oneUserId);
19005                }
19006            }
19007        } else {
19008            if (mSettings.removeIntentFilterVerificationLPw(packageName, userId)) {
19009                scheduleWritePackageRestrictionsLocked(userId);
19010            }
19011        }
19012    }
19013
19014    void clearDefaultBrowserIfNeeded(String packageName) {
19015        for (int oneUserId : sUserManager.getUserIds()) {
19016            String defaultBrowserPackageName = getDefaultBrowserPackageName(oneUserId);
19017            if (TextUtils.isEmpty(defaultBrowserPackageName)) continue;
19018            if (packageName.equals(defaultBrowserPackageName)) {
19019                setDefaultBrowserPackageName(null, oneUserId);
19020            }
19021        }
19022    }
19023
19024    @Override
19025    public void resetApplicationPreferences(int userId) {
19026        mContext.enforceCallingOrSelfPermission(
19027                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
19028        final long identity = Binder.clearCallingIdentity();
19029        // writer
19030        try {
19031            synchronized (mPackages) {
19032                clearPackagePreferredActivitiesLPw(null, userId);
19033                mSettings.applyDefaultPreferredAppsLPw(this, userId);
19034                // TODO: We have to reset the default SMS and Phone. This requires
19035                // significant refactoring to keep all default apps in the package
19036                // manager (cleaner but more work) or have the services provide
19037                // callbacks to the package manager to request a default app reset.
19038                applyFactoryDefaultBrowserLPw(userId);
19039                clearIntentFilterVerificationsLPw(userId);
19040                primeDomainVerificationsLPw(userId);
19041                resetUserChangesToRuntimePermissionsAndFlagsLPw(userId);
19042                scheduleWritePackageRestrictionsLocked(userId);
19043            }
19044            resetNetworkPolicies(userId);
19045        } finally {
19046            Binder.restoreCallingIdentity(identity);
19047        }
19048    }
19049
19050    @Override
19051    public int getPreferredActivities(List<IntentFilter> outFilters,
19052            List<ComponentName> outActivities, String packageName) {
19053
19054        int num = 0;
19055        final int userId = UserHandle.getCallingUserId();
19056        // reader
19057        synchronized (mPackages) {
19058            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
19059            if (pir != null) {
19060                final Iterator<PreferredActivity> it = pir.filterIterator();
19061                while (it.hasNext()) {
19062                    final PreferredActivity pa = it.next();
19063                    if (packageName == null
19064                            || (pa.mPref.mComponent.getPackageName().equals(packageName)
19065                                    && pa.mPref.mAlways)) {
19066                        if (outFilters != null) {
19067                            outFilters.add(new IntentFilter(pa));
19068                        }
19069                        if (outActivities != null) {
19070                            outActivities.add(pa.mPref.mComponent);
19071                        }
19072                    }
19073                }
19074            }
19075        }
19076
19077        return num;
19078    }
19079
19080    @Override
19081    public void addPersistentPreferredActivity(IntentFilter filter, ComponentName activity,
19082            int userId) {
19083        int callingUid = Binder.getCallingUid();
19084        if (callingUid != Process.SYSTEM_UID) {
19085            throw new SecurityException(
19086                    "addPersistentPreferredActivity can only be run by the system");
19087        }
19088        if (filter.countActions() == 0) {
19089            Slog.w(TAG, "Cannot set a preferred activity with no filter actions");
19090            return;
19091        }
19092        synchronized (mPackages) {
19093            Slog.i(TAG, "Adding persistent preferred activity " + activity + " for user " + userId +
19094                    ":");
19095            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
19096            mSettings.editPersistentPreferredActivitiesLPw(userId).addFilter(
19097                    new PersistentPreferredActivity(filter, activity));
19098            scheduleWritePackageRestrictionsLocked(userId);
19099            postPreferredActivityChangedBroadcast(userId);
19100        }
19101    }
19102
19103    @Override
19104    public void clearPackagePersistentPreferredActivities(String packageName, int userId) {
19105        int callingUid = Binder.getCallingUid();
19106        if (callingUid != Process.SYSTEM_UID) {
19107            throw new SecurityException(
19108                    "clearPackagePersistentPreferredActivities can only be run by the system");
19109        }
19110        ArrayList<PersistentPreferredActivity> removed = null;
19111        boolean changed = false;
19112        synchronized (mPackages) {
19113            for (int i=0; i<mSettings.mPersistentPreferredActivities.size(); i++) {
19114                final int thisUserId = mSettings.mPersistentPreferredActivities.keyAt(i);
19115                PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities
19116                        .valueAt(i);
19117                if (userId != thisUserId) {
19118                    continue;
19119                }
19120                Iterator<PersistentPreferredActivity> it = ppir.filterIterator();
19121                while (it.hasNext()) {
19122                    PersistentPreferredActivity ppa = it.next();
19123                    // Mark entry for removal only if it matches the package name.
19124                    if (ppa.mComponent.getPackageName().equals(packageName)) {
19125                        if (removed == null) {
19126                            removed = new ArrayList<PersistentPreferredActivity>();
19127                        }
19128                        removed.add(ppa);
19129                    }
19130                }
19131                if (removed != null) {
19132                    for (int j=0; j<removed.size(); j++) {
19133                        PersistentPreferredActivity ppa = removed.get(j);
19134                        ppir.removeFilter(ppa);
19135                    }
19136                    changed = true;
19137                }
19138            }
19139
19140            if (changed) {
19141                scheduleWritePackageRestrictionsLocked(userId);
19142                postPreferredActivityChangedBroadcast(userId);
19143            }
19144        }
19145    }
19146
19147    /**
19148     * Common machinery for picking apart a restored XML blob and passing
19149     * it to a caller-supplied functor to be applied to the running system.
19150     */
19151    private void restoreFromXml(XmlPullParser parser, int userId,
19152            String expectedStartTag, BlobXmlRestorer functor)
19153            throws IOException, XmlPullParserException {
19154        int type;
19155        while ((type = parser.next()) != XmlPullParser.START_TAG
19156                && type != XmlPullParser.END_DOCUMENT) {
19157        }
19158        if (type != XmlPullParser.START_TAG) {
19159            // oops didn't find a start tag?!
19160            if (DEBUG_BACKUP) {
19161                Slog.e(TAG, "Didn't find start tag during restore");
19162            }
19163            return;
19164        }
19165Slog.v(TAG, ":: restoreFromXml() : got to tag " + parser.getName());
19166        // this is supposed to be TAG_PREFERRED_BACKUP
19167        if (!expectedStartTag.equals(parser.getName())) {
19168            if (DEBUG_BACKUP) {
19169                Slog.e(TAG, "Found unexpected tag " + parser.getName());
19170            }
19171            return;
19172        }
19173
19174        // skip interfering stuff, then we're aligned with the backing implementation
19175        while ((type = parser.next()) == XmlPullParser.TEXT) { }
19176Slog.v(TAG, ":: stepped forward, applying functor at tag " + parser.getName());
19177        functor.apply(parser, userId);
19178    }
19179
19180    private interface BlobXmlRestorer {
19181        public void apply(XmlPullParser parser, int userId) throws IOException, XmlPullParserException;
19182    }
19183
19184    /**
19185     * Non-Binder method, support for the backup/restore mechanism: write the
19186     * full set of preferred activities in its canonical XML format.  Returns the
19187     * XML output as a byte array, or null if there is none.
19188     */
19189    @Override
19190    public byte[] getPreferredActivityBackup(int userId) {
19191        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
19192            throw new SecurityException("Only the system may call getPreferredActivityBackup()");
19193        }
19194
19195        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
19196        try {
19197            final XmlSerializer serializer = new FastXmlSerializer();
19198            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
19199            serializer.startDocument(null, true);
19200            serializer.startTag(null, TAG_PREFERRED_BACKUP);
19201
19202            synchronized (mPackages) {
19203                mSettings.writePreferredActivitiesLPr(serializer, userId, true);
19204            }
19205
19206            serializer.endTag(null, TAG_PREFERRED_BACKUP);
19207            serializer.endDocument();
19208            serializer.flush();
19209        } catch (Exception e) {
19210            if (DEBUG_BACKUP) {
19211                Slog.e(TAG, "Unable to write preferred activities for backup", e);
19212            }
19213            return null;
19214        }
19215
19216        return dataStream.toByteArray();
19217    }
19218
19219    @Override
19220    public void restorePreferredActivities(byte[] backup, int userId) {
19221        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
19222            throw new SecurityException("Only the system may call restorePreferredActivities()");
19223        }
19224
19225        try {
19226            final XmlPullParser parser = Xml.newPullParser();
19227            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
19228            restoreFromXml(parser, userId, TAG_PREFERRED_BACKUP,
19229                    new BlobXmlRestorer() {
19230                        @Override
19231                        public void apply(XmlPullParser parser, int userId)
19232                                throws XmlPullParserException, IOException {
19233                            synchronized (mPackages) {
19234                                mSettings.readPreferredActivitiesLPw(parser, userId);
19235                            }
19236                        }
19237                    } );
19238        } catch (Exception e) {
19239            if (DEBUG_BACKUP) {
19240                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
19241            }
19242        }
19243    }
19244
19245    /**
19246     * Non-Binder method, support for the backup/restore mechanism: write the
19247     * default browser (etc) settings in its canonical XML format.  Returns the default
19248     * browser XML representation as a byte array, or null if there is none.
19249     */
19250    @Override
19251    public byte[] getDefaultAppsBackup(int userId) {
19252        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
19253            throw new SecurityException("Only the system may call getDefaultAppsBackup()");
19254        }
19255
19256        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
19257        try {
19258            final XmlSerializer serializer = new FastXmlSerializer();
19259            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
19260            serializer.startDocument(null, true);
19261            serializer.startTag(null, TAG_DEFAULT_APPS);
19262
19263            synchronized (mPackages) {
19264                mSettings.writeDefaultAppsLPr(serializer, userId);
19265            }
19266
19267            serializer.endTag(null, TAG_DEFAULT_APPS);
19268            serializer.endDocument();
19269            serializer.flush();
19270        } catch (Exception e) {
19271            if (DEBUG_BACKUP) {
19272                Slog.e(TAG, "Unable to write default apps for backup", e);
19273            }
19274            return null;
19275        }
19276
19277        return dataStream.toByteArray();
19278    }
19279
19280    @Override
19281    public void restoreDefaultApps(byte[] backup, int userId) {
19282        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
19283            throw new SecurityException("Only the system may call restoreDefaultApps()");
19284        }
19285
19286        try {
19287            final XmlPullParser parser = Xml.newPullParser();
19288            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
19289            restoreFromXml(parser, userId, TAG_DEFAULT_APPS,
19290                    new BlobXmlRestorer() {
19291                        @Override
19292                        public void apply(XmlPullParser parser, int userId)
19293                                throws XmlPullParserException, IOException {
19294                            synchronized (mPackages) {
19295                                mSettings.readDefaultAppsLPw(parser, userId);
19296                            }
19297                        }
19298                    } );
19299        } catch (Exception e) {
19300            if (DEBUG_BACKUP) {
19301                Slog.e(TAG, "Exception restoring default apps: " + e.getMessage());
19302            }
19303        }
19304    }
19305
19306    @Override
19307    public byte[] getIntentFilterVerificationBackup(int userId) {
19308        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
19309            throw new SecurityException("Only the system may call getIntentFilterVerificationBackup()");
19310        }
19311
19312        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
19313        try {
19314            final XmlSerializer serializer = new FastXmlSerializer();
19315            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
19316            serializer.startDocument(null, true);
19317            serializer.startTag(null, TAG_INTENT_FILTER_VERIFICATION);
19318
19319            synchronized (mPackages) {
19320                mSettings.writeAllDomainVerificationsLPr(serializer, userId);
19321            }
19322
19323            serializer.endTag(null, TAG_INTENT_FILTER_VERIFICATION);
19324            serializer.endDocument();
19325            serializer.flush();
19326        } catch (Exception e) {
19327            if (DEBUG_BACKUP) {
19328                Slog.e(TAG, "Unable to write default apps for backup", e);
19329            }
19330            return null;
19331        }
19332
19333        return dataStream.toByteArray();
19334    }
19335
19336    @Override
19337    public void restoreIntentFilterVerification(byte[] backup, int userId) {
19338        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
19339            throw new SecurityException("Only the system may call restorePreferredActivities()");
19340        }
19341
19342        try {
19343            final XmlPullParser parser = Xml.newPullParser();
19344            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
19345            restoreFromXml(parser, userId, TAG_INTENT_FILTER_VERIFICATION,
19346                    new BlobXmlRestorer() {
19347                        @Override
19348                        public void apply(XmlPullParser parser, int userId)
19349                                throws XmlPullParserException, IOException {
19350                            synchronized (mPackages) {
19351                                mSettings.readAllDomainVerificationsLPr(parser, userId);
19352                                mSettings.writeLPr();
19353                            }
19354                        }
19355                    } );
19356        } catch (Exception e) {
19357            if (DEBUG_BACKUP) {
19358                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
19359            }
19360        }
19361    }
19362
19363    @Override
19364    public byte[] getPermissionGrantBackup(int userId) {
19365        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
19366            throw new SecurityException("Only the system may call getPermissionGrantBackup()");
19367        }
19368
19369        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
19370        try {
19371            final XmlSerializer serializer = new FastXmlSerializer();
19372            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
19373            serializer.startDocument(null, true);
19374            serializer.startTag(null, TAG_PERMISSION_BACKUP);
19375
19376            synchronized (mPackages) {
19377                serializeRuntimePermissionGrantsLPr(serializer, userId);
19378            }
19379
19380            serializer.endTag(null, TAG_PERMISSION_BACKUP);
19381            serializer.endDocument();
19382            serializer.flush();
19383        } catch (Exception e) {
19384            if (DEBUG_BACKUP) {
19385                Slog.e(TAG, "Unable to write default apps for backup", e);
19386            }
19387            return null;
19388        }
19389
19390        return dataStream.toByteArray();
19391    }
19392
19393    @Override
19394    public void restorePermissionGrants(byte[] backup, int userId) {
19395        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
19396            throw new SecurityException("Only the system may call restorePermissionGrants()");
19397        }
19398
19399        try {
19400            final XmlPullParser parser = Xml.newPullParser();
19401            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
19402            restoreFromXml(parser, userId, TAG_PERMISSION_BACKUP,
19403                    new BlobXmlRestorer() {
19404                        @Override
19405                        public void apply(XmlPullParser parser, int userId)
19406                                throws XmlPullParserException, IOException {
19407                            synchronized (mPackages) {
19408                                processRestoredPermissionGrantsLPr(parser, userId);
19409                            }
19410                        }
19411                    } );
19412        } catch (Exception e) {
19413            if (DEBUG_BACKUP) {
19414                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
19415            }
19416        }
19417    }
19418
19419    private void serializeRuntimePermissionGrantsLPr(XmlSerializer serializer, final int userId)
19420            throws IOException {
19421        serializer.startTag(null, TAG_ALL_GRANTS);
19422
19423        final int N = mSettings.mPackages.size();
19424        for (int i = 0; i < N; i++) {
19425            final PackageSetting ps = mSettings.mPackages.valueAt(i);
19426            boolean pkgGrantsKnown = false;
19427
19428            PermissionsState packagePerms = ps.getPermissionsState();
19429
19430            for (PermissionState state : packagePerms.getRuntimePermissionStates(userId)) {
19431                final int grantFlags = state.getFlags();
19432                // only look at grants that are not system/policy fixed
19433                if ((grantFlags & SYSTEM_RUNTIME_GRANT_MASK) == 0) {
19434                    final boolean isGranted = state.isGranted();
19435                    // And only back up the user-twiddled state bits
19436                    if (isGranted || (grantFlags & USER_RUNTIME_GRANT_MASK) != 0) {
19437                        final String packageName = mSettings.mPackages.keyAt(i);
19438                        if (!pkgGrantsKnown) {
19439                            serializer.startTag(null, TAG_GRANT);
19440                            serializer.attribute(null, ATTR_PACKAGE_NAME, packageName);
19441                            pkgGrantsKnown = true;
19442                        }
19443
19444                        final boolean userSet =
19445                                (grantFlags & FLAG_PERMISSION_USER_SET) != 0;
19446                        final boolean userFixed =
19447                                (grantFlags & FLAG_PERMISSION_USER_FIXED) != 0;
19448                        final boolean revoke =
19449                                (grantFlags & FLAG_PERMISSION_REVOKE_ON_UPGRADE) != 0;
19450
19451                        serializer.startTag(null, TAG_PERMISSION);
19452                        serializer.attribute(null, ATTR_PERMISSION_NAME, state.getName());
19453                        if (isGranted) {
19454                            serializer.attribute(null, ATTR_IS_GRANTED, "true");
19455                        }
19456                        if (userSet) {
19457                            serializer.attribute(null, ATTR_USER_SET, "true");
19458                        }
19459                        if (userFixed) {
19460                            serializer.attribute(null, ATTR_USER_FIXED, "true");
19461                        }
19462                        if (revoke) {
19463                            serializer.attribute(null, ATTR_REVOKE_ON_UPGRADE, "true");
19464                        }
19465                        serializer.endTag(null, TAG_PERMISSION);
19466                    }
19467                }
19468            }
19469
19470            if (pkgGrantsKnown) {
19471                serializer.endTag(null, TAG_GRANT);
19472            }
19473        }
19474
19475        serializer.endTag(null, TAG_ALL_GRANTS);
19476    }
19477
19478    private void processRestoredPermissionGrantsLPr(XmlPullParser parser, int userId)
19479            throws XmlPullParserException, IOException {
19480        String pkgName = null;
19481        int outerDepth = parser.getDepth();
19482        int type;
19483        while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
19484                && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) {
19485            if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) {
19486                continue;
19487            }
19488
19489            final String tagName = parser.getName();
19490            if (tagName.equals(TAG_GRANT)) {
19491                pkgName = parser.getAttributeValue(null, ATTR_PACKAGE_NAME);
19492                if (DEBUG_BACKUP) {
19493                    Slog.v(TAG, "+++ Restoring grants for package " + pkgName);
19494                }
19495            } else if (tagName.equals(TAG_PERMISSION)) {
19496
19497                final boolean isGranted = "true".equals(parser.getAttributeValue(null, ATTR_IS_GRANTED));
19498                final String permName = parser.getAttributeValue(null, ATTR_PERMISSION_NAME);
19499
19500                int newFlagSet = 0;
19501                if ("true".equals(parser.getAttributeValue(null, ATTR_USER_SET))) {
19502                    newFlagSet |= FLAG_PERMISSION_USER_SET;
19503                }
19504                if ("true".equals(parser.getAttributeValue(null, ATTR_USER_FIXED))) {
19505                    newFlagSet |= FLAG_PERMISSION_USER_FIXED;
19506                }
19507                if ("true".equals(parser.getAttributeValue(null, ATTR_REVOKE_ON_UPGRADE))) {
19508                    newFlagSet |= FLAG_PERMISSION_REVOKE_ON_UPGRADE;
19509                }
19510                if (DEBUG_BACKUP) {
19511                    Slog.v(TAG, "  + Restoring grant: pkg=" + pkgName + " perm=" + permName
19512                            + " granted=" + isGranted + " bits=0x" + Integer.toHexString(newFlagSet));
19513                }
19514                final PackageSetting ps = mSettings.mPackages.get(pkgName);
19515                if (ps != null) {
19516                    // Already installed so we apply the grant immediately
19517                    if (DEBUG_BACKUP) {
19518                        Slog.v(TAG, "        + already installed; applying");
19519                    }
19520                    PermissionsState perms = ps.getPermissionsState();
19521                    BasePermission bp = mSettings.mPermissions.get(permName);
19522                    if (bp != null) {
19523                        if (isGranted) {
19524                            perms.grantRuntimePermission(bp, userId);
19525                        }
19526                        if (newFlagSet != 0) {
19527                            perms.updatePermissionFlags(bp, userId, USER_RUNTIME_GRANT_MASK, newFlagSet);
19528                        }
19529                    }
19530                } else {
19531                    // Need to wait for post-restore install to apply the grant
19532                    if (DEBUG_BACKUP) {
19533                        Slog.v(TAG, "        - not yet installed; saving for later");
19534                    }
19535                    mSettings.processRestoredPermissionGrantLPr(pkgName, permName,
19536                            isGranted, newFlagSet, userId);
19537                }
19538            } else {
19539                PackageManagerService.reportSettingsProblem(Log.WARN,
19540                        "Unknown element under <" + TAG_PERMISSION_BACKUP + ">: " + tagName);
19541                XmlUtils.skipCurrentTag(parser);
19542            }
19543        }
19544
19545        scheduleWriteSettingsLocked();
19546        mSettings.writeRuntimePermissionsForUserLPr(userId, false);
19547    }
19548
19549    @Override
19550    public void addCrossProfileIntentFilter(IntentFilter intentFilter, String ownerPackage,
19551            int sourceUserId, int targetUserId, int flags) {
19552        mContext.enforceCallingOrSelfPermission(
19553                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
19554        int callingUid = Binder.getCallingUid();
19555        enforceOwnerRights(ownerPackage, callingUid);
19556        enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId);
19557        if (intentFilter.countActions() == 0) {
19558            Slog.w(TAG, "Cannot set a crossProfile intent filter with no filter actions");
19559            return;
19560        }
19561        synchronized (mPackages) {
19562            CrossProfileIntentFilter newFilter = new CrossProfileIntentFilter(intentFilter,
19563                    ownerPackage, targetUserId, flags);
19564            CrossProfileIntentResolver resolver =
19565                    mSettings.editCrossProfileIntentResolverLPw(sourceUserId);
19566            ArrayList<CrossProfileIntentFilter> existing = resolver.findFilters(intentFilter);
19567            // We have all those whose filter is equal. Now checking if the rest is equal as well.
19568            if (existing != null) {
19569                int size = existing.size();
19570                for (int i = 0; i < size; i++) {
19571                    if (newFilter.equalsIgnoreFilter(existing.get(i))) {
19572                        return;
19573                    }
19574                }
19575            }
19576            resolver.addFilter(newFilter);
19577            scheduleWritePackageRestrictionsLocked(sourceUserId);
19578        }
19579    }
19580
19581    @Override
19582    public void clearCrossProfileIntentFilters(int sourceUserId, String ownerPackage) {
19583        mContext.enforceCallingOrSelfPermission(
19584                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
19585        int callingUid = Binder.getCallingUid();
19586        enforceOwnerRights(ownerPackage, callingUid);
19587        enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId);
19588        synchronized (mPackages) {
19589            CrossProfileIntentResolver resolver =
19590                    mSettings.editCrossProfileIntentResolverLPw(sourceUserId);
19591            ArraySet<CrossProfileIntentFilter> set =
19592                    new ArraySet<CrossProfileIntentFilter>(resolver.filterSet());
19593            for (CrossProfileIntentFilter filter : set) {
19594                if (filter.getOwnerPackage().equals(ownerPackage)) {
19595                    resolver.removeFilter(filter);
19596                }
19597            }
19598            scheduleWritePackageRestrictionsLocked(sourceUserId);
19599        }
19600    }
19601
19602    // Enforcing that callingUid is owning pkg on userId
19603    private void enforceOwnerRights(String pkg, int callingUid) {
19604        // The system owns everything.
19605        if (UserHandle.getAppId(callingUid) == Process.SYSTEM_UID) {
19606            return;
19607        }
19608        int callingUserId = UserHandle.getUserId(callingUid);
19609        PackageInfo pi = getPackageInfo(pkg, 0, callingUserId);
19610        if (pi == null) {
19611            throw new IllegalArgumentException("Unknown package " + pkg + " on user "
19612                    + callingUserId);
19613        }
19614        if (!UserHandle.isSameApp(pi.applicationInfo.uid, callingUid)) {
19615            throw new SecurityException("Calling uid " + callingUid
19616                    + " does not own package " + pkg);
19617        }
19618    }
19619
19620    @Override
19621    public ComponentName getHomeActivities(List<ResolveInfo> allHomeCandidates) {
19622        return getHomeActivitiesAsUser(allHomeCandidates, UserHandle.getCallingUserId());
19623    }
19624
19625    private Intent getHomeIntent() {
19626        Intent intent = new Intent(Intent.ACTION_MAIN);
19627        intent.addCategory(Intent.CATEGORY_HOME);
19628        intent.addCategory(Intent.CATEGORY_DEFAULT);
19629        return intent;
19630    }
19631
19632    private IntentFilter getHomeFilter() {
19633        IntentFilter filter = new IntentFilter(Intent.ACTION_MAIN);
19634        filter.addCategory(Intent.CATEGORY_HOME);
19635        filter.addCategory(Intent.CATEGORY_DEFAULT);
19636        return filter;
19637    }
19638
19639    ComponentName getHomeActivitiesAsUser(List<ResolveInfo> allHomeCandidates,
19640            int userId) {
19641        Intent intent  = getHomeIntent();
19642        List<ResolveInfo> list = queryIntentActivitiesInternal(intent, null,
19643                PackageManager.GET_META_DATA, userId);
19644        ResolveInfo preferred = findPreferredActivity(intent, null, 0, list, 0,
19645                true, false, false, userId);
19646
19647        allHomeCandidates.clear();
19648        if (list != null) {
19649            for (ResolveInfo ri : list) {
19650                allHomeCandidates.add(ri);
19651            }
19652        }
19653        return (preferred == null || preferred.activityInfo == null)
19654                ? null
19655                : new ComponentName(preferred.activityInfo.packageName,
19656                        preferred.activityInfo.name);
19657    }
19658
19659    @Override
19660    public void setHomeActivity(ComponentName comp, int userId) {
19661        ArrayList<ResolveInfo> homeActivities = new ArrayList<>();
19662        getHomeActivitiesAsUser(homeActivities, userId);
19663
19664        boolean found = false;
19665
19666        final int size = homeActivities.size();
19667        final ComponentName[] set = new ComponentName[size];
19668        for (int i = 0; i < size; i++) {
19669            final ResolveInfo candidate = homeActivities.get(i);
19670            final ActivityInfo info = candidate.activityInfo;
19671            final ComponentName activityName = new ComponentName(info.packageName, info.name);
19672            set[i] = activityName;
19673            if (!found && activityName.equals(comp)) {
19674                found = true;
19675            }
19676        }
19677        if (!found) {
19678            throw new IllegalArgumentException("Component " + comp + " cannot be home on user "
19679                    + userId);
19680        }
19681        replacePreferredActivity(getHomeFilter(), IntentFilter.MATCH_CATEGORY_EMPTY,
19682                set, comp, userId);
19683    }
19684
19685    private @Nullable String getSetupWizardPackageName() {
19686        final Intent intent = new Intent(Intent.ACTION_MAIN);
19687        intent.addCategory(Intent.CATEGORY_SETUP_WIZARD);
19688
19689        final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, null,
19690                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE
19691                        | MATCH_DISABLED_COMPONENTS,
19692                UserHandle.myUserId());
19693        if (matches.size() == 1) {
19694            return matches.get(0).getComponentInfo().packageName;
19695        } else {
19696            Slog.e(TAG, "There should probably be exactly one setup wizard; found " + matches.size()
19697                    + ": matches=" + matches);
19698            return null;
19699        }
19700    }
19701
19702    private @Nullable String getStorageManagerPackageName() {
19703        final Intent intent = new Intent(StorageManager.ACTION_MANAGE_STORAGE);
19704
19705        final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, null,
19706                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE
19707                        | MATCH_DISABLED_COMPONENTS,
19708                UserHandle.myUserId());
19709        if (matches.size() == 1) {
19710            return matches.get(0).getComponentInfo().packageName;
19711        } else {
19712            Slog.e(TAG, "There should probably be exactly one storage manager; found "
19713                    + matches.size() + ": matches=" + matches);
19714            return null;
19715        }
19716    }
19717
19718    @Override
19719    public void setApplicationEnabledSetting(String appPackageName,
19720            int newState, int flags, int userId, String callingPackage) {
19721        if (!sUserManager.exists(userId)) return;
19722        if (callingPackage == null) {
19723            callingPackage = Integer.toString(Binder.getCallingUid());
19724        }
19725        setEnabledSetting(appPackageName, null, newState, flags, userId, callingPackage);
19726    }
19727
19728    @Override
19729    public void setComponentEnabledSetting(ComponentName componentName,
19730            int newState, int flags, int userId) {
19731        if (!sUserManager.exists(userId)) return;
19732        setEnabledSetting(componentName.getPackageName(),
19733                componentName.getClassName(), newState, flags, userId, null);
19734    }
19735
19736    private void setEnabledSetting(final String packageName, String className, int newState,
19737            final int flags, int userId, String callingPackage) {
19738        if (!(newState == COMPONENT_ENABLED_STATE_DEFAULT
19739              || newState == COMPONENT_ENABLED_STATE_ENABLED
19740              || newState == COMPONENT_ENABLED_STATE_DISABLED
19741              || newState == COMPONENT_ENABLED_STATE_DISABLED_USER
19742              || newState == COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED)) {
19743            throw new IllegalArgumentException("Invalid new component state: "
19744                    + newState);
19745        }
19746        PackageSetting pkgSetting;
19747        final int uid = Binder.getCallingUid();
19748        final int permission;
19749        if (uid == Process.SYSTEM_UID) {
19750            permission = PackageManager.PERMISSION_GRANTED;
19751        } else {
19752            permission = mContext.checkCallingOrSelfPermission(
19753                    android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
19754        }
19755        enforceCrossUserPermission(uid, userId,
19756                false /* requireFullPermission */, true /* checkShell */, "set enabled");
19757        final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
19758        boolean sendNow = false;
19759        boolean isApp = (className == null);
19760        String componentName = isApp ? packageName : className;
19761        int packageUid = -1;
19762        ArrayList<String> components;
19763
19764        // writer
19765        synchronized (mPackages) {
19766            pkgSetting = mSettings.mPackages.get(packageName);
19767            if (pkgSetting == null) {
19768                if (className == null) {
19769                    throw new IllegalArgumentException("Unknown package: " + packageName);
19770                }
19771                throw new IllegalArgumentException(
19772                        "Unknown component: " + packageName + "/" + className);
19773            }
19774        }
19775
19776        // Limit who can change which apps
19777        if (!UserHandle.isSameApp(uid, pkgSetting.appId)) {
19778            // Don't allow apps that don't have permission to modify other apps
19779            if (!allowedByPermission) {
19780                throw new SecurityException(
19781                        "Permission Denial: attempt to change component state from pid="
19782                        + Binder.getCallingPid()
19783                        + ", uid=" + uid + ", package uid=" + pkgSetting.appId);
19784            }
19785            // Don't allow changing protected packages.
19786            if (mProtectedPackages.isPackageStateProtected(userId, packageName)) {
19787                throw new SecurityException("Cannot disable a protected package: " + packageName);
19788            }
19789        }
19790
19791        synchronized (mPackages) {
19792            if (uid == Process.SHELL_UID
19793                    && (pkgSetting.pkgFlags & ApplicationInfo.FLAG_TEST_ONLY) == 0) {
19794                // Shell can only change whole packages between ENABLED and DISABLED_USER states
19795                // unless it is a test package.
19796                int oldState = pkgSetting.getEnabled(userId);
19797                if (className == null
19798                    &&
19799                    (oldState == COMPONENT_ENABLED_STATE_DISABLED_USER
19800                     || oldState == COMPONENT_ENABLED_STATE_DEFAULT
19801                     || oldState == COMPONENT_ENABLED_STATE_ENABLED)
19802                    &&
19803                    (newState == COMPONENT_ENABLED_STATE_DISABLED_USER
19804                     || newState == COMPONENT_ENABLED_STATE_DEFAULT
19805                     || newState == COMPONENT_ENABLED_STATE_ENABLED)) {
19806                    // ok
19807                } else {
19808                    throw new SecurityException(
19809                            "Shell cannot change component state for " + packageName + "/"
19810                            + className + " to " + newState);
19811                }
19812            }
19813            if (className == null) {
19814                // We're dealing with an application/package level state change
19815                if (pkgSetting.getEnabled(userId) == newState) {
19816                    // Nothing to do
19817                    return;
19818                }
19819                if (newState == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT
19820                    || newState == PackageManager.COMPONENT_ENABLED_STATE_ENABLED) {
19821                    // Don't care about who enables an app.
19822                    callingPackage = null;
19823                }
19824                pkgSetting.setEnabled(newState, userId, callingPackage);
19825                // pkgSetting.pkg.mSetEnabled = newState;
19826            } else {
19827                // We're dealing with a component level state change
19828                // First, verify that this is a valid class name.
19829                PackageParser.Package pkg = pkgSetting.pkg;
19830                if (pkg == null || !pkg.hasComponentClassName(className)) {
19831                    if (pkg != null &&
19832                            pkg.applicationInfo.targetSdkVersion >=
19833                                    Build.VERSION_CODES.JELLY_BEAN) {
19834                        throw new IllegalArgumentException("Component class " + className
19835                                + " does not exist in " + packageName);
19836                    } else {
19837                        Slog.w(TAG, "Failed setComponentEnabledSetting: component class "
19838                                + className + " does not exist in " + packageName);
19839                    }
19840                }
19841                switch (newState) {
19842                case COMPONENT_ENABLED_STATE_ENABLED:
19843                    if (!pkgSetting.enableComponentLPw(className, userId)) {
19844                        return;
19845                    }
19846                    break;
19847                case COMPONENT_ENABLED_STATE_DISABLED:
19848                    if (!pkgSetting.disableComponentLPw(className, userId)) {
19849                        return;
19850                    }
19851                    break;
19852                case COMPONENT_ENABLED_STATE_DEFAULT:
19853                    if (!pkgSetting.restoreComponentLPw(className, userId)) {
19854                        return;
19855                    }
19856                    break;
19857                default:
19858                    Slog.e(TAG, "Invalid new component state: " + newState);
19859                    return;
19860                }
19861            }
19862            scheduleWritePackageRestrictionsLocked(userId);
19863            updateSequenceNumberLP(packageName, new int[] { userId });
19864            components = mPendingBroadcasts.get(userId, packageName);
19865            final boolean newPackage = components == null;
19866            if (newPackage) {
19867                components = new ArrayList<String>();
19868            }
19869            if (!components.contains(componentName)) {
19870                components.add(componentName);
19871            }
19872            if ((flags&PackageManager.DONT_KILL_APP) == 0) {
19873                sendNow = true;
19874                // Purge entry from pending broadcast list if another one exists already
19875                // since we are sending one right away.
19876                mPendingBroadcasts.remove(userId, packageName);
19877            } else {
19878                if (newPackage) {
19879                    mPendingBroadcasts.put(userId, packageName, components);
19880                }
19881                if (!mHandler.hasMessages(SEND_PENDING_BROADCAST)) {
19882                    // Schedule a message
19883                    mHandler.sendEmptyMessageDelayed(SEND_PENDING_BROADCAST, BROADCAST_DELAY);
19884                }
19885            }
19886        }
19887
19888        long callingId = Binder.clearCallingIdentity();
19889        try {
19890            if (sendNow) {
19891                packageUid = UserHandle.getUid(userId, pkgSetting.appId);
19892                sendPackageChangedBroadcast(packageName,
19893                        (flags&PackageManager.DONT_KILL_APP) != 0, components, packageUid);
19894            }
19895        } finally {
19896            Binder.restoreCallingIdentity(callingId);
19897        }
19898    }
19899
19900    @Override
19901    public void flushPackageRestrictionsAsUser(int userId) {
19902        if (!sUserManager.exists(userId)) {
19903            return;
19904        }
19905        enforceCrossUserPermission(Binder.getCallingUid(), userId, false /* requireFullPermission*/,
19906                false /* checkShell */, "flushPackageRestrictions");
19907        synchronized (mPackages) {
19908            mSettings.writePackageRestrictionsLPr(userId);
19909            mDirtyUsers.remove(userId);
19910            if (mDirtyUsers.isEmpty()) {
19911                mHandler.removeMessages(WRITE_PACKAGE_RESTRICTIONS);
19912            }
19913        }
19914    }
19915
19916    private void sendPackageChangedBroadcast(String packageName,
19917            boolean killFlag, ArrayList<String> componentNames, int packageUid) {
19918        if (DEBUG_INSTALL)
19919            Log.v(TAG, "Sending package changed: package=" + packageName + " components="
19920                    + componentNames);
19921        Bundle extras = new Bundle(4);
19922        extras.putString(Intent.EXTRA_CHANGED_COMPONENT_NAME, componentNames.get(0));
19923        String nameList[] = new String[componentNames.size()];
19924        componentNames.toArray(nameList);
19925        extras.putStringArray(Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST, nameList);
19926        extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, killFlag);
19927        extras.putInt(Intent.EXTRA_UID, packageUid);
19928        // If this is not reporting a change of the overall package, then only send it
19929        // to registered receivers.  We don't want to launch a swath of apps for every
19930        // little component state change.
19931        final int flags = !componentNames.contains(packageName)
19932                ? Intent.FLAG_RECEIVER_REGISTERED_ONLY : 0;
19933        sendPackageBroadcast(Intent.ACTION_PACKAGE_CHANGED,  packageName, extras, flags, null, null,
19934                new int[] {UserHandle.getUserId(packageUid)});
19935    }
19936
19937    @Override
19938    public void setPackageStoppedState(String packageName, boolean stopped, int userId) {
19939        if (!sUserManager.exists(userId)) return;
19940        final int uid = Binder.getCallingUid();
19941        final int permission = mContext.checkCallingOrSelfPermission(
19942                android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
19943        final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
19944        enforceCrossUserPermission(uid, userId,
19945                true /* requireFullPermission */, true /* checkShell */, "stop package");
19946        // writer
19947        synchronized (mPackages) {
19948            if (mSettings.setPackageStoppedStateLPw(this, packageName, stopped,
19949                    allowedByPermission, uid, userId)) {
19950                scheduleWritePackageRestrictionsLocked(userId);
19951            }
19952        }
19953    }
19954
19955    @Override
19956    public String getInstallerPackageName(String packageName) {
19957        // reader
19958        synchronized (mPackages) {
19959            return mSettings.getInstallerPackageNameLPr(packageName);
19960        }
19961    }
19962
19963    public boolean isOrphaned(String packageName) {
19964        // reader
19965        synchronized (mPackages) {
19966            return mSettings.isOrphaned(packageName);
19967        }
19968    }
19969
19970    @Override
19971    public int getApplicationEnabledSetting(String packageName, int userId) {
19972        if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
19973        int uid = Binder.getCallingUid();
19974        enforceCrossUserPermission(uid, userId,
19975                false /* requireFullPermission */, false /* checkShell */, "get enabled");
19976        // reader
19977        synchronized (mPackages) {
19978            return mSettings.getApplicationEnabledSettingLPr(packageName, userId);
19979        }
19980    }
19981
19982    @Override
19983    public int getComponentEnabledSetting(ComponentName componentName, int userId) {
19984        if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
19985        int uid = Binder.getCallingUid();
19986        enforceCrossUserPermission(uid, userId,
19987                false /* requireFullPermission */, false /* checkShell */, "get component enabled");
19988        // reader
19989        synchronized (mPackages) {
19990            return mSettings.getComponentEnabledSettingLPr(componentName, userId);
19991        }
19992    }
19993
19994    @Override
19995    public void enterSafeMode() {
19996        enforceSystemOrRoot("Only the system can request entering safe mode");
19997
19998        if (!mSystemReady) {
19999            mSafeMode = true;
20000        }
20001    }
20002
20003    @Override
20004    public void systemReady() {
20005        mSystemReady = true;
20006
20007        // Disable any carrier apps. We do this very early in boot to prevent the apps from being
20008        // disabled after already being started.
20009        CarrierAppUtils.disableCarrierAppsUntilPrivileged(mContext.getOpPackageName(), this,
20010                mContext.getContentResolver(), UserHandle.USER_SYSTEM);
20011
20012        // Read the compatibilty setting when the system is ready.
20013        boolean compatibilityModeEnabled = android.provider.Settings.Global.getInt(
20014                mContext.getContentResolver(),
20015                android.provider.Settings.Global.COMPATIBILITY_MODE, 1) == 1;
20016        PackageParser.setCompatibilityModeEnabled(compatibilityModeEnabled);
20017        if (DEBUG_SETTINGS) {
20018            Log.d(TAG, "compatibility mode:" + compatibilityModeEnabled);
20019        }
20020
20021        int[] grantPermissionsUserIds = EMPTY_INT_ARRAY;
20022
20023        synchronized (mPackages) {
20024            // Verify that all of the preferred activity components actually
20025            // exist.  It is possible for applications to be updated and at
20026            // that point remove a previously declared activity component that
20027            // had been set as a preferred activity.  We try to clean this up
20028            // the next time we encounter that preferred activity, but it is
20029            // possible for the user flow to never be able to return to that
20030            // situation so here we do a sanity check to make sure we haven't
20031            // left any junk around.
20032            ArrayList<PreferredActivity> removed = new ArrayList<PreferredActivity>();
20033            for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
20034                PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
20035                removed.clear();
20036                for (PreferredActivity pa : pir.filterSet()) {
20037                    if (mActivities.mActivities.get(pa.mPref.mComponent) == null) {
20038                        removed.add(pa);
20039                    }
20040                }
20041                if (removed.size() > 0) {
20042                    for (int r=0; r<removed.size(); r++) {
20043                        PreferredActivity pa = removed.get(r);
20044                        Slog.w(TAG, "Removing dangling preferred activity: "
20045                                + pa.mPref.mComponent);
20046                        pir.removeFilter(pa);
20047                    }
20048                    mSettings.writePackageRestrictionsLPr(
20049                            mSettings.mPreferredActivities.keyAt(i));
20050                }
20051            }
20052
20053            for (int userId : UserManagerService.getInstance().getUserIds()) {
20054                if (!mSettings.areDefaultRuntimePermissionsGrantedLPr(userId)) {
20055                    grantPermissionsUserIds = ArrayUtils.appendInt(
20056                            grantPermissionsUserIds, userId);
20057                }
20058            }
20059        }
20060        sUserManager.systemReady();
20061
20062        // If we upgraded grant all default permissions before kicking off.
20063        for (int userId : grantPermissionsUserIds) {
20064            mDefaultPermissionPolicy.grantDefaultPermissions(userId);
20065        }
20066
20067        // If we did not grant default permissions, we preload from this the
20068        // default permission exceptions lazily to ensure we don't hit the
20069        // disk on a new user creation.
20070        if (grantPermissionsUserIds == EMPTY_INT_ARRAY) {
20071            mDefaultPermissionPolicy.scheduleReadDefaultPermissionExceptions();
20072        }
20073
20074        // Kick off any messages waiting for system ready
20075        if (mPostSystemReadyMessages != null) {
20076            for (Message msg : mPostSystemReadyMessages) {
20077                msg.sendToTarget();
20078            }
20079            mPostSystemReadyMessages = null;
20080        }
20081
20082        // Watch for external volumes that come and go over time
20083        final StorageManager storage = mContext.getSystemService(StorageManager.class);
20084        storage.registerListener(mStorageListener);
20085
20086        mInstallerService.systemReady();
20087        mPackageDexOptimizer.systemReady();
20088
20089        StorageManagerInternal StorageManagerInternal = LocalServices.getService(
20090                StorageManagerInternal.class);
20091        StorageManagerInternal.addExternalStoragePolicy(
20092                new StorageManagerInternal.ExternalStorageMountPolicy() {
20093            @Override
20094            public int getMountMode(int uid, String packageName) {
20095                if (Process.isIsolated(uid)) {
20096                    return Zygote.MOUNT_EXTERNAL_NONE;
20097                }
20098                if (checkUidPermission(WRITE_MEDIA_STORAGE, uid) == PERMISSION_GRANTED) {
20099                    return Zygote.MOUNT_EXTERNAL_DEFAULT;
20100                }
20101                if (checkUidPermission(READ_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) {
20102                    return Zygote.MOUNT_EXTERNAL_DEFAULT;
20103                }
20104                if (checkUidPermission(WRITE_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) {
20105                    return Zygote.MOUNT_EXTERNAL_READ;
20106                }
20107                return Zygote.MOUNT_EXTERNAL_WRITE;
20108            }
20109
20110            @Override
20111            public boolean hasExternalStorage(int uid, String packageName) {
20112                return true;
20113            }
20114        });
20115
20116        // Now that we're mostly running, clean up stale users and apps
20117        sUserManager.reconcileUsers(StorageManager.UUID_PRIVATE_INTERNAL);
20118        reconcileApps(StorageManager.UUID_PRIVATE_INTERNAL);
20119
20120        if (mPrivappPermissionsViolations != null) {
20121            Slog.wtf(TAG,"Signature|privileged permissions not in "
20122                    + "privapp-permissions whitelist: " + mPrivappPermissionsViolations);
20123            mPrivappPermissionsViolations = null;
20124        }
20125    }
20126
20127    public void waitForAppDataPrepared() {
20128        if (mPrepareAppDataFuture == null) {
20129            return;
20130        }
20131        ConcurrentUtils.waitForFutureNoInterrupt(mPrepareAppDataFuture, "wait for prepareAppData");
20132        mPrepareAppDataFuture = null;
20133    }
20134
20135    @Override
20136    public boolean isSafeMode() {
20137        return mSafeMode;
20138    }
20139
20140    @Override
20141    public boolean hasSystemUidErrors() {
20142        return mHasSystemUidErrors;
20143    }
20144
20145    static String arrayToString(int[] array) {
20146        StringBuffer buf = new StringBuffer(128);
20147        buf.append('[');
20148        if (array != null) {
20149            for (int i=0; i<array.length; i++) {
20150                if (i > 0) buf.append(", ");
20151                buf.append(array[i]);
20152            }
20153        }
20154        buf.append(']');
20155        return buf.toString();
20156    }
20157
20158    static class DumpState {
20159        public static final int DUMP_LIBS = 1 << 0;
20160        public static final int DUMP_FEATURES = 1 << 1;
20161        public static final int DUMP_ACTIVITY_RESOLVERS = 1 << 2;
20162        public static final int DUMP_SERVICE_RESOLVERS = 1 << 3;
20163        public static final int DUMP_RECEIVER_RESOLVERS = 1 << 4;
20164        public static final int DUMP_CONTENT_RESOLVERS = 1 << 5;
20165        public static final int DUMP_PERMISSIONS = 1 << 6;
20166        public static final int DUMP_PACKAGES = 1 << 7;
20167        public static final int DUMP_SHARED_USERS = 1 << 8;
20168        public static final int DUMP_MESSAGES = 1 << 9;
20169        public static final int DUMP_PROVIDERS = 1 << 10;
20170        public static final int DUMP_VERIFIERS = 1 << 11;
20171        public static final int DUMP_PREFERRED = 1 << 12;
20172        public static final int DUMP_PREFERRED_XML = 1 << 13;
20173        public static final int DUMP_KEYSETS = 1 << 14;
20174        public static final int DUMP_VERSION = 1 << 15;
20175        public static final int DUMP_INSTALLS = 1 << 16;
20176        public static final int DUMP_INTENT_FILTER_VERIFIERS = 1 << 17;
20177        public static final int DUMP_DOMAIN_PREFERRED = 1 << 18;
20178        public static final int DUMP_FROZEN = 1 << 19;
20179        public static final int DUMP_DEXOPT = 1 << 20;
20180        public static final int DUMP_COMPILER_STATS = 1 << 21;
20181        public static final int DUMP_ENABLED_OVERLAYS = 1 << 22;
20182
20183        public static final int OPTION_SHOW_FILTERS = 1 << 0;
20184
20185        private int mTypes;
20186
20187        private int mOptions;
20188
20189        private boolean mTitlePrinted;
20190
20191        private SharedUserSetting mSharedUser;
20192
20193        public boolean isDumping(int type) {
20194            if (mTypes == 0 && type != DUMP_PREFERRED_XML) {
20195                return true;
20196            }
20197
20198            return (mTypes & type) != 0;
20199        }
20200
20201        public void setDump(int type) {
20202            mTypes |= type;
20203        }
20204
20205        public boolean isOptionEnabled(int option) {
20206            return (mOptions & option) != 0;
20207        }
20208
20209        public void setOptionEnabled(int option) {
20210            mOptions |= option;
20211        }
20212
20213        public boolean onTitlePrinted() {
20214            final boolean printed = mTitlePrinted;
20215            mTitlePrinted = true;
20216            return printed;
20217        }
20218
20219        public boolean getTitlePrinted() {
20220            return mTitlePrinted;
20221        }
20222
20223        public void setTitlePrinted(boolean enabled) {
20224            mTitlePrinted = enabled;
20225        }
20226
20227        public SharedUserSetting getSharedUser() {
20228            return mSharedUser;
20229        }
20230
20231        public void setSharedUser(SharedUserSetting user) {
20232            mSharedUser = user;
20233        }
20234    }
20235
20236    @Override
20237    public void onShellCommand(FileDescriptor in, FileDescriptor out,
20238            FileDescriptor err, String[] args, ShellCallback callback,
20239            ResultReceiver resultReceiver) {
20240        (new PackageManagerShellCommand(this)).exec(
20241                this, in, out, err, args, callback, resultReceiver);
20242    }
20243
20244    @Override
20245    protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
20246        if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
20247                != PackageManager.PERMISSION_GRANTED) {
20248            pw.println("Permission Denial: can't dump ActivityManager from from pid="
20249                    + Binder.getCallingPid()
20250                    + ", uid=" + Binder.getCallingUid()
20251                    + " without permission "
20252                    + android.Manifest.permission.DUMP);
20253            return;
20254        }
20255
20256        DumpState dumpState = new DumpState();
20257        boolean fullPreferred = false;
20258        boolean checkin = false;
20259
20260        String packageName = null;
20261        ArraySet<String> permissionNames = null;
20262
20263        int opti = 0;
20264        while (opti < args.length) {
20265            String opt = args[opti];
20266            if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') {
20267                break;
20268            }
20269            opti++;
20270
20271            if ("-a".equals(opt)) {
20272                // Right now we only know how to print all.
20273            } else if ("-h".equals(opt)) {
20274                pw.println("Package manager dump options:");
20275                pw.println("  [-h] [-f] [--checkin] [cmd] ...");
20276                pw.println("    --checkin: dump for a checkin");
20277                pw.println("    -f: print details of intent filters");
20278                pw.println("    -h: print this help");
20279                pw.println("  cmd may be one of:");
20280                pw.println("    l[ibraries]: list known shared libraries");
20281                pw.println("    f[eatures]: list device features");
20282                pw.println("    k[eysets]: print known keysets");
20283                pw.println("    r[esolvers] [activity|service|receiver|content]: dump intent resolvers");
20284                pw.println("    perm[issions]: dump permissions");
20285                pw.println("    permission [name ...]: dump declaration and use of given permission");
20286                pw.println("    pref[erred]: print preferred package settings");
20287                pw.println("    preferred-xml [--full]: print preferred package settings as xml");
20288                pw.println("    prov[iders]: dump content providers");
20289                pw.println("    p[ackages]: dump installed packages");
20290                pw.println("    s[hared-users]: dump shared user IDs");
20291                pw.println("    m[essages]: print collected runtime messages");
20292                pw.println("    v[erifiers]: print package verifier info");
20293                pw.println("    d[omain-preferred-apps]: print domains preferred apps");
20294                pw.println("    i[ntent-filter-verifiers]|ifv: print intent filter verifier info");
20295                pw.println("    version: print database version info");
20296                pw.println("    write: write current settings now");
20297                pw.println("    installs: details about install sessions");
20298                pw.println("    check-permission <permission> <package> [<user>]: does pkg hold perm?");
20299                pw.println("    dexopt: dump dexopt state");
20300                pw.println("    compiler-stats: dump compiler statistics");
20301                pw.println("    enabled-overlays: dump list of enabled overlay packages");
20302                pw.println("    <package.name>: info about given package");
20303                return;
20304            } else if ("--checkin".equals(opt)) {
20305                checkin = true;
20306            } else if ("-f".equals(opt)) {
20307                dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS);
20308            } else {
20309                pw.println("Unknown argument: " + opt + "; use -h for help");
20310            }
20311        }
20312
20313        // Is the caller requesting to dump a particular piece of data?
20314        if (opti < args.length) {
20315            String cmd = args[opti];
20316            opti++;
20317            // Is this a package name?
20318            if ("android".equals(cmd) || cmd.contains(".")) {
20319                packageName = cmd;
20320                // When dumping a single package, we always dump all of its
20321                // filter information since the amount of data will be reasonable.
20322                dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS);
20323            } else if ("check-permission".equals(cmd)) {
20324                if (opti >= args.length) {
20325                    pw.println("Error: check-permission missing permission argument");
20326                    return;
20327                }
20328                String perm = args[opti];
20329                opti++;
20330                if (opti >= args.length) {
20331                    pw.println("Error: check-permission missing package argument");
20332                    return;
20333                }
20334
20335                String pkg = args[opti];
20336                opti++;
20337                int user = UserHandle.getUserId(Binder.getCallingUid());
20338                if (opti < args.length) {
20339                    try {
20340                        user = Integer.parseInt(args[opti]);
20341                    } catch (NumberFormatException e) {
20342                        pw.println("Error: check-permission user argument is not a number: "
20343                                + args[opti]);
20344                        return;
20345                    }
20346                }
20347
20348                // Normalize package name to handle renamed packages and static libs
20349                pkg = resolveInternalPackageNameLPr(pkg, PackageManager.VERSION_CODE_HIGHEST);
20350
20351                pw.println(checkPermission(perm, pkg, user));
20352                return;
20353            } else if ("l".equals(cmd) || "libraries".equals(cmd)) {
20354                dumpState.setDump(DumpState.DUMP_LIBS);
20355            } else if ("f".equals(cmd) || "features".equals(cmd)) {
20356                dumpState.setDump(DumpState.DUMP_FEATURES);
20357            } else if ("r".equals(cmd) || "resolvers".equals(cmd)) {
20358                if (opti >= args.length) {
20359                    dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS
20360                            | DumpState.DUMP_SERVICE_RESOLVERS
20361                            | DumpState.DUMP_RECEIVER_RESOLVERS
20362                            | DumpState.DUMP_CONTENT_RESOLVERS);
20363                } else {
20364                    while (opti < args.length) {
20365                        String name = args[opti];
20366                        if ("a".equals(name) || "activity".equals(name)) {
20367                            dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS);
20368                        } else if ("s".equals(name) || "service".equals(name)) {
20369                            dumpState.setDump(DumpState.DUMP_SERVICE_RESOLVERS);
20370                        } else if ("r".equals(name) || "receiver".equals(name)) {
20371                            dumpState.setDump(DumpState.DUMP_RECEIVER_RESOLVERS);
20372                        } else if ("c".equals(name) || "content".equals(name)) {
20373                            dumpState.setDump(DumpState.DUMP_CONTENT_RESOLVERS);
20374                        } else {
20375                            pw.println("Error: unknown resolver table type: " + name);
20376                            return;
20377                        }
20378                        opti++;
20379                    }
20380                }
20381            } else if ("perm".equals(cmd) || "permissions".equals(cmd)) {
20382                dumpState.setDump(DumpState.DUMP_PERMISSIONS);
20383            } else if ("permission".equals(cmd)) {
20384                if (opti >= args.length) {
20385                    pw.println("Error: permission requires permission name");
20386                    return;
20387                }
20388                permissionNames = new ArraySet<>();
20389                while (opti < args.length) {
20390                    permissionNames.add(args[opti]);
20391                    opti++;
20392                }
20393                dumpState.setDump(DumpState.DUMP_PERMISSIONS
20394                        | DumpState.DUMP_PACKAGES | DumpState.DUMP_SHARED_USERS);
20395            } else if ("pref".equals(cmd) || "preferred".equals(cmd)) {
20396                dumpState.setDump(DumpState.DUMP_PREFERRED);
20397            } else if ("preferred-xml".equals(cmd)) {
20398                dumpState.setDump(DumpState.DUMP_PREFERRED_XML);
20399                if (opti < args.length && "--full".equals(args[opti])) {
20400                    fullPreferred = true;
20401                    opti++;
20402                }
20403            } else if ("d".equals(cmd) || "domain-preferred-apps".equals(cmd)) {
20404                dumpState.setDump(DumpState.DUMP_DOMAIN_PREFERRED);
20405            } else if ("p".equals(cmd) || "packages".equals(cmd)) {
20406                dumpState.setDump(DumpState.DUMP_PACKAGES);
20407            } else if ("s".equals(cmd) || "shared-users".equals(cmd)) {
20408                dumpState.setDump(DumpState.DUMP_SHARED_USERS);
20409            } else if ("prov".equals(cmd) || "providers".equals(cmd)) {
20410                dumpState.setDump(DumpState.DUMP_PROVIDERS);
20411            } else if ("m".equals(cmd) || "messages".equals(cmd)) {
20412                dumpState.setDump(DumpState.DUMP_MESSAGES);
20413            } else if ("v".equals(cmd) || "verifiers".equals(cmd)) {
20414                dumpState.setDump(DumpState.DUMP_VERIFIERS);
20415            } else if ("i".equals(cmd) || "ifv".equals(cmd)
20416                    || "intent-filter-verifiers".equals(cmd)) {
20417                dumpState.setDump(DumpState.DUMP_INTENT_FILTER_VERIFIERS);
20418            } else if ("version".equals(cmd)) {
20419                dumpState.setDump(DumpState.DUMP_VERSION);
20420            } else if ("k".equals(cmd) || "keysets".equals(cmd)) {
20421                dumpState.setDump(DumpState.DUMP_KEYSETS);
20422            } else if ("installs".equals(cmd)) {
20423                dumpState.setDump(DumpState.DUMP_INSTALLS);
20424            } else if ("frozen".equals(cmd)) {
20425                dumpState.setDump(DumpState.DUMP_FROZEN);
20426            } else if ("dexopt".equals(cmd)) {
20427                dumpState.setDump(DumpState.DUMP_DEXOPT);
20428            } else if ("compiler-stats".equals(cmd)) {
20429                dumpState.setDump(DumpState.DUMP_COMPILER_STATS);
20430            } else if ("enabled-overlays".equals(cmd)) {
20431                dumpState.setDump(DumpState.DUMP_ENABLED_OVERLAYS);
20432            } else if ("write".equals(cmd)) {
20433                synchronized (mPackages) {
20434                    mSettings.writeLPr();
20435                    pw.println("Settings written.");
20436                    return;
20437                }
20438            }
20439        }
20440
20441        if (checkin) {
20442            pw.println("vers,1");
20443        }
20444
20445        // reader
20446        synchronized (mPackages) {
20447            if (dumpState.isDumping(DumpState.DUMP_VERSION) && packageName == null) {
20448                if (!checkin) {
20449                    if (dumpState.onTitlePrinted())
20450                        pw.println();
20451                    pw.println("Database versions:");
20452                    mSettings.dumpVersionLPr(new IndentingPrintWriter(pw, "  "));
20453                }
20454            }
20455
20456            if (dumpState.isDumping(DumpState.DUMP_VERIFIERS) && packageName == null) {
20457                if (!checkin) {
20458                    if (dumpState.onTitlePrinted())
20459                        pw.println();
20460                    pw.println("Verifiers:");
20461                    pw.print("  Required: ");
20462                    pw.print(mRequiredVerifierPackage);
20463                    pw.print(" (uid=");
20464                    pw.print(getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING,
20465                            UserHandle.USER_SYSTEM));
20466                    pw.println(")");
20467                } else if (mRequiredVerifierPackage != null) {
20468                    pw.print("vrfy,"); pw.print(mRequiredVerifierPackage);
20469                    pw.print(",");
20470                    pw.println(getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING,
20471                            UserHandle.USER_SYSTEM));
20472                }
20473            }
20474
20475            if (dumpState.isDumping(DumpState.DUMP_INTENT_FILTER_VERIFIERS) &&
20476                    packageName == null) {
20477                if (mIntentFilterVerifierComponent != null) {
20478                    String verifierPackageName = mIntentFilterVerifierComponent.getPackageName();
20479                    if (!checkin) {
20480                        if (dumpState.onTitlePrinted())
20481                            pw.println();
20482                        pw.println("Intent Filter Verifier:");
20483                        pw.print("  Using: ");
20484                        pw.print(verifierPackageName);
20485                        pw.print(" (uid=");
20486                        pw.print(getPackageUid(verifierPackageName, MATCH_DEBUG_TRIAGED_MISSING,
20487                                UserHandle.USER_SYSTEM));
20488                        pw.println(")");
20489                    } else if (verifierPackageName != null) {
20490                        pw.print("ifv,"); pw.print(verifierPackageName);
20491                        pw.print(",");
20492                        pw.println(getPackageUid(verifierPackageName, MATCH_DEBUG_TRIAGED_MISSING,
20493                                UserHandle.USER_SYSTEM));
20494                    }
20495                } else {
20496                    pw.println();
20497                    pw.println("No Intent Filter Verifier available!");
20498                }
20499            }
20500
20501            if (dumpState.isDumping(DumpState.DUMP_LIBS) && packageName == null) {
20502                boolean printedHeader = false;
20503                final Iterator<String> it = mSharedLibraries.keySet().iterator();
20504                while (it.hasNext()) {
20505                    String libName = it.next();
20506                    SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(libName);
20507                    if (versionedLib == null) {
20508                        continue;
20509                    }
20510                    final int versionCount = versionedLib.size();
20511                    for (int i = 0; i < versionCount; i++) {
20512                        SharedLibraryEntry libEntry = versionedLib.valueAt(i);
20513                        if (!checkin) {
20514                            if (!printedHeader) {
20515                                if (dumpState.onTitlePrinted())
20516                                    pw.println();
20517                                pw.println("Libraries:");
20518                                printedHeader = true;
20519                            }
20520                            pw.print("  ");
20521                        } else {
20522                            pw.print("lib,");
20523                        }
20524                        pw.print(libEntry.info.getName());
20525                        if (libEntry.info.isStatic()) {
20526                            pw.print(" version=" + libEntry.info.getVersion());
20527                        }
20528                        if (!checkin) {
20529                            pw.print(" -> ");
20530                        }
20531                        if (libEntry.path != null) {
20532                            pw.print(" (jar) ");
20533                            pw.print(libEntry.path);
20534                        } else {
20535                            pw.print(" (apk) ");
20536                            pw.print(libEntry.apk);
20537                        }
20538                        pw.println();
20539                    }
20540                }
20541            }
20542
20543            if (dumpState.isDumping(DumpState.DUMP_FEATURES) && packageName == null) {
20544                if (dumpState.onTitlePrinted())
20545                    pw.println();
20546                if (!checkin) {
20547                    pw.println("Features:");
20548                }
20549
20550                synchronized (mAvailableFeatures) {
20551                    for (FeatureInfo feat : mAvailableFeatures.values()) {
20552                        if (checkin) {
20553                            pw.print("feat,");
20554                            pw.print(feat.name);
20555                            pw.print(",");
20556                            pw.println(feat.version);
20557                        } else {
20558                            pw.print("  ");
20559                            pw.print(feat.name);
20560                            if (feat.version > 0) {
20561                                pw.print(" version=");
20562                                pw.print(feat.version);
20563                            }
20564                            pw.println();
20565                        }
20566                    }
20567                }
20568            }
20569
20570            if (!checkin && dumpState.isDumping(DumpState.DUMP_ACTIVITY_RESOLVERS)) {
20571                if (mActivities.dump(pw, dumpState.getTitlePrinted() ? "\nActivity Resolver Table:"
20572                        : "Activity Resolver Table:", "  ", packageName,
20573                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
20574                    dumpState.setTitlePrinted(true);
20575                }
20576            }
20577            if (!checkin && dumpState.isDumping(DumpState.DUMP_RECEIVER_RESOLVERS)) {
20578                if (mReceivers.dump(pw, dumpState.getTitlePrinted() ? "\nReceiver Resolver Table:"
20579                        : "Receiver Resolver Table:", "  ", packageName,
20580                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
20581                    dumpState.setTitlePrinted(true);
20582                }
20583            }
20584            if (!checkin && dumpState.isDumping(DumpState.DUMP_SERVICE_RESOLVERS)) {
20585                if (mServices.dump(pw, dumpState.getTitlePrinted() ? "\nService Resolver Table:"
20586                        : "Service Resolver Table:", "  ", packageName,
20587                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
20588                    dumpState.setTitlePrinted(true);
20589                }
20590            }
20591            if (!checkin && dumpState.isDumping(DumpState.DUMP_CONTENT_RESOLVERS)) {
20592                if (mProviders.dump(pw, dumpState.getTitlePrinted() ? "\nProvider Resolver Table:"
20593                        : "Provider Resolver Table:", "  ", packageName,
20594                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
20595                    dumpState.setTitlePrinted(true);
20596                }
20597            }
20598
20599            if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED)) {
20600                for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
20601                    PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
20602                    int user = mSettings.mPreferredActivities.keyAt(i);
20603                    if (pir.dump(pw,
20604                            dumpState.getTitlePrinted()
20605                                ? "\nPreferred Activities User " + user + ":"
20606                                : "Preferred Activities User " + user + ":", "  ",
20607                            packageName, true, false)) {
20608                        dumpState.setTitlePrinted(true);
20609                    }
20610                }
20611            }
20612
20613            if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED_XML)) {
20614                pw.flush();
20615                FileOutputStream fout = new FileOutputStream(fd);
20616                BufferedOutputStream str = new BufferedOutputStream(fout);
20617                XmlSerializer serializer = new FastXmlSerializer();
20618                try {
20619                    serializer.setOutput(str, StandardCharsets.UTF_8.name());
20620                    serializer.startDocument(null, true);
20621                    serializer.setFeature(
20622                            "http://xmlpull.org/v1/doc/features.html#indent-output", true);
20623                    mSettings.writePreferredActivitiesLPr(serializer, 0, fullPreferred);
20624                    serializer.endDocument();
20625                    serializer.flush();
20626                } catch (IllegalArgumentException e) {
20627                    pw.println("Failed writing: " + e);
20628                } catch (IllegalStateException e) {
20629                    pw.println("Failed writing: " + e);
20630                } catch (IOException e) {
20631                    pw.println("Failed writing: " + e);
20632                }
20633            }
20634
20635            if (!checkin
20636                    && dumpState.isDumping(DumpState.DUMP_DOMAIN_PREFERRED)
20637                    && packageName == null) {
20638                pw.println();
20639                int count = mSettings.mPackages.size();
20640                if (count == 0) {
20641                    pw.println("No applications!");
20642                    pw.println();
20643                } else {
20644                    final String prefix = "  ";
20645                    Collection<PackageSetting> allPackageSettings = mSettings.mPackages.values();
20646                    if (allPackageSettings.size() == 0) {
20647                        pw.println("No domain preferred apps!");
20648                        pw.println();
20649                    } else {
20650                        pw.println("App verification status:");
20651                        pw.println();
20652                        count = 0;
20653                        for (PackageSetting ps : allPackageSettings) {
20654                            IntentFilterVerificationInfo ivi = ps.getIntentFilterVerificationInfo();
20655                            if (ivi == null || ivi.getPackageName() == null) continue;
20656                            pw.println(prefix + "Package: " + ivi.getPackageName());
20657                            pw.println(prefix + "Domains: " + ivi.getDomainsString());
20658                            pw.println(prefix + "Status:  " + ivi.getStatusString());
20659                            pw.println();
20660                            count++;
20661                        }
20662                        if (count == 0) {
20663                            pw.println(prefix + "No app verification established.");
20664                            pw.println();
20665                        }
20666                        for (int userId : sUserManager.getUserIds()) {
20667                            pw.println("App linkages for user " + userId + ":");
20668                            pw.println();
20669                            count = 0;
20670                            for (PackageSetting ps : allPackageSettings) {
20671                                final long status = ps.getDomainVerificationStatusForUser(userId);
20672                                if (status >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED
20673                                        && !DEBUG_DOMAIN_VERIFICATION) {
20674                                    continue;
20675                                }
20676                                pw.println(prefix + "Package: " + ps.name);
20677                                pw.println(prefix + "Domains: " + dumpDomainString(ps.name));
20678                                String statusStr = IntentFilterVerificationInfo.
20679                                        getStatusStringFromValue(status);
20680                                pw.println(prefix + "Status:  " + statusStr);
20681                                pw.println();
20682                                count++;
20683                            }
20684                            if (count == 0) {
20685                                pw.println(prefix + "No configured app linkages.");
20686                                pw.println();
20687                            }
20688                        }
20689                    }
20690                }
20691            }
20692
20693            if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS)) {
20694                mSettings.dumpPermissionsLPr(pw, packageName, permissionNames, dumpState);
20695                if (packageName == null && permissionNames == null) {
20696                    for (int iperm=0; iperm<mAppOpPermissionPackages.size(); iperm++) {
20697                        if (iperm == 0) {
20698                            if (dumpState.onTitlePrinted())
20699                                pw.println();
20700                            pw.println("AppOp Permissions:");
20701                        }
20702                        pw.print("  AppOp Permission ");
20703                        pw.print(mAppOpPermissionPackages.keyAt(iperm));
20704                        pw.println(":");
20705                        ArraySet<String> pkgs = mAppOpPermissionPackages.valueAt(iperm);
20706                        for (int ipkg=0; ipkg<pkgs.size(); ipkg++) {
20707                            pw.print("    "); pw.println(pkgs.valueAt(ipkg));
20708                        }
20709                    }
20710                }
20711            }
20712
20713            if (!checkin && dumpState.isDumping(DumpState.DUMP_PROVIDERS)) {
20714                boolean printedSomething = false;
20715                for (PackageParser.Provider p : mProviders.mProviders.values()) {
20716                    if (packageName != null && !packageName.equals(p.info.packageName)) {
20717                        continue;
20718                    }
20719                    if (!printedSomething) {
20720                        if (dumpState.onTitlePrinted())
20721                            pw.println();
20722                        pw.println("Registered ContentProviders:");
20723                        printedSomething = true;
20724                    }
20725                    pw.print("  "); p.printComponentShortName(pw); pw.println(":");
20726                    pw.print("    "); pw.println(p.toString());
20727                }
20728                printedSomething = false;
20729                for (Map.Entry<String, PackageParser.Provider> entry :
20730                        mProvidersByAuthority.entrySet()) {
20731                    PackageParser.Provider p = entry.getValue();
20732                    if (packageName != null && !packageName.equals(p.info.packageName)) {
20733                        continue;
20734                    }
20735                    if (!printedSomething) {
20736                        if (dumpState.onTitlePrinted())
20737                            pw.println();
20738                        pw.println("ContentProvider Authorities:");
20739                        printedSomething = true;
20740                    }
20741                    pw.print("  ["); pw.print(entry.getKey()); pw.println("]:");
20742                    pw.print("    "); pw.println(p.toString());
20743                    if (p.info != null && p.info.applicationInfo != null) {
20744                        final String appInfo = p.info.applicationInfo.toString();
20745                        pw.print("      applicationInfo="); pw.println(appInfo);
20746                    }
20747                }
20748            }
20749
20750            if (!checkin && dumpState.isDumping(DumpState.DUMP_KEYSETS)) {
20751                mSettings.mKeySetManagerService.dumpLPr(pw, packageName, dumpState);
20752            }
20753
20754            if (dumpState.isDumping(DumpState.DUMP_PACKAGES)) {
20755                mSettings.dumpPackagesLPr(pw, packageName, permissionNames, dumpState, checkin);
20756            }
20757
20758            if (dumpState.isDumping(DumpState.DUMP_SHARED_USERS)) {
20759                mSettings.dumpSharedUsersLPr(pw, packageName, permissionNames, dumpState, checkin);
20760            }
20761
20762            if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS) && packageName == null) {
20763                mSettings.dumpRestoredPermissionGrantsLPr(pw, dumpState);
20764            }
20765
20766            if (!checkin && dumpState.isDumping(DumpState.DUMP_INSTALLS) && packageName == null) {
20767                // XXX should handle packageName != null by dumping only install data that
20768                // the given package is involved with.
20769                if (dumpState.onTitlePrinted()) pw.println();
20770                mInstallerService.dump(new IndentingPrintWriter(pw, "  ", 120));
20771            }
20772
20773            if (!checkin && dumpState.isDumping(DumpState.DUMP_FROZEN) && packageName == null) {
20774                // XXX should handle packageName != null by dumping only install data that
20775                // the given package is involved with.
20776                if (dumpState.onTitlePrinted()) pw.println();
20777
20778                final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, "  ", 120);
20779                ipw.println();
20780                ipw.println("Frozen packages:");
20781                ipw.increaseIndent();
20782                if (mFrozenPackages.size() == 0) {
20783                    ipw.println("(none)");
20784                } else {
20785                    for (int i = 0; i < mFrozenPackages.size(); i++) {
20786                        ipw.println(mFrozenPackages.valueAt(i));
20787                    }
20788                }
20789                ipw.decreaseIndent();
20790            }
20791
20792            if (!checkin && dumpState.isDumping(DumpState.DUMP_DEXOPT)) {
20793                if (dumpState.onTitlePrinted()) pw.println();
20794                dumpDexoptStateLPr(pw, packageName);
20795            }
20796
20797            if (!checkin && dumpState.isDumping(DumpState.DUMP_COMPILER_STATS)) {
20798                if (dumpState.onTitlePrinted()) pw.println();
20799                dumpCompilerStatsLPr(pw, packageName);
20800            }
20801
20802            if (!checkin && dumpState.isDumping(DumpState.DUMP_ENABLED_OVERLAYS)) {
20803                if (dumpState.onTitlePrinted()) pw.println();
20804                dumpEnabledOverlaysLPr(pw);
20805            }
20806
20807            if (!checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES) && packageName == null) {
20808                if (dumpState.onTitlePrinted()) pw.println();
20809                mSettings.dumpReadMessagesLPr(pw, dumpState);
20810
20811                pw.println();
20812                pw.println("Package warning messages:");
20813                BufferedReader in = null;
20814                String line = null;
20815                try {
20816                    in = new BufferedReader(new FileReader(getSettingsProblemFile()));
20817                    while ((line = in.readLine()) != null) {
20818                        if (line.contains("ignored: updated version")) continue;
20819                        pw.println(line);
20820                    }
20821                } catch (IOException ignored) {
20822                } finally {
20823                    IoUtils.closeQuietly(in);
20824                }
20825            }
20826
20827            if (checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES)) {
20828                BufferedReader in = null;
20829                String line = null;
20830                try {
20831                    in = new BufferedReader(new FileReader(getSettingsProblemFile()));
20832                    while ((line = in.readLine()) != null) {
20833                        if (line.contains("ignored: updated version")) continue;
20834                        pw.print("msg,");
20835                        pw.println(line);
20836                    }
20837                } catch (IOException ignored) {
20838                } finally {
20839                    IoUtils.closeQuietly(in);
20840                }
20841            }
20842        }
20843    }
20844
20845    private void dumpDexoptStateLPr(PrintWriter pw, String packageName) {
20846        final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, "  ", 120);
20847        ipw.println();
20848        ipw.println("Dexopt state:");
20849        ipw.increaseIndent();
20850        Collection<PackageParser.Package> packages = null;
20851        if (packageName != null) {
20852            PackageParser.Package targetPackage = mPackages.get(packageName);
20853            if (targetPackage != null) {
20854                packages = Collections.singletonList(targetPackage);
20855            } else {
20856                ipw.println("Unable to find package: " + packageName);
20857                return;
20858            }
20859        } else {
20860            packages = mPackages.values();
20861        }
20862
20863        for (PackageParser.Package pkg : packages) {
20864            ipw.println("[" + pkg.packageName + "]");
20865            ipw.increaseIndent();
20866            mPackageDexOptimizer.dumpDexoptState(ipw, pkg);
20867            ipw.decreaseIndent();
20868        }
20869    }
20870
20871    private void dumpCompilerStatsLPr(PrintWriter pw, String packageName) {
20872        final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, "  ", 120);
20873        ipw.println();
20874        ipw.println("Compiler stats:");
20875        ipw.increaseIndent();
20876        Collection<PackageParser.Package> packages = null;
20877        if (packageName != null) {
20878            PackageParser.Package targetPackage = mPackages.get(packageName);
20879            if (targetPackage != null) {
20880                packages = Collections.singletonList(targetPackage);
20881            } else {
20882                ipw.println("Unable to find package: " + packageName);
20883                return;
20884            }
20885        } else {
20886            packages = mPackages.values();
20887        }
20888
20889        for (PackageParser.Package pkg : packages) {
20890            ipw.println("[" + pkg.packageName + "]");
20891            ipw.increaseIndent();
20892
20893            CompilerStats.PackageStats stats = getCompilerPackageStats(pkg.packageName);
20894            if (stats == null) {
20895                ipw.println("(No recorded stats)");
20896            } else {
20897                stats.dump(ipw);
20898            }
20899            ipw.decreaseIndent();
20900        }
20901    }
20902
20903    private void dumpEnabledOverlaysLPr(PrintWriter pw) {
20904        pw.println("Enabled overlay paths:");
20905        final int N = mEnabledOverlayPaths.size();
20906        for (int i = 0; i < N; i++) {
20907            final int userId = mEnabledOverlayPaths.keyAt(i);
20908            pw.println(String.format("    User %d:", userId));
20909            final ArrayMap<String, ArrayList<String>> userSpecificOverlays =
20910                mEnabledOverlayPaths.valueAt(i);
20911            final int M = userSpecificOverlays.size();
20912            for (int j = 0; j < M; j++) {
20913                final String targetPackageName = userSpecificOverlays.keyAt(j);
20914                final ArrayList<String> overlayPackagePaths = userSpecificOverlays.valueAt(j);
20915                pw.println(String.format("        %s: %s", targetPackageName, overlayPackagePaths));
20916            }
20917        }
20918    }
20919
20920    private String dumpDomainString(String packageName) {
20921        List<IntentFilterVerificationInfo> iviList = getIntentFilterVerifications(packageName)
20922                .getList();
20923        List<IntentFilter> filters = getAllIntentFilters(packageName).getList();
20924
20925        ArraySet<String> result = new ArraySet<>();
20926        if (iviList.size() > 0) {
20927            for (IntentFilterVerificationInfo ivi : iviList) {
20928                for (String host : ivi.getDomains()) {
20929                    result.add(host);
20930                }
20931            }
20932        }
20933        if (filters != null && filters.size() > 0) {
20934            for (IntentFilter filter : filters) {
20935                if (filter.hasCategory(Intent.CATEGORY_BROWSABLE)
20936                        && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) ||
20937                                filter.hasDataScheme(IntentFilter.SCHEME_HTTPS))) {
20938                    result.addAll(filter.getHostsList());
20939                }
20940            }
20941        }
20942
20943        StringBuilder sb = new StringBuilder(result.size() * 16);
20944        for (String domain : result) {
20945            if (sb.length() > 0) sb.append(" ");
20946            sb.append(domain);
20947        }
20948        return sb.toString();
20949    }
20950
20951    // ------- apps on sdcard specific code -------
20952    static final boolean DEBUG_SD_INSTALL = false;
20953
20954    private static final String SD_ENCRYPTION_KEYSTORE_NAME = "AppsOnSD";
20955
20956    private static final String SD_ENCRYPTION_ALGORITHM = "AES";
20957
20958    private boolean mMediaMounted = false;
20959
20960    static String getEncryptKey() {
20961        try {
20962            String sdEncKey = SystemKeyStore.getInstance().retrieveKeyHexString(
20963                    SD_ENCRYPTION_KEYSTORE_NAME);
20964            if (sdEncKey == null) {
20965                sdEncKey = SystemKeyStore.getInstance().generateNewKeyHexString(128,
20966                        SD_ENCRYPTION_ALGORITHM, SD_ENCRYPTION_KEYSTORE_NAME);
20967                if (sdEncKey == null) {
20968                    Slog.e(TAG, "Failed to create encryption keys");
20969                    return null;
20970                }
20971            }
20972            return sdEncKey;
20973        } catch (NoSuchAlgorithmException nsae) {
20974            Slog.e(TAG, "Failed to create encryption keys with exception: " + nsae);
20975            return null;
20976        } catch (IOException ioe) {
20977            Slog.e(TAG, "Failed to retrieve encryption keys with exception: " + ioe);
20978            return null;
20979        }
20980    }
20981
20982    /*
20983     * Update media status on PackageManager.
20984     */
20985    @Override
20986    public void updateExternalMediaStatus(final boolean mediaStatus, final boolean reportStatus) {
20987        int callingUid = Binder.getCallingUid();
20988        if (callingUid != 0 && callingUid != Process.SYSTEM_UID) {
20989            throw new SecurityException("Media status can only be updated by the system");
20990        }
20991        // reader; this apparently protects mMediaMounted, but should probably
20992        // be a different lock in that case.
20993        synchronized (mPackages) {
20994            Log.i(TAG, "Updating external media status from "
20995                    + (mMediaMounted ? "mounted" : "unmounted") + " to "
20996                    + (mediaStatus ? "mounted" : "unmounted"));
20997            if (DEBUG_SD_INSTALL)
20998                Log.i(TAG, "updateExternalMediaStatus:: mediaStatus=" + mediaStatus
20999                        + ", mMediaMounted=" + mMediaMounted);
21000            if (mediaStatus == mMediaMounted) {
21001                final Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1
21002                        : 0, -1);
21003                mHandler.sendMessage(msg);
21004                return;
21005            }
21006            mMediaMounted = mediaStatus;
21007        }
21008        // Queue up an async operation since the package installation may take a
21009        // little while.
21010        mHandler.post(new Runnable() {
21011            public void run() {
21012                updateExternalMediaStatusInner(mediaStatus, reportStatus, true);
21013            }
21014        });
21015    }
21016
21017    /**
21018     * Called by StorageManagerService when the initial ASECs to scan are available.
21019     * Should block until all the ASEC containers are finished being scanned.
21020     */
21021    public void scanAvailableAsecs() {
21022        updateExternalMediaStatusInner(true, false, false);
21023    }
21024
21025    /*
21026     * Collect information of applications on external media, map them against
21027     * existing containers and update information based on current mount status.
21028     * Please note that we always have to report status if reportStatus has been
21029     * set to true especially when unloading packages.
21030     */
21031    private void updateExternalMediaStatusInner(boolean isMounted, boolean reportStatus,
21032            boolean externalStorage) {
21033        ArrayMap<AsecInstallArgs, String> processCids = new ArrayMap<>();
21034        int[] uidArr = EmptyArray.INT;
21035
21036        final String[] list = PackageHelper.getSecureContainerList();
21037        if (ArrayUtils.isEmpty(list)) {
21038            Log.i(TAG, "No secure containers found");
21039        } else {
21040            // Process list of secure containers and categorize them
21041            // as active or stale based on their package internal state.
21042
21043            // reader
21044            synchronized (mPackages) {
21045                for (String cid : list) {
21046                    // Leave stages untouched for now; installer service owns them
21047                    if (PackageInstallerService.isStageName(cid)) continue;
21048
21049                    if (DEBUG_SD_INSTALL)
21050                        Log.i(TAG, "Processing container " + cid);
21051                    String pkgName = getAsecPackageName(cid);
21052                    if (pkgName == null) {
21053                        Slog.i(TAG, "Found stale container " + cid + " with no package name");
21054                        continue;
21055                    }
21056                    if (DEBUG_SD_INSTALL)
21057                        Log.i(TAG, "Looking for pkg : " + pkgName);
21058
21059                    final PackageSetting ps = mSettings.mPackages.get(pkgName);
21060                    if (ps == null) {
21061                        Slog.i(TAG, "Found stale container " + cid + " with no matching settings");
21062                        continue;
21063                    }
21064
21065                    /*
21066                     * Skip packages that are not external if we're unmounting
21067                     * external storage.
21068                     */
21069                    if (externalStorage && !isMounted && !isExternal(ps)) {
21070                        continue;
21071                    }
21072
21073                    final AsecInstallArgs args = new AsecInstallArgs(cid,
21074                            getAppDexInstructionSets(ps), ps.isForwardLocked());
21075                    // The package status is changed only if the code path
21076                    // matches between settings and the container id.
21077                    if (ps.codePathString != null
21078                            && ps.codePathString.startsWith(args.getCodePath())) {
21079                        if (DEBUG_SD_INSTALL) {
21080                            Log.i(TAG, "Container : " + cid + " corresponds to pkg : " + pkgName
21081                                    + " at code path: " + ps.codePathString);
21082                        }
21083
21084                        // We do have a valid package installed on sdcard
21085                        processCids.put(args, ps.codePathString);
21086                        final int uid = ps.appId;
21087                        if (uid != -1) {
21088                            uidArr = ArrayUtils.appendInt(uidArr, uid);
21089                        }
21090                    } else {
21091                        Slog.i(TAG, "Found stale container " + cid + ": expected codePath="
21092                                + ps.codePathString);
21093                    }
21094                }
21095            }
21096
21097            Arrays.sort(uidArr);
21098        }
21099
21100        // Process packages with valid entries.
21101        if (isMounted) {
21102            if (DEBUG_SD_INSTALL)
21103                Log.i(TAG, "Loading packages");
21104            loadMediaPackages(processCids, uidArr, externalStorage);
21105            startCleaningPackages();
21106            mInstallerService.onSecureContainersAvailable();
21107        } else {
21108            if (DEBUG_SD_INSTALL)
21109                Log.i(TAG, "Unloading packages");
21110            unloadMediaPackages(processCids, uidArr, reportStatus);
21111        }
21112    }
21113
21114    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
21115            ArrayList<ApplicationInfo> infos, IIntentReceiver finishedReceiver) {
21116        final int size = infos.size();
21117        final String[] packageNames = new String[size];
21118        final int[] packageUids = new int[size];
21119        for (int i = 0; i < size; i++) {
21120            final ApplicationInfo info = infos.get(i);
21121            packageNames[i] = info.packageName;
21122            packageUids[i] = info.uid;
21123        }
21124        sendResourcesChangedBroadcast(mediaStatus, replacing, packageNames, packageUids,
21125                finishedReceiver);
21126    }
21127
21128    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
21129            ArrayList<String> pkgList, int uidArr[], IIntentReceiver finishedReceiver) {
21130        sendResourcesChangedBroadcast(mediaStatus, replacing,
21131                pkgList.toArray(new String[pkgList.size()]), uidArr, finishedReceiver);
21132    }
21133
21134    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
21135            String[] pkgList, int uidArr[], IIntentReceiver finishedReceiver) {
21136        int size = pkgList.length;
21137        if (size > 0) {
21138            // Send broadcasts here
21139            Bundle extras = new Bundle();
21140            extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList);
21141            if (uidArr != null) {
21142                extras.putIntArray(Intent.EXTRA_CHANGED_UID_LIST, uidArr);
21143            }
21144            if (replacing) {
21145                extras.putBoolean(Intent.EXTRA_REPLACING, replacing);
21146            }
21147            String action = mediaStatus ? Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE
21148                    : Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE;
21149            sendPackageBroadcast(action, null, extras, 0, null, finishedReceiver, null);
21150        }
21151    }
21152
21153   /*
21154     * Look at potentially valid container ids from processCids If package
21155     * information doesn't match the one on record or package scanning fails,
21156     * the cid is added to list of removeCids. We currently don't delete stale
21157     * containers.
21158     */
21159    private void loadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int[] uidArr,
21160            boolean externalStorage) {
21161        ArrayList<String> pkgList = new ArrayList<String>();
21162        Set<AsecInstallArgs> keys = processCids.keySet();
21163
21164        for (AsecInstallArgs args : keys) {
21165            String codePath = processCids.get(args);
21166            if (DEBUG_SD_INSTALL)
21167                Log.i(TAG, "Loading container : " + args.cid);
21168            int retCode = PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
21169            try {
21170                // Make sure there are no container errors first.
21171                if (args.doPreInstall(PackageManager.INSTALL_SUCCEEDED) != PackageManager.INSTALL_SUCCEEDED) {
21172                    Slog.e(TAG, "Failed to mount cid : " + args.cid
21173                            + " when installing from sdcard");
21174                    continue;
21175                }
21176                // Check code path here.
21177                if (codePath == null || !codePath.startsWith(args.getCodePath())) {
21178                    Slog.e(TAG, "Container " + args.cid + " cachepath " + args.getCodePath()
21179                            + " does not match one in settings " + codePath);
21180                    continue;
21181                }
21182                // Parse package
21183                int parseFlags = mDefParseFlags;
21184                if (args.isExternalAsec()) {
21185                    parseFlags |= PackageParser.PARSE_EXTERNAL_STORAGE;
21186                }
21187                if (args.isFwdLocked()) {
21188                    parseFlags |= PackageParser.PARSE_FORWARD_LOCK;
21189                }
21190
21191                synchronized (mInstallLock) {
21192                    PackageParser.Package pkg = null;
21193                    try {
21194                        // Sadly we don't know the package name yet to freeze it
21195                        pkg = scanPackageTracedLI(new File(codePath), parseFlags,
21196                                SCAN_IGNORE_FROZEN, 0, null);
21197                    } catch (PackageManagerException e) {
21198                        Slog.w(TAG, "Failed to scan " + codePath + ": " + e.getMessage());
21199                    }
21200                    // Scan the package
21201                    if (pkg != null) {
21202                        /*
21203                         * TODO why is the lock being held? doPostInstall is
21204                         * called in other places without the lock. This needs
21205                         * to be straightened out.
21206                         */
21207                        // writer
21208                        synchronized (mPackages) {
21209                            retCode = PackageManager.INSTALL_SUCCEEDED;
21210                            pkgList.add(pkg.packageName);
21211                            // Post process args
21212                            args.doPostInstall(PackageManager.INSTALL_SUCCEEDED,
21213                                    pkg.applicationInfo.uid);
21214                        }
21215                    } else {
21216                        Slog.i(TAG, "Failed to install pkg from  " + codePath + " from sdcard");
21217                    }
21218                }
21219
21220            } finally {
21221                if (retCode != PackageManager.INSTALL_SUCCEEDED) {
21222                    Log.w(TAG, "Container " + args.cid + " is stale, retCode=" + retCode);
21223                }
21224            }
21225        }
21226        // writer
21227        synchronized (mPackages) {
21228            // If the platform SDK has changed since the last time we booted,
21229            // we need to re-grant app permission to catch any new ones that
21230            // appear. This is really a hack, and means that apps can in some
21231            // cases get permissions that the user didn't initially explicitly
21232            // allow... it would be nice to have some better way to handle
21233            // this situation.
21234            final VersionInfo ver = externalStorage ? mSettings.getExternalVersion()
21235                    : mSettings.getInternalVersion();
21236            final String volumeUuid = externalStorage ? StorageManager.UUID_PRIMARY_PHYSICAL
21237                    : StorageManager.UUID_PRIVATE_INTERNAL;
21238
21239            int updateFlags = UPDATE_PERMISSIONS_ALL;
21240            if (ver.sdkVersion != mSdkVersion) {
21241                logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to "
21242                        + mSdkVersion + "; regranting permissions for external");
21243                updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL;
21244            }
21245            updatePermissionsLPw(null, null, volumeUuid, updateFlags);
21246
21247            // Yay, everything is now upgraded
21248            ver.forceCurrent();
21249
21250            // can downgrade to reader
21251            // Persist settings
21252            mSettings.writeLPr();
21253        }
21254        // Send a broadcast to let everyone know we are done processing
21255        if (pkgList.size() > 0) {
21256            sendResourcesChangedBroadcast(true, false, pkgList, uidArr, null);
21257        }
21258    }
21259
21260   /*
21261     * Utility method to unload a list of specified containers
21262     */
21263    private void unloadAllContainers(Set<AsecInstallArgs> cidArgs) {
21264        // Just unmount all valid containers.
21265        for (AsecInstallArgs arg : cidArgs) {
21266            synchronized (mInstallLock) {
21267                arg.doPostDeleteLI(false);
21268           }
21269       }
21270   }
21271
21272    /*
21273     * Unload packages mounted on external media. This involves deleting package
21274     * data from internal structures, sending broadcasts about disabled packages,
21275     * gc'ing to free up references, unmounting all secure containers
21276     * corresponding to packages on external media, and posting a
21277     * UPDATED_MEDIA_STATUS message if status has been requested. Please note
21278     * that we always have to post this message if status has been requested no
21279     * matter what.
21280     */
21281    private void unloadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int uidArr[],
21282            final boolean reportStatus) {
21283        if (DEBUG_SD_INSTALL)
21284            Log.i(TAG, "unloading media packages");
21285        ArrayList<String> pkgList = new ArrayList<String>();
21286        ArrayList<AsecInstallArgs> failedList = new ArrayList<AsecInstallArgs>();
21287        final Set<AsecInstallArgs> keys = processCids.keySet();
21288        for (AsecInstallArgs args : keys) {
21289            String pkgName = args.getPackageName();
21290            if (DEBUG_SD_INSTALL)
21291                Log.i(TAG, "Trying to unload pkg : " + pkgName);
21292            // Delete package internally
21293            PackageRemovedInfo outInfo = new PackageRemovedInfo();
21294            synchronized (mInstallLock) {
21295                final int deleteFlags = PackageManager.DELETE_KEEP_DATA;
21296                final boolean res;
21297                try (PackageFreezer freezer = freezePackageForDelete(pkgName, deleteFlags,
21298                        "unloadMediaPackages")) {
21299                    res = deletePackageLIF(pkgName, null, false, null, deleteFlags, outInfo, false,
21300                            null);
21301                }
21302                if (res) {
21303                    pkgList.add(pkgName);
21304                } else {
21305                    Slog.e(TAG, "Failed to delete pkg from sdcard : " + pkgName);
21306                    failedList.add(args);
21307                }
21308            }
21309        }
21310
21311        // reader
21312        synchronized (mPackages) {
21313            // We didn't update the settings after removing each package;
21314            // write them now for all packages.
21315            mSettings.writeLPr();
21316        }
21317
21318        // We have to absolutely send UPDATED_MEDIA_STATUS only
21319        // after confirming that all the receivers processed the ordered
21320        // broadcast when packages get disabled, force a gc to clean things up.
21321        // and unload all the containers.
21322        if (pkgList.size() > 0) {
21323            sendResourcesChangedBroadcast(false, false, pkgList, uidArr,
21324                    new IIntentReceiver.Stub() {
21325                public void performReceive(Intent intent, int resultCode, String data,
21326                        Bundle extras, boolean ordered, boolean sticky,
21327                        int sendingUser) throws RemoteException {
21328                    Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS,
21329                            reportStatus ? 1 : 0, 1, keys);
21330                    mHandler.sendMessage(msg);
21331                }
21332            });
21333        } else {
21334            Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 : 0, -1,
21335                    keys);
21336            mHandler.sendMessage(msg);
21337        }
21338    }
21339
21340    private void loadPrivatePackages(final VolumeInfo vol) {
21341        mHandler.post(new Runnable() {
21342            @Override
21343            public void run() {
21344                loadPrivatePackagesInner(vol);
21345            }
21346        });
21347    }
21348
21349    private void loadPrivatePackagesInner(VolumeInfo vol) {
21350        final String volumeUuid = vol.fsUuid;
21351        if (TextUtils.isEmpty(volumeUuid)) {
21352            Slog.e(TAG, "Loading internal storage is probably a mistake; ignoring");
21353            return;
21354        }
21355
21356        final ArrayList<PackageFreezer> freezers = new ArrayList<>();
21357        final ArrayList<ApplicationInfo> loaded = new ArrayList<>();
21358        final int parseFlags = mDefParseFlags | PackageParser.PARSE_EXTERNAL_STORAGE;
21359
21360        final VersionInfo ver;
21361        final List<PackageSetting> packages;
21362        synchronized (mPackages) {
21363            ver = mSettings.findOrCreateVersion(volumeUuid);
21364            packages = mSettings.getVolumePackagesLPr(volumeUuid);
21365        }
21366
21367        for (PackageSetting ps : packages) {
21368            freezers.add(freezePackage(ps.name, "loadPrivatePackagesInner"));
21369            synchronized (mInstallLock) {
21370                final PackageParser.Package pkg;
21371                try {
21372                    pkg = scanPackageTracedLI(ps.codePath, parseFlags, SCAN_INITIAL, 0, null);
21373                    loaded.add(pkg.applicationInfo);
21374
21375                } catch (PackageManagerException e) {
21376                    Slog.w(TAG, "Failed to scan " + ps.codePath + ": " + e.getMessage());
21377                }
21378
21379                if (!Build.FINGERPRINT.equals(ver.fingerprint)) {
21380                    clearAppDataLIF(ps.pkg, UserHandle.USER_ALL,
21381                            StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE
21382                                    | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
21383                }
21384            }
21385        }
21386
21387        // Reconcile app data for all started/unlocked users
21388        final StorageManager sm = mContext.getSystemService(StorageManager.class);
21389        final UserManager um = mContext.getSystemService(UserManager.class);
21390        UserManagerInternal umInternal = getUserManagerInternal();
21391        for (UserInfo user : um.getUsers()) {
21392            final int flags;
21393            if (umInternal.isUserUnlockingOrUnlocked(user.id)) {
21394                flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
21395            } else if (umInternal.isUserRunning(user.id)) {
21396                flags = StorageManager.FLAG_STORAGE_DE;
21397            } else {
21398                continue;
21399            }
21400
21401            try {
21402                sm.prepareUserStorage(volumeUuid, user.id, user.serialNumber, flags);
21403                synchronized (mInstallLock) {
21404                    reconcileAppsDataLI(volumeUuid, user.id, flags, true /* migrateAppData */);
21405                }
21406            } catch (IllegalStateException e) {
21407                // Device was probably ejected, and we'll process that event momentarily
21408                Slog.w(TAG, "Failed to prepare storage: " + e);
21409            }
21410        }
21411
21412        synchronized (mPackages) {
21413            int updateFlags = UPDATE_PERMISSIONS_ALL;
21414            if (ver.sdkVersion != mSdkVersion) {
21415                logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to "
21416                        + mSdkVersion + "; regranting permissions for " + volumeUuid);
21417                updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL;
21418            }
21419            updatePermissionsLPw(null, null, volumeUuid, updateFlags);
21420
21421            // Yay, everything is now upgraded
21422            ver.forceCurrent();
21423
21424            mSettings.writeLPr();
21425        }
21426
21427        for (PackageFreezer freezer : freezers) {
21428            freezer.close();
21429        }
21430
21431        if (DEBUG_INSTALL) Slog.d(TAG, "Loaded packages " + loaded);
21432        sendResourcesChangedBroadcast(true, false, loaded, null);
21433    }
21434
21435    private void unloadPrivatePackages(final VolumeInfo vol) {
21436        mHandler.post(new Runnable() {
21437            @Override
21438            public void run() {
21439                unloadPrivatePackagesInner(vol);
21440            }
21441        });
21442    }
21443
21444    private void unloadPrivatePackagesInner(VolumeInfo vol) {
21445        final String volumeUuid = vol.fsUuid;
21446        if (TextUtils.isEmpty(volumeUuid)) {
21447            Slog.e(TAG, "Unloading internal storage is probably a mistake; ignoring");
21448            return;
21449        }
21450
21451        final ArrayList<ApplicationInfo> unloaded = new ArrayList<>();
21452        synchronized (mInstallLock) {
21453        synchronized (mPackages) {
21454            final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(volumeUuid);
21455            for (PackageSetting ps : packages) {
21456                if (ps.pkg == null) continue;
21457
21458                final ApplicationInfo info = ps.pkg.applicationInfo;
21459                final int deleteFlags = PackageManager.DELETE_KEEP_DATA;
21460                final PackageRemovedInfo outInfo = new PackageRemovedInfo();
21461
21462                try (PackageFreezer freezer = freezePackageForDelete(ps.name, deleteFlags,
21463                        "unloadPrivatePackagesInner")) {
21464                    if (deletePackageLIF(ps.name, null, false, null, deleteFlags, outInfo,
21465                            false, null)) {
21466                        unloaded.add(info);
21467                    } else {
21468                        Slog.w(TAG, "Failed to unload " + ps.codePath);
21469                    }
21470                }
21471
21472                // Try very hard to release any references to this package
21473                // so we don't risk the system server being killed due to
21474                // open FDs
21475                AttributeCache.instance().removePackage(ps.name);
21476            }
21477
21478            mSettings.writeLPr();
21479        }
21480        }
21481
21482        if (DEBUG_INSTALL) Slog.d(TAG, "Unloaded packages " + unloaded);
21483        sendResourcesChangedBroadcast(false, false, unloaded, null);
21484
21485        // Try very hard to release any references to this path so we don't risk
21486        // the system server being killed due to open FDs
21487        ResourcesManager.getInstance().invalidatePath(vol.getPath().getAbsolutePath());
21488
21489        for (int i = 0; i < 3; i++) {
21490            System.gc();
21491            System.runFinalization();
21492        }
21493    }
21494
21495    private void assertPackageKnown(String volumeUuid, String packageName)
21496            throws PackageManagerException {
21497        synchronized (mPackages) {
21498            // Normalize package name to handle renamed packages
21499            packageName = normalizePackageNameLPr(packageName);
21500
21501            final PackageSetting ps = mSettings.mPackages.get(packageName);
21502            if (ps == null) {
21503                throw new PackageManagerException("Package " + packageName + " is unknown");
21504            } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) {
21505                throw new PackageManagerException(
21506                        "Package " + packageName + " found on unknown volume " + volumeUuid
21507                                + "; expected volume " + ps.volumeUuid);
21508            }
21509        }
21510    }
21511
21512    private void assertPackageKnownAndInstalled(String volumeUuid, String packageName, int userId)
21513            throws PackageManagerException {
21514        synchronized (mPackages) {
21515            // Normalize package name to handle renamed packages
21516            packageName = normalizePackageNameLPr(packageName);
21517
21518            final PackageSetting ps = mSettings.mPackages.get(packageName);
21519            if (ps == null) {
21520                throw new PackageManagerException("Package " + packageName + " is unknown");
21521            } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) {
21522                throw new PackageManagerException(
21523                        "Package " + packageName + " found on unknown volume " + volumeUuid
21524                                + "; expected volume " + ps.volumeUuid);
21525            } else if (!ps.getInstalled(userId)) {
21526                throw new PackageManagerException(
21527                        "Package " + packageName + " not installed for user " + userId);
21528            }
21529        }
21530    }
21531
21532    private List<String> collectAbsoluteCodePaths() {
21533        synchronized (mPackages) {
21534            List<String> codePaths = new ArrayList<>();
21535            final int packageCount = mSettings.mPackages.size();
21536            for (int i = 0; i < packageCount; i++) {
21537                final PackageSetting ps = mSettings.mPackages.valueAt(i);
21538                codePaths.add(ps.codePath.getAbsolutePath());
21539            }
21540            return codePaths;
21541        }
21542    }
21543
21544    /**
21545     * Examine all apps present on given mounted volume, and destroy apps that
21546     * aren't expected, either due to uninstallation or reinstallation on
21547     * another volume.
21548     */
21549    private void reconcileApps(String volumeUuid) {
21550        List<String> absoluteCodePaths = collectAbsoluteCodePaths();
21551        List<File> filesToDelete = null;
21552
21553        final File[] files = FileUtils.listFilesOrEmpty(
21554                Environment.getDataAppDirectory(volumeUuid));
21555        for (File file : files) {
21556            final boolean isPackage = (isApkFile(file) || file.isDirectory())
21557                    && !PackageInstallerService.isStageName(file.getName());
21558            if (!isPackage) {
21559                // Ignore entries which are not packages
21560                continue;
21561            }
21562
21563            String absolutePath = file.getAbsolutePath();
21564
21565            boolean pathValid = false;
21566            final int absoluteCodePathCount = absoluteCodePaths.size();
21567            for (int i = 0; i < absoluteCodePathCount; i++) {
21568                String absoluteCodePath = absoluteCodePaths.get(i);
21569                if (absolutePath.startsWith(absoluteCodePath)) {
21570                    pathValid = true;
21571                    break;
21572                }
21573            }
21574
21575            if (!pathValid) {
21576                if (filesToDelete == null) {
21577                    filesToDelete = new ArrayList<>();
21578                }
21579                filesToDelete.add(file);
21580            }
21581        }
21582
21583        if (filesToDelete != null) {
21584            final int fileToDeleteCount = filesToDelete.size();
21585            for (int i = 0; i < fileToDeleteCount; i++) {
21586                File fileToDelete = filesToDelete.get(i);
21587                logCriticalInfo(Log.WARN, "Destroying orphaned" + fileToDelete);
21588                synchronized (mInstallLock) {
21589                    removeCodePathLI(fileToDelete);
21590                }
21591            }
21592        }
21593    }
21594
21595    /**
21596     * Reconcile all app data for the given user.
21597     * <p>
21598     * Verifies that directories exist and that ownership and labeling is
21599     * correct for all installed apps on all mounted volumes.
21600     */
21601    void reconcileAppsData(int userId, int flags, boolean migrateAppsData) {
21602        final StorageManager storage = mContext.getSystemService(StorageManager.class);
21603        for (VolumeInfo vol : storage.getWritablePrivateVolumes()) {
21604            final String volumeUuid = vol.getFsUuid();
21605            synchronized (mInstallLock) {
21606                reconcileAppsDataLI(volumeUuid, userId, flags, migrateAppsData);
21607            }
21608        }
21609    }
21610
21611    private void reconcileAppsDataLI(String volumeUuid, int userId, int flags,
21612            boolean migrateAppData) {
21613        reconcileAppsDataLI(volumeUuid, userId, flags, migrateAppData, false /* onlyCoreApps */);
21614    }
21615
21616    /**
21617     * Reconcile all app data on given mounted volume.
21618     * <p>
21619     * Destroys app data that isn't expected, either due to uninstallation or
21620     * reinstallation on another volume.
21621     * <p>
21622     * Verifies that directories exist and that ownership and labeling is
21623     * correct for all installed apps.
21624     * @returns list of skipped non-core packages (if {@code onlyCoreApps} is true)
21625     */
21626    private List<String> reconcileAppsDataLI(String volumeUuid, int userId, int flags,
21627            boolean migrateAppData, boolean onlyCoreApps) {
21628        Slog.v(TAG, "reconcileAppsData for " + volumeUuid + " u" + userId + " 0x"
21629                + Integer.toHexString(flags) + " migrateAppData=" + migrateAppData);
21630        List<String> result = onlyCoreApps ? new ArrayList<>() : null;
21631
21632        final File ceDir = Environment.getDataUserCeDirectory(volumeUuid, userId);
21633        final File deDir = Environment.getDataUserDeDirectory(volumeUuid, userId);
21634
21635        // First look for stale data that doesn't belong, and check if things
21636        // have changed since we did our last restorecon
21637        if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) {
21638            if (StorageManager.isFileEncryptedNativeOrEmulated()
21639                    && !StorageManager.isUserKeyUnlocked(userId)) {
21640                throw new RuntimeException(
21641                        "Yikes, someone asked us to reconcile CE storage while " + userId
21642                                + " was still locked; this would have caused massive data loss!");
21643            }
21644
21645            final File[] files = FileUtils.listFilesOrEmpty(ceDir);
21646            for (File file : files) {
21647                final String packageName = file.getName();
21648                try {
21649                    assertPackageKnownAndInstalled(volumeUuid, packageName, userId);
21650                } catch (PackageManagerException e) {
21651                    logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e);
21652                    try {
21653                        mInstaller.destroyAppData(volumeUuid, packageName, userId,
21654                                StorageManager.FLAG_STORAGE_CE, 0);
21655                    } catch (InstallerException e2) {
21656                        logCriticalInfo(Log.WARN, "Failed to destroy: " + e2);
21657                    }
21658                }
21659            }
21660        }
21661        if ((flags & StorageManager.FLAG_STORAGE_DE) != 0) {
21662            final File[] files = FileUtils.listFilesOrEmpty(deDir);
21663            for (File file : files) {
21664                final String packageName = file.getName();
21665                try {
21666                    assertPackageKnownAndInstalled(volumeUuid, packageName, userId);
21667                } catch (PackageManagerException e) {
21668                    logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e);
21669                    try {
21670                        mInstaller.destroyAppData(volumeUuid, packageName, userId,
21671                                StorageManager.FLAG_STORAGE_DE, 0);
21672                    } catch (InstallerException e2) {
21673                        logCriticalInfo(Log.WARN, "Failed to destroy: " + e2);
21674                    }
21675                }
21676            }
21677        }
21678
21679        // Ensure that data directories are ready to roll for all packages
21680        // installed for this volume and user
21681        final List<PackageSetting> packages;
21682        synchronized (mPackages) {
21683            packages = mSettings.getVolumePackagesLPr(volumeUuid);
21684        }
21685        int preparedCount = 0;
21686        for (PackageSetting ps : packages) {
21687            final String packageName = ps.name;
21688            if (ps.pkg == null) {
21689                Slog.w(TAG, "Odd, missing scanned package " + packageName);
21690                // TODO: might be due to legacy ASEC apps; we should circle back
21691                // and reconcile again once they're scanned
21692                continue;
21693            }
21694            // Skip non-core apps if requested
21695            if (onlyCoreApps && !ps.pkg.coreApp) {
21696                result.add(packageName);
21697                continue;
21698            }
21699
21700            if (ps.getInstalled(userId)) {
21701                prepareAppDataAndMigrateLIF(ps.pkg, userId, flags, migrateAppData);
21702                preparedCount++;
21703            }
21704        }
21705
21706        Slog.v(TAG, "reconcileAppsData finished " + preparedCount + " packages");
21707        return result;
21708    }
21709
21710    /**
21711     * Prepare app data for the given app just after it was installed or
21712     * upgraded. This method carefully only touches users that it's installed
21713     * for, and it forces a restorecon to handle any seinfo changes.
21714     * <p>
21715     * Verifies that directories exist and that ownership and labeling is
21716     * correct for all installed apps. If there is an ownership mismatch, it
21717     * will try recovering system apps by wiping data; third-party app data is
21718     * left intact.
21719     * <p>
21720     * <em>Note: To avoid a deadlock, do not call this method with {@code mPackages} lock held</em>
21721     */
21722    private void prepareAppDataAfterInstallLIF(PackageParser.Package pkg) {
21723        final PackageSetting ps;
21724        synchronized (mPackages) {
21725            ps = mSettings.mPackages.get(pkg.packageName);
21726            mSettings.writeKernelMappingLPr(ps);
21727        }
21728
21729        final UserManager um = mContext.getSystemService(UserManager.class);
21730        UserManagerInternal umInternal = getUserManagerInternal();
21731        for (UserInfo user : um.getUsers()) {
21732            final int flags;
21733            if (umInternal.isUserUnlockingOrUnlocked(user.id)) {
21734                flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
21735            } else if (umInternal.isUserRunning(user.id)) {
21736                flags = StorageManager.FLAG_STORAGE_DE;
21737            } else {
21738                continue;
21739            }
21740
21741            if (ps.getInstalled(user.id)) {
21742                // TODO: when user data is locked, mark that we're still dirty
21743                prepareAppDataLIF(pkg, user.id, flags);
21744            }
21745        }
21746    }
21747
21748    /**
21749     * Prepare app data for the given app.
21750     * <p>
21751     * Verifies that directories exist and that ownership and labeling is
21752     * correct for all installed apps. If there is an ownership mismatch, this
21753     * will try recovering system apps by wiping data; third-party app data is
21754     * left intact.
21755     */
21756    private void prepareAppDataLIF(PackageParser.Package pkg, int userId, int flags) {
21757        if (pkg == null) {
21758            Slog.wtf(TAG, "Package was null!", new Throwable());
21759            return;
21760        }
21761        prepareAppDataLeafLIF(pkg, userId, flags);
21762        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
21763        for (int i = 0; i < childCount; i++) {
21764            prepareAppDataLeafLIF(pkg.childPackages.get(i), userId, flags);
21765        }
21766    }
21767
21768    private void prepareAppDataAndMigrateLIF(PackageParser.Package pkg, int userId, int flags,
21769            boolean maybeMigrateAppData) {
21770        prepareAppDataLIF(pkg, userId, flags);
21771
21772        if (maybeMigrateAppData && maybeMigrateAppDataLIF(pkg, userId)) {
21773            // We may have just shuffled around app data directories, so
21774            // prepare them one more time
21775            prepareAppDataLIF(pkg, userId, flags);
21776        }
21777    }
21778
21779    private void prepareAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) {
21780        if (DEBUG_APP_DATA) {
21781            Slog.v(TAG, "prepareAppData for " + pkg.packageName + " u" + userId + " 0x"
21782                    + Integer.toHexString(flags));
21783        }
21784
21785        final String volumeUuid = pkg.volumeUuid;
21786        final String packageName = pkg.packageName;
21787        final ApplicationInfo app = pkg.applicationInfo;
21788        final int appId = UserHandle.getAppId(app.uid);
21789
21790        Preconditions.checkNotNull(app.seInfo);
21791
21792        long ceDataInode = -1;
21793        try {
21794            ceDataInode = mInstaller.createAppData(volumeUuid, packageName, userId, flags,
21795                    appId, app.seInfo, app.targetSdkVersion);
21796        } catch (InstallerException e) {
21797            if (app.isSystemApp()) {
21798                logCriticalInfo(Log.ERROR, "Failed to create app data for " + packageName
21799                        + ", but trying to recover: " + e);
21800                destroyAppDataLeafLIF(pkg, userId, flags);
21801                try {
21802                    ceDataInode = mInstaller.createAppData(volumeUuid, packageName, userId, flags,
21803                            appId, app.seInfo, app.targetSdkVersion);
21804                    logCriticalInfo(Log.DEBUG, "Recovery succeeded!");
21805                } catch (InstallerException e2) {
21806                    logCriticalInfo(Log.DEBUG, "Recovery failed!");
21807                }
21808            } else {
21809                Slog.e(TAG, "Failed to create app data for " + packageName + ": " + e);
21810            }
21811        }
21812
21813        if ((flags & StorageManager.FLAG_STORAGE_CE) != 0 && ceDataInode != -1) {
21814            // TODO: mark this structure as dirty so we persist it!
21815            synchronized (mPackages) {
21816                final PackageSetting ps = mSettings.mPackages.get(packageName);
21817                if (ps != null) {
21818                    ps.setCeDataInode(ceDataInode, userId);
21819                }
21820            }
21821        }
21822
21823        prepareAppDataContentsLeafLIF(pkg, userId, flags);
21824    }
21825
21826    private void prepareAppDataContentsLIF(PackageParser.Package pkg, int userId, int flags) {
21827        if (pkg == null) {
21828            Slog.wtf(TAG, "Package was null!", new Throwable());
21829            return;
21830        }
21831        prepareAppDataContentsLeafLIF(pkg, userId, flags);
21832        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
21833        for (int i = 0; i < childCount; i++) {
21834            prepareAppDataContentsLeafLIF(pkg.childPackages.get(i), userId, flags);
21835        }
21836    }
21837
21838    private void prepareAppDataContentsLeafLIF(PackageParser.Package pkg, int userId, int flags) {
21839        final String volumeUuid = pkg.volumeUuid;
21840        final String packageName = pkg.packageName;
21841        final ApplicationInfo app = pkg.applicationInfo;
21842
21843        if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) {
21844            // Create a native library symlink only if we have native libraries
21845            // and if the native libraries are 32 bit libraries. We do not provide
21846            // this symlink for 64 bit libraries.
21847            if (app.primaryCpuAbi != null && !VMRuntime.is64BitAbi(app.primaryCpuAbi)) {
21848                final String nativeLibPath = app.nativeLibraryDir;
21849                try {
21850                    mInstaller.linkNativeLibraryDirectory(volumeUuid, packageName,
21851                            nativeLibPath, userId);
21852                } catch (InstallerException e) {
21853                    Slog.e(TAG, "Failed to link native for " + packageName + ": " + e);
21854                }
21855            }
21856        }
21857    }
21858
21859    /**
21860     * For system apps on non-FBE devices, this method migrates any existing
21861     * CE/DE data to match the {@code defaultToDeviceProtectedStorage} flag
21862     * requested by the app.
21863     */
21864    private boolean maybeMigrateAppDataLIF(PackageParser.Package pkg, int userId) {
21865        if (pkg.isSystemApp() && !StorageManager.isFileEncryptedNativeOrEmulated()
21866                && PackageManager.APPLY_DEFAULT_TO_DEVICE_PROTECTED_STORAGE) {
21867            final int storageTarget = pkg.applicationInfo.isDefaultToDeviceProtectedStorage()
21868                    ? StorageManager.FLAG_STORAGE_DE : StorageManager.FLAG_STORAGE_CE;
21869            try {
21870                mInstaller.migrateAppData(pkg.volumeUuid, pkg.packageName, userId,
21871                        storageTarget);
21872            } catch (InstallerException e) {
21873                logCriticalInfo(Log.WARN,
21874                        "Failed to migrate " + pkg.packageName + ": " + e.getMessage());
21875            }
21876            return true;
21877        } else {
21878            return false;
21879        }
21880    }
21881
21882    public PackageFreezer freezePackage(String packageName, String killReason) {
21883        return freezePackage(packageName, UserHandle.USER_ALL, killReason);
21884    }
21885
21886    public PackageFreezer freezePackage(String packageName, int userId, String killReason) {
21887        return new PackageFreezer(packageName, userId, killReason);
21888    }
21889
21890    public PackageFreezer freezePackageForInstall(String packageName, int installFlags,
21891            String killReason) {
21892        return freezePackageForInstall(packageName, UserHandle.USER_ALL, installFlags, killReason);
21893    }
21894
21895    public PackageFreezer freezePackageForInstall(String packageName, int userId, int installFlags,
21896            String killReason) {
21897        if ((installFlags & PackageManager.INSTALL_DONT_KILL_APP) != 0) {
21898            return new PackageFreezer();
21899        } else {
21900            return freezePackage(packageName, userId, killReason);
21901        }
21902    }
21903
21904    public PackageFreezer freezePackageForDelete(String packageName, int deleteFlags,
21905            String killReason) {
21906        return freezePackageForDelete(packageName, UserHandle.USER_ALL, deleteFlags, killReason);
21907    }
21908
21909    public PackageFreezer freezePackageForDelete(String packageName, int userId, int deleteFlags,
21910            String killReason) {
21911        if ((deleteFlags & PackageManager.DELETE_DONT_KILL_APP) != 0) {
21912            return new PackageFreezer();
21913        } else {
21914            return freezePackage(packageName, userId, killReason);
21915        }
21916    }
21917
21918    /**
21919     * Class that freezes and kills the given package upon creation, and
21920     * unfreezes it upon closing. This is typically used when doing surgery on
21921     * app code/data to prevent the app from running while you're working.
21922     */
21923    private class PackageFreezer implements AutoCloseable {
21924        private final String mPackageName;
21925        private final PackageFreezer[] mChildren;
21926
21927        private final boolean mWeFroze;
21928
21929        private final AtomicBoolean mClosed = new AtomicBoolean();
21930        private final CloseGuard mCloseGuard = CloseGuard.get();
21931
21932        /**
21933         * Create and return a stub freezer that doesn't actually do anything,
21934         * typically used when someone requested
21935         * {@link PackageManager#INSTALL_DONT_KILL_APP} or
21936         * {@link PackageManager#DELETE_DONT_KILL_APP}.
21937         */
21938        public PackageFreezer() {
21939            mPackageName = null;
21940            mChildren = null;
21941            mWeFroze = false;
21942            mCloseGuard.open("close");
21943        }
21944
21945        public PackageFreezer(String packageName, int userId, String killReason) {
21946            synchronized (mPackages) {
21947                mPackageName = packageName;
21948                mWeFroze = mFrozenPackages.add(mPackageName);
21949
21950                final PackageSetting ps = mSettings.mPackages.get(mPackageName);
21951                if (ps != null) {
21952                    killApplication(ps.name, ps.appId, userId, killReason);
21953                }
21954
21955                final PackageParser.Package p = mPackages.get(packageName);
21956                if (p != null && p.childPackages != null) {
21957                    final int N = p.childPackages.size();
21958                    mChildren = new PackageFreezer[N];
21959                    for (int i = 0; i < N; i++) {
21960                        mChildren[i] = new PackageFreezer(p.childPackages.get(i).packageName,
21961                                userId, killReason);
21962                    }
21963                } else {
21964                    mChildren = null;
21965                }
21966            }
21967            mCloseGuard.open("close");
21968        }
21969
21970        @Override
21971        protected void finalize() throws Throwable {
21972            try {
21973                mCloseGuard.warnIfOpen();
21974                close();
21975            } finally {
21976                super.finalize();
21977            }
21978        }
21979
21980        @Override
21981        public void close() {
21982            mCloseGuard.close();
21983            if (mClosed.compareAndSet(false, true)) {
21984                synchronized (mPackages) {
21985                    if (mWeFroze) {
21986                        mFrozenPackages.remove(mPackageName);
21987                    }
21988
21989                    if (mChildren != null) {
21990                        for (PackageFreezer freezer : mChildren) {
21991                            freezer.close();
21992                        }
21993                    }
21994                }
21995            }
21996        }
21997    }
21998
21999    /**
22000     * Verify that given package is currently frozen.
22001     */
22002    private void checkPackageFrozen(String packageName) {
22003        synchronized (mPackages) {
22004            if (!mFrozenPackages.contains(packageName)) {
22005                Slog.wtf(TAG, "Expected " + packageName + " to be frozen!", new Throwable());
22006            }
22007        }
22008    }
22009
22010    @Override
22011    public int movePackage(final String packageName, final String volumeUuid) {
22012        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null);
22013
22014        final UserHandle user = new UserHandle(UserHandle.getCallingUserId());
22015        final int moveId = mNextMoveId.getAndIncrement();
22016        mHandler.post(new Runnable() {
22017            @Override
22018            public void run() {
22019                try {
22020                    movePackageInternal(packageName, volumeUuid, moveId, user);
22021                } catch (PackageManagerException e) {
22022                    Slog.w(TAG, "Failed to move " + packageName, e);
22023                    mMoveCallbacks.notifyStatusChanged(moveId,
22024                            PackageManager.MOVE_FAILED_INTERNAL_ERROR);
22025                }
22026            }
22027        });
22028        return moveId;
22029    }
22030
22031    private void movePackageInternal(final String packageName, final String volumeUuid,
22032            final int moveId, UserHandle user) throws PackageManagerException {
22033        final StorageManager storage = mContext.getSystemService(StorageManager.class);
22034        final PackageManager pm = mContext.getPackageManager();
22035
22036        final boolean currentAsec;
22037        final String currentVolumeUuid;
22038        final File codeFile;
22039        final String installerPackageName;
22040        final String packageAbiOverride;
22041        final int appId;
22042        final String seinfo;
22043        final String label;
22044        final int targetSdkVersion;
22045        final PackageFreezer freezer;
22046        final int[] installedUserIds;
22047
22048        // reader
22049        synchronized (mPackages) {
22050            final PackageParser.Package pkg = mPackages.get(packageName);
22051            final PackageSetting ps = mSettings.mPackages.get(packageName);
22052            if (pkg == null || ps == null) {
22053                throw new PackageManagerException(MOVE_FAILED_DOESNT_EXIST, "Missing package");
22054            }
22055
22056            if (pkg.applicationInfo.isSystemApp()) {
22057                throw new PackageManagerException(MOVE_FAILED_SYSTEM_PACKAGE,
22058                        "Cannot move system application");
22059            }
22060
22061            final boolean isInternalStorage = VolumeInfo.ID_PRIVATE_INTERNAL.equals(volumeUuid);
22062            final boolean allow3rdPartyOnInternal = mContext.getResources().getBoolean(
22063                    com.android.internal.R.bool.config_allow3rdPartyAppOnInternal);
22064            if (isInternalStorage && !allow3rdPartyOnInternal) {
22065                throw new PackageManagerException(MOVE_FAILED_3RD_PARTY_NOT_ALLOWED_ON_INTERNAL,
22066                        "3rd party apps are not allowed on internal storage");
22067            }
22068
22069            if (pkg.applicationInfo.isExternalAsec()) {
22070                currentAsec = true;
22071                currentVolumeUuid = StorageManager.UUID_PRIMARY_PHYSICAL;
22072            } else if (pkg.applicationInfo.isForwardLocked()) {
22073                currentAsec = true;
22074                currentVolumeUuid = "forward_locked";
22075            } else {
22076                currentAsec = false;
22077                currentVolumeUuid = ps.volumeUuid;
22078
22079                final File probe = new File(pkg.codePath);
22080                final File probeOat = new File(probe, "oat");
22081                if (!probe.isDirectory() || !probeOat.isDirectory()) {
22082                    throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
22083                            "Move only supported for modern cluster style installs");
22084                }
22085            }
22086
22087            if (Objects.equals(currentVolumeUuid, volumeUuid)) {
22088                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
22089                        "Package already moved to " + volumeUuid);
22090            }
22091            if (pkg.applicationInfo.isInternal() && isPackageDeviceAdminOnAnyUser(packageName)) {
22092                throw new PackageManagerException(MOVE_FAILED_DEVICE_ADMIN,
22093                        "Device admin cannot be moved");
22094            }
22095
22096            if (mFrozenPackages.contains(packageName)) {
22097                throw new PackageManagerException(MOVE_FAILED_OPERATION_PENDING,
22098                        "Failed to move already frozen package");
22099            }
22100
22101            codeFile = new File(pkg.codePath);
22102            installerPackageName = ps.installerPackageName;
22103            packageAbiOverride = ps.cpuAbiOverrideString;
22104            appId = UserHandle.getAppId(pkg.applicationInfo.uid);
22105            seinfo = pkg.applicationInfo.seInfo;
22106            label = String.valueOf(pm.getApplicationLabel(pkg.applicationInfo));
22107            targetSdkVersion = pkg.applicationInfo.targetSdkVersion;
22108            freezer = freezePackage(packageName, "movePackageInternal");
22109            installedUserIds = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
22110        }
22111
22112        final Bundle extras = new Bundle();
22113        extras.putString(Intent.EXTRA_PACKAGE_NAME, packageName);
22114        extras.putString(Intent.EXTRA_TITLE, label);
22115        mMoveCallbacks.notifyCreated(moveId, extras);
22116
22117        int installFlags;
22118        final boolean moveCompleteApp;
22119        final File measurePath;
22120
22121        if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, volumeUuid)) {
22122            installFlags = INSTALL_INTERNAL;
22123            moveCompleteApp = !currentAsec;
22124            measurePath = Environment.getDataAppDirectory(volumeUuid);
22125        } else if (Objects.equals(StorageManager.UUID_PRIMARY_PHYSICAL, volumeUuid)) {
22126            installFlags = INSTALL_EXTERNAL;
22127            moveCompleteApp = false;
22128            measurePath = storage.getPrimaryPhysicalVolume().getPath();
22129        } else {
22130            final VolumeInfo volume = storage.findVolumeByUuid(volumeUuid);
22131            if (volume == null || volume.getType() != VolumeInfo.TYPE_PRIVATE
22132                    || !volume.isMountedWritable()) {
22133                freezer.close();
22134                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
22135                        "Move location not mounted private volume");
22136            }
22137
22138            Preconditions.checkState(!currentAsec);
22139
22140            installFlags = INSTALL_INTERNAL;
22141            moveCompleteApp = true;
22142            measurePath = Environment.getDataAppDirectory(volumeUuid);
22143        }
22144
22145        final PackageStats stats = new PackageStats(null, -1);
22146        synchronized (mInstaller) {
22147            for (int userId : installedUserIds) {
22148                if (!getPackageSizeInfoLI(packageName, userId, stats)) {
22149                    freezer.close();
22150                    throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
22151                            "Failed to measure package size");
22152                }
22153            }
22154        }
22155
22156        if (DEBUG_INSTALL) Slog.d(TAG, "Measured code size " + stats.codeSize + ", data size "
22157                + stats.dataSize);
22158
22159        final long startFreeBytes = measurePath.getFreeSpace();
22160        final long sizeBytes;
22161        if (moveCompleteApp) {
22162            sizeBytes = stats.codeSize + stats.dataSize;
22163        } else {
22164            sizeBytes = stats.codeSize;
22165        }
22166
22167        if (sizeBytes > storage.getStorageBytesUntilLow(measurePath)) {
22168            freezer.close();
22169            throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
22170                    "Not enough free space to move");
22171        }
22172
22173        mMoveCallbacks.notifyStatusChanged(moveId, 10);
22174
22175        final CountDownLatch installedLatch = new CountDownLatch(1);
22176        final IPackageInstallObserver2 installObserver = new IPackageInstallObserver2.Stub() {
22177            @Override
22178            public void onUserActionRequired(Intent intent) throws RemoteException {
22179                throw new IllegalStateException();
22180            }
22181
22182            @Override
22183            public void onPackageInstalled(String basePackageName, int returnCode, String msg,
22184                    Bundle extras) throws RemoteException {
22185                if (DEBUG_INSTALL) Slog.d(TAG, "Install result for move: "
22186                        + PackageManager.installStatusToString(returnCode, msg));
22187
22188                installedLatch.countDown();
22189                freezer.close();
22190
22191                final int status = PackageManager.installStatusToPublicStatus(returnCode);
22192                switch (status) {
22193                    case PackageInstaller.STATUS_SUCCESS:
22194                        mMoveCallbacks.notifyStatusChanged(moveId,
22195                                PackageManager.MOVE_SUCCEEDED);
22196                        break;
22197                    case PackageInstaller.STATUS_FAILURE_STORAGE:
22198                        mMoveCallbacks.notifyStatusChanged(moveId,
22199                                PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE);
22200                        break;
22201                    default:
22202                        mMoveCallbacks.notifyStatusChanged(moveId,
22203                                PackageManager.MOVE_FAILED_INTERNAL_ERROR);
22204                        break;
22205                }
22206            }
22207        };
22208
22209        final MoveInfo move;
22210        if (moveCompleteApp) {
22211            // Kick off a thread to report progress estimates
22212            new Thread() {
22213                @Override
22214                public void run() {
22215                    while (true) {
22216                        try {
22217                            if (installedLatch.await(1, TimeUnit.SECONDS)) {
22218                                break;
22219                            }
22220                        } catch (InterruptedException ignored) {
22221                        }
22222
22223                        final long deltaFreeBytes = startFreeBytes - measurePath.getFreeSpace();
22224                        final int progress = 10 + (int) MathUtils.constrain(
22225                                ((deltaFreeBytes * 80) / sizeBytes), 0, 80);
22226                        mMoveCallbacks.notifyStatusChanged(moveId, progress);
22227                    }
22228                }
22229            }.start();
22230
22231            final String dataAppName = codeFile.getName();
22232            move = new MoveInfo(moveId, currentVolumeUuid, volumeUuid, packageName,
22233                    dataAppName, appId, seinfo, targetSdkVersion);
22234        } else {
22235            move = null;
22236        }
22237
22238        installFlags |= PackageManager.INSTALL_REPLACE_EXISTING;
22239
22240        final Message msg = mHandler.obtainMessage(INIT_COPY);
22241        final OriginInfo origin = OriginInfo.fromExistingFile(codeFile);
22242        final InstallParams params = new InstallParams(origin, move, installObserver, installFlags,
22243                installerPackageName, volumeUuid, null /*verificationInfo*/, user,
22244                packageAbiOverride, null /*grantedPermissions*/, null /*certificates*/,
22245                PackageManager.INSTALL_REASON_UNKNOWN);
22246        params.setTraceMethod("movePackage").setTraceCookie(System.identityHashCode(params));
22247        msg.obj = params;
22248
22249        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "movePackage",
22250                System.identityHashCode(msg.obj));
22251        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
22252                System.identityHashCode(msg.obj));
22253
22254        mHandler.sendMessage(msg);
22255    }
22256
22257    @Override
22258    public int movePrimaryStorage(String volumeUuid) throws RemoteException {
22259        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null);
22260
22261        final int realMoveId = mNextMoveId.getAndIncrement();
22262        final Bundle extras = new Bundle();
22263        extras.putString(VolumeRecord.EXTRA_FS_UUID, volumeUuid);
22264        mMoveCallbacks.notifyCreated(realMoveId, extras);
22265
22266        final IPackageMoveObserver callback = new IPackageMoveObserver.Stub() {
22267            @Override
22268            public void onCreated(int moveId, Bundle extras) {
22269                // Ignored
22270            }
22271
22272            @Override
22273            public void onStatusChanged(int moveId, int status, long estMillis) {
22274                mMoveCallbacks.notifyStatusChanged(realMoveId, status, estMillis);
22275            }
22276        };
22277
22278        final StorageManager storage = mContext.getSystemService(StorageManager.class);
22279        storage.setPrimaryStorageUuid(volumeUuid, callback);
22280        return realMoveId;
22281    }
22282
22283    @Override
22284    public int getMoveStatus(int moveId) {
22285        mContext.enforceCallingOrSelfPermission(
22286                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
22287        return mMoveCallbacks.mLastStatus.get(moveId);
22288    }
22289
22290    @Override
22291    public void registerMoveCallback(IPackageMoveObserver callback) {
22292        mContext.enforceCallingOrSelfPermission(
22293                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
22294        mMoveCallbacks.register(callback);
22295    }
22296
22297    @Override
22298    public void unregisterMoveCallback(IPackageMoveObserver callback) {
22299        mContext.enforceCallingOrSelfPermission(
22300                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
22301        mMoveCallbacks.unregister(callback);
22302    }
22303
22304    @Override
22305    public boolean setInstallLocation(int loc) {
22306        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WRITE_SECURE_SETTINGS,
22307                null);
22308        if (getInstallLocation() == loc) {
22309            return true;
22310        }
22311        if (loc == PackageHelper.APP_INSTALL_AUTO || loc == PackageHelper.APP_INSTALL_INTERNAL
22312                || loc == PackageHelper.APP_INSTALL_EXTERNAL) {
22313            android.provider.Settings.Global.putInt(mContext.getContentResolver(),
22314                    android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, loc);
22315            return true;
22316        }
22317        return false;
22318   }
22319
22320    @Override
22321    public int getInstallLocation() {
22322        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
22323                android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION,
22324                PackageHelper.APP_INSTALL_AUTO);
22325    }
22326
22327    /** Called by UserManagerService */
22328    void cleanUpUser(UserManagerService userManager, int userHandle) {
22329        synchronized (mPackages) {
22330            mDirtyUsers.remove(userHandle);
22331            mUserNeedsBadging.delete(userHandle);
22332            mSettings.removeUserLPw(userHandle);
22333            mPendingBroadcasts.remove(userHandle);
22334            mInstantAppRegistry.onUserRemovedLPw(userHandle);
22335            removeUnusedPackagesLPw(userManager, userHandle);
22336        }
22337    }
22338
22339    /**
22340     * We're removing userHandle and would like to remove any downloaded packages
22341     * that are no longer in use by any other user.
22342     * @param userHandle the user being removed
22343     */
22344    private void removeUnusedPackagesLPw(UserManagerService userManager, final int userHandle) {
22345        final boolean DEBUG_CLEAN_APKS = false;
22346        int [] users = userManager.getUserIds();
22347        Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator();
22348        while (psit.hasNext()) {
22349            PackageSetting ps = psit.next();
22350            if (ps.pkg == null) {
22351                continue;
22352            }
22353            final String packageName = ps.pkg.packageName;
22354            // Skip over if system app
22355            if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0) {
22356                continue;
22357            }
22358            if (DEBUG_CLEAN_APKS) {
22359                Slog.i(TAG, "Checking package " + packageName);
22360            }
22361            boolean keep = shouldKeepUninstalledPackageLPr(packageName);
22362            if (keep) {
22363                if (DEBUG_CLEAN_APKS) {
22364                    Slog.i(TAG, "  Keeping package " + packageName + " - requested by DO");
22365                }
22366            } else {
22367                for (int i = 0; i < users.length; i++) {
22368                    if (users[i] != userHandle && ps.getInstalled(users[i])) {
22369                        keep = true;
22370                        if (DEBUG_CLEAN_APKS) {
22371                            Slog.i(TAG, "  Keeping package " + packageName + " for user "
22372                                    + users[i]);
22373                        }
22374                        break;
22375                    }
22376                }
22377            }
22378            if (!keep) {
22379                if (DEBUG_CLEAN_APKS) {
22380                    Slog.i(TAG, "  Removing package " + packageName);
22381                }
22382                mHandler.post(new Runnable() {
22383                    public void run() {
22384                        deletePackageX(packageName, PackageManager.VERSION_CODE_HIGHEST,
22385                                userHandle, 0);
22386                    } //end run
22387                });
22388            }
22389        }
22390    }
22391
22392    /** Called by UserManagerService */
22393    void createNewUser(int userId, String[] disallowedPackages) {
22394        synchronized (mInstallLock) {
22395            mSettings.createNewUserLI(this, mInstaller, userId, disallowedPackages);
22396        }
22397        synchronized (mPackages) {
22398            scheduleWritePackageRestrictionsLocked(userId);
22399            scheduleWritePackageListLocked(userId);
22400            applyFactoryDefaultBrowserLPw(userId);
22401            primeDomainVerificationsLPw(userId);
22402        }
22403    }
22404
22405    void onNewUserCreated(final int userId) {
22406        mDefaultPermissionPolicy.grantDefaultPermissions(userId);
22407        // If permission review for legacy apps is required, we represent
22408        // dagerous permissions for such apps as always granted runtime
22409        // permissions to keep per user flag state whether review is needed.
22410        // Hence, if a new user is added we have to propagate dangerous
22411        // permission grants for these legacy apps.
22412        if (mPermissionReviewRequired) {
22413            updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL
22414                    | UPDATE_PERMISSIONS_REPLACE_ALL);
22415        }
22416    }
22417
22418    @Override
22419    public VerifierDeviceIdentity getVerifierDeviceIdentity() throws RemoteException {
22420        mContext.enforceCallingOrSelfPermission(
22421                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
22422                "Only package verification agents can read the verifier device identity");
22423
22424        synchronized (mPackages) {
22425            return mSettings.getVerifierDeviceIdentityLPw();
22426        }
22427    }
22428
22429    @Override
22430    public void setPermissionEnforced(String permission, boolean enforced) {
22431        // TODO: Now that we no longer change GID for storage, this should to away.
22432        mContext.enforceCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS,
22433                "setPermissionEnforced");
22434        if (READ_EXTERNAL_STORAGE.equals(permission)) {
22435            synchronized (mPackages) {
22436                if (mSettings.mReadExternalStorageEnforced == null
22437                        || mSettings.mReadExternalStorageEnforced != enforced) {
22438                    mSettings.mReadExternalStorageEnforced = enforced;
22439                    mSettings.writeLPr();
22440                }
22441            }
22442            // kill any non-foreground processes so we restart them and
22443            // grant/revoke the GID.
22444            final IActivityManager am = ActivityManager.getService();
22445            if (am != null) {
22446                final long token = Binder.clearCallingIdentity();
22447                try {
22448                    am.killProcessesBelowForeground("setPermissionEnforcement");
22449                } catch (RemoteException e) {
22450                } finally {
22451                    Binder.restoreCallingIdentity(token);
22452                }
22453            }
22454        } else {
22455            throw new IllegalArgumentException("No selective enforcement for " + permission);
22456        }
22457    }
22458
22459    @Override
22460    @Deprecated
22461    public boolean isPermissionEnforced(String permission) {
22462        return true;
22463    }
22464
22465    @Override
22466    public boolean isStorageLow() {
22467        final long token = Binder.clearCallingIdentity();
22468        try {
22469            final DeviceStorageMonitorInternal
22470                    dsm = LocalServices.getService(DeviceStorageMonitorInternal.class);
22471            if (dsm != null) {
22472                return dsm.isMemoryLow();
22473            } else {
22474                return false;
22475            }
22476        } finally {
22477            Binder.restoreCallingIdentity(token);
22478        }
22479    }
22480
22481    @Override
22482    public IPackageInstaller getPackageInstaller() {
22483        return mInstallerService;
22484    }
22485
22486    private boolean userNeedsBadging(int userId) {
22487        int index = mUserNeedsBadging.indexOfKey(userId);
22488        if (index < 0) {
22489            final UserInfo userInfo;
22490            final long token = Binder.clearCallingIdentity();
22491            try {
22492                userInfo = sUserManager.getUserInfo(userId);
22493            } finally {
22494                Binder.restoreCallingIdentity(token);
22495            }
22496            final boolean b;
22497            if (userInfo != null && userInfo.isManagedProfile()) {
22498                b = true;
22499            } else {
22500                b = false;
22501            }
22502            mUserNeedsBadging.put(userId, b);
22503            return b;
22504        }
22505        return mUserNeedsBadging.valueAt(index);
22506    }
22507
22508    @Override
22509    public KeySet getKeySetByAlias(String packageName, String alias) {
22510        if (packageName == null || alias == null) {
22511            return null;
22512        }
22513        synchronized(mPackages) {
22514            final PackageParser.Package pkg = mPackages.get(packageName);
22515            if (pkg == null) {
22516                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
22517                throw new IllegalArgumentException("Unknown package: " + packageName);
22518            }
22519            KeySetManagerService ksms = mSettings.mKeySetManagerService;
22520            return new KeySet(ksms.getKeySetByAliasAndPackageNameLPr(packageName, alias));
22521        }
22522    }
22523
22524    @Override
22525    public KeySet getSigningKeySet(String packageName) {
22526        if (packageName == null) {
22527            return null;
22528        }
22529        synchronized(mPackages) {
22530            final PackageParser.Package pkg = mPackages.get(packageName);
22531            if (pkg == null) {
22532                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
22533                throw new IllegalArgumentException("Unknown package: " + packageName);
22534            }
22535            if (pkg.applicationInfo.uid != Binder.getCallingUid()
22536                    && Process.SYSTEM_UID != Binder.getCallingUid()) {
22537                throw new SecurityException("May not access signing KeySet of other apps.");
22538            }
22539            KeySetManagerService ksms = mSettings.mKeySetManagerService;
22540            return new KeySet(ksms.getSigningKeySetByPackageNameLPr(packageName));
22541        }
22542    }
22543
22544    @Override
22545    public boolean isPackageSignedByKeySet(String packageName, KeySet ks) {
22546        if (packageName == null || ks == null) {
22547            return false;
22548        }
22549        synchronized(mPackages) {
22550            final PackageParser.Package pkg = mPackages.get(packageName);
22551            if (pkg == null) {
22552                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
22553                throw new IllegalArgumentException("Unknown package: " + packageName);
22554            }
22555            IBinder ksh = ks.getToken();
22556            if (ksh instanceof KeySetHandle) {
22557                KeySetManagerService ksms = mSettings.mKeySetManagerService;
22558                return ksms.packageIsSignedByLPr(packageName, (KeySetHandle) ksh);
22559            }
22560            return false;
22561        }
22562    }
22563
22564    @Override
22565    public boolean isPackageSignedByKeySetExactly(String packageName, KeySet ks) {
22566        if (packageName == null || ks == null) {
22567            return false;
22568        }
22569        synchronized(mPackages) {
22570            final PackageParser.Package pkg = mPackages.get(packageName);
22571            if (pkg == null) {
22572                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
22573                throw new IllegalArgumentException("Unknown package: " + packageName);
22574            }
22575            IBinder ksh = ks.getToken();
22576            if (ksh instanceof KeySetHandle) {
22577                KeySetManagerService ksms = mSettings.mKeySetManagerService;
22578                return ksms.packageIsSignedByExactlyLPr(packageName, (KeySetHandle) ksh);
22579            }
22580            return false;
22581        }
22582    }
22583
22584    private void deletePackageIfUnusedLPr(final String packageName) {
22585        PackageSetting ps = mSettings.mPackages.get(packageName);
22586        if (ps == null) {
22587            return;
22588        }
22589        if (!ps.isAnyInstalled(sUserManager.getUserIds())) {
22590            // TODO Implement atomic delete if package is unused
22591            // It is currently possible that the package will be deleted even if it is installed
22592            // after this method returns.
22593            mHandler.post(new Runnable() {
22594                public void run() {
22595                    deletePackageX(packageName, PackageManager.VERSION_CODE_HIGHEST,
22596                            0, PackageManager.DELETE_ALL_USERS);
22597                }
22598            });
22599        }
22600    }
22601
22602    /**
22603     * Check and throw if the given before/after packages would be considered a
22604     * downgrade.
22605     */
22606    private static void checkDowngrade(PackageParser.Package before, PackageInfoLite after)
22607            throws PackageManagerException {
22608        if (after.versionCode < before.mVersionCode) {
22609            throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
22610                    "Update version code " + after.versionCode + " is older than current "
22611                    + before.mVersionCode);
22612        } else if (after.versionCode == before.mVersionCode) {
22613            if (after.baseRevisionCode < before.baseRevisionCode) {
22614                throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
22615                        "Update base revision code " + after.baseRevisionCode
22616                        + " is older than current " + before.baseRevisionCode);
22617            }
22618
22619            if (!ArrayUtils.isEmpty(after.splitNames)) {
22620                for (int i = 0; i < after.splitNames.length; i++) {
22621                    final String splitName = after.splitNames[i];
22622                    final int j = ArrayUtils.indexOf(before.splitNames, splitName);
22623                    if (j != -1) {
22624                        if (after.splitRevisionCodes[i] < before.splitRevisionCodes[j]) {
22625                            throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
22626                                    "Update split " + splitName + " revision code "
22627                                    + after.splitRevisionCodes[i] + " is older than current "
22628                                    + before.splitRevisionCodes[j]);
22629                        }
22630                    }
22631                }
22632            }
22633        }
22634    }
22635
22636    private static class MoveCallbacks extends Handler {
22637        private static final int MSG_CREATED = 1;
22638        private static final int MSG_STATUS_CHANGED = 2;
22639
22640        private final RemoteCallbackList<IPackageMoveObserver>
22641                mCallbacks = new RemoteCallbackList<>();
22642
22643        private final SparseIntArray mLastStatus = new SparseIntArray();
22644
22645        public MoveCallbacks(Looper looper) {
22646            super(looper);
22647        }
22648
22649        public void register(IPackageMoveObserver callback) {
22650            mCallbacks.register(callback);
22651        }
22652
22653        public void unregister(IPackageMoveObserver callback) {
22654            mCallbacks.unregister(callback);
22655        }
22656
22657        @Override
22658        public void handleMessage(Message msg) {
22659            final SomeArgs args = (SomeArgs) msg.obj;
22660            final int n = mCallbacks.beginBroadcast();
22661            for (int i = 0; i < n; i++) {
22662                final IPackageMoveObserver callback = mCallbacks.getBroadcastItem(i);
22663                try {
22664                    invokeCallback(callback, msg.what, args);
22665                } catch (RemoteException ignored) {
22666                }
22667            }
22668            mCallbacks.finishBroadcast();
22669            args.recycle();
22670        }
22671
22672        private void invokeCallback(IPackageMoveObserver callback, int what, SomeArgs args)
22673                throws RemoteException {
22674            switch (what) {
22675                case MSG_CREATED: {
22676                    callback.onCreated(args.argi1, (Bundle) args.arg2);
22677                    break;
22678                }
22679                case MSG_STATUS_CHANGED: {
22680                    callback.onStatusChanged(args.argi1, args.argi2, (long) args.arg3);
22681                    break;
22682                }
22683            }
22684        }
22685
22686        private void notifyCreated(int moveId, Bundle extras) {
22687            Slog.v(TAG, "Move " + moveId + " created " + extras.toString());
22688
22689            final SomeArgs args = SomeArgs.obtain();
22690            args.argi1 = moveId;
22691            args.arg2 = extras;
22692            obtainMessage(MSG_CREATED, args).sendToTarget();
22693        }
22694
22695        private void notifyStatusChanged(int moveId, int status) {
22696            notifyStatusChanged(moveId, status, -1);
22697        }
22698
22699        private void notifyStatusChanged(int moveId, int status, long estMillis) {
22700            Slog.v(TAG, "Move " + moveId + " status " + status);
22701
22702            final SomeArgs args = SomeArgs.obtain();
22703            args.argi1 = moveId;
22704            args.argi2 = status;
22705            args.arg3 = estMillis;
22706            obtainMessage(MSG_STATUS_CHANGED, args).sendToTarget();
22707
22708            synchronized (mLastStatus) {
22709                mLastStatus.put(moveId, status);
22710            }
22711        }
22712    }
22713
22714    private final static class OnPermissionChangeListeners extends Handler {
22715        private static final int MSG_ON_PERMISSIONS_CHANGED = 1;
22716
22717        private final RemoteCallbackList<IOnPermissionsChangeListener> mPermissionListeners =
22718                new RemoteCallbackList<>();
22719
22720        public OnPermissionChangeListeners(Looper looper) {
22721            super(looper);
22722        }
22723
22724        @Override
22725        public void handleMessage(Message msg) {
22726            switch (msg.what) {
22727                case MSG_ON_PERMISSIONS_CHANGED: {
22728                    final int uid = msg.arg1;
22729                    handleOnPermissionsChanged(uid);
22730                } break;
22731            }
22732        }
22733
22734        public void addListenerLocked(IOnPermissionsChangeListener listener) {
22735            mPermissionListeners.register(listener);
22736
22737        }
22738
22739        public void removeListenerLocked(IOnPermissionsChangeListener listener) {
22740            mPermissionListeners.unregister(listener);
22741        }
22742
22743        public void onPermissionsChanged(int uid) {
22744            if (mPermissionListeners.getRegisteredCallbackCount() > 0) {
22745                obtainMessage(MSG_ON_PERMISSIONS_CHANGED, uid, 0).sendToTarget();
22746            }
22747        }
22748
22749        private void handleOnPermissionsChanged(int uid) {
22750            final int count = mPermissionListeners.beginBroadcast();
22751            try {
22752                for (int i = 0; i < count; i++) {
22753                    IOnPermissionsChangeListener callback = mPermissionListeners
22754                            .getBroadcastItem(i);
22755                    try {
22756                        callback.onPermissionsChanged(uid);
22757                    } catch (RemoteException e) {
22758                        Log.e(TAG, "Permission listener is dead", e);
22759                    }
22760                }
22761            } finally {
22762                mPermissionListeners.finishBroadcast();
22763            }
22764        }
22765    }
22766
22767    private class PackageManagerInternalImpl extends PackageManagerInternal {
22768        @Override
22769        public void setLocationPackagesProvider(PackagesProvider provider) {
22770            synchronized (mPackages) {
22771                mDefaultPermissionPolicy.setLocationPackagesProviderLPw(provider);
22772            }
22773        }
22774
22775        @Override
22776        public void setVoiceInteractionPackagesProvider(PackagesProvider provider) {
22777            synchronized (mPackages) {
22778                mDefaultPermissionPolicy.setVoiceInteractionPackagesProviderLPw(provider);
22779            }
22780        }
22781
22782        @Override
22783        public void setSmsAppPackagesProvider(PackagesProvider provider) {
22784            synchronized (mPackages) {
22785                mDefaultPermissionPolicy.setSmsAppPackagesProviderLPw(provider);
22786            }
22787        }
22788
22789        @Override
22790        public void setDialerAppPackagesProvider(PackagesProvider provider) {
22791            synchronized (mPackages) {
22792                mDefaultPermissionPolicy.setDialerAppPackagesProviderLPw(provider);
22793            }
22794        }
22795
22796        @Override
22797        public void setSimCallManagerPackagesProvider(PackagesProvider provider) {
22798            synchronized (mPackages) {
22799                mDefaultPermissionPolicy.setSimCallManagerPackagesProviderLPw(provider);
22800            }
22801        }
22802
22803        @Override
22804        public void setSyncAdapterPackagesprovider(SyncAdapterPackagesProvider provider) {
22805            synchronized (mPackages) {
22806                mDefaultPermissionPolicy.setSyncAdapterPackagesProviderLPw(provider);
22807            }
22808        }
22809
22810        @Override
22811        public void grantDefaultPermissionsToDefaultSmsApp(String packageName, int userId) {
22812            synchronized (mPackages) {
22813                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSmsAppLPr(
22814                        packageName, userId);
22815            }
22816        }
22817
22818        @Override
22819        public void grantDefaultPermissionsToDefaultDialerApp(String packageName, int userId) {
22820            synchronized (mPackages) {
22821                mSettings.setDefaultDialerPackageNameLPw(packageName, userId);
22822                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultDialerAppLPr(
22823                        packageName, userId);
22824            }
22825        }
22826
22827        @Override
22828        public void grantDefaultPermissionsToDefaultSimCallManager(String packageName, int userId) {
22829            synchronized (mPackages) {
22830                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSimCallManagerLPr(
22831                        packageName, userId);
22832            }
22833        }
22834
22835        @Override
22836        public void setKeepUninstalledPackages(final List<String> packageList) {
22837            Preconditions.checkNotNull(packageList);
22838            List<String> removedFromList = null;
22839            synchronized (mPackages) {
22840                if (mKeepUninstalledPackages != null) {
22841                    final int packagesCount = mKeepUninstalledPackages.size();
22842                    for (int i = 0; i < packagesCount; i++) {
22843                        String oldPackage = mKeepUninstalledPackages.get(i);
22844                        if (packageList != null && packageList.contains(oldPackage)) {
22845                            continue;
22846                        }
22847                        if (removedFromList == null) {
22848                            removedFromList = new ArrayList<>();
22849                        }
22850                        removedFromList.add(oldPackage);
22851                    }
22852                }
22853                mKeepUninstalledPackages = new ArrayList<>(packageList);
22854                if (removedFromList != null) {
22855                    final int removedCount = removedFromList.size();
22856                    for (int i = 0; i < removedCount; i++) {
22857                        deletePackageIfUnusedLPr(removedFromList.get(i));
22858                    }
22859                }
22860            }
22861        }
22862
22863        @Override
22864        public boolean isPermissionsReviewRequired(String packageName, int userId) {
22865            synchronized (mPackages) {
22866                // If we do not support permission review, done.
22867                if (!mPermissionReviewRequired) {
22868                    return false;
22869                }
22870
22871                PackageSetting packageSetting = mSettings.mPackages.get(packageName);
22872                if (packageSetting == null) {
22873                    return false;
22874                }
22875
22876                // Permission review applies only to apps not supporting the new permission model.
22877                if (packageSetting.pkg.applicationInfo.targetSdkVersion >= Build.VERSION_CODES.M) {
22878                    return false;
22879                }
22880
22881                // Legacy apps have the permission and get user consent on launch.
22882                PermissionsState permissionsState = packageSetting.getPermissionsState();
22883                return permissionsState.isPermissionReviewRequired(userId);
22884            }
22885        }
22886
22887        @Override
22888        public ApplicationInfo getApplicationInfo(String packageName, int userId) {
22889            return PackageManagerService.this.getApplicationInfo(packageName, 0 /*flags*/, userId);
22890        }
22891
22892        @Override
22893        public ComponentName getHomeActivitiesAsUser(List<ResolveInfo> allHomeCandidates,
22894                int userId) {
22895            return PackageManagerService.this.getHomeActivitiesAsUser(allHomeCandidates, userId);
22896        }
22897
22898        @Override
22899        public void setDeviceAndProfileOwnerPackages(
22900                int deviceOwnerUserId, String deviceOwnerPackage,
22901                SparseArray<String> profileOwnerPackages) {
22902            mProtectedPackages.setDeviceAndProfileOwnerPackages(
22903                    deviceOwnerUserId, deviceOwnerPackage, profileOwnerPackages);
22904        }
22905
22906        @Override
22907        public boolean isPackageDataProtected(int userId, String packageName) {
22908            return mProtectedPackages.isPackageDataProtected(userId, packageName);
22909        }
22910
22911        @Override
22912        public boolean isPackageEphemeral(int userId, String packageName) {
22913            synchronized (mPackages) {
22914                final PackageSetting ps = mSettings.mPackages.get(packageName);
22915                return ps != null ? ps.getInstantApp(userId) : false;
22916            }
22917        }
22918
22919        @Override
22920        public boolean wasPackageEverLaunched(String packageName, int userId) {
22921            synchronized (mPackages) {
22922                return mSettings.wasPackageEverLaunchedLPr(packageName, userId);
22923            }
22924        }
22925
22926        @Override
22927        public void grantRuntimePermission(String packageName, String name, int userId,
22928                boolean overridePolicy) {
22929            PackageManagerService.this.grantRuntimePermission(packageName, name, userId,
22930                    overridePolicy);
22931        }
22932
22933        @Override
22934        public void revokeRuntimePermission(String packageName, String name, int userId,
22935                boolean overridePolicy) {
22936            PackageManagerService.this.revokeRuntimePermission(packageName, name, userId,
22937                    overridePolicy);
22938        }
22939
22940        @Override
22941        public String getNameForUid(int uid) {
22942            return PackageManagerService.this.getNameForUid(uid);
22943        }
22944
22945        @Override
22946        public void requestInstantAppResolutionPhaseTwo(AuxiliaryResolveInfo responseObj,
22947                Intent origIntent, String resolvedType, String callingPackage, int userId) {
22948            PackageManagerService.this.requestInstantAppResolutionPhaseTwo(
22949                    responseObj, origIntent, resolvedType, callingPackage, userId);
22950        }
22951
22952        @Override
22953        public void grantEphemeralAccess(int userId, Intent intent,
22954                int targetAppId, int ephemeralAppId) {
22955            synchronized (mPackages) {
22956                mInstantAppRegistry.grantInstantAccessLPw(userId, intent,
22957                        targetAppId, ephemeralAppId);
22958            }
22959        }
22960
22961        @Override
22962        public void pruneInstantApps() {
22963            synchronized (mPackages) {
22964                mInstantAppRegistry.pruneInstantAppsLPw();
22965            }
22966        }
22967
22968        @Override
22969        public String getSetupWizardPackageName() {
22970            return mSetupWizardPackage;
22971        }
22972
22973        public void setExternalSourcesPolicy(ExternalSourcesPolicy policy) {
22974            if (policy != null) {
22975                mExternalSourcesPolicy = policy;
22976            }
22977        }
22978
22979        @Override
22980        public boolean isPackagePersistent(String packageName) {
22981            synchronized (mPackages) {
22982                PackageParser.Package pkg = mPackages.get(packageName);
22983                return pkg != null
22984                        ? ((pkg.applicationInfo.flags&(ApplicationInfo.FLAG_SYSTEM
22985                                        | ApplicationInfo.FLAG_PERSISTENT)) ==
22986                                (ApplicationInfo.FLAG_SYSTEM | ApplicationInfo.FLAG_PERSISTENT))
22987                        : false;
22988            }
22989        }
22990
22991        @Override
22992        public List<PackageInfo> getOverlayPackages(int userId) {
22993            final ArrayList<PackageInfo> overlayPackages = new ArrayList<PackageInfo>();
22994            synchronized (mPackages) {
22995                for (PackageParser.Package p : mPackages.values()) {
22996                    if (p.mOverlayTarget != null) {
22997                        PackageInfo pkg = generatePackageInfo((PackageSetting)p.mExtras, 0, userId);
22998                        if (pkg != null) {
22999                            overlayPackages.add(pkg);
23000                        }
23001                    }
23002                }
23003            }
23004            return overlayPackages;
23005        }
23006
23007        @Override
23008        public List<String> getTargetPackageNames(int userId) {
23009            List<String> targetPackages = new ArrayList<>();
23010            synchronized (mPackages) {
23011                for (PackageParser.Package p : mPackages.values()) {
23012                    if (p.mOverlayTarget == null) {
23013                        targetPackages.add(p.packageName);
23014                    }
23015                }
23016            }
23017            return targetPackages;
23018        }
23019
23020        @Override
23021        public boolean setEnabledOverlayPackages(int userId, @NonNull String targetPackageName,
23022                @Nullable List<String> overlayPackageNames) {
23023            synchronized (mPackages) {
23024                if (targetPackageName == null || mPackages.get(targetPackageName) == null) {
23025                    Slog.e(TAG, "failed to find package " + targetPackageName);
23026                    return false;
23027                }
23028
23029                ArrayList<String> paths = null;
23030                if (overlayPackageNames != null) {
23031                    final int N = overlayPackageNames.size();
23032                    paths = new ArrayList<String>(N);
23033                    for (int i = 0; i < N; i++) {
23034                        final String packageName = overlayPackageNames.get(i);
23035                        final PackageParser.Package pkg = mPackages.get(packageName);
23036                        if (pkg == null) {
23037                            Slog.e(TAG, "failed to find package " + packageName);
23038                            return false;
23039                        }
23040                        paths.add(pkg.baseCodePath);
23041                    }
23042                }
23043
23044                ArrayMap<String, ArrayList<String>> userSpecificOverlays =
23045                    mEnabledOverlayPaths.get(userId);
23046                if (userSpecificOverlays == null) {
23047                    userSpecificOverlays = new ArrayMap<String, ArrayList<String>>();
23048                    mEnabledOverlayPaths.put(userId, userSpecificOverlays);
23049                }
23050
23051                if (paths != null && paths.size() > 0) {
23052                    userSpecificOverlays.put(targetPackageName, paths);
23053                } else {
23054                    userSpecificOverlays.remove(targetPackageName);
23055                }
23056                return true;
23057            }
23058        }
23059
23060        public ResolveInfo resolveIntent(Intent intent, String resolvedType,
23061                int flags, int userId) {
23062            return resolveIntentInternal(
23063                    intent, resolvedType, flags, userId, true /*includeInstantApp*/);
23064        }
23065    }
23066
23067    @Override
23068    public void grantDefaultPermissionsToEnabledCarrierApps(String[] packageNames, int userId) {
23069        enforceSystemOrPhoneCaller("grantPermissionsToEnabledCarrierApps");
23070        synchronized (mPackages) {
23071            final long identity = Binder.clearCallingIdentity();
23072            try {
23073                mDefaultPermissionPolicy.grantDefaultPermissionsToEnabledCarrierAppsLPr(
23074                        packageNames, userId);
23075            } finally {
23076                Binder.restoreCallingIdentity(identity);
23077            }
23078        }
23079    }
23080
23081    @Override
23082    public void grantDefaultPermissionsToEnabledImsServices(String[] packageNames, int userId) {
23083        enforceSystemOrPhoneCaller("grantDefaultPermissionsToEnabledImsServices");
23084        synchronized (mPackages) {
23085            final long identity = Binder.clearCallingIdentity();
23086            try {
23087                mDefaultPermissionPolicy.grantDefaultPermissionsToEnabledImsServicesLPr(
23088                        packageNames, userId);
23089            } finally {
23090                Binder.restoreCallingIdentity(identity);
23091            }
23092        }
23093    }
23094
23095    private static void enforceSystemOrPhoneCaller(String tag) {
23096        int callingUid = Binder.getCallingUid();
23097        if (callingUid != Process.PHONE_UID && callingUid != Process.SYSTEM_UID) {
23098            throw new SecurityException(
23099                    "Cannot call " + tag + " from UID " + callingUid);
23100        }
23101    }
23102
23103    boolean isHistoricalPackageUsageAvailable() {
23104        return mPackageUsage.isHistoricalPackageUsageAvailable();
23105    }
23106
23107    /**
23108     * Return a <b>copy</b> of the collection of packages known to the package manager.
23109     * @return A copy of the values of mPackages.
23110     */
23111    Collection<PackageParser.Package> getPackages() {
23112        synchronized (mPackages) {
23113            return new ArrayList<>(mPackages.values());
23114        }
23115    }
23116
23117    /**
23118     * Logs process start information (including base APK hash) to the security log.
23119     * @hide
23120     */
23121    public void logAppProcessStartIfNeeded(String processName, int uid, String seinfo,
23122            String apkFile, int pid) {
23123        if (!SecurityLog.isLoggingEnabled()) {
23124            return;
23125        }
23126        Bundle data = new Bundle();
23127        data.putLong("startTimestamp", System.currentTimeMillis());
23128        data.putString("processName", processName);
23129        data.putInt("uid", uid);
23130        data.putString("seinfo", seinfo);
23131        data.putString("apkFile", apkFile);
23132        data.putInt("pid", pid);
23133        Message msg = mProcessLoggingHandler.obtainMessage(
23134                ProcessLoggingHandler.LOG_APP_PROCESS_START_MSG);
23135        msg.setData(data);
23136        mProcessLoggingHandler.sendMessage(msg);
23137    }
23138
23139    public CompilerStats.PackageStats getCompilerPackageStats(String pkgName) {
23140        return mCompilerStats.getPackageStats(pkgName);
23141    }
23142
23143    public CompilerStats.PackageStats getOrCreateCompilerPackageStats(PackageParser.Package pkg) {
23144        return getOrCreateCompilerPackageStats(pkg.packageName);
23145    }
23146
23147    public CompilerStats.PackageStats getOrCreateCompilerPackageStats(String pkgName) {
23148        return mCompilerStats.getOrCreatePackageStats(pkgName);
23149    }
23150
23151    public void deleteCompilerPackageStats(String pkgName) {
23152        mCompilerStats.deletePackageStats(pkgName);
23153    }
23154
23155    @Override
23156    public int getInstallReason(String packageName, int userId) {
23157        enforceCrossUserPermission(Binder.getCallingUid(), userId,
23158                true /* requireFullPermission */, false /* checkShell */,
23159                "get install reason");
23160        synchronized (mPackages) {
23161            final PackageSetting ps = mSettings.mPackages.get(packageName);
23162            if (ps != null) {
23163                return ps.getInstallReason(userId);
23164            }
23165        }
23166        return PackageManager.INSTALL_REASON_UNKNOWN;
23167    }
23168
23169    @Override
23170    public boolean canRequestPackageInstalls(String packageName, int userId) {
23171        int callingUid = Binder.getCallingUid();
23172        int uid = getPackageUid(packageName, 0, userId);
23173        if (callingUid != uid && callingUid != Process.ROOT_UID
23174                && callingUid != Process.SYSTEM_UID) {
23175            throw new SecurityException(
23176                    "Caller uid " + callingUid + " does not own package " + packageName);
23177        }
23178        ApplicationInfo info = getApplicationInfo(packageName, 0, userId);
23179        if (info == null) {
23180            return false;
23181        }
23182        if (info.targetSdkVersion < Build.VERSION_CODES.O) {
23183            throw new UnsupportedOperationException(
23184                    "Operation only supported on apps targeting Android O or higher");
23185        }
23186        String appOpPermission = Manifest.permission.REQUEST_INSTALL_PACKAGES;
23187        String[] packagesDeclaringPermission = getAppOpPermissionPackages(appOpPermission);
23188        if (!ArrayUtils.contains(packagesDeclaringPermission, packageName)) {
23189            throw new SecurityException("Need to declare " + appOpPermission + " to call this api");
23190        }
23191        if (sUserManager.hasUserRestriction(UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES, userId)) {
23192            return false;
23193        }
23194        if (mExternalSourcesPolicy != null) {
23195            int isTrusted = mExternalSourcesPolicy.getPackageTrustedToInstallApps(packageName, uid);
23196            if (isTrusted != PackageManagerInternal.ExternalSourcesPolicy.USER_DEFAULT) {
23197                return isTrusted == PackageManagerInternal.ExternalSourcesPolicy.USER_TRUSTED;
23198            }
23199        }
23200        return checkUidPermission(appOpPermission, uid) == PERMISSION_GRANTED;
23201    }
23202}
23203